summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.copr/Makefile6
-rw-r--r--Code-map.md1
-rw-r--r--README.md32
-rw-r--r--abi-check-plugin/src/main/java/com/yahoo/abicheck/collector/Util.java11
-rw-r--r--application-preprocessor/pom.xml30
-rw-r--r--application-preprocessor/src/main/java/com/yahoo/application/preprocessor/ApplicationPreprocessor.java13
-rw-r--r--application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java26
-rw-r--r--application/abi-spec.json1
-rw-r--r--application/pom.xml29
-rw-r--r--application/src/main/java/com/yahoo/application/Application.java19
-rw-r--r--application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd17
-rw-r--r--application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml3
-rw-r--r--application/src/test/app-packages/withqueryprofile/services.xml29
-rw-r--r--application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java53
-rw-r--r--application/src/test/java/com/yahoo/application/ApplicationTest.java114
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java80
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java23
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java62
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java48
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java24
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerTest.java35
-rw-r--r--application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java77
-rw-r--r--application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java10
-rw-r--r--athenz-identity-provider-service/pom.xml35
-rw-r--r--athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java2
-rw-r--r--athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/Certificates.java4
-rw-r--r--athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiHandler.java13
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java32
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java28
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificateTester.java4
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java20
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java68
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java10
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java38
-rw-r--r--bundle-plugin-test/integration-test/pom.xml13
-rw-r--r--bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java36
-rw-r--r--bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java18
-rw-r--r--bundle-plugin/pom.xml15
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java20
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java58
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java26
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java6
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java10
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java24
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java40
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java18
-rw-r--r--client/README.md32
-rw-r--r--client/go/cmd/api_key.go5
-rw-r--r--client/go/cmd/api_key_test.go3
-rw-r--r--client/go/cmd/cert.go9
-rw-r--r--client/go/cmd/cert_test.go6
-rw-r--r--client/go/cmd/config.go16
-rw-r--r--client/go/cmd/config_test.go6
-rw-r--r--client/go/cmd/curl.go2
-rw-r--r--client/go/cmd/curl_test.go1
-rw-r--r--client/go/cmd/deploy.go2
-rw-r--r--client/go/cmd/document.go2
-rw-r--r--client/go/cmd/logfmt/handleline.go116
-rw-r--r--client/go/cmd/logfmt/internal.go106
-rw-r--r--client/go/cmd/logfmt/internal_names.txt782
-rw-r--r--client/go/cmd/logfmt/internal_notnames.txt8
-rw-r--r--client/go/cmd/logfmt/internal_test.go34
-rw-r--r--client/go/cmd/logfmt/levelflags.go72
-rw-r--r--client/go/cmd/logfmt/levelflags_test.go74
-rw-r--r--client/go/cmd/logfmt/options.go47
-rw-r--r--client/go/cmd/logfmt/plusminusflag.go67
-rw-r--r--client/go/cmd/logfmt/regexflag.go38
-rw-r--r--client/go/cmd/logfmt/regexflag_test.go41
-rw-r--r--client/go/cmd/logfmt/runlogfmt.go78
-rw-r--r--client/go/cmd/logfmt/showflags.go76
-rw-r--r--client/go/cmd/logfmt/showflags_test.go61
-rw-r--r--client/go/cmd/logfmt/tail.go169
-rw-r--r--client/go/cmd/query.go2
-rw-r--r--client/go/cmd/root.go13
-rw-r--r--client/go/cmd/status.go2
-rw-r--r--client/go/vespa-logfmt/cmd.go45
-rw-r--r--client/go/vespa-logfmt/main.go9
-rw-r--r--client/go/vespa/target_cloud.go30
-rw-r--r--client/js/app/README.md57
-rw-r--r--client/js/app/img/JaegerExample.pngbin0 -> 24416 bytes
-rw-r--r--client/js/app/img/TraceConverter.pngbin0 -> 14448 bytes
-rw-r--r--client/js/app/img/result.pngbin0 -> 369263 bytes
-rw-r--r--client/js/app/package.json36
-rw-r--r--client/js/app/src/app/app.jsx27
-rw-r--r--client/js/app/src/app/assets/img/vespa-logo.svg254
-rw-r--r--client/js/app/src/app/assets/index.js1
-rw-r--r--client/js/app/src/app/components/card-link/card-link.jsx36
-rw-r--r--client/js/app/src/app/components/containers/container.jsx14
-rw-r--r--client/js/app/src/app/components/containers/content.jsx32
-rw-r--r--client/js/app/src/app/components/containers/message.jsx16
-rw-r--r--client/js/app/src/app/components/containers/section.jsx17
-rw-r--r--client/js/app/src/app/components/icon/icon.jsx47
-rw-r--r--client/js/app/src/app/components/index.js7
-rw-r--r--client/js/app/src/app/components/layout/header-logo.jsx7
-rw-r--r--client/js/app/src/app/components/layout/header.jsx12
-rw-r--r--client/js/app/src/app/components/layout/layout.jsx6
-rw-r--r--client/js/app/src/app/components/link/link.jsx23
-rw-r--r--client/js/app/src/app/libs/app-router.jsx42
-rw-r--r--client/js/app/src/app/libs/notification/index.jsx2
-rw-r--r--client/js/app/src/app/libs/notification/messages.jsx77
-rw-r--r--client/js/app/src/app/libs/notification/rest-message.jsx43
-rw-r--r--client/js/app/src/app/libs/router.jsx52
-rw-r--r--client/js/app/src/app/libs/theme-provider.jsx19
-rw-r--r--client/js/app/src/app/pages/home/home.jsx28
-rw-r--r--client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx349
-rw-r--r--client/js/app/src/app/pages/querybuilder/context/__test__/query-builder-provider.test.jsx179
-rw-r--r--client/js/app/src/app/pages/querybuilder/context/parameters.jsx120
-rw-r--r--client/js/app/src/app/pages/querybuilder/context/query-builder-provider.jsx217
-rw-r--r--client/js/app/src/app/pages/querybuilder/index.jsx36
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-builder.jsx5
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-derived/query-derived.jsx57
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-endpoint/query-endpoint.jsx63
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-filters/query-filters.jsx128
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-response/download-jeager.jsx55
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-response/query-response.jsx58
-rw-r--r--client/js/app/src/app/pages/querytracer/query-tracer.jsx25
-rw-r--r--client/js/app/src/app/styles/default/default-props.js9
-rw-r--r--client/js/app/src/app/styles/default/default-styles.js393
-rw-r--r--client/js/app/src/app/styles/default/index.js2
-rw-r--r--client/js/app/src/app/styles/global.js39
-rw-r--r--client/js/app/src/app/styles/theme/colors.js69
-rw-r--r--client/js/app/src/app/styles/theme/common-colors.js158
-rw-r--r--client/js/app/src/app/styles/theme/common.js35
-rw-r--r--client/js/app/src/app/styles/theme/components.js10
-rw-r--r--client/js/app/src/app/styles/theme/index.js7
-rw-r--r--client/js/app/yarn.lock3935
-rw-r--r--cloud-tenant-base-dependencies-enforcer/pom.xml9
-rw-r--r--clustercontroller-apps/pom.xml27
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java26
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java20
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java8
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java4
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java16
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java10
-rw-r--r--clustercontroller-core/pom.xml21
-rw-r--r--clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ContentCluster.java61
-rw-r--r--clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetController.java46
-rw-r--r--clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicator.java46
-rw-r--r--clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RpcServer.java31
-rw-r--r--clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/LegacyIndexPageRequestHandler.java104
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java36
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java51
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java134
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java28
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java18
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java8
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java22
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java27
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java17
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DummyVdsNode.java77
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java58
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java19
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java118
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java57
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java30
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java16
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java155
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java14
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java7
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java24
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java71
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java73
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java15
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java291
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java51
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java18
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java343
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java23
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java60
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java42
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java16
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java9
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java44
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java21
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java91
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java102
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java160
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java72
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java48
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java11
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java192
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java143
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java65
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java18
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/StateWaiter.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java7
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java42
-rw-r--r--clustercontroller-reindexer/pom.xml14
-rw-r--r--clustercontroller-reindexer/src/main/java/ai/vespa/reindexing/ReindexingMetrics.java22
-rw-r--r--clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/ReindexerTest.java20
-rw-r--r--clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java2
-rw-r--r--clustercontroller-utils/pom.xml17
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java32
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java34
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java10
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java22
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java30
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java335
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java6
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java10
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java6
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java8
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java42
-rwxr-xr-xcomponent/pom.xml15
-rw-r--r--component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java32
-rw-r--r--component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java118
-rw-r--r--component/src/test/java/com/yahoo/component/VersionTestCase.java150
-rw-r--r--config-application-package/src/main/java/com/yahoo/config/application/ValidationProcessor.java18
-rw-r--r--config-application-package/src/main/java/com/yahoo/config/application/XmlPreProcessor.java4
-rw-r--r--config-application-package/src/main/java/com/yahoo/config/model/application/provider/DeployData.java18
-rw-r--r--config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java6
-rw-r--r--config-application-package/src/main/java/com/yahoo/config/model/application/provider/SchemaValidators.java31
-rw-r--r--config-application-package/src/test/java/com/yahoo/config/application/MultiOverrideProcessorTest.java8
-rw-r--r--config-bundle/pom.xml6
-rw-r--r--config-lib/pom.xml15
-rw-r--r--config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java8
-rw-r--r--config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java78
-rw-r--r--config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java36
-rw-r--r--config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java12
-rw-r--r--config-lib/src/test/java/com/yahoo/config/FileNodeTest.java12
-rw-r--r--config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/LongNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java97
-rw-r--r--config-lib/src/test/java/com/yahoo/config/PathNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/StringNodeTest.java19
-rw-r--r--config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java6
-rw-r--r--config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java10
-rw-r--r--config-model-api/abi-spec.json1
-rw-r--r--config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationMetaData.java24
-rw-r--r--config-model-api/src/main/java/com/yahoo/config/model/api/EndpointCertificateSecrets.java19
-rw-r--r--config-model-api/src/main/java/com/yahoo/config/model/api/ModelContext.java18
-rw-r--r--config-model/pom.xml21
-rw-r--r--config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java56
-rw-r--r--config-model/src/main/java/com/yahoo/config/model/provision/InMemoryProvisioner.java2
-rw-r--r--config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java34
-rw-r--r--config-model/src/main/java/com/yahoo/config/model/test/MockRoot.java2
-rw-r--r--config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java2
-rw-r--r--config-model/src/main/java/com/yahoo/schema/derived/IndexInfo.java22
-rw-r--r--config-model/src/main/java/com/yahoo/schema/derived/SummaryClass.java6
-rw-r--r--config-model/src/main/java/com/yahoo/schema/derived/SummaryMap.java14
-rw-r--r--config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java5
-rw-r--r--config-model/src/main/java/com/yahoo/schema/document/ImmutableSDField.java8
-rw-r--r--config-model/src/main/java/com/yahoo/schema/document/SDField.java9
-rw-r--r--config-model/src/main/java/com/yahoo/schema/parser/IntermediateCollection.java2
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/AddExtraFieldsToDocument.java2
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java3
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/Processing.java1
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/RankingExpressionTypeResolver.java6
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/SummaryConsistency.java18
-rw-r--r--config-model/src/main/java/com/yahoo/schema/processing/SummaryTransformForDocumentId.java32
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentManager.java8
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentTypes.java1
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/documentmodel/DocumentModel.java16
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryField.java16
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryTransform.java5
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/HostSystem.java15
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/Logserver.java15
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerCluster.java1
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainer.java6
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java9
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java20
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/DefaultMetrics.java44
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/VespaMetricSet.java6
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/AbstractBundleValidator.java14
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldAttributesValidator.java (renamed from config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidator.java)4
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldIndexesValidator.java75
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidator.java7
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/QuotaValidator.java17
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/UriBindingsValidator.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/application/validation/Validation.java3
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomClientProviderBuilder.java3
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomHandlerBuilder.java19
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilder.java6
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/clients/ContainerDocumentApi.java80
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainer.java12
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainerCluster.java10
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/Container.java21
-rwxr-xr-xconfig-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java95
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/ContainerModelEvaluation.java4
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java12
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/DefaultThreadpoolProvider.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/IdentityProvider.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java52
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java6
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java46
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/component/SimpleComponent.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/component/chain/ProcessingHandler.java17
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/docproc/ContainerDocproc.java66
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/docproc/DocprocChains.java10
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/docproc/MbusClient.java3
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java14
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java12
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/http/FilterChains.java5
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/ContainerSearch.java9
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/DispatcherComponent.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/GUIHandler.java5
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/RpcResourcePoolComponent.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcher.java8
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/LocalClustersCreator.java9
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/VespaSearchChainsCreator.java28
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java6
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/CloudSecretStore.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java48
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocprocOptionsBuilder.java60
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocumentApiOptionsBuilder.java5
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/SearchHandler.java33
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/xml/document/DocumentFactoryBuilder.java2
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/content/Content.java3
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/content/ContentNode.java24
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/content/DispatchTuning.java4
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java5
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/routing/DocumentProtocol.java79
-rw-r--r--config-model/src/main/resources/schema/containercluster.rnc1
-rw-r--r--config-model/src/main/resources/schema/docproc.rnc11
-rw-r--r--config-model/src/test/cfg/admin/adminconfigbaseport/hosts.xml7
-rw-r--r--config-model/src/test/cfg/admin/adminconfigbaseport/services.xml17
-rw-r--r--config-model/src/test/cfg/application/app_qrserverandgw/hosts.xml7
-rw-r--r--config-model/src/test/cfg/application/app_qrserverandgw/schemas/message.sd9
-rw-r--r--config-model/src/test/cfg/application/app_qrserverandgw/services.xml29
-rw-r--r--config-model/src/test/configmodel/types/documentmanager.cfg2
-rw-r--r--config-model/src/test/configmodel/types/documenttypes.cfg2
-rw-r--r--config-model/src/test/configmodel/types/documenttypes_with_doc_field.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documentmanager_multiple_imported_fields.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documentmanager_refs_to_other_types.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documentmanager_refs_to_same_type.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documenttypes_multiple_imported_fields.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documenttypes_ref_to_self_type.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documenttypes_refs_to_other_types.cfg2
-rw-r--r--config-model/src/test/configmodel/types/references/documenttypes_refs_to_same_type.cfg2
-rw-r--r--config-model/src/test/derived/advanced/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/advanced/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/annotationsimplicitstruct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationsinheritance/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationsinheritance2/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationspolymorphy/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationsreference/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationssimple/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationsstruct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/annotationsstructarray/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/array_of_struct_attribute/summary.cfg9
-rw-r--r--config-model/src/test/derived/array_of_struct_attribute/summarymap.cfg10
-rw-r--r--config-model/src/test/derived/array_of_struct_attribute/test.sd3
-rw-r--r--config-model/src/test/derived/arrays/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/attributeprefetch/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/attributeprefetch/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/attributes/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/complex/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/complex/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/declstruct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/duplicate_struct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/duplicate_struct/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/emptydefault/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/emptydefault/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/id/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/id/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/imported_fields_inherited_reference/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/imported_position_field/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/imported_position_field_summary/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/imported_struct_fields/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/importedfields/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/indexswitches/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/indexswitches/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/inheritance/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/inheritance/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/inheritdiamond/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/inheritfromgrandparent/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/inheritfromparent/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/inheritfromparent/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/inheritfromparent/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/mail/onlydoc/documentmanager.cfg1
-rw-r--r--config-model/src/test/derived/map_attribute/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/map_of_struct_attribute/summary.cfg17
-rw-r--r--config-model/src/test/derived/map_of_struct_attribute/summarymap.cfg13
-rw-r--r--config-model/src/test/derived/map_of_struct_attribute/test.sd4
-rw-r--r--config-model/src/test/derived/multi_struct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/multi_struct/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/multiplesummaries/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/music/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/namecollision/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/newrank/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/position_nosummary/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/position_summary/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/predicate_attribute/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/prefixexactattribute/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/rankingexpression/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/ranktypes/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/ranktypes/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/reference_fields/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/reference_from_several/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/schemainheritance/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/schemainheritance/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/streamingstruct/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/streamingstruct/summarymap.cfg3
-rw-r--r--config-model/src/test/derived/structandfieldset/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/structanyorder/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/structinheritance/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/structinheritance/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/tensor/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/tensor/documenttypes.cfg2
-rw-r--r--config-model/src/test/derived/types/documentmanager.cfg2
-rw-r--r--config-model/src/test/derived/types/summarymap.cfg3
-rw-r--r--config-model/src/test/examples/fieldoftypedocument-doctypes.cfg2
-rw-r--r--config-model/src/test/examples/fieldoftypedocument.cfg2
-rw-r--r--config-model/src/test/examples/structresult.cfg2
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java144
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java44
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java32
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java48
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java25
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java4
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java29
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java63
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java46
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java23
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java286
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java38
-rw-r--r--config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java65
-rw-r--r--config-model/src/test/java/com/yahoo/schema/CommentTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java13
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java101
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java86
-rw-r--r--config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java30
-rw-r--r--config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java29
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java24
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java68
-rw-r--r--config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java15
-rw-r--r--config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java143
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java42
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java82
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java25
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java56
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java302
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java43
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java21
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java441
-rw-r--r--config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java10
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/StructTestCase.java24
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java93
-rw-r--r--config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java18
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java42
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java82
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java7
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java138
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java47
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java30
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java5
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java13
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java10
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java4
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java6
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java37
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java61
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java17
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java38
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java75
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java15
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java55
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java134
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java2
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java21
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java83
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java46
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java85
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java76
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java119
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java28
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java90
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java48
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java39
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java2
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java176
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java77
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java184
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java27
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java79
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java37
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java86
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java31
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java34
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java56
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java146
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java70
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java166
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java55
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java46
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java92
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java62
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidatorTestCase.java124
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java167
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java324
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java30
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java37
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java43
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java38
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java28
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java11
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java94
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java4
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java82
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java147
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java50
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java563
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java61
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java121
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java41
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java9
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java27
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java6
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java247
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java55
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java44
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/docproc/StandaloneDocprocContainerTest.java82
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java9
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java48
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java97
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java58
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java260
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java86
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java49
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java642
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java40
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java57
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java115
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java66
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java34
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java39
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java (renamed from config-model/src/test/java/com/yahoo/vespa/model/container/xml/ApplicationBuilderTest.java)127
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java127
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java25
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java738
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java39
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java87
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java31
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java110
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java99
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java17
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java119
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java15
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java42
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java15
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java12
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java72
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java78
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java19
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java133
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java36
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java17
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java122
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java85
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java35
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java24
-rw-r--r--config-model/src/test/java/helpers/CompareConfigTestHelper.java2
-rwxr-xr-xconfig-model/src/test/schema-test-files/hosts.xml6
-rw-r--r--config-model/src/test/schema-test-files/services.xml7
-rw-r--r--config-provisioning/pom.xml23
-rw-r--r--config-provisioning/src/main/java/com/yahoo/config/provision/zone/NodeSlice.java46
-rw-r--r--config-provisioning/src/main/java/com/yahoo/config/provision/zone/UpgradePolicy.java57
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java67
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java42
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java36
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java6
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java30
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java42
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java22
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java6
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java16
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java8
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java22
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java8
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java12
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java10
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java10
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/zone/NodeSliceTest.java32
-rw-r--r--config-proxy/pom.xml26
-rw-r--r--config-proxy/src/main/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClient.java2
-rw-r--r--config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/FileDistributionAndUrlDownload.java15
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java107
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java19
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java16
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java6
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java8
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java14
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java44
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java25
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java32
-rwxr-xr-xconfig/pom.xml5
-rwxr-xr-xconfig/src/main/java/com/yahoo/config/subscription/ConfigGetter.java3
-rw-r--r--config/src/main/java/com/yahoo/config/subscription/impl/JRTConfigRequester.java8
-rw-r--r--config/src/main/java/com/yahoo/config/subscription/impl/MockConnection.java6
-rw-r--r--config/src/main/java/com/yahoo/vespa/config/Connection.java6
-rw-r--r--config/src/main/java/com/yahoo/vespa/config/JRTConnection.java5
-rw-r--r--config/src/main/java/com/yahoo/vespa/config/UrlDownloader.java3
-rw-r--r--config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java3
-rw-r--r--config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceDeserializer.java22
-rw-r--r--config/src/test/java/com/yahoo/config/subscription/ConfigGetterTest.java1
-rw-r--r--config/src/test/java/com/yahoo/config/subscription/FunctionTest.java5
-rw-r--r--config/src/test/java/com/yahoo/config/subscription/NamespaceTest.java1
-rw-r--r--config/src/test/java/com/yahoo/config/subscription/UnicodeTest.java1
-rw-r--r--configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java (renamed from container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/package-info.java)2
-rw-r--r--configdefinitions/src/vespa/configserver.def5
-rw-r--r--configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def18
-rw-r--r--configgen/pom.xml9
-rw-r--r--configgen/src/main/java/com/yahoo/config/codegen/CppClassBuilder.java60
-rw-r--r--configgen/src/main/java/com/yahoo/config/codegen/DefParser.java16
-rw-r--r--configgen/src/main/java/com/yahoo/config/codegen/MakeConfig.java3
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java59
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java41
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java40
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java115
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java102
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java20
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java18
-rw-r--r--configserver-flags/pom.xml39
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java18
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java20
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java41
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/ApplicationRepository.java22
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/ConfigActivationListener.java (renamed from configserver/src/main/java/com/yahoo/vespa/config/server/ReloadListener.java)8
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelController.java2
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelRequestHandler.java6
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java2
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/application/TenantApplications.java41
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ModelContextImpl.java33
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDirectory.java13
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDistributionImpl.java3
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileServer.java128
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/http/ProxyResponse.java5
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/ApplicationPackageMaintainer.java20
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/SessionsMaintainer.java9
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/modelfactory/ModelsBuilder.java2
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponses.java9
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/rpc/GetConfigProcessor.java40
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java71
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizer.java8
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/session/Session.java4
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionPreparer.java80
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java149
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionStateWatcher.java46
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/tenant/EndpointCertificateRetriever.java12
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java14
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplication.java4
-rw-r--r--configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplicationPackage.java9
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/ApplicationRepositoryTest.java15
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java14
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java33
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/deploy/ZooKeeperClientTest.java4
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/filedistribution/FileServerTest.java34
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcServerTest.java26
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcTester.java2
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizerTest.java10
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java11
-rw-r--r--configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TestTenantRepository.java15
-rw-r--r--container-core/abi-spec.json6
-rw-r--r--container-core/pom.xml24
-rw-r--r--container-core/src/main/java/com/yahoo/component/chain/model/ChainSpecification.java14
-rw-r--r--container-core/src/main/java/com/yahoo/container/bundle/BundleInstantiationSpecification.java37
-rw-r--r--container-core/src/main/java/com/yahoo/container/di/Container.java2
-rw-r--r--container-core/src/main/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandler.java2
-rw-r--r--container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java22
-rw-r--r--container-core/src/main/java/com/yahoo/jdisc/http/filter/util/FilterUtils.java5
-rw-r--r--container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java113
-rw-r--r--container-core/src/main/java/com/yahoo/jdisc/http/ssl/impl/ConfiguredSslContextFactoryProvider.java2
-rw-r--r--container-core/src/main/java/com/yahoo/osgi/provider/model/ComponentModel.java4
-rw-r--r--container-core/src/main/java/com/yahoo/processing/request/CompoundName.java95
-rw-r--r--container-core/src/main/resources/configdefinitions/container.core.application-metadata.def3
-rw-r--r--container-core/src/main/resources/configdefinitions/container.jdisc.state.metrics-packets-handler.def2
-rw-r--r--container-core/src/main/resources/configdefinitions/jdisc.http.jdisc.http.connector.def8
-rwxr-xr-xcontainer-core/src/main/sh/find-pid2
-rw-r--r--container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java14
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java38
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java19
-rw-r--r--container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java31
-rw-r--r--container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java33
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ContainerTest.java38
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java20
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java147
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java49
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java22
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java25
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java51
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java24
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java35
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java26
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java18
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java35
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java12
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java64
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java144
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java8
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java280
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java114
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java16
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java80
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java37
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java24
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java489
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java39
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java19
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java35
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java28
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java56
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java12
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java225
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java9
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java72
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java23
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java26
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java19
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java22
-rw-r--r--container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java23
-rw-r--r--container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java30
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java38
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java77
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java143
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java48
-rw-r--r--container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java295
-rw-r--r--container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java17
-rw-r--r--container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java140
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java153
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameBenchmark.java19
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameTestCase.java66
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java74
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java32
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java86
-rw-r--r--container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java9
-rw-r--r--container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java50
-rw-r--r--container-core/src/test/java/com/yahoo/restapi/PathTest.java26
-rw-r--r--container-dependency-versions/pom.xml1
-rw-r--r--container-disc/pom.xml47
-rw-r--r--container-disc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java (renamed from container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java)166
-rw-r--r--container-disc/src/main/java/com/yahoo/container/handler/observability/package-info.java (renamed from jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java)2
-rw-r--r--container-disc/src/main/java/com/yahoo/container/jdisc/SystemInfoProvider.java2
-rw-r--r--container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java4
-rw-r--r--container-disc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def (renamed from container-search-and-docproc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def)0
-rwxr-xr-xcontainer-disc/src/main/sh/vespa-start-container-daemon.sh7
-rw-r--r--container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java (renamed from container-search-and-docproc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java)17
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java60
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java8
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java6
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java11
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java12
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java8
-rw-r--r--container-messagebus/src/main/java/com/yahoo/messagebus/shared/SharedMessageBus.java10
-rw-r--r--container-messagebus/src/main/resources/configdefinitions/container.jdisc.container-mbus.def4
-rw-r--r--container-search-gui/pom.xml32
-rw-r--r--container-search/abi-spec.json4
-rw-r--r--container-search/pom.xml35
-rw-r--r--container-search/src/main/java/com/yahoo/prelude/query/parser/StructuredParser.java1
-rw-r--r--container-search/src/main/java/com/yahoo/search/Query.java4
-rw-r--r--container-search/src/main/java/com/yahoo/search/dispatch/searchcluster/Group.java2
-rw-r--r--container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java35
-rw-r--r--container-search/src/main/java/com/yahoo/search/grouping/vespa/RequestBuilder.java3
-rw-r--r--container-search/src/main/java/com/yahoo/search/handler/Json2SingleLevelMap.java2
-rw-r--r--container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java1
-rw-r--r--container-search/src/main/java/com/yahoo/search/handler/observability/SearchStatusExtension.java32
-rw-r--r--container-search/src/main/java/com/yahoo/search/handler/observability/package-info.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/https/package-info.java)2
-rw-r--r--container-search/src/main/java/com/yahoo/search/query/profile/ChainedMap.java107
-rw-r--r--container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java8
-rw-r--r--container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileConfigurer.java1
-rw-r--r--container-search/src/main/java/com/yahoo/search/query/ranking/RankFeatures.java12
-rw-r--r--container-search/src/main/java/com/yahoo/search/querytransform/WeakAndReplacementSearcher.java13
-rw-r--r--container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java2
-rw-r--r--container-search/src/main/java/com/yahoo/search/searchchain/model/federation/FederationSearcherModel.java8
-rw-r--r--container-search/src/main/java/com/yahoo/search/searchchain/model/federation/LocalProviderSpec.java4
-rw-r--r--container-search/src/main/java/com/yahoo/search/yql/MinimalQueryInserter.java12
-rw-r--r--container-search/src/main/java/com/yahoo/search/yql/YqlParser.java30
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/IndexFactsFactory.java1
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java43
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java83
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java29
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java96
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java500
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java73
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java1191
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java11
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java149
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java85
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java39
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java64
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java289
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java156
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java30
-rwxr-xr-xcontainer-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java61
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java141
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java108
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java34
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java35
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java69
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java34
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java61
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java36
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java2
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java2
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java11
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java92
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java73
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java114
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java114
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java43
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java60
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java55
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java13
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java41
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java47
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java52
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java380
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java60
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java132
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java44
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java263
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java495
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java898
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java160
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java15
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java224
-rw-r--r--container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java11
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java36
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java68
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java96
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java80
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java48
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java49
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java19
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java40
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java48
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java66
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java46
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java69
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java54
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java230
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java240
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java34
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java95
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java376
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java1476
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java46
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java86
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java144
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java41
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java174
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java31
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java134
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java100
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java138
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java98
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java58
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java66
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java27
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java55
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java37
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java61
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java62
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java337
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java76
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java15
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java122
-rw-r--r--container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java2
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java51
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java53
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java39
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java35
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java51
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java41
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java27
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java35
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java8
-rwxr-xr-xcontainer-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java341
-rw-r--r--container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java130
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java98
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java170
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java566
-rw-r--r--container-search/src/test/java/com/yahoo/select/SelectTestCase.java205
-rw-r--r--container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java77
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java40
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java10
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java4
-rw-r--r--controller-api/pom.xml16
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZmsClientMock.java10
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZtsClientMock.java2
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/NoopRoleService.java5
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/RoleService.java2
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateDetails.java237
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateValidatorImpl.java2
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/Node.java18
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/NodeRepoStats.java9
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobType.java23
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/TestReport.java2
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepoStatsData.java9
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepositoryNode.java18
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/user/UserSessionManager.java13
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java4
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/role/PathGroup.java1
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/tenant/CloudTenant.java11
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java167
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java10
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java8
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java6
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java51
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java22
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java48
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java96
-rw-r--r--controller-server/pom.xml32
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/Application.java30
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/ApplicationController.java21
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/LockedTenant.java26
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java34
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatusList.java13
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java23
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunner.java31
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobController.java14
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobList.java9
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java2
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationMetaDataGarbageCollector.java5
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java1
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirer.java113
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintenance.java10
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainer.java26
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/InfrastructureUpgrader.java60
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java52
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainer.java5
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeScheduler.java171
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgrader.java24
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainer.java2
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgrader.java12
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainer.java20
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/Upgrader.java38
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainer.java21
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/notification/Notifier.java25
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStore.java12
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/CuratorDb.java8
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializer.java5
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java58
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelper.java4
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2.java9
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiHandler.java19
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/StatsResponse.java2
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiHandler.java33
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiHandler.java78
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManager.java50
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java4
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/VespaVersion.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java476
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java5
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java86
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java20
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java59
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java46
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java2
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java444
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java21
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java34
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java2
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ZoneApiMock.java5
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java46
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java15
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java47
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java15
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java18
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java50
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java47
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java11
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java166
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java107
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java143
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java50
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java135
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java256
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java33
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java39
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java130
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java73
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java20
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java44
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java102
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java85
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java22
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java52
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java1126
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java18
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java66
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview-2.json2
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview.json3
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-first-part.json7
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-second-part.json7
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1.json40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/instance1-metering.json46
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/jobs.json1
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/prod-us-central-1.json74
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/staging-test-log.json7
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-details.json7
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-log.json7
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/tenant-with-application-with-metadata.json19
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java37
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java26
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java60
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/responses/stats.json4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java60
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java26
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java58
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/responses/versions-all-upgraded.json2
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java190
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java151
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java36
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/application-roles.json19
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-keys.json4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-secrets.json4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-without-applications.json4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java235
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java60
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManagerTest.java64
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java30
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java195
-rw-r--r--controller-server/src/test/resources/horizon/filters-complex.expected.json2
-rw-r--r--controller-server/src/test/resources/horizon/filters-complex.json2
-rw-r--r--defaults/src/main/java/com/yahoo/vespa/defaults/Defaults.java17
-rw-r--r--dist/vespa-engine.repo8
-rw-r--r--dist/vespa.spec5
-rw-r--r--docker/.gitignore3
-rw-r--r--docker/OWNERS1
-rw-r--r--docker/README.md26
-rwxr-xr-xdocker/build-vespa.sh18
-rwxr-xr-xdocker/build/build-vespa-internal.sh45
-rw-r--r--docproc/pom.xml12
-rw-r--r--docproc/src/main/java/com/yahoo/docproc/jdisc/observability/DocprocsStatusExtension.java51
-rw-r--r--docproc/src/main/java/com/yahoo/docproc/jdisc/observability/package-info.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/policy/package-info.java)2
-rw-r--r--docprocs/src/test/java/com/yahoo/docprocs/indexing/IndexingProcessorTestCase.java1
-rw-r--r--document/abi-spec.json4
-rw-r--r--document/src/main/java/com/yahoo/document/DataType.java2
-rw-r--r--document/src/main/java/com/yahoo/document/DocumentTypeManager.java27
-rw-r--r--document/src/main/java/com/yahoo/document/DocumentTypeManagerConfigurer.java6
-rw-r--r--document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java2
-rw-r--r--document/src/main/java/com/yahoo/document/json/JsonReader.java4
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/AddRemoveCreator.java19
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/ArrayReader.java9
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/CompositeReader.java10
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/MapReader.java35
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/SingleValueReader.java8
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/StructReader.java20
-rw-r--r--document/src/main/java/com/yahoo/document/json/readers/VespaJsonDocumentReader.java28
-rw-r--r--document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java39
-rw-r--r--document/src/test/java/com/yahoo/document/json/JsonWriterTestCase.java2
-rw-r--r--document/src/vespa/document/config/documentmanager.def4
-rw-r--r--document/src/vespa/document/config/documenttypes.def4
-rw-r--r--document/src/vespa/document/datatype/documenttype.cpp1
-rw-r--r--document/src/vespa/document/datatype/structdatatype.cpp1
-rw-r--r--document/src/vespa/document/select/CMakeLists.txt3
-rw-r--r--documentapi-dependencies/pom.xml5
-rwxr-xr-xdocumentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java5
-rw-r--r--documentapi/src/tests/policies/policies_test.cpp6
-rw-r--r--documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.cpp34
-rw-r--r--documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.h45
-rw-r--r--documentapi/src/vespa/documentapi/messagebus/policies/loadbalancerpolicy.cpp2
-rw-r--r--eval/src/vespa/eval/eval/interpreted_function.h2
-rw-r--r--eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h2
-rw-r--r--eval/src/vespa/eval/eval/value_codec.h2
-rw-r--r--fat-model-dependencies/pom.xml5
-rw-r--r--fbench/src/fbench/fbench.cpp15
-rw-r--r--fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/FileAcquirerImpl.java4
-rw-r--r--fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java11
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/EmptyFileReferenceData.java2
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileDownloader.java23
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReceiver.java28
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceCompressor.java26
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceData.java7
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownload.java2
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownloader.java28
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyFileReferenceData.java4
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyTemporaryStorageFileReferenceData.java4
-rw-r--r--filedistribution/src/main/java/com/yahoo/vespa/filedistribution/RpcTester.java4
-rw-r--r--filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java38
-rw-r--r--filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReceiverTest.java23
-rw-r--r--filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReferenceDataTest.java9
-rw-r--r--flags/pom.xml33
-rw-r--r--flags/src/main/java/com/yahoo/vespa/flags/Flags.java165
-rw-r--r--flags/src/main/java/com/yahoo/vespa/flags/PermanentFlags.java2
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java32
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java8
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java8
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java10
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java13
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java14
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java10
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java12
-rw-r--r--fnet/src/tests/frt/rpc/invoke.cpp55
-rw-r--r--fnet/src/tests/info/info.cpp2
-rw-r--r--fnet/src/vespa/fnet/connection.cpp10
-rw-r--r--fnet/src/vespa/fnet/connection.h22
-rw-r--r--fnet/src/vespa/fnet/frt/CMakeLists.txt1
-rw-r--r--fnet/src/vespa/fnet/frt/error.cpp54
-rw-r--r--fnet/src/vespa/fnet/frt/error.h31
-rw-r--r--fnet/src/vespa/fnet/frt/invoker.cpp6
-rw-r--r--fnet/src/vespa/fnet/frt/reflection.cpp17
-rw-r--r--fnet/src/vespa/fnet/frt/reflection.h9
-rw-r--r--fnet/src/vespa/fnet/frt/request_access_filter.h24
-rw-r--r--fnet/src/vespa/fnet/frt/require_capabilities.cpp29
-rw-r--r--fnet/src/vespa/fnet/frt/require_capabilities.h21
-rw-r--r--hosted-api/pom.xml6
-rw-r--r--hosted-api/src/main/java/ai/vespa/hosted/api/ControllerHttpClient.java17
-rw-r--r--hosted-tenant-base/pom.xml15
-rw-r--r--hosted-zone-api/abi-spec.json19
-rw-r--r--hosted-zone-api/pom.xml19
-rw-r--r--hosted-zone-api/src/main/java/ai/vespa/cloud/Cloud.java11
-rw-r--r--hosted-zone-api/src/main/java/ai/vespa/cloud/SystemInfo.java13
-rw-r--r--hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java18
-rw-r--r--http-client/pom.xml6
-rw-r--r--http-utils/pom.xml13
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java10
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java16
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java20
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java14
-rw-r--r--jdisc-security-filters/pom.xml28
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java1
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java3
-rw-r--r--jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def2
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java38
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java16
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java18
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java18
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java8
-rw-r--r--jdisc_core/pom.xml44
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java1
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleCollisionHook.java3
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java90
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/handler/UnsafeContentInputStream.java7
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java77
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java40
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java46
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java78
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java26
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java18
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java112
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java4
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java4
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java23
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java19
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java40
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java114
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java78
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java18
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java120
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java47
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java54
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java26
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java36
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java48
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java54
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java57
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java2
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java20
-rw-r--r--jdisc_core/src/test/resources/exportPackages.properties3
-rw-r--r--jrt/src/com/yahoo/jrt/Connection.java20
-rw-r--r--jrt/src/com/yahoo/jrt/CryptoSocket.java12
-rw-r--r--jrt/src/com/yahoo/jrt/ErrorCode.java3
-rw-r--r--jrt/src/com/yahoo/jrt/InvocationServer.java6
-rw-r--r--jrt/src/com/yahoo/jrt/MaybeTlsCryptoSocket.java5
-rw-r--r--jrt/src/com/yahoo/jrt/Method.java6
-rw-r--r--jrt/src/com/yahoo/jrt/RequestAccessFilter.java17
-rw-r--r--jrt/src/com/yahoo/jrt/RequireCapabilitiesFilter.java34
-rw-r--r--jrt/src/com/yahoo/jrt/SecurityContext.java24
-rw-r--r--jrt/src/com/yahoo/jrt/Target.java27
-rw-r--r--jrt/src/com/yahoo/jrt/TlsCryptoSocket.java46
-rw-r--r--jrt/src/com/yahoo/jrt/slobrok/api/Mirror.java3
-rw-r--r--jrt/src/com/yahoo/jrt/slobrok/api/Register.java3
-rw-r--r--jrt/src/com/yahoo/jrt/slobrok/server/Slobrok.java3
-rw-r--r--jrt/src/com/yahoo/jrt/tool/RpcInvoker.java3
-rw-r--r--jrt/tests/com/yahoo/jrt/AbortTest.java6
-rw-r--r--jrt/tests/com/yahoo/jrt/BackTargetTest.java18
-rw-r--r--jrt/tests/com/yahoo/jrt/CryptoUtils.java11
-rw-r--r--jrt/tests/com/yahoo/jrt/DetachTest.java8
-rw-r--r--jrt/tests/com/yahoo/jrt/EchoTest.java27
-rw-r--r--jrt/tests/com/yahoo/jrt/InvokeAsyncTest.java26
-rw-r--r--jrt/tests/com/yahoo/jrt/InvokeErrorTest.java63
-rw-r--r--jrt/tests/com/yahoo/jrt/InvokeSyncTest.java22
-rw-r--r--jrt/tests/com/yahoo/jrt/InvokeVoidTest.java6
-rw-r--r--jrt/tests/com/yahoo/jrt/LatencyTest.java3
-rw-r--r--jrt/tests/com/yahoo/jrt/MandatoryMethodsTest.java7
-rw-r--r--jrt/tests/com/yahoo/jrt/SimpleRequestAccessFilter.java9
-rw-r--r--jrt/tests/com/yahoo/jrt/TimeoutTest.java8
-rw-r--r--logserver/pom.xml5
-rw-r--r--logserver/src/main/java/com/yahoo/logserver/testutils/VerifyLogfile.java66
-rw-r--r--logserver/src/test/java/ai/vespa/logserver/protocol/ArchiveLogMessagesMethodTest.java3
-rw-r--r--messagebus/pom.xml15
-rw-r--r--messagebus/src/main/java/com/yahoo/messagebus/MessageBus.java12
-rw-r--r--messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCNetwork.java3
-rwxr-xr-xmessagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCTarget.java7
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java42
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java16
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java44
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java11
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java34
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java14
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java14
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java22
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java81
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java22
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java47
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java24
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java89
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java31
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java10
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java11
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java34
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java28
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java24
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java29
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java19
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java23
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java68
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java47
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java43
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java82
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java66
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java50
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java284
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java482
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java10
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java16
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java8
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java24
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java6
-rw-r--r--messagebus/src/tests/messenger/messenger.cpp2
-rw-r--r--messagebus/src/vespa/messagebus/messagebus.cpp6
-rw-r--r--messagebus/src/vespa/messagebus/messagebus.h2
-rw-r--r--messagebus/src/vespa/messagebus/messenger.cpp18
-rw-r--r--messagebus/src/vespa/messagebus/messenger.h6
-rw-r--r--messagebus/src/vespa/messagebus/network/rpcnetwork.cpp12
-rw-r--r--messagebus/src/vespa/messagebus/network/rpcnetwork.h7
-rw-r--r--messagebus/src/vespa/messagebus/network/rpcnetworkparams.cpp6
-rw-r--r--messagebus/src/vespa/messagebus/network/rpcnetworkparams.h74
-rw-r--r--messagebus/src/vespa/messagebus/network/rpcsend.cpp19
-rw-r--r--messagebus/src/vespa/messagebus/rpcmessagebus.cpp2
-rw-r--r--messagebus/src/vespa/messagebus/testlib/testserver.cpp2
-rw-r--r--metrics-proxy/pom.xml6
-rw-r--r--metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/MetricsFormatter.java4
-rw-r--r--metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/ConfigSentinelClient.java4
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/http/application/ApplicationMetricsHandlerTest.java2
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/IntegrationTester.java4
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcHealthMetricsTest.java11
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcMetricsTest.java11
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelClientTest.java22
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelDummy.java6
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockConfigSentinelClient.java4
-rw-r--r--metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/VespaServiceTest.java16
-rw-r--r--metrics-proxy/src/test/resources/generic-sample.json2
-rw-r--r--metrics-proxy/src/test/resources/rpc-json-output-check.json2
-rw-r--r--metrics/src/vespa/metrics/metric.cpp2
-rw-r--r--metrics/src/vespa/metrics/metric.h4
-rw-r--r--model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelTester.java4
-rw-r--r--model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelsEvaluatorTest.java3
-rw-r--r--model-evaluation/src/test/java/ai/vespa/models/evaluation/OnnxEvaluatorTest.java1
-rw-r--r--model-evaluation/src/test/java/ai/vespa/models/handler/ModelsEvaluationHandlerTest.java1
-rw-r--r--model-evaluation/src/test/java/ai/vespa/models/handler/OnnxEvaluationHandlerTest.java1
-rw-r--r--node-admin/pom.xml24
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/ConnectionException.java2
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/HttpException.java9
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeRepositoryException.java6
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorException.java7
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImpl.java6
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorNotFoundException.java2
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java6
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java8
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java2
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java21
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ConvergenceException.java29
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImpl.java55
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdater.java4
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfo.java12
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfoReader.java42
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgent.java8
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java10
-rw-r--r--node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddresses.java13
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java49
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java37
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java16
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java167
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java35
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java16
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java82
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerTester.java7
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java18
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java182
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java44
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java92
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java30
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java43
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java31
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java3
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java16
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java18
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java38
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java76
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java9
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java14
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java15
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java9
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java10
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java13
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java10
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java52
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java37
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java26
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java57
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java17
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java60
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java43
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java114
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java10
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodeRepoStats.java17
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocatableClusterResources.java32
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocationOptimizer.java58
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Autoscaler.java8
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModel.java100
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterNodesTimeseries.java38
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Load.java78
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/NodeTimeseries.java5
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ResourceTarget.java52
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java72
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java5
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailer.java111
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java4
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/History.java7
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Nodes.java4
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/filter/NodeListFilter.java1
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/DelegatingOsUpgrader.java3
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsUpgrader.java8
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsVersions.java16
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RebuildingOsUpgrader.java5
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RetiringOsUpgrader.java13
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/ArchiveUris.java7
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeRepositoryProvisioner.java6
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/ApplicationSerializer.java2
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java3
-rw-r--r--node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiHandler.java3
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/NodeRepoStatsTest.java23
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingIntegrationTest.java51
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTest.java1052
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTester.java234
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModelTest.java70
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Fixture.java181
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Loader.java160
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/AutoscalingMaintainerTest.java3
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainerTest.java33
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java6
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailerTest.java22
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/os/OsVersionsTest.java2
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/ProvisioningTest.java4
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningCompleteHostCalculatorTest.java11
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningTest.java6
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiTest.java3
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application1.json2
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application2.json6
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-os-upgrade-complete.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-2.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-3.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-4.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node2.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node3.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node4.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node5.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost1-with-firmware-data.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost6.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/node9.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/parent2.json1
-rw-r--r--node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/stats.json4
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorContext.java2
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorImpl.java8
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClient.java7
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImpl.java21
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ContentService.java14
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNode.java3
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNodeImpl.java31
-rw-r--r--orchestrator/src/main/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicy.java27
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java22
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorTest.java3
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientFactoryMock.java15
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImplTest.java12
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ModelTestUtils.java6
-rw-r--r--orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java24
-rw-r--r--parent/pom.xml50
-rw-r--r--persistence/src/vespa/persistence/conformancetest/conformancetest.cpp4
-rw-r--r--persistence/src/vespa/persistence/dummyimpl/dummypersistence.cpp8
-rw-r--r--persistence/src/vespa/persistence/dummyimpl/dummypersistence.h2
-rw-r--r--persistence/src/vespa/persistence/spi/CMakeLists.txt1
-rw-r--r--persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp4
-rw-r--r--persistence/src/vespa/persistence/spi/id_and_timestamp.cpp17
-rw-r--r--persistence/src/vespa/persistence/spi/id_and_timestamp.h38
-rw-r--r--persistence/src/vespa/persistence/spi/persistenceprovider.cpp4
-rw-r--r--persistence/src/vespa/persistence/spi/persistenceprovider.h3
-rw-r--r--pom.xml1
-rw-r--r--predicate-search-core/pom.xml21
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java28
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java23
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java78
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java73
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java33
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java8
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java6
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java54
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java62
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java6
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java24
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java33
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java25
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java22
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java102
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java18
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java36
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java22
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java16
-rw-r--r--predicate-search/pom.xml15
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java21
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java18
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java30
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java22
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java14
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java19
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java32
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java93
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java38
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java12
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java8
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java28
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java22
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java18
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java2
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java12
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java25
-rwxr-xr-xscrewdriver/build-vespa.sh17
-rwxr-xr-xscrewdriver/delete-old-artifactory-artifacts.sh9
-rwxr-xr-xscrewdriver/release-rpms.sh4
-rwxr-xr-xscrewdriver/update-vespa-version-in-sample-apps.sh4
-rw-r--r--searchcore/src/apps/vespa-feed-bm/vespa_feed_bm.cpp9
-rw-r--r--searchcore/src/apps/vespa-redistribute-bm/vespa_redistribute_bm.cpp8
-rw-r--r--searchcore/src/tests/proton/docsummary/CMakeLists.txt8
-rw-r--r--searchcore/src/tests/proton/docsummary/docsummary.cpp60
-rwxr-xr-xsearchcore/src/tests/proton/docsummary/docsummary_test.sh1
-rw-r--r--searchcore/src/tests/proton/docsummary/summary.cfg4
-rw-r--r--searchcore/src/tests/proton/matching/request_context/request_context_test.cpp23
-rw-r--r--searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.cpp1
-rw-r--r--searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.h3
-rw-r--r--searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp13
-rw-r--r--searchcore/src/vespa/searchcore/bmcluster/bm_node.cpp1
-rw-r--r--searchcore/src/vespa/searchcore/bmcluster/spi_bm_feed_handler.cpp4
-rw-r--r--searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.cpp10
-rw-r--r--searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.h5
-rw-r--r--searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp7
-rw-r--r--searchcore/src/vespa/searchcore/proton/docsummary/summarymanager.cpp19
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/extract_features.cpp5
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/match_tools.cpp2
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/match_tools.h2
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/querynodes.h113
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/requestcontext.cpp32
-rw-r--r--searchcore/src/vespa/searchcore/proton/matching/requestcontext.h16
-rw-r--r--searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp16
-rw-r--r--searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.h4
-rw-r--r--searchcore/src/vespa/searchcore/proton/server/buckethandler.cpp3
-rw-r--r--searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp2
-rw-r--r--searchcore/src/vespa/searchcorespi/index/warmupindexcollection.h2
-rw-r--r--searchlib/CMakeLists.txt1
-rw-r--r--searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/transform/Simplifier.java4
-rw-r--r--searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/HyperLogLogPrecisionBenchmark.java1
-rw-r--r--searchlib/src/tests/attribute/tensorattribute/tensorattribute_test.cpp25
-rw-r--r--searchlib/src/tests/docstore/logdatastore/logdatastore_test.cpp4
-rw-r--r--searchlib/src/tests/features/nns_closeness/CMakeLists.txt1
-rw-r--r--searchlib/src/tests/features/nns_closeness/nns_closeness_test.cpp131
-rw-r--r--searchlib/src/tests/features/nns_distance/CMakeLists.txt1
-rw-r--r--searchlib/src/tests/features/nns_distance/nns_distance_test.cpp140
-rw-r--r--searchlib/src/tests/queryeval/nearest_neighbor/nearest_neighbor_test.cpp18
-rw-r--r--searchlib/src/vespa/searchlib/attribute/attribute_blueprint_factory.cpp53
-rw-r--r--searchlib/src/vespa/searchlib/common/bitvector.h1
-rw-r--r--searchlib/src/vespa/searchlib/diskindex/diskindex.cpp2
-rw-r--r--searchlib/src/vespa/searchlib/diskindex/diskindex.h2
-rw-r--r--searchlib/src/vespa/searchlib/features/CMakeLists.txt3
-rw-r--r--searchlib/src/vespa/searchlib/features/closenessfeature.cpp51
-rw-r--r--searchlib/src/vespa/searchlib/features/closenessfeature.h1
-rw-r--r--searchlib/src/vespa/searchlib/features/distance_calculator_bundle.cpp172
-rw-r--r--searchlib/src/vespa/searchlib/features/distance_calculator_bundle.h59
-rw-r--r--searchlib/src/vespa/searchlib/features/distancefeature.cpp50
-rw-r--r--searchlib/src/vespa/searchlib/features/distancefeature.h1
-rw-r--r--searchlib/src/vespa/searchlib/features/queryfeature.cpp201
-rw-r--r--searchlib/src/vespa/searchlib/features/queryfeature.h10
-rw-r--r--searchlib/src/vespa/searchlib/features/termeditdistancefeature.cpp4
-rw-r--r--searchlib/src/vespa/searchlib/features/termeditdistancefeature.h4
-rw-r--r--searchlib/src/vespa/searchlib/fef/CMakeLists.txt1
-rw-r--r--searchlib/src/vespa/searchlib/fef/itermdata.h7
-rw-r--r--searchlib/src/vespa/searchlib/fef/objectstore.cpp4
-rw-r--r--searchlib/src/vespa/searchlib/fef/query_value.cpp231
-rw-r--r--searchlib/src/vespa/searchlib/fef/query_value.h90
-rw-r--r--searchlib/src/vespa/searchlib/fef/simpletermdata.cpp10
-rw-r--r--searchlib/src/vespa/searchlib/fef/simpletermdata.h35
-rw-r--r--searchlib/src/vespa/searchlib/fef/test/labels.h2
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/fake_requestcontext.h10
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/irequestcontext.h2
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp72
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.h11
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.cpp21
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.h27
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.cpp8
-rw-r--r--searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.h2
-rw-r--r--searchlib/src/vespa/searchlib/tensor/CMakeLists.txt1
-rw-r--r--searchlib/src/vespa/searchlib/tensor/distance_calculator.cpp137
-rw-r--r--searchlib/src/vespa/searchlib/tensor/distance_calculator.h64
-rw-r--r--searchlib/src/vespa/searchlib/tensor/distance_function.h2
-rw-r--r--searchlib/src/vespa/searchlib/test/CMakeLists.txt1
-rw-r--r--searchlib/src/vespa/searchlib/test/features/CMakeLists.txt7
-rw-r--r--searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.cpp112
-rw-r--r--searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.h84
-rw-r--r--searchsummary/CMakeLists.txt2
-rw-r--r--searchsummary/src/tests/docsumformat/docsum-pack.cpp10
-rw-r--r--searchsummary/src/tests/docsummary/attribute_combiner/attribute_combiner_test.cpp6
-rw-r--r--searchsummary/src/tests/docsummary/attributedfw/attributedfw_test.cpp4
-rw-r--r--searchsummary/src/tests/docsummary/document_id_dfw/CMakeLists.txt10
-rw-r--r--searchsummary/src/tests/docsummary/document_id_dfw/document_id_dfw_test.cpp153
-rw-r--r--searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp7
-rw-r--r--searchsummary/src/tests/docsummary/positionsdfw_test.cpp2
-rw-r--r--searchsummary/src/tests/docsummary/summary_field_converter/CMakeLists.txt8
-rw-r--r--searchsummary/src/tests/docsummary/summary_field_converter/summary_field_converter_test.cpp (renamed from searchcore/src/tests/proton/docsummary/summaryfieldconverter_test.cpp)0
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/CMakeLists.txt12
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.cpp1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.h1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp6
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.h9
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/attributedfw.cpp25
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/attributedfw.h30
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.cpp131
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.h41
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.cpp (renamed from searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.cpp)85
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.h31
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsum_blob_entry_filter.h29
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.cpp27
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.h41
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.cpp53
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.h25
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.cpp24
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.h4
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.h85
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.cpp6
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.h15
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.cpp42
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.h14
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.cpp31
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.h22
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp32
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.cpp19
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.h22
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/general_result.cpp66
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/general_result.h29
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/geoposdfw.cpp1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/i_docsum_store_document.h28
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h68
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/juniper_input.cpp30
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/juniper_input.h26
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/juniperdfw.h15
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.cpp11
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.h18
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.cpp5
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.h2
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.h6
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/res_type.h30
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.cpp29
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.h102
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultclass.cpp6
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultclass.h43
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultconfig.cpp33
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultconfig.h95
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultpacker.cpp11
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/resultpacker.h20
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.cpp13
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.h20
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/struct_map_attribute_combiner_dfw.cpp1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp1
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.h4
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.cpp13
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.h4
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp51
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.h29
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/tokenizer.cpp108
-rw-r--r--searchsummary/src/vespa/searchsummary/docsummary/tokenizer.h43
-rw-r--r--security-tools/pom.xml13
-rw-r--r--security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java24
-rw-r--r--security-utils/pom.xml25
-rw-r--r--security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/AutoReloadingX509KeyManager.java)8
-rw-r--r--security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/KeyManagerUtils.java)5
-rw-r--r--security-utils/src/main/java/com/yahoo/security/MutableX509KeyManager.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/MutableX509KeyManager.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/MutableX509TrustManager.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/MutableX509TrustManager.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/Pkcs10CsrBuilder.java4
-rw-r--r--security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java6
-rw-r--r--security-utils/src/main/java/com/yahoo/security/SubjectAlternativeName.java18
-rw-r--r--security-utils/src/main/java/com/yahoo/security/TrustAllX509TrustManager.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/TrustAllX509TrustManager.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/TrustManagerUtils.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/X509CertificateBuilder.java4
-rw-r--r--security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java8
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/AuthorizedPeers.java32
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/Capability.java32
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/CapabilityMode.java26
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/CapabilitySet.java106
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/ConfigFileBasedTlsContext.java10
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/ConnectionAuthContext.java122
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java13
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/GlobPattern.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/policy/GlobPattern.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/HostGlobPattern.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/policy/HostGlobPattern.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/MissingCapabilitiesException.java13
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizationFailedException.java23
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizer.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizer.java)40
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizerTrustManager.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizerTrustManager.java)82
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/PeerPolicy.java24
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/RequiredPeerCredential.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/policy/RequiredPeerCredential.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptions.java9
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsEntity.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsEntity.java)4
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializer.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializer.java)81
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityUtils.java28
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/UriGlobPattern.java (renamed from security-utils/src/main/java/com/yahoo/security/tls/policy/UriGlobPattern.java)2
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/authz/AuthorizationResult.java55
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/authz/package-info.java8
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/json/package-info.java8
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/policy/AuthorizedPeers.java53
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/policy/PeerPolicy.java71
-rw-r--r--security-utils/src/main/java/com/yahoo/security/tls/policy/Role.java40
-rw-r--r--security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/AutoReloadingX509KeyManagerTest.java)20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java24
-rw-r--r--security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/MutableX509KeyManagerTest.java)7
-rw-r--r--security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/MutableX509TrustManagerTest.java)12
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java6
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java18
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java8
-rw-r--r--security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java26
-rw-r--r--security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java39
-rw-r--r--security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java27
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/CapabilitySetTest.java27
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java21
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/ConnectionAuthContextTest.java62
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java9
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/GlobPatternTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/policy/GlobPatternTest.java)2
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/policy/HostGlobPatternTest.java)22
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/authz/PeerAuthorizerTest.java)105
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializerTest.java)51
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java8
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/UriGlobPatternTest.java (renamed from security-utils/src/test/java/com/yahoo/security/tls/policy/UriGlobPatternTest.java)2
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/policy/AuthorizedPeersTest.java27
-rw-r--r--security-utils/src/test/resources/transport-security-options-with-authz-rules.json5
-rw-r--r--standalone-container/pom.xml12
-rw-r--r--storage/src/tests/persistence/common/persistenceproviderwrapper.cpp6
-rw-r--r--storage/src/tests/persistence/common/persistenceproviderwrapper.h2
-rw-r--r--storage/src/tests/storageapi/mbusprot/storageprotocoltest.cpp50
-rw-r--r--storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp36
-rw-r--r--storage/src/vespa/storage/config/stor-communicationmanager.def22
-rw-r--r--storage/src/vespa/storage/distributor/externaloperationhandler.cpp4
-rw-r--r--storage/src/vespa/storage/persistence/asynchandler.cpp4
-rw-r--r--storage/src/vespa/storage/persistence/mergehandler.cpp6
-rw-r--r--storage/src/vespa/storage/persistence/provider_error_wrapper.cpp2
-rw-r--r--storage/src/vespa/storage/persistence/provider_error_wrapper.h2
-rw-r--r--storage/src/vespa/storage/storageserver/communicationmanager.cpp141
-rw-r--r--storage/src/vespa/storage/storageserver/communicationmanager.h4
-rw-r--r--storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.cpp27
-rw-r--r--storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.h4
-rw-r--r--storage/src/vespa/storageapi/mbusprot/CMakeLists.txt5
-rw-r--r--storage/src/vespa/storageapi/mbusprot/legacyprotocolserialization.h31
-rw-r--r--storage/src/vespa/storageapi/mbusprot/oldreturncodemapper.h68
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization.cpp6
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.cpp553
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.h72
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.cpp622
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.h73
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.cpp198
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.h34
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.cpp64
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.h32
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.cpp40
-rw-r--r--storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.h24
-rw-r--r--storage/src/vespa/storageapi/mbusprot/storageprotocol.cpp101
-rw-r--r--storage/src/vespa/storageapi/mbusprot/storageprotocol.h6
-rw-r--r--streamingvisitors/src/vespa/searchvisitor/hitcollector.cpp5
-rw-r--r--streamingvisitors/src/vespa/vsm/vsm/docsumconfig.cpp23
-rw-r--r--streamingvisitors/src/vespa/vsm/vsm/docsumconfig.h2
-rw-r--r--streamingvisitors/src/vespa/vsm/vsm/docsumfilter.cpp97
-rw-r--r--streamingvisitors/src/vespa/vsm/vsm/vsm-adapter.cpp16
-rw-r--r--tenant-base/pom.xml7
-rw-r--r--tenant-cd-api/abi-spec.json64
-rw-r--r--tenant-cd-api/pom.xml15
-rw-r--r--tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInInstances.java43
-rw-r--r--tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInRegions.java44
-rw-r--r--tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInInstances.java43
-rw-r--r--tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInRegions.java43
-rw-r--r--testutil/src/main/java/com/yahoo/test/JunitCompat.java65
-rw-r--r--testutil/src/main/java/com/yahoo/test/PartialOrderTester.java9
-rw-r--r--testutil/src/main/java/com/yahoo/test/TotalOrderTester.java9
-rw-r--r--testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java6
-rw-r--r--vdslib/src/test/java/com/yahoo/vdslib/distribution/DistributionTestFactory.java1
-rw-r--r--vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java15
-rw-r--r--vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/Version.java1
-rw-r--r--vespa-athenz/pom.xml39
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzIdentity.java5
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java18
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/ZmsClient.java4
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/MembershipEntity.java20
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/DefaultZtsClient.java16
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/ZtsClient.java13
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/utils/RoleCsrGenerator.java4
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java2
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImpl.java2
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/CsrGenerator.java16
-rw-r--r--vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java14
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java17
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java12
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java14
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java27
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java36
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java8
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java18
-rw-r--r--vespa-feed-client-api/abi-spec.json1
-rw-r--r--vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java4
-rw-r--r--vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java33
-rw-r--r--vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliClient.java81
-rw-r--r--vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliArgumentsTest.java26
-rw-r--r--vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliClientTest.java31
-rw-r--r--vespa-feed-client-cli/src/test/resources/help.txt16
-rw-r--r--vespa-feed-client/pom.xml31
-rw-r--r--vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/ApacheCluster.java8
-rw-r--r--vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/BenchmarkingCluster.java12
-rw-r--r--vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java7
-rw-r--r--vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/HttpFeedClient.java7
-rw-r--r--vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/TlsDetailsFactory.java16
-rw-r--r--vespa-feed-client/src/main/java9/ai/vespa/feed/client/impl/TlsDetailsFactory.java20
-rw-r--r--vespa-hadoop/pom.xml13
-rw-r--r--vespa-maven-plugin/pom.xml6
-rw-r--r--vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/CompileVersionMojo.java3
-rw-r--r--vespa-osgi-testrunner/pom.xml45
-rw-r--r--vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java29
-rw-r--r--vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReport.java34
-rw-r--r--vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReportGeneratingListener.java2
-rw-r--r--vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestRunnerHandler.java187
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledClassTest.java2
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledTest.java2
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SampleTest.java2
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SucceedingTest.java2
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/UsingTestRuntimeTest.java2
-rw-r--r--vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/testrunner/TestRunnerHandlerTest.java9
-rw-r--r--vespa-osgi-testrunner/src/test/resources/output.json78
-rw-r--r--vespa-osgi-testrunner/src/test/resources/report.json222
-rw-r--r--vespabase/desc.services14
-rw-r--r--vespabase/desc.vespa_base36
-rw-r--r--vespabase/desc.vespa_base_dev35
-rw-r--r--vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/resource/DocumentV1ApiHandler.java36
-rw-r--r--vespaclient-container-plugin/src/test/java/com/yahoo/document/restapi/resource/DocumentV1ApiTest.java95
-rw-r--r--vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerTest.java2
-rw-r--r--vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerV3Test.java2
-rw-r--r--vespaclient-core/src/main/java/com/yahoo/vespaclient/ClusterList.java1
-rw-r--r--vespaclient-java/pom.xml16
-rw-r--r--vespaclient-java/src/main/java/com/yahoo/vespasummarybenchmark/VespaSummaryBenchmark.java3
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java8
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java18
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java62
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java75
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java82
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java20
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java39
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java36
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java27
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java13
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java71
-rw-r--r--vespajlib/abi-spec.json332
-rw-r--r--vespajlib/pom.xml6
-rw-r--r--vespajlib/src/main/java/ai/vespa/validation/PathValidator.java36
-rw-r--r--vespajlib/src/main/java/com/yahoo/concurrent/Threads.java30
-rw-r--r--vespajlib/src/main/java/com/yahoo/text/XML.java60
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/Exceptions.java (renamed from yolean/src/main/java/com/yahoo/yolean/Exceptions.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java (renamed from yolean/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/chain/After.java (renamed from yolean/src/main/java/com/yahoo/yolean/chain/After.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/chain/Before.java (renamed from yolean/src/main/java/com/yahoo/yolean/chain/Before.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/chain/Provides.java (renamed from yolean/src/main/java/com/yahoo/yolean/chain/Provides.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/chain/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/chain/package-info.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/Memoized.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/Memoized.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/concurrent/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/concurrent/package-info.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java (renamed from yolean/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java (renamed from yolean/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java (renamed from yolean/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/function/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/function/package-info.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/package-info.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/system/CatchSignals.java (renamed from yolean/src/main/java/com/yahoo/yolean/system/CatchSignals.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/system/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/system/package-info.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java (renamed from yolean/src/main/java/com/yahoo/yolean/trace/TraceNode.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java (renamed from yolean/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java)0
-rw-r--r--vespajlib/src/main/java/com/yahoo/yolean/trace/package-info.java (renamed from yolean/src/main/java/com/yahoo/yolean/trace/package-info.java)0
-rw-r--r--vespajlib/src/test/java/ai/vespa/validation/PathValidatorTest.java35
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java (renamed from yolean/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java (renamed from yolean/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java (renamed from yolean/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java (renamed from yolean/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java (renamed from yolean/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java (renamed from yolean/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java)0
-rw-r--r--vespajlib/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java (renamed from yolean/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java)0
-rw-r--r--vespalib/CMakeLists.txt1
-rw-r--r--vespalib/src/apps/vespa-tsan-digest/tsan_digest.cpp4
-rw-r--r--vespalib/src/tests/datastore/buffer_type/buffer_type_test.cpp4
-rw-r--r--vespalib/src/tests/net/tls/capabilities/CMakeLists.txt10
-rw-r--r--vespalib/src/tests/net/tls/capabilities/capabilities_test.cpp196
-rw-r--r--vespalib/src/tests/net/tls/openssl_impl/openssl_impl_test.cpp27
-rw-r--r--vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp111
-rw-r--r--vespalib/src/tests/net/tls/transport_options/transport_options_reading_test.cpp62
-rw-r--r--vespalib/src/tests/util/generationhandler_stress/generation_handler_stress_test.cpp4
-rw-r--r--vespalib/src/vespa/vespalib/net/CMakeLists.txt1
-rw-r--r--vespalib/src/vespa/vespalib/net/connection_auth_context.cpp21
-rw-r--r--vespalib/src/vespa/vespalib/net/connection_auth_context.h29
-rw-r--r--vespalib/src/vespa/vespalib/net/crypto_socket.cpp9
-rw-r--r--vespalib/src/vespa/vespalib/net/crypto_socket.h14
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/CMakeLists.txt3
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/assumed_roles.cpp95
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/assumed_roles.h80
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/capability.cpp62
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/capability.h104
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/capability_set.cpp95
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/capability_set.h117
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/certificate_verification_callback.h2
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/crypto_codec.h6
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.cpp7
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.h1
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h12
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/impl/openssl_tls_context_impl.cpp2
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/peer_policies.cpp11
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/peer_policies.h14
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp10
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/tls_crypto_socket.h2
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/transport_security_options_reading.cpp34
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/verification_result.cpp14
-rw-r--r--vespalib/src/vespa/vespalib/net/tls/verification_result.h25
-rw-r--r--vespalib/src/vespa/vespalib/process/process.cpp1
-rw-r--r--vespalib/src/vespa/vespalib/stllike/hash_fun.h4
-rw-r--r--vespalib/src/vespa/vespalib/test/peer_policy_utils.cpp26
-rw-r--r--vespalib/src/vespa/vespalib/test/peer_policy_utils.h9
-rw-r--r--vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.cpp2
-rw-r--r--vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.h2
-rw-r--r--vespalib/src/vespa/vespalib/util/signalhandler.cpp3
-rw-r--r--vespalog/src/logctl/logctl.cpp4
-rw-r--r--vespamalloc/CMakeLists.txt1
-rwxr-xr-xvespamalloc/bin/parsememorydump.pl314
-rw-r--r--yolean/.gitignore2
-rw-r--r--yolean/OWNERS1
-rwxr-xr-xyolean/README.sh13
-rw-r--r--yolean/abi-spec.json332
-rw-r--r--yolean/pom.xml51
-rw-r--r--zkfacade/pom.xml12
-rw-r--r--zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorCompletionWaiter.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/api/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/api/transaction/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/listen/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/recipes/atomic/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/recipes/barriers/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/recipes/cache/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/recipes/locks/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/framework/state/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/package-info.java2
-rw-r--r--zkfacade/src/main/java/org/apache/curator/retry/package-info.java2
-rw-r--r--zookeeper-client-common/pom.xml9
-rw-r--r--zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java10
-rw-r--r--zookeeper-server/CMakeLists.txt2
-rw-r--r--zookeeper-server/README4
-rw-r--r--zookeeper-server/pom.xml2
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/CMakeLists.txt (renamed from zookeeper-server/zookeeper-server-3.7.1/CMakeLists.txt)2
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/pom.xml (renamed from zookeeper-server/zookeeper-server-3.7.1/pom.xml)4
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/common/NetUtils.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/common/NetUtils.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java)0
-rw-r--r--zookeeper-server/zookeeper-server-3.8.0/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java (renamed from zookeeper-server/zookeeper-server-3.7.1/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java)0
-rw-r--r--zookeeper-server/zookeeper-server-common/src/test/java/com/yahoo/vespa/zookeeper/ConfiguratorTest.java2
-rw-r--r--zookeeper-server/zookeeper-server/CMakeLists.txt4
-rw-r--r--zookeeper-server/zookeeper-server/pom.xml4
2464 files changed, 50387 insertions, 40426 deletions
diff --git a/.copr/Makefile b/.copr/Makefile
index bb37e1c4401..c1d72525053 100644
--- a/.copr/Makefile
+++ b/.copr/Makefile
@@ -17,7 +17,11 @@ srpm: deps
rpmbuild -bs --define "_topdir $(RPMTOPDIR)" $(SPECDIR)/vespa-$(VESPA_VERSION).spec
cp -a $(RPMTOPDIR)/SRPMS/* $(outdir)
+rpms: srpm
+ rpmbuild --rebuild $(outdir)/*.src.rpm
+ cp -a $(RPMTOPDIR)/RPMS/*/*.rpm $(outdir)
+
clean:
-rm -rf $(RPMTOPDIR)
-.PHONY: clean deps srpm
+.PHONY: clean deps srpm rpms
diff --git a/Code-map.md b/Code-map.md
index dfd11fffdab..17c27327c5a 100644
--- a/Code-map.md
+++ b/Code-map.md
@@ -94,7 +94,6 @@ Libraries used throughput the code.
- [vespalib](https://github.com/vespa-engine/vespa/tree/master/vespalib) - general utility library for C++
- [vespajlib](https://github.com/vespa-engine/vespa/tree/master/vespajlib) - general utility library for Java. Includes the Java implementation of the tensor library.
-- [yolean](https://github.com/vespa-engine/vespa/tree/master/yolean) - another (more stable) general Java utility library
diff --git a/README.md b/README.md
index 64bd0897d74..df9e1109a2b 100644
--- a/README.md
+++ b/README.md
@@ -2,14 +2,14 @@
[![#Vespa](https://vespa.ai/assets/vespa-logo-color.png)](https://vespa.ai)
-The open big data serving engine - Store, search, organize and make machine-learned inferences
+The open big data serving engine - Store, search, organize and make machine-learned inferences
over big data at serving time.
-This is the primary repository for Vespa where all development is happening.
+This is the primary repository for Vespa where all development is happening.
New production releases from this repository's master branch are made each weekday from Monday through Thursday.
-* Home page: [https://vespa.ai](https://vespa.ai)
-* Documentation: [https://docs.vespa.ai](https://docs.vespa.ai)
+* Home page: [https://vespa.ai](https://vespa.ai)
+* Documentation: [https://docs.vespa.ai](https://docs.vespa.ai)
* Continuous build: [https://factory.vespa.oath.cloud](https://factory.vespa.oath.cloud)
* Run applications in the cloud for free: [https://cloud.vespa.ai](https://cloud.vespa.ai)
@@ -23,26 +23,26 @@ Vespa build status: [![Vespa Build Status](https://cd.screwdriver.cd/pipelines/6
- [Contribute](#contribute)
- [Building](#building)
- [License](#license)
-
+
## Background
Use cases such as search, recommendation and personalization need to select a subset of data in a large corpus,
evaluate machine-learned models over the selected data, organize and aggregate it and return it, typically in less
-than 100 milliseconds, all while the data corpus is continuously changing.
+than 100 milliseconds, all while the data corpus is continuously changing.
-This is hard to do, especially with large data sets that needs to be distributed over multiple nodes and evaluated in
-parallel. Vespa is a platform which performs these operations for you with high availability and performance.
-It has been in development for many years and is used on a number of large internet services and apps which serve
+This is hard to do, especially with large data sets that needs to be distributed over multiple nodes and evaluated in
+parallel. Vespa is a platform which performs these operations for you with high availability and performance.
+It has been in development for many years and is used on a number of large internet services and apps which serve
hundreds of thousands of queries from Vespa per second.
## Install
-Run your own Vespa instance: [https://docs.vespa.ai/en/getting-started.html](https://docs.vespa.ai/en/getting-started.html)
+Run your own Vespa instance: [https://docs.vespa.ai/en/getting-started.html](https://docs.vespa.ai/en/getting-started.html)
Or deploy your Vespa applications to the cloud service: [https://cloud.vespa.ai](https://cloud.vespa.ai)
-## Usage
+## Usage
- The application created in the getting started guide is fully functional and production ready, but you may want to [add more nodes](https://docs.vespa.ai/en/multinode-systems.html) for redundancy.
- See [developing applications](https://docs.vespa.ai/en/developer-guide.html) on adding your own Java components to your Vespa application.
@@ -69,11 +69,11 @@ Some suggested improvements with pointers to code are in [TODO.md](TODO.md).
### Development environment
-C++ and Java building is supported on CentOS 7.
-The Java source can also be built on any platform having Java 11 and Maven installed.
+C++ and Java building is supported on CentOS Stream 8.
+The Java source can also be built on any platform having Java 17 and Maven installed.
Use the following guide to set up a complete development environment using Docker
for building Vespa, running unit tests and running system tests:
-[Vespa development on CentOS 7](https://github.com/vespa-engine/docker-image-dev#vespa-development-on-centos-7).
+[Vespa development on CentOS Stream 8](https://github.com/vespa-engine/docker-image-dev#vespa-development-on-centos-stream-8).
### Build Java modules
@@ -83,10 +83,6 @@ for building Vespa, running unit tests and running system tests:
Use this if you only need to build the Java modules, otherwise follow the complete development guide above.
-### Build RPM packages
-
-See [Building Vespa RPM](docker/README.md#building-vespa-rpm) for details.
-
## License
diff --git a/abi-check-plugin/src/main/java/com/yahoo/abicheck/collector/Util.java b/abi-check-plugin/src/main/java/com/yahoo/abicheck/collector/Util.java
index 2c08936aff0..a5dde14532e 100644
--- a/abi-check-plugin/src/main/java/com/yahoo/abicheck/collector/Util.java
+++ b/abi-check-plugin/src/main/java/com/yahoo/abicheck/collector/Util.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.abicheck.collector;
+import org.objectweb.asm.Opcodes;
+
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import org.objectweb.asm.Opcodes;
public class Util {
- public static final List<AccessFlag> classFlags = Arrays.asList(
+ public static final List<AccessFlag> classFlags = List.of(
AccessFlag.make(Opcodes.ACC_PUBLIC, "public"),
AccessFlag.make(Opcodes.ACC_PRIVATE, "private"),
AccessFlag.make(Opcodes.ACC_PROTECTED, "protected"),
@@ -19,12 +19,13 @@ public class Util {
AccessFlag.make(Opcodes.ACC_SYNTHETIC, "synthetic"), // FIXME: Do we want this?
AccessFlag.make(Opcodes.ACC_ANNOTATION, "annotation"),
AccessFlag.make(Opcodes.ACC_ENUM, "enum"),
+ AccessFlag.make(Opcodes.ACC_RECORD, "record"),
// FIXME: Module support
// AccessFlag.make(Opcodes.ACC_MODULE, "module")
AccessFlag.ignored(Opcodes.ACC_DEPRECATED)
);
- public static final List<AccessFlag> methodFlags = Arrays.asList(
+ public static final List<AccessFlag> methodFlags = List.of(
AccessFlag.make(Opcodes.ACC_PUBLIC, "public"),
AccessFlag.make(Opcodes.ACC_PRIVATE, "private"),
AccessFlag.make(Opcodes.ACC_PROTECTED, "protected"),
@@ -40,7 +41,7 @@ public class Util {
AccessFlag.ignored(Opcodes.ACC_DEPRECATED)
);
- public static final List<AccessFlag> fieldFlags = Arrays.asList(
+ public static final List<AccessFlag> fieldFlags = List.of(
AccessFlag.make(Opcodes.ACC_PUBLIC, "public"),
AccessFlag.make(Opcodes.ACC_PRIVATE, "private"),
AccessFlag.make(Opcodes.ACC_PROTECTED, "protected"),
diff --git a/application-preprocessor/pom.xml b/application-preprocessor/pom.xml
index f8b521140f7..aae9f6bb13a 100644
--- a/application-preprocessor/pom.xml
+++ b/application-preprocessor/pom.xml
@@ -19,9 +19,9 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>config-model-api</artifactId>
- <version>${project.version}</version>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>config-model-api</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -33,10 +33,10 @@
<artifactId>config-model</artifactId>
<version>${project.version}</version>
<exclusions>
- <exclusion>
- <groupId>org.antlr</groupId>
- <artifactId>antlr4-runtime</artifactId>
- </exclusion>
+ <exclusion>
+ <groupId>org.antlr</groupId>
+ <artifactId>antlr4-runtime</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -50,18 +50,18 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
</dependencies>
<build>
diff --git a/application-preprocessor/src/main/java/com/yahoo/application/preprocessor/ApplicationPreprocessor.java b/application-preprocessor/src/main/java/com/yahoo/application/preprocessor/ApplicationPreprocessor.java
index 785e6d9b61b..081e9ad6036 100644
--- a/application-preprocessor/src/main/java/com/yahoo/application/preprocessor/ApplicationPreprocessor.java
+++ b/application-preprocessor/src/main/java/com/yahoo/application/preprocessor/ApplicationPreprocessor.java
@@ -2,14 +2,12 @@
package com.yahoo.application.preprocessor;
import com.yahoo.config.application.api.ApplicationPackage;
-import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.application.provider.BaseDeployLogger;
import com.yahoo.config.model.application.provider.FilesApplicationPackage;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Zone;
import com.yahoo.yolean.Exceptions;
-
import java.io.File;
import java.io.IOException;
import java.util.Optional;
@@ -34,19 +32,18 @@ public class ApplicationPreprocessor {
}
public void run() throws IOException {
- DeployLogger logger = new BaseDeployLogger();
FilesApplicationPackage.Builder applicationPackageBuilder = new FilesApplicationPackage.Builder(applicationDir);
outputDir.ifPresent(applicationPackageBuilder::preprocessedDir);
ApplicationPackage preprocessed = applicationPackageBuilder.build().preprocess(
new Zone(environment.orElse(Environment.defaultEnvironment()), region.orElse(RegionName.defaultName())),
- logger);
+ new BaseDeployLogger());
preprocessed.validateXML();
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
int argCount = args.length;
if (argCount < 1) {
- System.out.println("Usage: application-preprocessor <application> [environment] [region] [outputDirectory]");
+ System.out.println("Usage: vespa-application-preprocessor <application package path> [environment] [region] [output path]");
System.exit(1);
}
File applicationDir = new File(args[0]);
@@ -56,8 +53,8 @@ public class ApplicationPreprocessor {
ApplicationPreprocessor preprocessor = new ApplicationPreprocessor(applicationDir, outputDir, environment, region);
try {
preprocessor.run();
- System.out.println("Application preprocessed successfully. Preprocessed application stored in " +
- new File(applicationDir, FilesApplicationPackage.preprocessed).getAbsolutePath());
+ System.out.println("Application preprocessed successfully and written to " +
+ outputDir.orElse(new File(applicationDir, FilesApplicationPackage.preprocessed)).getAbsolutePath());
} catch (Exception e) {
System.err.println("Error validating application package: " + Exceptions.toMessageString(e));
System.exit(1);
diff --git a/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java b/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
index 5039b05b393..0e5d8fb2784 100644
--- a/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
+++ b/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
@@ -1,9 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application.preprocessor;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
@@ -14,17 +13,26 @@ import java.util.Optional;
public class ApplicationPreprocessorTest {
- @Rule
- public TemporaryFolder outputDir = new TemporaryFolder();
+ @TempDir
+ public File outputDir;
// Basic test just to check that instantiation and run() works. Unit testing is in config-application-package
@Test
- public void basic() throws ParserConfigurationException, TransformerException, SAXException, IOException {
+ void basic() throws ParserConfigurationException, TransformerException, SAXException, IOException {
ApplicationPreprocessor preprocessor = new ApplicationPreprocessor(new File("src/test/resources/simple"),
- Optional.of(outputDir.newFolder()),
- Optional.empty(),
- Optional.empty());
+ Optional.of(newFolder(outputDir, "basic")),
+ Optional.empty(),
+ Optional.empty());
preprocessor.run();
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/application/abi-spec.json b/application/abi-spec.json
index 2053eabd9ad..75ae9842982 100644
--- a/application/abi-spec.json
+++ b/application/abi-spec.json
@@ -57,6 +57,7 @@
"public static com.yahoo.application.Application fromApplicationPackage(java.nio.file.Path, com.yahoo.application.Networking)",
"public static com.yahoo.application.Application fromApplicationPackage(java.io.File, com.yahoo.application.Networking)",
"public com.yahoo.application.container.JDisc getJDisc(java.lang.String)",
+ "public com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry getCompiledQueryProfileRegistry()",
"public void close()"
],
"fields": [
diff --git a/application/pom.xml b/application/pom.xml
index 51448502d1d..34bf1b56c0d 100644
--- a/application/pom.xml
+++ b/application/pom.xml
@@ -60,11 +60,6 @@
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
<!-- All dependencies that should be visible in test classpath, but not compile classpath,
for user projects must be added in compile scope here.
@@ -127,6 +122,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- START JETTY embedded jars -->
@@ -172,6 +181,16 @@
<artifactId>jetty-servlets</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<!-- END JETTY embedded jars -->
</dependencies>
diff --git a/application/src/main/java/com/yahoo/application/Application.java b/application/src/main/java/com/yahoo/application/Application.java
index 1b81897b230..5d8123de48f 100644
--- a/application/src/main/java/com/yahoo/application/Application.java
+++ b/application/src/main/java/com/yahoo/application/Application.java
@@ -26,6 +26,8 @@ import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.ClientProvider;
import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.search.Searcher;
+import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
+import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.search.rendering.Renderer;
import com.yahoo.text.StringUtilities;
import com.yahoo.text.Utf8;
@@ -71,6 +73,7 @@ public final class Application implements AutoCloseable {
private final List<ContentCluster> contentClusters;
private final Path path;
private final boolean deletePathWhenClosing;
+ private final CompiledQueryProfileRegistry compiledQueryProfileRegistry;
// For internal use only
Application(Path path, Networking networking, boolean deletePathWhenClosing) {
@@ -79,6 +82,7 @@ public final class Application implements AutoCloseable {
this.deletePathWhenClosing = deletePathWhenClosing;
contentClusters = ContentCluster.fromPath(path);
container = JDisc.fromPath(path, networking, createVespaModel().configModelRepo());
+ compiledQueryProfileRegistry = readQueryProfilesFromApplicationPackage(path);
}
@Beta
@@ -123,6 +127,17 @@ public final class Application implements AutoCloseable {
return fromApplicationPackage(file.toPath(), networking);
}
+ private CompiledQueryProfileRegistry readQueryProfilesFromApplicationPackage(Path path) {
+ String queryProfilePath = path + "/search/query-profiles";
+ QueryProfileXMLReader queryProfileXMLReader = new QueryProfileXMLReader();
+
+ File f = new File(queryProfilePath);
+ if(f.exists() && f.isDirectory()) {
+ return queryProfileXMLReader.read(queryProfilePath).compile();
+ }
+ return CompiledQueryProfileRegistry.empty;
+ }
+
private VespaModel createVespaModel() {
try {
List<MlModelImporter> modelImporters = List.of(new VespaImporter(),
@@ -149,6 +164,10 @@ public final class Application implements AutoCloseable {
return container;
}
+ public CompiledQueryProfileRegistry getCompiledQueryProfileRegistry() {
+ return compiledQueryProfileRegistry;
+ }
+
/**
* Shuts down all services.
*/
diff --git a/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd b/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd
new file mode 100644
index 00000000000..ca6fa37a8e6
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd
@@ -0,0 +1,17 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+search mydoc {
+
+ document mydoc {
+
+ field title type string {
+ indexing: index
+ }
+
+ field substring type string {
+ indexing: index
+ match: gram
+ }
+
+ }
+
+}
diff --git a/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml b/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml
new file mode 100644
index 00000000000..c9ed6ab3d12
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml
@@ -0,0 +1,3 @@
+<query-profile id="default">
+ <field name="hits">2</field>
+</query-profile>
diff --git a/application/src/test/app-packages/withqueryprofile/services.xml b/application/src/test/app-packages/withqueryprofile/services.xml
new file mode 100644
index 00000000000..028ca561160
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/services.xml
@@ -0,0 +1,29 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+<services>
+
+ <container version="1.0">
+ <!-- Avoid using DefaultLinguisticsProvider -->
+ <component id="com.yahoo.language.simple.SimpleLinguistics" />
+
+ <search>
+ <chain id="default" inherits="vespa"/>
+ <provider id="bar" type="local" cluster="foo">
+ <searcher id="MockResultSearcher" class="com.yahoo.application.MockResultSearcher"/>
+ </provider>
+ </search>
+
+ <accesslog type="disabled" />
+ </container>
+
+ <content version="1.0" id="foo">
+ <redundancy>2</redundancy>
+ <documents>
+ <document type="mydoc" mode="index"/>
+ </documents>
+ <nodes>
+ <node hostalias="node1" distribution-key="1"/>
+ </nodes>
+ </content>
+
+</services>
diff --git a/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java b/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
index 800c30ac8b8..503f11ca0d7 100644
--- a/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
+++ b/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
@@ -2,13 +2,12 @@
package com.yahoo.application;
import com.yahoo.io.IOUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -16,55 +15,53 @@ import static org.junit.Assert.assertTrue;
*/
public class ApplicationBuilderTest {
@Test
- public void query_profile_types_can_be_added() throws Exception {
+ void query_profile_types_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.queryProfileType("MyProfileType", "<query-profile-type id=\"MyProfileType\">" + //
- "<field name=\"age\" type=\"integer\" />" + //
- "<field name=\"profession\" type=\"string\" />" + //
- "<field name=\"user\" type=\"query-profile:MyUserProfile\" />" + //
- "</query-profile-type>");
+ "<field name=\"age\" type=\"integer\" />" + //
+ "<field name=\"profession\" type=\"string\" />" + //
+ "<field name=\"user\" type=\"query-profile:MyUserProfile\" />" + //
+ "</query-profile-type>");
assertTrue(Files.exists(builder.getPath().resolve("search/query-profiles/types/MyProfileType.xml")));
});
}
@Test
- public void query_profile_can_be_added() throws Exception {
+ void query_profile_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.queryProfile("MyProfile",
- "<query-profile id=\"MyProfile\">" +
- "<field name=\"message\">Hello world!</field>" +
- "</query-profile>");
+ "<query-profile id=\"MyProfile\">" +
+ "<field name=\"message\">Hello world!</field>" +
+ "</query-profile>");
assertTrue(Files.exists(builder.getPath().resolve("search/query-profiles/MyProfile.xml")));
});
}
@Test
- public void rank_expression_can_be_added() throws Exception {
+ void rank_expression_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.rankExpression("myExpression", "content");
assertTrue(Files.exists(builder.getPath().resolve("schemas/myExpression.expression")));
});
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
+ // application unreferenced inside try
@Test
- @SuppressWarnings("try") // application unreferenced inside try
- public void builder_cannot_be_reused() throws Exception {
- expectedException.expect(RuntimeException.class);
- expectedException.expectMessage("build method");
+ @SuppressWarnings("try")
+ void builder_cannot_be_reused() throws Exception {
+ Throwable exception = assertThrows(RuntimeException.class, () -> {
- ApplicationBuilder builder = new ApplicationBuilder();
- builder.servicesXml("<container version=\"1.0\" />");
- try (Application application = builder.build()) {
- // do nothing
- }
+ ApplicationBuilder builder = new ApplicationBuilder();
+ builder.servicesXml("<container version=\"1.0\" />");
+ try (Application application = builder.build()) {
+ // do nothing
+ }
- builder.servicesXml(""); // should fail
+ builder.servicesXml(""); // should fail
+ });
+ assertTrue(exception.getMessage().contains("build method")); // should fail
}
private interface TestCase {
diff --git a/application/src/test/java/com/yahoo/application/ApplicationTest.java b/application/src/test/java/com/yahoo/application/ApplicationTest.java
index 6ae49cc4802..5b4a68756f0 100644
--- a/application/src/test/java/com/yahoo/application/ApplicationTest.java
+++ b/application/src/test/java/com/yahoo/application/ApplicationTest.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application;
-import com.yahoo.application.container.MockClient;
import com.yahoo.application.container.MockServer;
-import com.yahoo.application.container.docprocs.MockDispatchDocproc;
import com.yahoo.application.container.docprocs.MockDocproc;
import com.yahoo.application.container.handler.Request;
import com.yahoo.application.container.handler.Response;
@@ -12,10 +10,8 @@ import com.yahoo.application.container.renderers.MockRenderer;
import com.yahoo.application.container.searchers.MockSearcher;
import com.yahoo.component.Component;
import com.yahoo.component.ComponentSpecification;
-import com.yahoo.docproc.DocumentProcessor;
+import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.docproc.Processing;
-import com.yahoo.document.Document;
-import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentRemove;
import com.yahoo.document.DocumentType;
import com.yahoo.jdisc.handler.RequestHandler;
@@ -25,7 +21,7 @@ import com.yahoo.search.handler.SearchHandler;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -37,10 +33,11 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -49,31 +46,44 @@ import static org.junit.Assert.fail;
public class ApplicationTest {
@Test
- public void minimal_application_can_be_constructed() {
+ void minimal_application_can_be_constructed() {
try (Application application = Application.fromServicesXml("<container version=\"1.0\"/>", Networking.disable)) {
- Application unused = application;
+ Application unused = application;
}
}
/** Tests that an application with search chains referencing a content cluster can be constructed. */
@Test
- public void container_and_referenced_content() {
+ void container_and_referenced_content() {
try (Application application =
- Application.fromApplicationPackage(new File("src/test/app-packages/withcontent"), Networking.disable)) {
+ Application.fromApplicationPackage(new File("src/test/app-packages/withcontent"), Networking.disable)) {
Result result = application.getJDisc("default").search().process(new ComponentSpecification("default"),
- new Query("?query=substring:foobar&timeout=20000"));
+ new Query("?query=substring:foobar&timeout=20000"));
assertEquals("WEAKAND(100) (AND substring:fo substring:oo substring:ob substring:ba substring:ar)",
- result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
+ result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
}
}
+ @Test
+ void application_with_query_profile_sets_up_query_profile_registry() {
+ try (Application application =
+ Application.fromApplicationPackage(new File("src/test/app-packages/withqueryprofile"), Networking.disable)) {
+ Query query = new Query(HttpRequest.createTestRequest("?query=substring:foobar&timeout=20000", com.yahoo.jdisc.http.HttpRequest.Method.GET), application.getCompiledQueryProfileRegistry().findQueryProfile("default"));
+ Result result = application.getJDisc("default").search().process(new ComponentSpecification("default"), query);
+
+ assertEquals("WEAKAND(100) (AND substring:fo substring:oo substring:ob substring:ba substring:ar)",
+ result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
+ assertEquals("2", application.getCompiledQueryProfileRegistry().findQueryProfile("default").get("hits"));
+ assertEquals("select * from sources * where weakAnd(substring contains \"foobar\") limit 2 timeout 20000000", result.getQuery().yqlRepresentation(true));
+ }
+ }
private void printTrace(Result result) {
for (String message : result.getQuery().getContext(true).getTrace().traceNode().descendants(String.class))
System.out.println(message);
}
@Test
- public void empty_container() throws Exception {
+ void empty_container() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container())))) {
try {
app.process(new DocumentRemove(null));
@@ -99,7 +109,7 @@ public class ApplicationTest {
}
@Test
- public void config() throws Exception {
+ void config() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.documentProcessor("docproc", "default", MockDocproc.class)
@@ -113,7 +123,7 @@ public class ApplicationTest {
.mymap("key2", "value2")
.mymapstruct("key1", new MockApplicationConfig.Mymapstruct.Builder().id("mapid1").value("mapvalue1"))
.mymapstruct("key2", new MockApplicationConfig.Mymapstruct.Builder().id("mapid2").value("mapvalue2")))))))
- ) {
+ ) {
MockDocproc docproc = (MockDocproc) app.getComponentById("docproc@default");
assertNotNull(docproc);
@@ -153,11 +163,11 @@ public class ApplicationTest {
}
@Test
- public void handler() throws Exception {
+ void handler() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.handler("http://*/", MockHttpHandler.class))))
- ) {
+ ) {
RequestHandler handler = app.getRequestHandlerById(MockHttpHandler.class.getName());
assertNotNull(handler);
@@ -182,13 +192,13 @@ public class ApplicationTest {
}
}
- @Test
// TODO: Creates access log
- public void renderer() throws Exception {
+ @Test
+ void renderer() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.renderer("mock", MockRenderer.class))))
- ) {
+ ) {
Request request = new Request("http://localhost:" + getDefaults().vespaWebServicePort() + "/search/?format=mock");
Response response = app.handleRequest(request);
@@ -199,36 +209,36 @@ public class ApplicationTest {
}
@Test
- public void search_default() throws Exception {
+ void search_default() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.searcher(MockSearcher.class))))
- ) {
+ ) {
Result result = app.search(new Query("?query=foo&timeout=20000"));
assertEquals(1, result.hits().size());
}
}
@Test
- public void search() throws Exception {
+ void search() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.searcher("foo", MockSearcher.class))))
- ) {
+ ) {
Result result = app.search("foo", new Query("?query=foo&timeout=20000"));
assertEquals(1, result.hits().size());
}
}
@Test
- public void document_type() throws Exception {
+ void document_type() throws Exception {
try (
Application app = Application.fromBuilder(new Application.Builder()
.documentType("test", new String(this.getClass().getResourceAsStream("/test.sd").readAllBytes(), StandardCharsets.UTF_8))
.container("default", new Application.Builder.Container()
- .documentProcessor(MockDocproc.class)
- .config(new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar"))))))
- ) {
+ .documentProcessor(MockDocproc.class)
+ .config(new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar"))))))
+ ) {
Map<String, DocumentType> typeMap = app.getJDisc("jdisc").documentProcessing().getDocumentTypes();
assertNotNull(typeMap);
assertTrue(typeMap.containsKey("test"));
@@ -236,7 +246,7 @@ public class ApplicationTest {
}
@Test
- public void get_search_handler() throws Exception {
+ void get_search_handler() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container().search(true))))) {
SearchHandler searchHandler = (SearchHandler) app.getRequestHandlerById("com.yahoo.search.handler.SearchHandler");
assertNotNull(searchHandler);
@@ -244,7 +254,7 @@ public class ApplicationTest {
}
@Test
- public void component() throws Exception {
+ void component() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.component(MockSearcher.class))))) {
Component c = app.getComponentById(MockSearcher.class.getName());
@@ -253,7 +263,7 @@ public class ApplicationTest {
}
@Test
- public void component_with_config() throws Exception {
+ void component_with_config() throws Exception {
MockApplicationConfig config = new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar")));
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.component("foo", MockDocproc.class, config))))) {
@@ -263,7 +273,7 @@ public class ApplicationTest {
}
@Test
- public void file_distribution() {
+ void file_distribution() {
try (Application application = Application.fromApplicationPackage(new File("src/test/app-packages/filedistribution/"), Networking.disable)) {
// Deployment succeeded
Application unused = application;
@@ -271,7 +281,7 @@ public class ApplicationTest {
}
@Test
- public void server() throws Exception {
+ void server() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.server("foo", MockServer.class)))
)) {
@@ -282,7 +292,7 @@ public class ApplicationTest {
}
@Test
- public void query_profile() throws Exception {
+ void query_profile() throws Exception {
try (Application app = Application.fromBuilder(new Application.Builder()
.queryProfile("default", "<query-profile id=\"default\">\n" +
"<field name=\"defaultage\">7d</field>\n" +
@@ -293,25 +303,27 @@ public class ApplicationTest {
.rankExpression("re", "commonfirstphase(globalstaticrank)")
.documentType("test", new String(this.getClass().getResourceAsStream("/test.sd").readAllBytes(), StandardCharsets.UTF_8))
.container("default", new Application.Builder.Container()
- .search(true)
+ .search(true)
))) {
Application unused = app;
}
}
- @Test(expected = ConnectException.class)
- public void http_interface_is_off_when_networking_is_disabled() throws Exception {
- int httpPort = getFreePort();
- try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.disable)) {
- HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
- int statusCode = client.execute(new HttpGet("http://localhost:" + httpPort)).getStatusLine().getStatusCode();
- fail("Networking.disable is specified, but the network interface is enabled! Got status code: " + statusCode);
- Application unused = application;
- }
+ @Test
+ void http_interface_is_off_when_networking_is_disabled() throws Exception {
+ assertThrows(ConnectException.class, () -> {
+ int httpPort = getFreePort();
+ try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.disable)) {
+ HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
+ int statusCode = client.execute(new HttpGet("http://localhost:" + httpPort)).getStatusLine().getStatusCode();
+ fail("Networking.disable is specified, but the network interface is enabled! Got status code: " + statusCode);
+ Application unused = application;
+ }
+ });
}
@Test
- public void http_interface_is_on_when_networking_is_enabled() throws Exception {
+ void http_interface_is_on_when_networking_is_enabled() throws Exception {
int httpPort = getFreePort();
try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.enable)) {
HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
@@ -329,7 +341,7 @@ public class ApplicationTest {
}
@Test
- public void athenz_in_deployment_xml() {
+ void athenz_in_deployment_xml() {
try (Application application = Application.fromApplicationPackage(new File("src/test/app-packages/athenz-in-deployment-xml/"), Networking.disable)) {
// Deployment succeeded
Application unused = application;
@@ -351,7 +363,7 @@ public class ApplicationTest {
}
@Test
- public void application_with_access_control_can_be_constructed() {
+ void application_with_access_control_can_be_constructed() {
try (Application application = Application.fromServicesXml(servicesXmlWithAccessControl(), Networking.disable)) {
Application unused = application;
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java b/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
index 7c786d35fab..7dad204a8ce 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
@@ -13,12 +13,13 @@ import com.yahoo.document.Document;
import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentType;
import com.yahoo.processing.execution.chain.ChainRegistry;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -47,16 +48,16 @@ public class ContainerDocprocTest {
return xml;
}
- @Before
+ @BeforeEach
public void resetContainer() {
Container.resetInstance();
}
@Test
- public void requireThatBasicDocumentProcessingWorks() throws Exception {
+ void requireThatBasicDocumentProcessingWorks() throws Exception {
try (Application app = new ApplicationBuilder()
- .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
- .documentType("music", DOCUMENT).build()) {
+ .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
+ .documentType("music", DOCUMENT).build()) {
JDisc container = app.getJDisc("container");
DocumentProcessing docProc = container.documentProcessing();
@@ -84,11 +85,11 @@ public class ContainerDocprocTest {
}
@Test
- public void requireThatLaterDocumentProcessingWorks() throws Exception {
+ void requireThatLaterDocumentProcessingWorks() throws Exception {
try (Application app = new ApplicationBuilder()
- .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
- .networking(Networking.disable)
- .documentType("music", DOCUMENT).build()) {
+ .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
+ .networking(Networking.disable)
+ .documentType("music", DOCUMENT).build()) {
JDisc container = app.getJDisc("container");
DocumentProcessing docProc = container.documentProcessing();
DocumentType type = docProc.getDocumentTypes().get("music");
@@ -118,35 +119,44 @@ public class ContainerDocprocTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatUnknownChainThrows() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.documentProcessing().process(ComponentSpecification.fromString("unknown"),
- new com.yahoo.docproc.Processing());
- }
+ @Test
+ void requireThatUnknownChainThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.documentProcessing().process(ComponentSpecification.fromString("unknown"),
+ new com.yahoo.docproc.Processing());
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatProcessingFails() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.processing();
- }
+ @Test
+ void requireThatProcessingFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.processing();
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatSearchFails() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.search();
- }
+ @Test
+ void requireThatSearchFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.search();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java b/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
index f76008b4e02..656660f7580 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
@@ -9,16 +9,16 @@ import com.yahoo.application.container.handler.Response;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.test.json.JsonTestHelper;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Verify that we can create a JDisc (and hence Application) instance capable of doing model evaluation
@@ -27,22 +27,23 @@ import static org.junit.Assume.assumeTrue;
*/
public class ContainerModelEvaluationTest {
+ // This should ideally work but may not be worth the effort
@Test
- @Ignore // This should ideally work but may not be worth the effort
- public void testCreateJDiscInstanceWithModelEvaluation() {
+ @Disabled
+ void testCreateJDiscInstanceWithModelEvaluation() {
try (JDisc jdisc =
- JDisc.fromPath(new File("src/test/app-packages/model-evaluation").toPath(),
- Networking.disable)) {
+ JDisc.fromPath(new File("src/test/app-packages/model-evaluation").toPath(),
+ Networking.disable)) {
assertLoadedModels(jdisc);
}
}
@Test
- public void testCreateApplicationInstanceWithModelEvaluation() {
+ void testCreateApplicationInstanceWithModelEvaluation() {
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
try (Application application =
- Application.fromApplicationPackage(new File("src/test/app-packages/model-evaluation"),
- Networking.disable)) {
+ Application.fromApplicationPackage(new File("src/test/app-packages/model-evaluation"),
+ Networking.disable)) {
assertLoadedModels(application.getJDisc("default"));
}
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java b/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
index e5019d6b54f..b10d62e72e0 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
@@ -7,13 +7,14 @@ import com.yahoo.component.ComponentSpecification;
import com.yahoo.container.Container;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -36,13 +37,13 @@ public class ContainerProcessingTest {
return xml;
}
- @Before
+ @BeforeEach
public void resetContainer() {
Container.resetInstance();
}
@Test
- public void requireThatBasicProcessingWorks() {
+ void requireThatBasicProcessingWorks() {
try (JDisc container = getContainerWithRot13()) {
Processing processing = container.processing();
@@ -55,10 +56,10 @@ public class ContainerProcessingTest {
}
@Test
- public void requireThatBasicProcessingDoesNotTruncateBigResponse() {
- int SIZE = 50*1000;
+ void requireThatBasicProcessingDoesNotTruncateBigResponse() {
+ int SIZE = 50 * 1000;
StringBuilder foo = new StringBuilder();
- for (int j = 0 ; j < SIZE ; j++) {
+ for (int j = 0; j < SIZE; j++) {
foo.append('b');
}
@@ -69,13 +70,13 @@ public class ContainerProcessingTest {
container.handleRequest(
new com.yahoo.application.container.handler.Request("http://foo/processing/?chain=foo&title=" + foo.toString()));
- assertEquals(SIZE+26, response.getBody().length);
+ assertEquals(SIZE + 26, response.getBody().length);
}
}
}
@Test
- public void processing_and_rendering_works() throws Exception {
+ void processing_and_rendering_works() throws Exception {
try (JDisc container = getContainerWithRot13()) {
Processing processing = container.processing();
@@ -90,27 +91,36 @@ public class ContainerProcessingTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatUnknownChainThrows() {
- try (JDisc container = getContainerWithRot13()) {
- container.processing().process(ComponentSpecification.fromString("unknown"), new Request());
- }
+ @Test
+ void requireThatUnknownChainThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.processing().process(ComponentSpecification.fromString("unknown"), new Request());
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatDocprocFails() {
- try (JDisc container = getContainerWithRot13()) {
- container.documentProcessing();
- }
+ @Test
+ void requireThatDocprocFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.documentProcessing();
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatSearchFails() {
- try (JDisc container = getContainerWithRot13()) {
- container.search();
- }
+ @Test
+ void requireThatSearchFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.search();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java b/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
index 911d57a7d6e..24cae99b5ab 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
@@ -11,12 +11,13 @@ import com.yahoo.application.container.handlers.HeaderEchoRequestHandler;
import com.yahoo.application.container.handlers.ThrowingInWriteRequestHandler;
import com.yahoo.application.container.handlers.WriteException;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.CharacterCodingException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -37,7 +38,7 @@ public class ContainerRequestTest {
}
@Test
- public void requireThatRequestBodyWorks() throws CharacterCodingException {
+ void requireThatRequestBodyWorks() throws CharacterCodingException {
String DATA = "we have no bananas today";
Request req = new Request("http://banana/echo", DATA.getBytes(Utf8.getCharset()));
@@ -50,7 +51,7 @@ public class ContainerRequestTest {
}
@Test
- public void requireThatCustomRequestHeadersWork() {
+ void requireThatCustomRequestHeadersWork() {
Request req = new Request("http://banana/echo");
req.getHeaders().add("X-Foo", "Bar");
@@ -62,26 +63,31 @@ public class ContainerRequestTest {
}
}
- @Test(expected = WriteException.class)
- public void requireThatRequestHandlerThatThrowsInWriteWorks() {
- String DATA = "we have no bananas today";
- Request req = new Request("http://banana/throwwrite", DATA.getBytes(Utf8.getCharset()));
+ @Test
+ void requireThatRequestHandlerThatThrowsInWriteWorks() {
+ assertThrows(WriteException.class, () -> {
+ String DATA = "we have no bananas today";
+ Request req = new Request("http://banana/throwwrite", DATA.getBytes(Utf8.getCharset()));
- try (JDisc container = JDisc.fromServicesXml(getXML(ThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/throwwrite"), Networking.disable)) {
- Response response = container.handleRequest(req);
- req.toString();
- }
+ try (JDisc container = JDisc.fromServicesXml(getXML(ThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/throwwrite"), Networking.disable)) {
+ Response response = container.handleRequest(req);
+ req.toString();
+ }
+ });
}
- @Test(expected = DelayedWriteException.class)
- public void requireThatRequestHandlerThatThrowsDelayedInWriteWorks() {
- String DATA = "we have no bananas today";
- Request req = new Request("http://banana/delayedthrowwrite", DATA.getBytes(Utf8.getCharset()));
+ @Test
+ void requireThatRequestHandlerThatThrowsDelayedInWriteWorks() {
+ assertThrows(DelayedWriteException.class, () -> {
+ String DATA = "we have no bananas today";
+ Request req = new Request("http://banana/delayedthrowwrite", DATA.getBytes(Utf8.getCharset()));
- try (JDisc container = JDisc.fromServicesXml(getXML(DelayedThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/delayedthrowwrite"), Networking.disable)) {
- Response response = container.handleRequest(req);
- req.toString();
- }
+ try (JDisc container = JDisc.fromServicesXml(getXML(DelayedThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/delayedthrowwrite"), Networking.disable)) {
+ Response response = container.handleRequest(req);
+ req.toString();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java b/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
index e1e520bccc9..465bdef87a3 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
@@ -6,12 +6,13 @@ import com.yahoo.application.container.searchers.AddHitSearcher;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -20,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerSchemaTest {
@Test
- public void processing_and_rendering_works() throws Exception {
+ void processing_and_rendering_works() throws Exception {
final String searcherId = AddHitSearcher.class.getName();
try (JDisc container = containerWithSearch(searcherId)) {
@@ -32,7 +33,7 @@ public class ContainerSchemaTest {
}
@Test
- public void searching_works() {
+ void searching_works() {
final String searcherId = AddHitSearcher.class.getName();
try (JDisc container = containerWithSearch(searcherId)) {
@@ -54,11 +55,14 @@ public class ContainerSchemaTest {
"</container>", Networking.disable);
}
- @Test(expected = UnsupportedOperationException.class)
- public void retrieving_search_from_container_without_search_is_illegal() {
- try (JDisc container = JDisc.fromServicesXml("<container version=\"1.0\" />", Networking.disable)) {
- container.search(); // throws
- }
+ @Test
+ void retrieving_search_from_container_without_search_is_illegal() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml("<container version=\"1.0\" />", Networking.disable)) {
+ container.search(); // throws
+ }
+
+ });
}
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerTest.java b/application/src/test/java/com/yahoo/application/container/ContainerTest.java
index fda8e0c597a..31e0b71d186 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerTest.java
@@ -10,17 +10,17 @@ import com.yahoo.application.container.handlers.TestHandler;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.nio.charset.CharacterCodingException;
import java.nio.file.FileSystems;
import static com.yahoo.application.container.JDisc.fromServicesXml;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Tony Vaagenes
@@ -30,7 +30,7 @@ import static org.junit.Assert.fail;
public class ContainerTest {
@Test
- public void container_can_be_used_as_top_level_element() {
+ void container_can_be_used_as_top_level_element() {
try (JDisc container = fromServicesXml("<container version=\"1.0\">" + //
"<search />" + //
"</container>", Networking.disable)) {
@@ -39,7 +39,7 @@ public class ContainerTest {
}
@Test
- public void container_id_can_be_set() {
+ void container_id_can_be_set() {
try (JDisc container = fromServicesXml("<container version=\"1.0\" id=\"my-service-id\">" + //
"<search />" + //
"</container>", Networking.disable)) {
@@ -48,7 +48,7 @@ public class ContainerTest {
}
@Test
- public void container_can_be_embedded_in_services_tag() {
+ void container_can_be_embedded_in_services_tag() {
try (JDisc container = fromServicesXml("<services>" + //
"<container version=\"1.0\" id=\"my-service-id\">" + //
"<search />" + //
@@ -58,9 +58,10 @@ public class ContainerTest {
}
}
+ // container is unused inside the try block
@Test
- @SuppressWarnings("try") // container is unused inside the try block
- public void multiple_container_elements_gives_exception() {
+ @SuppressWarnings("try")
+ void multiple_container_elements_gives_exception() {
try (JDisc container = fromServicesXml("<services>" + //
"<container version=\"1.0\" id=\"id1\" />" + //
"<container version=\"1.0\" />" + //
@@ -72,7 +73,7 @@ public class ContainerTest {
}
@Test
- public void handleRequest_yields_response_from_correct_request_handler() {
+ void handleRequest_yields_response_from_correct_request_handler() {
final String handlerClass = TestHandler.class.getName();
try (JDisc container = fromServicesXml("<container version=\"1.0\">" + //
"<handler id=\"test-handler\" class=\"" + handlerClass + "\">" + //
@@ -89,7 +90,7 @@ public class ContainerTest {
}
@Test
- public void load_searcher_from_bundle() {
+ void load_searcher_from_bundle() {
try (JDisc container = JDisc.fromPath(FileSystems.getDefault().getPath("src/test/app-packages/searcher-app"),
Networking.disable)) {
Result result = container.search().process(ComponentSpecification.fromString("default"),
@@ -99,7 +100,7 @@ public class ContainerTest {
}
@Test
- public void document_types_can_be_accessed() throws Exception {
+ void document_types_can_be_accessed() throws Exception {
try (Application application = new ApplicationBuilder().documentType("example", EXAMPLE_DOCUMENT)
.servicesXml(CONTAINER_WITH_DOCUMENT_PROCESSING).build()) {
JDisc container = application.getJDisc("container");
@@ -109,7 +110,7 @@ public class ContainerTest {
}
@Test
- public void annotation_types_can_be_accessed() throws Exception {
+ void annotation_types_can_be_accessed() throws Exception {
try (Application application = new ApplicationBuilder().documentType("example", "search example {\n" + //
" " + EXAMPLE_DOCUMENT + "\n" + //
" annotation exampleAnnotation {}\n" + //
@@ -121,9 +122,9 @@ public class ContainerTest {
}
}
- @Ignore // Enable this when static state has been removed.
+ @Disabled // Enable this when static state has been removed.
@Test
- public void multiple_containers_can_be_run_in_parallel() throws Exception {
+ void multiple_containers_can_be_run_in_parallel() throws Exception {
try (JDisc jdisc1 = jdiscWithHttp(); JDisc jdisc2 = jdiscWithHttp()) {
sendRequest(jdisc1);
sendRequest(jdisc2);
diff --git a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java
index d88d69f247e..19d5176c108 100644
--- a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java
+++ b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application.container.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
@@ -12,12 +12,13 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -27,7 +28,7 @@ import static org.junit.Assert.fail;
public class HeadersTestCase {
@Test
- public void requireThatSizeWorksAsExpected() {
+ void requireThatSizeWorksAsExpected() {
Headers headers = new Headers();
assertEquals(0, headers.size());
headers.add("foo", "bar");
@@ -43,7 +44,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatIsEmptyWorksAsExpected() {
+ void requireThatIsEmptyWorksAsExpected() {
Headers headers = new Headers();
assertTrue(headers.isEmpty());
headers.add("foo", "bar");
@@ -53,7 +54,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsKeyWorksAsExpected() {
+ void requireThatContainsKeyWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsKey("foo"));
assertFalse(headers.containsKey("FOO"));
@@ -63,7 +64,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsValueWorksAsExpected() {
+ void requireThatContainsValueWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsValue(Arrays.asList("bar")));
headers.add("foo", "bar");
@@ -71,7 +72,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsWorksAsExpected() {
+ void requireThatContainsWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.contains("foo", "bar"));
assertFalse(headers.contains("FOO", "bar"));
@@ -85,7 +86,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsIgnoreCaseWorksAsExpected() {
+ void requireThatContainsIgnoreCaseWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsIgnoreCase("foo", "bar"));
assertFalse(headers.containsIgnoreCase("FOO", "bar"));
@@ -99,7 +100,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddStringWorksAsExpected() {
+ void requireThatAddStringWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -109,7 +110,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddListWorksAsExpected() {
+ void requireThatAddListWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", Arrays.asList("bar"));
@@ -119,7 +120,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddAllWorksAsExpected() {
+ void requireThatAddAllWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -136,7 +137,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutStringWorksAsExpected() {
+ void requireThatPutStringWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.put("foo", "bar");
@@ -146,7 +147,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutListWorksAsExpected() {
+ void requireThatPutListWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.put("foo", Arrays.asList("bar"));
@@ -156,7 +157,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutAllWorksAsExpected() {
+ void requireThatPutAllWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -173,7 +174,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatRemoveWorksAsExpected() {
+ void requireThatRemoveWorksAsExpected() {
Headers headers = new Headers();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -183,7 +184,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatRemoveStringWorksAsExpected() {
+ void requireThatRemoveStringWorksAsExpected() {
Headers headers = new Headers();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -196,7 +197,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatClearWorksAsExpected() {
+ void requireThatClearWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -208,7 +209,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatGetWorksAsExpected() {
+ void requireThatGetWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -216,7 +217,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatGetFirstWorksAsExpected() {
+ void requireThatGetFirstWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.getFirst("foo"));
headers.add("foo", Arrays.asList("bar", "baz"));
@@ -224,7 +225,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatIsTrueWorksAsExpected() {
+ void requireThatIsTrueWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.isTrue("foo"));
headers.put("foo", Arrays.asList("true"));
@@ -242,7 +243,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatKeySetWorksAsExpected() {
+ void requireThatKeySetWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.<Set<String>>emptySet(), headers.keySet());
headers.add("foo", "bar");
@@ -252,7 +253,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatValuesWorksAsExpected() {
+ void requireThatValuesWorksAsExpected() {
Headers headers = new Headers();
assertTrue(headers.values().isEmpty());
headers.add("foo", "bar");
@@ -268,7 +269,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntrySetWorksAsExpected() {
+ void requireThatEntrySetWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.emptySet(), headers.entrySet());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -282,7 +283,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntriesWorksAsExpected() {
+ void requireThatEntriesWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.emptyList(), headers.entries());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -301,7 +302,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntryIsUnmodifiable() {
+ void requireThatEntryIsUnmodifiable() {
Headers headers = new Headers();
headers.put("foo", "bar");
Map.Entry<String, String> entry = headers.entries().get(0);
@@ -314,7 +315,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntriesAreUnmodifiable() {
+ void requireThatEntriesAreUnmodifiable() {
Headers headers = new Headers();
headers.put("foo", "bar");
List<Map.Entry<String, String>> entries = headers.entries();
@@ -333,25 +334,25 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEqualsWorksAsExpected() {
+ void requireThatEqualsWorksAsExpected() {
Headers lhs = new Headers();
Headers rhs = new Headers();
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
lhs.add("foo", "bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.add("foo", "bar");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatHashCodeWorksAsExpected() {
+ void requireThatHashCodeWorksAsExpected() {
Headers lhs = new Headers();
Headers rhs = new Headers();
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
lhs.add("foo", "bar");
assertTrue(lhs.hashCode() != rhs.hashCode());
rhs.add("foo", "bar");
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
}
private static class MyEntry implements Map.Entry<String, String> {
diff --git a/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java b/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java
index edd2acb630d..b0971c141d6 100644
--- a/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java
+++ b/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application.container.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Einar M R Rosenvinge
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertNotNull;
public class ResponseTestCase {
@Test
- public void requireThatCharsetParsingWorks() {
+ void requireThatCharsetParsingWorks() {
assertEquals("utf-8", Response.charset("text/foobar").toString().toLowerCase());
assertEquals("utf-8", Response.charset("adsf").toString().toLowerCase());
assertEquals("utf-8", Response.charset("").toString().toLowerCase());
@@ -26,7 +26,7 @@ public class ResponseTestCase {
}
@Test
- public void testDefaultResponseBody() {
+ void testDefaultResponseBody() {
Response res1 = new Response();
Response res2 = new Response(new byte[0]);
diff --git a/athenz-identity-provider-service/pom.xml b/athenz-identity-provider-service/pom.xml
index d5e6b85f571..f4daa43b8e3 100644
--- a/athenz-identity-provider-service/pom.xml
+++ b/athenz-identity-provider-service/pom.xml
@@ -93,14 +93,19 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>orchestrator</artifactId>
- <version>${project.version}</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>orchestrator</artifactId>
+ <version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -113,12 +118,32 @@
<artifactId>application</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java
index 147a05bc27e..61a4a0fe41f 100644
--- a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java
+++ b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java
@@ -8,7 +8,7 @@ import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.tls.DefaultTlsContext;
-import com.yahoo.security.tls.MutableX509KeyManager;
+import com.yahoo.security.MutableX509KeyManager;
import com.yahoo.security.tls.PeerAuthentication;
import com.yahoo.security.tls.TlsContext;
import com.yahoo.vespa.athenz.api.AthenzService;
diff --git a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/Certificates.java b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/Certificates.java
index 61dc67bd7d4..df904bf8010 100644
--- a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/Certificates.java
+++ b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/Certificates.java
@@ -17,7 +17,7 @@ import java.util.Optional;
import java.util.stream.Collectors;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
/**
* Helper class for creating {@link X509Certificate}s.
@@ -66,7 +66,7 @@ public class Certificates {
private static Optional<String> getInstanceIdFromSAN(List<SubjectAlternativeName> subjectAlternativeNames) {
return subjectAlternativeNames.stream()
- .filter(san -> san.getType() == DNS_NAME)
+ .filter(san -> san.getType() == DNS)
.map(SubjectAlternativeName::getValue)
.map(Certificates::parseInstanceId)
.flatMap(Optional::stream)
diff --git a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiHandler.java b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiHandler.java
index 9bd6153f159..531a815922b 100644
--- a/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiHandler.java
+++ b/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiHandler.java
@@ -37,7 +37,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.logging.Level;
-import java.util.stream.Stream;
/**
* REST API for issuing and refreshing node certificates in a hosted Vespa system.
@@ -97,8 +96,8 @@ public class CertificateAuthorityApiHandler extends ThreadedHttpRequestHandler {
var instanceRegistration = deserializeRequest(request, InstanceSerializer::registrationFromSlime);
InstanceConfirmation confirmation = new InstanceConfirmation(instanceRegistration.provider(), instanceRegistration.domain(), instanceRegistration.service(), EntityBindingsMapper.toSignedIdentityDocumentEntity(instanceRegistration.attestationData()));
- confirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
- confirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.DNS_NAME));
+ confirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.IP));
+ confirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.DNS));
if (!instanceValidator.isValidInstance(confirmation)) {
log.log(Level.INFO, "Invalid instance registration for " + instanceRegistration.toString());
return ErrorResponse.forbidden("Unable to launch service: " +instanceRegistration.service());
@@ -130,8 +129,8 @@ public class CertificateAuthorityApiHandler extends ThreadedHttpRequestHandler {
refreshesSameService(instanceRefresh, athenzService);
InstanceConfirmation instanceConfirmation = new InstanceConfirmation(provider, athenzService.getDomain().getName(), athenzService.getName(), null);
- instanceConfirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
- instanceConfirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.DNS_NAME));
+ instanceConfirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.IP));
+ instanceConfirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.DNS));
if(!instanceValidator.isValidRefresh(instanceConfirmation)) {
return ErrorResponse.forbidden("Unable to refresh cert: " + instanceRefresh.csr().getSubject().toString());
}
@@ -177,9 +176,7 @@ public class CertificateAuthorityApiHandler extends ThreadedHttpRequestHandler {
private AthenzService getRequestAthenzService(HttpRequest request) {
return getRequestCertificateChain(request).stream()
.findFirst()
- .map(X509CertificateUtils::getSubjectCommonNames)
- .map(List::stream)
- .flatMap(Stream::findFirst)
+ .flatMap(X509CertificateUtils::getSubjectCommonName)
.map(AthenzService::new)
.orElseThrow(() -> new RuntimeException("No certificate found"));
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
index 508124935c1..9205baff0fc 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
@@ -25,14 +25,14 @@ import com.yahoo.vespa.hosted.provision.node.Generation;
import com.yahoo.vespa.hosted.provision.node.IP;
import com.yahoo.vespa.hosted.provision.node.Nodes;
import com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Set;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.TestUtils.getAthenzProviderConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,27 +45,27 @@ public class IdentityDocumentGeneratorTest {
private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1"));
@Test
- public void generates_valid_identity_document() {
+ void generates_valid_identity_document() {
String parentHostname = "docker-host";
String containerHostname = "docker-container";
ApplicationId appid = ApplicationId.from(
TenantName.from("tenant"), ApplicationName.from("application"), InstanceName.from("default"));
Allocation allocation = new Allocation(appid,
- ClusterMembership.from("container/default/0/0", Version.fromString("1.2.3"), Optional.empty()),
- new NodeResources(1, 1, 1, 1),
- Generation.initial(),
- false);
+ ClusterMembership.from("container/default/0/0", Version.fromString("1.2.3"), Optional.empty()),
+ new NodeResources(1, 1, 1, 1),
+ Generation.initial(),
+ false);
Node parentNode = Node.create("ostkid",
- IP.Config.ofEmptyPool(Set.of("127.0.0.1")),
- parentHostname,
- new MockNodeFlavors().getFlavorOrThrow("default"),
- NodeType.host).build();
+ IP.Config.ofEmptyPool(Set.of("127.0.0.1")),
+ parentHostname,
+ new MockNodeFlavors().getFlavorOrThrow("default"),
+ NodeType.host).build();
Node containerNode = Node.reserve(Set.of("::1"),
- containerHostname,
- parentHostname,
- new MockNodeFlavors().getFlavorOrThrow("default").resources(),
- NodeType.tenant)
+ containerHostname,
+ parentHostname,
+ new MockNodeFlavors().getFlavorOrThrow("default").resources(),
+ NodeType.tenant)
.allocation(allocation).build();
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
index 6dc2e58059f..9a91d7372da 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
@@ -25,7 +25,7 @@ import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.IP;
import com.yahoo.vespa.hosted.provision.node.Nodes;
import com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -42,8 +42,8 @@ import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.InstanceValidator.SERVICE_PROPERTIES_DOMAIN_KEY;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.InstanceValidator.SERVICE_PROPERTIES_SERVICE_KEY;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -62,14 +62,14 @@ public class InstanceValidatorTest {
private final AthenzService vespaTenantDomain = new AthenzService("vespa.vespa.tenant");
@Test
- public void application_does_not_exist() {
+ void application_does_not_exist() {
SuperModelProvider superModelProvider = mockSuperModelProvider();
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, null, vespaTenantDomain);
assertFalse(instanceValidator.isValidInstance(createRegisterInstanceConfirmation(applicationId, domain, service)));
}
@Test
- public void application_does_not_have_domain_set() {
+ void application_does_not_have_domain_set() {
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.emptyList()));
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, new IdentityDocumentSigner(), vespaTenantDomain);
@@ -78,9 +78,9 @@ public class InstanceValidatorTest {
}
@Test
- public void application_has_wrong_domain() {
+ void application_has_wrong_domain() {
ServiceInfo serviceInfo = new ServiceInfo("serviceName", "type", Collections.emptyList(),
- Collections.singletonMap(SERVICE_PROPERTIES_DOMAIN_KEY, "not-domain"), "confId", "hostName");
+ Collections.singletonMap(SERVICE_PROPERTIES_DOMAIN_KEY, "not-domain"), "confId", "hostName");
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.singletonList(serviceInfo)));
@@ -90,13 +90,13 @@ public class InstanceValidatorTest {
}
@Test
- public void application_has_same_domain_and_service() {
+ void application_has_same_domain_and_service() {
Map<String, String> properties = new HashMap<>();
properties.put(SERVICE_PROPERTIES_DOMAIN_KEY, domain);
properties.put(SERVICE_PROPERTIES_SERVICE_KEY, service);
ServiceInfo serviceInfo = new ServiceInfo("serviceName", "type", Collections.emptyList(),
- properties, "confId", "hostName");
+ properties, "confId", "hostName");
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.singletonList(serviceInfo)));
@@ -108,7 +108,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_invalid_provider_unique_id_in_csr() {
+ void rejects_invalid_provider_unique_id_in_csr() {
SuperModelProvider superModelProvider = mockSuperModelProvider();
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, null, vespaTenantDomain);
InstanceConfirmation instanceConfirmation = createRegisterInstanceConfirmation(applicationId, domain, service);
@@ -118,7 +118,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_unknown_ips_in_csr() {
+ void rejects_unknown_ips_in_csr() {
NodeRepository nodeRepository = mockNodeRepo();
InstanceValidator instanceValidator = new InstanceValidator(null, mockSuperModelProvider(), nodeRepository, null, vespaTenantDomain);
InstanceConfirmation instanceConfirmation = createRegisterInstanceConfirmation(applicationId, domain, service);
@@ -134,7 +134,7 @@ public class InstanceValidatorTest {
}
@Test
- public void accepts_valid_refresh_requests() {
+ void accepts_valid_refresh_requests() {
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
when(nodeRepository.nodes()).thenReturn(nodes);
@@ -151,7 +151,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_refresh_on_ip_mismatch() {
+ void rejects_refresh_on_ip_mismatch() {
NodeRepository nodeRepository = mockNodeRepo();
InstanceValidator instanceValidator = new InstanceValidator(null, null, nodeRepository, new IdentityDocumentSigner(), vespaTenantDomain);
@@ -169,7 +169,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_refresh_when_node_is_not_allocated() {
+ void rejects_refresh_when_node_is_not_allocated() {
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
when(nodeRepository.nodes()).thenReturn(nodes);
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificateTester.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificateTester.java
index b225cbef21c..4012776949e 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificateTester.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificateTester.java
@@ -68,10 +68,10 @@ public class CertificateTester {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
var builder = Pkcs10CsrBuilder.fromKeypair(subject, keyPair, SignatureAlgorithm.SHA512_WITH_ECDSA);
for (var dnsName : dnsNames) {
- builder = builder.addSubjectAlternativeName(SubjectAlternativeName.Type.DNS_NAME, dnsName);
+ builder = builder.addSubjectAlternativeName(SubjectAlternativeName.Type.DNS, dnsName);
}
for (var ipAddress : ipAddresses) {
- builder = builder.addSubjectAlternativeName(SubjectAlternativeName.Type.IP_ADDRESS, ipAddress);
+ builder = builder.addSubjectAlternativeName(SubjectAlternativeName.Type.IP, ipAddress);
}
return builder.build();
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
index 613ced895e9..dd3ddeeb804 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
@@ -5,7 +5,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SubjectAlternativeName;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -13,8 +13,8 @@ import java.time.Duration;
import java.util.List;
import static java.time.temporal.ChronoUnit.SECONDS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author mpolden
@@ -25,7 +25,7 @@ public class CertificatesTest {
private final X509Certificate caCertificate = CertificateTester.createCertificate("CA", keyPair);
@Test
- public void expiry() {
+ void expiry() {
var clock = new ManualClock();
var certificates = new Certificates(clock);
var csr = CertificateTester.createCsr();
@@ -37,7 +37,7 @@ public class CertificatesTest {
}
@Test
- public void add_san_from_csr() throws Exception {
+ void add_san_from_csr() throws Exception {
var certificates = new Certificates(new ManualClock());
var dnsName = "host.example.com";
var ip = "192.0.2.42";
@@ -48,14 +48,14 @@ public class CertificatesTest {
assertEquals(2, certificate.getSubjectAlternativeNames().size());
var subjectAlternativeNames = List.copyOf(certificate.getSubjectAlternativeNames());
- assertEquals(List.of(SubjectAlternativeName.Type.DNS_NAME.getTag(), dnsName),
- subjectAlternativeNames.get(0));
- assertEquals(List.of(SubjectAlternativeName.Type.IP_ADDRESS.getTag(), ip),
- subjectAlternativeNames.get(1));
+ assertEquals(List.of(SubjectAlternativeName.Type.DNS.getTag(), dnsName),
+ subjectAlternativeNames.get(0));
+ assertEquals(List.of(SubjectAlternativeName.Type.IP.getTag(), ip),
+ subjectAlternativeNames.get(1));
}
@Test
- public void parse_instance_id() {
+ void parse_instance_id() {
var instanceId = "1.cluster1.default.app1.tenant1.us-north-1.prod.node";
var instanceIdWithSuffix = instanceId + ".instanceid.athenz.dev-us-north-1.vespa.aws.oath.cloud";
var csr = CertificateTester.createCsr(List.of("foo", "bar", instanceIdWithSuffix));
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
index 7bfc4ad41a4..bf2115e8759 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
@@ -17,8 +17,8 @@ import com.yahoo.vespa.athenz.client.zts.DefaultZtsClient;
import com.yahoo.vespa.hosted.ca.CertificateTester;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import java.net.URI;
@@ -28,9 +28,9 @@ import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -45,25 +45,25 @@ public class CertificateAuthorityApiTest extends ContainerTester {
private static final String CONTAINER_IDENTITY = "vespa.external.tenant";
private static final String HOST_IDENTITY = "vespa.external.tenant-host";
- @Before
+ @BeforeEach
public void before() {
setCaCertificateAndKey();
}
@Test
- public void register_instance() throws Exception {
+ void register_instance() throws Exception {
// POST instance registration
var csr = CertificateTester.createCsr(List.of("node1.example.com", INSTANCE_ID_WITH_SUFFIX));
assertIdentityResponse(new Request("http://localhost:12345/ca/v1/instance/",
- instanceRegistrationJson(csr),
- Request.Method.POST));
+ instanceRegistrationJson(csr),
+ Request.Method.POST));
// POST instance registration with ZTS client
var ztsClient = new TestZtsClient(new AthenzPrincipal(new AthenzService(HOST_IDENTITY)), null, URI.create("http://localhost:12345/ca/v1/"), SSLContext.getDefault());
var instanceIdentity = ztsClient.registerInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- getAttestationData(),
- csr);
+ new AthenzService(CONTAINER_IDENTITY),
+ getAttestationData(),
+ csr);
assertEquals("CN=Vespa CA", instanceIdentity.certificate().getIssuerX500Principal().getName());
}
@@ -84,7 +84,7 @@ public class CertificateAuthorityApiTest extends ContainerTester {
}
@Test
- public void refresh_instance() throws Exception {
+ void refresh_instance() throws Exception {
// Register instance to get cert
var certificate = registerInstance();
@@ -92,41 +92,41 @@ public class CertificateAuthorityApiTest extends ContainerTester {
var principal = new AthenzPrincipal(new AthenzService(CONTAINER_IDENTITY));
var csr = CertificateTester.createCsr(principal.getIdentity().getFullName(), List.of("node1.example.com", INSTANCE_ID_WITH_SUFFIX));
var request = new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
- instanceRefreshJson(csr),
- Request.Method.POST,
- principal);
+ instanceRefreshJson(csr),
+ Request.Method.POST,
+ principal);
request.getAttributes().put(RequestUtils.JDISC_REQUEST_X509CERT, new X509Certificate[]{certificate});
assertIdentityResponse(request);
// POST instance refresh with ZTS client
var ztsClient = new TestZtsClient(principal, certificate, URI.create("http://localhost:12345/ca/v1/"), SSLContext.getDefault());
var instanceIdentity = ztsClient.refreshInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- INSTANCE_ID,
- csr);
+ new AthenzService(CONTAINER_IDENTITY),
+ INSTANCE_ID,
+ csr);
assertEquals("CN=Vespa CA", instanceIdentity.certificate().getIssuerX500Principal().getName());
}
@Test
- public void invalid_requests() throws Exception {
+ void invalid_requests() throws Exception {
// POST instance registration with missing fields
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/ failed: Missing required field 'provider'\"}",
- new Request("http://localhost:12345/ca/v1/instance/",
- new byte[0],
- Request.Method.POST));
+ new Request("http://localhost:12345/ca/v1/instance/",
+ new byte[0],
+ Request.Method.POST));
// POST instance registration without DNS name in CSR
var csr = CertificateTester.createCsr();
var request = new Request("http://localhost:12345/ca/v1/instance/",
- instanceRegistrationJson(csr),
- Request.Method.POST);
+ instanceRegistrationJson(csr),
+ Request.Method.POST);
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/ failed: No instance ID found in CSR\"}", request);
// POST instance refresh with missing field
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/1.cluster1.default.app1.tenant1.us-north-1.prod.node failed: Missing required field 'csr'\"}",
- new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
- new byte[0],
- Request.Method.POST));
+ new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
+ new byte[0],
+ Request.Method.POST));
// POST instance refresh where instanceId does not match CSR dnsName
var principal = new AthenzPrincipal(new AthenzService(CONTAINER_IDENTITY));
@@ -148,9 +148,9 @@ public class CertificateAuthorityApiTest extends ContainerTester {
try {
var invalidCsr = CertificateTester.createCsr(principal.getIdentity().getFullName(), List.of("node1.example.com", INVALID_INSTANCE_ID_WITH_SUFFIX));
var instanceIdentity = ztsClient.refreshInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- INSTANCE_ID,
- invalidCsr);
+ new AthenzService(CONTAINER_IDENTITY),
+ INSTANCE_ID,
+ invalidCsr);
fail("Refresh instance should have failed");
} catch (Exception e) {
String expectedMessage = "Received error from ZTS: code=0, message=\"POST http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/1.cluster1.default.app1.tenant1.us-north-1.prod.node failed: Mismatch between instance ID in URL path and instance ID in CSR [instanceId=1.cluster1.default.app1.tenant1.us-north-1.prod.node,instanceIdFromCsr=1.cluster1.default.otherapp.othertenant.us-north-1.prod.node]\"";
@@ -174,9 +174,9 @@ public class CertificateAuthorityApiTest extends ContainerTester {
assertEquals("tenant", root.field("service").asString());
assertEquals(INSTANCE_ID, root.field("instanceId").asString());
var pemEncodedCertificate = root.field("x509Certificate").asString();
- assertTrue("Response contains PEM certificate",
- pemEncodedCertificate.startsWith("-----BEGIN CERTIFICATE-----") &&
- pemEncodedCertificate.endsWith("-----END CERTIFICATE-----\n"));
+ assertTrue(pemEncodedCertificate.startsWith("-----BEGIN CERTIFICATE-----") &&
+ pemEncodedCertificate.endsWith("-----END CERTIFICATE-----\n"),
+ "Response contains PEM certificate");
}, request);
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
index ad0715cbbea..8112f5779e5 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
@@ -5,14 +5,14 @@ import com.yahoo.application.Networking;
import com.yahoo.application.container.JDisc;
import com.yahoo.application.container.handler.Request;
import com.yahoo.vespa.hosted.ca.restapi.mock.SecretStoreMock;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.io.UncheckedIOException;
import java.nio.charset.CharacterCodingException;
import java.util.function.Consumer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The superclass of REST API tests which require a functional container instance.
@@ -23,12 +23,12 @@ public class ContainerTester {
private JDisc container;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(), Networking.enable);
}
- @After
+ @AfterEach
public void stopContainer() {
container.close();
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
index 904ebc65f35..df75e09b957 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.ca.CertificateTester;
import com.yahoo.vespa.hosted.ca.instance.InstanceIdentity;
import com.yahoo.vespa.hosted.ca.instance.InstanceRefresh;
import com.yahoo.vespa.hosted.ca.instance.InstanceRegistration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -25,7 +25,7 @@ import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -33,7 +33,7 @@ import static org.junit.Assert.assertEquals;
public class InstanceSerializerTest {
@Test
- public void deserialize_instance_registration() {
+ void deserialize_instance_registration() {
var csr = CertificateTester.createCsr();
var csrPem = Pkcs10CsrUtils.toPem(csr);
SignedIdentityDocument signedIdentityDocument = new SignedIdentityDocument(
@@ -49,36 +49,36 @@ public class InstanceSerializerTest {
IdentityType.NODE);
var json = String.format("{\n" +
- " \"provider\": \"provider_prod_us-north-1\",\n" +
- " \"domain\": \"vespa.external\",\n" +
- " \"service\": \"tenant\",\n" +
- " \"attestationData\":\"%s\",\n" +
- " \"csr\": \"" + csrPem + "\"\n" +
- "}", StringUtilities.escape(EntityBindingsMapper.toAttestationData(signedIdentityDocument)));
+ " \"provider\": \"provider_prod_us-north-1\",\n" +
+ " \"domain\": \"vespa.external\",\n" +
+ " \"service\": \"tenant\",\n" +
+ " \"attestationData\":\"%s\",\n" +
+ " \"csr\": \"" + csrPem + "\"\n" +
+ "}", StringUtilities.escape(EntityBindingsMapper.toAttestationData(signedIdentityDocument)));
var instanceRegistration = new InstanceRegistration("provider_prod_us-north-1", "vespa.external",
- "tenant", signedIdentityDocument,
- csr);
+ "tenant", signedIdentityDocument,
+ csr);
var deserialized = InstanceSerializer.registrationFromSlime(SlimeUtils.jsonToSlime(json));
assertEquals(instanceRegistration, deserialized);
}
@Test
- public void serialize_instance_identity() {
+ void serialize_instance_identity() {
var certificate = CertificateTester.createCertificate();
var pem = X509CertificateUtils.toPem(certificate);
var identity = new InstanceIdentity("provider_prod_us-north-1", "tenant", "node1.example.com",
- Optional.of(certificate));
+ Optional.of(certificate));
var json = "{" +
- "\"provider\":\"provider_prod_us-north-1\"," +
- "\"service\":\"tenant\"," +
- "\"instanceId\":\"node1.example.com\"," +
- "\"x509Certificate\":\"" + pem.replace("\n", "\\n") + "\"" +
- "}";
+ "\"provider\":\"provider_prod_us-north-1\"," +
+ "\"service\":\"tenant\"," +
+ "\"instanceId\":\"node1.example.com\"," +
+ "\"x509Certificate\":\"" + pem.replace("\n", "\\n") + "\"" +
+ "}";
assertEquals(json, asJsonString(InstanceSerializer.identityToSlime(identity)));
}
@Test
- public void serialize_instance_refresh() {
+ void serialize_instance_refresh() {
var csr = CertificateTester.createCsr();
var csrPem = Pkcs10CsrUtils.toPem(csr);
var json = "{\"csr\": \"" + csrPem + "\"}";
diff --git a/bundle-plugin-test/integration-test/pom.xml b/bundle-plugin-test/integration-test/pom.xml
index a97d30fbaec..7384bf3aea6 100644
--- a/bundle-plugin-test/integration-test/pom.xml
+++ b/bundle-plugin-test/integration-test/pom.xml
@@ -29,13 +29,18 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-artifact</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-artifact</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
diff --git a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
index faa33542f5c..2e3a3204ef5 100644
--- a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
+++ b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
@@ -2,8 +2,8 @@
package com.yahoo.container.plugin;
import com.yahoo.vespa.config.VespaVersion;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -18,9 +18,9 @@ import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies the bundle jar file built and its manifest.
@@ -38,7 +38,7 @@ public class BundleTest {
private JarFile jarFile;
private Attributes mainAttributes;
- @Before
+ @BeforeEach
public void setup() {
try {
File componentJar = findBundleJar("main");
@@ -60,7 +60,7 @@ public class BundleTest {
}
@Test
- public void require_that_bundle_version_is_added_to_manifest() {
+ void require_that_bundle_version_is_added_to_manifest() {
String bundleVersion = mainAttributes.getValue("Bundle-Version");
// Because of snapshot builds, we can only verify the major version.
@@ -69,12 +69,12 @@ public class BundleTest {
}
@Test
- public void require_that_bundle_symbolic_name_matches_pom_artifactId() {
+ void require_that_bundle_symbolic_name_matches_pom_artifactId() {
assertEquals("main", mainAttributes.getValue("Bundle-SymbolicName"));
}
@Test
- public void require_that_manifest_contains_inferred_imports() {
+ void require_that_manifest_contains_inferred_imports() {
String importPackage = mainAttributes.getValue("Import-Package");
// From SimpleSearcher
@@ -87,35 +87,35 @@ public class BundleTest {
}
@Test
- public void require_that_manifest_contains_manual_imports() {
+ void require_that_manifest_contains_manual_imports() {
String importPackage = mainAttributes.getValue("Import-Package");
assertTrue(importPackage.contains("manualImport.withoutVersion"));
assertTrue(importPackage.contains("manualImport.withVersion;version=\"12.3.4\""));
- for (int i=1; i<=2; ++i)
+ for (int i = 1; i <= 2; ++i)
assertTrue(importPackage.contains("multiple.packages.with.the.same.version" + i + ";version=\"[1,2)\""));
}
@Test
- public void require_that_manifest_contains_exports() {
+ void require_that_manifest_contains_exports() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("com.yahoo.test;version=1.2.3.RELEASE"));
}
- @Test
// TODO: use another jar than jrt, which now pulls in a lot of dependencies that pollute the manifest of the
// generated bundle. (It's compile scoped in pom.xml to be added to the bundle-cp.)
- public void require_that_manifest_contains_bundle_class_path() {
+ @Test
+ void require_that_manifest_contains_bundle_class_path() {
String bundleClassPath = mainAttributes.getValue("Bundle-ClassPath");
assertTrue(bundleClassPath.contains(".,"));
Pattern jrtPattern = Pattern.compile("dependencies/jrt" + snapshotOrVersionOrNone);
- assertTrue("Bundle class path did not contain jrt.", jrtPattern.matcher(bundleClassPath).find());
+ assertTrue(jrtPattern.matcher(bundleClassPath).find(), "Bundle class path did not contain jrt.");
}
@Test
- public void require_that_component_jar_file_contains_compile_artifacts() {
+ void require_that_component_jar_file_contains_compile_artifacts() {
String depJrt = "dependencies/jrt";
Pattern jrtPattern = Pattern.compile(depJrt + snapshotOrVersionOrNone);
ZipEntry jrtEntry = null;
@@ -130,12 +130,12 @@ public class BundleTest {
}
}
}
- assertNotNull("Component jar file did not contain jrt dependency.", jrtEntry);
+ assertNotNull(jrtEntry, "Component jar file did not contain jrt dependency.");
}
@Test
- public void require_that_web_inf_url_is_propagated_to_the_manifest() {
+ void require_that_web_inf_url_is_propagated_to_the_manifest() {
String webInfUrl = mainAttributes.getValue("WebInfUrl");
assertTrue(webInfUrl.contains("/WEB-INF/web.xml"));
}
diff --git a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
index f99f1583324..67a191f1f94 100644
--- a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
+++ b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -10,8 +10,8 @@ import java.util.jar.Attributes;
import java.util.jar.JarFile;
import static com.yahoo.container.plugin.BundleTest.findBundleJar;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies that the 'useArtifactVersionForExportPackages' setting for the bundle-plugin works as intended.
@@ -23,7 +23,7 @@ public class ExportPackageVersionTest {
private static Attributes mainAttributes;
private static String bundleVersion;
- @BeforeClass
+ @BeforeAll
public static void setup() {
try {
File componentJar = findBundleJar("artifact-version-for-exports");
@@ -36,7 +36,7 @@ public class ExportPackageVersionTest {
}
@Test
- public void artifact_version_without_qualifier_is_used_as_export_version() {
+ void artifact_version_without_qualifier_is_used_as_export_version() {
// Bundle-Version is artifact version without qualifier
String expectedExport = "ai.vespa.noversion;version=" + bundleVersion;
@@ -48,13 +48,13 @@ public class ExportPackageVersionTest {
}
@Test
- public void explicit_version_in_ExportPackage_annotation_overrides_artifact_version() {
+ void explicit_version_in_ExportPackage_annotation_overrides_artifact_version() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("ai.vespa.explicitversion;version=2.4.6.RELEASE"));
}
@Test
- public void artifact_version_of_dependency_is_used_as_export_version_for_package_in_compile_scoped_dependency() {
+ void artifact_version_of_dependency_is_used_as_export_version_for_package_in_compile_scoped_dependency() {
String exportPackage = mainAttributes.getValue("Export-Package");
// TODO: This test should have checked for a fixed version of the dependency bundle, different than the main bundle version.
@@ -63,7 +63,7 @@ public class ExportPackageVersionTest {
}
@Test
- public void explicit_version_in_ExportPackage_annotation_overrides_artifact_version_of_compile_scoped_dependency() {
+ void explicit_version_in_ExportPackage_annotation_overrides_artifact_version_of_compile_scoped_dependency() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("ai.vespa.explicitversion_dep;version=3.6.9.RELEASE"));
}
diff --git a/bundle-plugin/pom.xml b/bundle-plugin/pom.xml
index be5d2d59de2..4911f88b61a 100644
--- a/bundle-plugin/pom.xml
+++ b/bundle-plugin/pom.xml
@@ -33,6 +33,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
</dependency>
@@ -51,11 +61,6 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
</dependency>
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
index 62ecd780d7e..97c2bf02d9b 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
@@ -3,17 +3,17 @@ package com.yahoo.container.plugin.bundle;
import com.yahoo.container.plugin.osgi.ExportPackages;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Tony Vaagenes
@@ -37,29 +37,29 @@ public class AnalyzeBundleTest {
}
@Test
- public void require_that_non_osgi_bundles_are_ignored() {
+ void require_that_non_osgi_bundles_are_ignored() {
assertFalse(exportsByPackageName.containsKey("com.yahoo.sample.exported.package.ignored"));
}
@Test
- public void require_that_exports_are_retrieved_from_manifest_in_jars() {
+ void require_that_exports_are_retrieved_from_manifest_in_jars() {
assertEquals(1, exportsByPackageName.keySet().size());
assertTrue(exportsByPackageName.containsKey("com.yahoo.sample.exported.package"));
}
@Test
- public void exported_class_names_can_be_retrieved() {
+ void exported_class_names_can_be_retrieved() {
assertEquals(ExportPackages.packageNames(exports), exports.get(0).getPackageNames().stream().collect(Collectors.toSet()));
}
@Test
- public void require_that_invalid_exports_throws_exception() {
+ void require_that_invalid_exports_throws_exception() {
try {
AnalyzeBundle.exportedPackages(jarFile("errorExport.jar"));
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().contains("Invalid manifest in bundle 'src/test/resources/jar/errorExport.jar'"));
- assertTrue(e.getCause().getMessage(), e.getCause().getMessage().startsWith("Failed parsing Export-Package"));
+ assertTrue(e.getCause().getMessage().startsWith("Failed parsing Export-Package"), e.getCause().getMessage());
}
}
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
index f9f56a31b20..8f78363dab5 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
@@ -17,7 +17,7 @@ import com.yahoo.container.plugin.classanalysis.sampleclasses.MethodAnnotation;
import com.yahoo.container.plugin.classanalysis.sampleclasses.MethodInvocation;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.login.LoginException;
import java.awt.Image;
@@ -29,10 +29,10 @@ import java.util.Optional;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.analyzeClass;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.classFile;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.name;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests that analysis of class files works.
@@ -43,23 +43,23 @@ import static org.junit.Assert.fail;
public class AnalyzeClassTest {
@Test
- public void full_class_name_is_returned() {
+ void full_class_name_is_returned() {
assertEquals(name(Base.class), analyzeClass(Base.class).getName());
}
@Test
- public void base_class_is_included() {
+ void base_class_is_included() {
assertTrue(analyzeClass(Derived.class).getReferencedClasses().contains(name(Base.class)));
}
@Test
- public void implemented_interfaces_are_included() {
+ void implemented_interfaces_are_included() {
assertTrue(analyzeClass(Base.class).getReferencedClasses().containsAll(
List.of(name(Interface1.class), name(Interface2.class))));
}
@Test
- public void interface_can_be_analyzed() {
+ void interface_can_be_analyzed() {
ClassFileMetaData classMetaData = analyzeClass(Interface1.class);
assertEquals(name(Interface1.class), classMetaData.getName());
@@ -67,77 +67,77 @@ public class AnalyzeClassTest {
}
@Test
- public void return_type_is_included() {
+ void return_type_is_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(Image.class)));
}
@Test
- public void parameters_are_included() {
+ void parameters_are_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(Kernel.class)));
}
@Test
- public void exceptions_are_included() {
+ void exceptions_are_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(ImagingOpException.class)));
}
@Test
- public void basic_types_ignored() {
+ void basic_types_ignored() {
List.of("int", "float").forEach(type ->
assertFalse(analyzeClass(Interface1.class).getReferencedClasses().contains(type)));
}
@Test
- public void arrays_of_basic_types_ignored() {
+ void arrays_of_basic_types_ignored() {
List.of("int[]", "int[][]").forEach(type ->
assertFalse(analyzeClass(Interface1.class).getReferencedClasses().contains(type)));
}
@Test
- public void instance_field_types_are_included() {
+ void instance_field_types_are_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(String.class)));
}
@Test
- public void static_field_types_are_included() {
+ void static_field_types_are_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(java.util.List.class)));
}
@Test
- public void field_annotation_is_included() {
+ void field_annotation_is_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void class_annotation_is_included() {
+ void class_annotation_is_included() {
assertTrue(analyzeClass(ClassAnnotation.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void invisible_annotation_not_included() {
+ void invisible_annotation_not_included() {
assertFalse(analyzeClass(InvisibleAnnotation.class).getReferencedClasses().contains(name(InvisibleDummyAnnotation.class)));
}
@Test
- public void method_annotation_is_included() {
+ void method_annotation_is_included() {
assertTrue(analyzeClass(MethodAnnotation.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void export_package_annotations_are_ignored() {
+ void export_package_annotations_are_ignored() {
List.of(ExportPackage.class, Version.class).forEach(type ->
assertFalse(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.package-info"))
.getReferencedClasses().contains(type)));
}
@Test
- public void export_annotations_are_processed() {
+ void export_annotations_are_processed() {
assertEquals(Optional.of(new ExportPackageAnnotation(3, 1, 4, "TEST_QUALIFIER-2")),
Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.package-info")).getExportPackage());
}
@Test
- public void export_annotations_are_validated() {
+ void export_annotations_are_validated() {
try {
Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.invalid.package-info"));
@@ -150,38 +150,38 @@ public class AnalyzeClassTest {
}
@Test
- public void catch_clauses_are_included() {
+ void catch_clauses_are_included() {
assertTrue(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.CatchException"))
.getReferencedClasses().contains(name(LoginException.class)));
}
@Test
- public void class_references_are_included() {
+ void class_references_are_included() {
assertTrue(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.ClassReference"))
.getReferencedClasses().contains(name(Interface1.class)));
}
@Test
- public void return_type_of_method_invocations_are_included() {
+ void return_type_of_method_invocations_are_included() {
assertTrue(analyzeClass(MethodInvocation.class).getReferencedClasses().contains(name(Image.class)));
}
@Test
- public void attributes_are_included() {
+ void attributes_are_included() {
//Uses com/coremedia/iso/Utf8.class from com.googlecode.mp4parser:isoparser:1.0-RC-1
assertTrue(Analyze.analyzeClass(classFile("class/Utf8")).getReferencedClasses()
.contains("org.aspectj.weaver.MethodDeclarationLineNumber"));
}
@Test
- public void switch_statements_are_analyzed() {
+ void switch_statements_are_analyzed() {
var referencedClasses = analyzeClass(SwitchStatement.class).getReferencedClasses();
assertTrue(referencedClasses.contains(name(ImmutableList.class)));
assertTrue(referencedClasses.contains(name(IllegalArgumentException.class)));
}
@Test
- public void records_are_analyzed() {
+ void records_are_analyzed() {
var referencedClasses = analyzeClass(RecordWithOverride.class).getReferencedClasses();
assertTrue(referencedClasses.containsAll(List.of(
name(java.util.List.class),
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
index 0076869eaa5..2b2e83fb024 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
@@ -9,15 +9,15 @@ import com.yahoo.container.plugin.classanalysis.sampleclasses.Fields;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Interface1;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Interface3;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Methods;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.PrintStream;
import java.util.List;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.analyzeClass;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.name;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests that classes used in method bodies are included in the imports list.
@@ -27,52 +27,52 @@ import static org.junit.Assert.assertTrue;
public class AnalyzeMethodBodyTest {
@Test
- public void class_of_locals_are_included() {
+ void class_of_locals_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Base.class)));
}
@Test
- public void class_of_locals_in_static_method_are_included() {
+ void class_of_locals_in_static_method_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Derived.class)));
}
@Test
- public void field_references_are_included() {
+ void field_references_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().containsAll(List.of(name(java.util.List.class), name(Fields.class))));
}
@Test
- public void class_owning_field_is_included() {
+ void class_owning_field_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(System.class)));
}
@Test
- public void class_containing_method_is_included() {
+ void class_containing_method_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(PrintStream.class)));
}
@Test
- public void element_of_new_multidimensional_array_is_included() {
+ void element_of_new_multidimensional_array_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Interface1.class)));
}
@Test
- public void basic_arrays_are_not_included() {
+ void basic_arrays_are_not_included() {
assertFalse(analyzeClass(Methods.class).getReferencedClasses().contains("int[]"));
}
@Test
- public void container_generic_parameters_are_included() {
+ void container_generic_parameters_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Dummy.class)));
}
@Test
- public void functional_interface_usage_is_included() {
+ void functional_interface_usage_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Interface3.class)));
}
@Test
- public void class_owning_method_handler_is_included() {
+ void class_owning_method_handler_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(ClassWithMethod.class)));
}
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
index 31abe785cbe..002959959ec 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.classanalysis;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class PackageTallyTest {
@Test
- public void referenced_packages_missing_from_available_packages_are_detected() {
+ void referenced_packages_missing_from_available_packages_are_detected() {
PackageTally tally = new PackageTally(Map.of(), Set.of("p1", "java.util", "com.yahoo.api.annotations", "missing"));
Set<String> missingPackages = tally.referencedPackagesMissingFrom(Set.of("p1"));
assertEquals(Set.of("missing"), missingPackages);
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
index 3b75d9dcb7d..4edc9c3712d 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
@@ -2,10 +2,10 @@
package com.yahoo.container.plugin.mojo;
import org.apache.maven.plugin.MojoExecutionException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* @author Simon Thoresen Hult
@@ -13,10 +13,10 @@ import static org.junit.Assume.assumeNotNull;
public class GenerateSourcesMojoTest {
@Test
- public void requireThatDefaultConfigGenVersionIsLoadedFromBuildProperties() throws MojoExecutionException {
+ void requireThatDefaultConfigGenVersionIsLoadedFromBuildProperties() throws MojoExecutionException {
String expected = System.getProperty("expectedDefaultConfigGenVersion");
System.out.println("expectedDefaultConfigGenVersion = " + expected);
- assumeNotNull(expected);
+ assumeTrue(expected != null);
String actual = GenerateSourcesMojo.loadDefaultConfigGenVersion();
System.out.println("defaultConfigGenVersion = " + actual);
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
index 2c9b32a325f..de5c0f2be9d 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.plugin.osgi;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
import com.yahoo.container.plugin.osgi.ExportPackages.Parameter;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ public class ExportPackageParserTest {
private final Parameter versionParameter = new Parameter("version", "1.2.3.sample");
@Test
- public void require_that_package_is_parsed_correctly() {
+ void require_that_package_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("sample.exported.package");
assertEquals(1, exports.size());
@@ -28,7 +28,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_version_is_parsed_correctly() {
+ void require_that_version_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("com.yahoo.sample.exported.package;version=\"1.2.3.sample\"");
assertEquals(1, exports.size());
@@ -38,7 +38,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_multiple_packages_with_same_parameters_is_parsed_correctly() {
+ void require_that_multiple_packages_with_same_parameters_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1;exported.package2;version=\"1.2.3.sample\"");
assertEquals(1, exports.size());
@@ -48,7 +48,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_spaces_between_separators_are_allowed() {
+ void require_that_spaces_between_separators_are_allowed() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1 , exported.package2 ; version = \"1.2.3.sample\" ");
assertEquals(2, exports.size());
@@ -61,7 +61,7 @@ public class ExportPackageParserTest {
@SuppressWarnings("unchecked")
@Test
- public void require_that_multiple_parameters_for_a_package_is_parsed_correctly() {
+ void require_that_multiple_parameters_for_a_package_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package;version=\"1.2.3.sample\";param2=true");
assertEquals(1, exports.size());
@@ -70,7 +70,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_multiple_exports_are_parsed_correctly() {
+ void require_that_multiple_exports_are_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1,exported.package2");
assertEquals(2, exports.size());
Export export = exports.get(0);
@@ -100,9 +100,9 @@ public class ExportPackageParserTest {
}
// TODO: MAVEN_OPTS are not propagated by the maven-surefire-plugin. Either try to fix the underlying problem or set -Xss in plugin config.
- @Ignore // Frequently causes StackOverflowError
+ @Disabled // Frequently causes StackOverflowError
@Test
- public void require_that_long_string_literals_do_not_cause_stack_overflow_error() {
+ void require_that_long_string_literals_do_not_cause_stack_overflow_error() {
//From jersey-server-1.13.jar
String exportHeader = "com.sun.jersey.server.impl.wadl;uses:=\"com.sun.jersey.api.model,com.sun.resea"
+ "rch.ws.wadl,com.sun.jersey.api.wadl.config,com.sun.jersey.server.wadl,com.sun."
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
index 29f2be838a1..aa74746bfff 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
@@ -4,9 +4,7 @@ package com.yahoo.container.plugin.osgi;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
import com.yahoo.container.plugin.osgi.ExportPackages.Parameter;
import com.yahoo.container.plugin.osgi.ImportPackages.Import;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashSet;
@@ -15,8 +13,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -34,37 +33,37 @@ public class ImportPackageTest {
}
@Test
- public void require_that_non_implemented_import_with_matching_export_is_included() {
+ void require_that_non_implemented_import_with_matching_export_is_included() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), exports);
assertEquals(1, imports.stream().filter(imp -> imp.packageName().equals(PACKAGE_NAME) && imp.version().isEmpty()).count());
}
@Test
- public void require_that_non_implemented_import_without_matching_export_is_excluded() {
+ void require_that_non_implemented_import_without_matching_export_is_excluded() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), Map.of());
assertTrue(imports.isEmpty());
}
@Test
- public void require_that_implemented_import_with_matching_export_is_excluded() {
+ void require_that_implemented_import_with_matching_export_is_excluded() {
Set<Import> imports = calculateImports(referencedPackages, referencedPackages, exports);
assertTrue(imports.isEmpty());
}
@Test
- public void require_that_version_is_included() {
+ void require_that_version_is_included() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), exportsWithVersion);
assertEquals(1, imports.stream().filter(imp -> imp.packageName().equals(PACKAGE_NAME) && imp.version().equals("1.3")).count());
}
@Test
- public void require_that_all_versions_up_to_the_next_major_version_is_in_range() {
+ void require_that_all_versions_up_to_the_next_major_version_is_in_range() {
assertEquals("[1.2,2)", new Import("foo", Optional.of("1.2")).importVersionRange().get());
}
// TODO: Detecting guava packages should be based on bundle-symbolicName, not package name.
@Test
- public void require_that_for_guava_all_future_major_versions_are_in_range() {
+ void require_that_for_guava_all_future_major_versions_are_in_range() {
Optional<String> rangeWithInfiniteUpperLimit = Optional.of("[18.1," + ImportPackages.INFINITE_VERSION + ")");
assertEquals(rangeWithInfiniteUpperLimit, new Import("com.google.common", Optional.of("18.1")).importVersionRange());
assertEquals(rangeWithInfiniteUpperLimit, new Import("com.google.common.foo", Optional.of("18.1")).importVersionRange());
@@ -72,32 +71,29 @@ public class ImportPackageTest {
}
@Test
- public void require_that_none_version_gives_non_version_range() {
+ void require_that_none_version_gives_non_version_range() {
assertTrue(new Import("foo", Optional.empty()).importVersionRange().isEmpty());
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
- public void require_that_exception_is_thrown_when_major_component_is_non_numeric() {
- expectedException.expect(IllegalArgumentException.class);
- new Import("foo", Optional.of("1notValid.2"));
+ void require_that_exception_is_thrown_when_major_component_is_non_numeric() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new Import("foo", Optional.of("1notValid.2"));
+ });
}
@Test
- public void require_that_osgi_import_supports_missing_version() {
+ void require_that_osgi_import_supports_missing_version() {
assertEquals("com.yahoo.exported", new Import("com.yahoo.exported", Optional.empty()).asOsgiImport());
}
@Test
- public void require_that_osgi_import_version_range_includes_all_versions_from_the_current_up_to_the_next_major_version() {
+ void require_that_osgi_import_version_range_includes_all_versions_from_the_current_up_to_the_next_major_version() {
assertEquals("com.yahoo.exported;version=\"[1.2,2)\"", new Import("com.yahoo.exported", Optional.of("1.2")).asOsgiImport());
}
@Test
- public void require_that_osgi_import_version_range_ignores_qualifier() {
+ void require_that_osgi_import_version_range_ignores_qualifier() {
assertEquals("com.yahoo.exported;version=\"[1.2.3,2)\"", new Import("com.yahoo.exported", Optional.of("1.2.3.qualifier")).asOsgiImport());
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
index ada2f8d208a..d20bbe0e073 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
@@ -5,7 +5,7 @@ package com.yahoo.container.plugin.util;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -14,7 +14,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -24,7 +24,7 @@ public class TestBundleDependencyScopeTranslatorTest {
private static final String GROUP_ID = "com.test";
@Test
- public void test_dependencies_are_translated_to_compile_scope_by_default() {
+ void test_dependencies_are_translated_to_compile_scope_by_default() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
@@ -40,7 +40,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void non_test_scope_dependencies_keep_original_scope() {
+ void non_test_scope_dependencies_keep_original_scope() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "provided", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "provided", List.of("a"));
@@ -61,14 +61,14 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void ordering_in_config_string_determines_translation() {
+ void ordering_in_config_string_determines_translation() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
{
String configString =
"com.test:a-a:runtime," +
- "com.test:a:test,";
+ "com.test:a:test,";
TestBundleDependencyScopeTranslator translator = TestBundleDependencyScopeTranslator.from(artifacts, configString);
assertScope(translator, a, "test");
assertScope(translator, aa, "runtime");
@@ -76,7 +76,7 @@ public class TestBundleDependencyScopeTranslatorTest {
{
String configString =
"com.test:a:test," +
- "com.test:a-a:runtime";
+ "com.test:a-a:runtime";
TestBundleDependencyScopeTranslator translator = TestBundleDependencyScopeTranslator.from(artifacts, configString);
assertScope(translator, a, "test");
assertScope(translator, aa, "test");
@@ -84,7 +84,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void transitive_non_test_dependencies_of_test_dependencies_keep_original_scope() {
+ void transitive_non_test_dependencies_of_test_dependencies_keep_original_scope() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
@@ -108,7 +108,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void different_classifiers_are_handled_separately() {
+ void different_classifiers_are_handled_separately() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact ab = createArtifact(artifacts, "a-b", "provided", List.of("a"));
diff --git a/client/README.md b/client/README.md
index a459ea65b1d..8403e02a485 100644
--- a/client/README.md
+++ b/client/README.md
@@ -1,19 +1,45 @@
<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+![Vespa logo](https://vespa.ai/assets/vespa-logo-color.png)
+
# Vespa clients
+This part of the Vespa repository got Vespa client implementations for operations like
+* deploy
+* read/write
+* query
+
+<!-- ToDo: illustration -->
+
+
## Vespa CLI
The Vespa command-line tool, see the [README](go/README.md).
+Use the Vespa CLI to deploy, feed and query a Vespa application,
+for local, self-hosted or [Vespa Cloud](https://cloud.vespa.ai/) instances.
+
+
+
+## pyvespa
+[pyvespa](https://pyvespa.readthedocs.io/) provides a python API to Vespa -
+use it to create, modify, deploy and interact with running Vespa instances.
+The main pyvespa goal is to allow for faster prototyping
+and to facilitate Machine Learning experiments for Vespa applications.
+
## Vespa FE (fixme: better name and description here)
-This is a work-in-progress javascript app for various use cases.
+This is a [work-in-progress javascript app](js/app) for querying a Vespa application.
+
-## vespa_query_dsl
+----
+
+## Misc
+
+<!-- ToDo: move this / demote this somehow -->
+### vespa_query_dsl
This lib is used for composing Vespa
[YQL queries](https://docs.vespa.ai/en/reference/query-language-reference.html).
-
For usage, refer to the [QTest.java](src/test/java/ai/vespa/client/dsl/QTest.java) unit test.
ToDos:
diff --git a/client/go/cmd/api_key.go b/client/go/cmd/api_key.go
index 00630be7603..a7d405963b0 100644
--- a/client/go/cmd/api_key.go
+++ b/client/go/cmd/api_key.go
@@ -14,7 +14,7 @@ import (
"github.com/vespa-engine/vespa/client/go/vespa"
)
-func newAPIKeyCmd(cli *CLI, deprecated bool) *cobra.Command {
+func newAPIKeyCmd(cli *CLI) *cobra.Command {
var overwriteKey bool
cmd := &cobra.Command{
Use: "api-key",
@@ -46,9 +46,6 @@ always be used. It's not possible to specify a tenant-specific key.`,
return doApiKey(cli, overwriteKey, args)
},
}
- if deprecated {
- cmd.Deprecated = "use 'vespa auth api-key' instead"
- }
cmd.Flags().BoolVarP(&overwriteKey, "force", "f", false, "Force overwrite of existing API key")
cmd.MarkPersistentFlagRequired(applicationFlag)
return cmd
diff --git a/client/go/cmd/api_key_test.go b/client/go/cmd/api_key_test.go
index 3e3a7fa0a31..9c14033f85b 100644
--- a/client/go/cmd/api_key_test.go
+++ b/client/go/cmd/api_key_test.go
@@ -13,9 +13,6 @@ func TestAPIKey(t *testing.T) {
t.Run("auth api-key", func(t *testing.T) {
testAPIKey(t, []string{"auth", "api-key"})
})
- t.Run("api-key (deprecated)", func(t *testing.T) {
- testAPIKey(t, []string{"api-key"})
- })
}
func testAPIKey(t *testing.T, subcommand []string) {
diff --git a/client/go/cmd/cert.go b/client/go/cmd/cert.go
index 581c76b8721..ac4d5085782 100644
--- a/client/go/cmd/cert.go
+++ b/client/go/cmd/cert.go
@@ -16,7 +16,7 @@ import (
"github.com/vespa-engine/vespa/client/go/vespa"
)
-func newCertCmd(cli *CLI, deprecated bool) *cobra.Command {
+func newCertCmd(cli *CLI) *cobra.Command {
var (
noApplicationPackage bool
overwriteCertificate bool
@@ -57,12 +57,7 @@ $ vespa auth cert -a my-tenant.my-app.my-instance path/to/application/package`,
},
}
cmd.Flags().BoolVarP(&overwriteCertificate, "force", "f", false, "Force overwrite of existing certificate and private key")
- if deprecated {
- // TODO: Remove this after 2022-06-01
- cmd.Deprecated = "use 'vespa auth cert' instead"
- } else {
- cmd.Flags().BoolVarP(&noApplicationPackage, "no-add", "N", false, "Do not add certificate to the application package")
- }
+ cmd.Flags().BoolVarP(&noApplicationPackage, "no-add", "N", false, "Do not add certificate to the application package")
cmd.MarkPersistentFlagRequired(applicationFlag)
return cmd
}
diff --git a/client/go/cmd/cert_test.go b/client/go/cmd/cert_test.go
index ee0c21adaf5..fe983e0ad5a 100644
--- a/client/go/cmd/cert_test.go
+++ b/client/go/cmd/cert_test.go
@@ -20,9 +20,6 @@ func TestCert(t *testing.T) {
t.Run("auth cert", func(t *testing.T) {
testCert(t, []string{"auth", "cert"})
})
- t.Run("cert (deprecated)", func(t *testing.T) {
- testCert(t, []string{"cert"})
- })
}
func testCert(t *testing.T, subcommand []string) {
@@ -53,9 +50,6 @@ func TestCertCompressedPackage(t *testing.T) {
t.Run("auth cert", func(t *testing.T) {
testCertCompressedPackage(t, []string{"auth", "cert"})
})
- t.Run("cert (deprecated)", func(t *testing.T) {
- testCertCompressedPackage(t, []string{"cert"})
- })
}
func testCertCompressedPackage(t *testing.T, subcommand []string) {
diff --git a/client/go/cmd/config.go b/client/go/cmd/config.go
index b8a7cb9c24c..8f81f8e359f 100644
--- a/client/go/cmd/config.go
+++ b/client/go/cmd/config.go
@@ -62,6 +62,14 @@ and "hosted" targets. See https://cloud.vespa.ai/en/tenant-apps-instances for
more details. This has no default value. Examples: tenant1.app1,
tenant1.app1.instance1
+cluster
+
+Specifies the container cluster to manage. If left empty (default) and the
+application has only one container cluster, that cluster is chosen
+automatically. When an application has multiple cluster this must be set a
+valid cluster name, as specified in services.xml. See
+https://docs.vespa.ai/en/reference/services-container.html for more details.
+
color
Controls how Vespa CLI uses colors. Setting this to "auto" (default) enables
@@ -353,6 +361,11 @@ func (c *Config) application() (vespa.ApplicationID, error) {
return application, nil
}
+func (c *Config) cluster() string {
+ cluster, _ := c.get(clusterFlag)
+ return cluster
+}
+
func (c *Config) deploymentIn(system vespa.System) (vespa.Deployment, error) {
zone := system.DefaultZone
zoneName, ok := c.get(zoneFlag)
@@ -558,6 +571,9 @@ func (c *Config) set(option, value string) error {
case instanceFlag:
c.config.Set(option, value)
return nil
+ case clusterFlag:
+ c.config.Set(clusterFlag, value)
+ return nil
case waitFlag:
if n, err := strconv.Atoi(value); err != nil || n < 0 {
return fmt.Errorf("%s option must be an integer >= 0, got %q", option, value)
diff --git a/client/go/cmd/config_test.go b/client/go/cmd/config_test.go
index 86c7e2695fa..7d701931a04 100644
--- a/client/go/cmd/config_test.go
+++ b/client/go/cmd/config_test.go
@@ -35,6 +35,11 @@ func TestConfig(t *testing.T) {
assertConfigCommand(t, configHome, "", "config", "set", "application", "t1.a1")
assertConfigCommand(t, configHome, "application = t1.a1.default\n", "config", "get", "application")
+ // cluster
+ assertConfigCommand(t, configHome, "cluster = <unset>\n", "config", "get", "cluster")
+ assertConfigCommand(t, configHome, "", "config", "set", "cluster", "feed")
+ assertConfigCommand(t, configHome, "cluster = feed\n", "config", "get", "cluster")
+
// instance
assertConfigCommand(t, configHome, "instance = <unset>\n", "config", "get", "instance")
assertConfigCommand(t, configHome, "", "config", "set", "instance", "i2")
@@ -99,6 +104,7 @@ func TestLocalConfig(t *testing.T) {
// get merges settings from local and global config
assertConfigCommand(t, configHome, "", "config", "set", "--local", "application", "t1.a1")
assertConfigCommand(t, configHome, `application = t1.a1.default
+cluster = <unset>
color = auto
instance = foo
quiet = false
diff --git a/client/go/cmd/curl.go b/client/go/cmd/curl.go
index 41e37f5319b..4b2eb9ba987 100644
--- a/client/go/cmd/curl.go
+++ b/client/go/cmd/curl.go
@@ -38,7 +38,7 @@ $ vespa curl -- -v --data-urlencode "yql=select * from music where album contain
if err != nil {
return err
}
- service, err := target.Service(curlService, 0, 0, "")
+ service, err := target.Service(curlService, 0, 0, cli.config.cluster())
if err != nil {
return err
}
diff --git a/client/go/cmd/curl_test.go b/client/go/cmd/curl_test.go
index 520cf41e308..3eca0726bb4 100644
--- a/client/go/cmd/curl_test.go
+++ b/client/go/cmd/curl_test.go
@@ -14,6 +14,7 @@ func TestCurl(t *testing.T) {
cli.Environment["VESPA_CLI_ENDPOINTS"] = "{\"endpoints\":[{\"cluster\":\"container\",\"url\":\"http://127.0.0.1:8080\"}]}"
assert.Nil(t, cli.Run("config", "set", "application", "t1.a1.i1"))
assert.Nil(t, cli.Run("config", "set", "target", "cloud"))
+ assert.Nil(t, cli.Run("config", "set", "cluster", "container"))
assert.Nil(t, cli.Run("auth", "api-key"))
assert.Nil(t, cli.Run("auth", "cert", "--no-add"))
diff --git a/client/go/cmd/deploy.go b/client/go/cmd/deploy.go
index 930e25dddc7..e72667e49b6 100644
--- a/client/go/cmd/deploy.go
+++ b/client/go/cmd/deploy.go
@@ -178,7 +178,7 @@ func waitForQueryService(cli *CLI, target vespa.Target, sessionOrRunID int64) er
}
if timeout > 0 {
log.Println()
- _, err := cli.service(target, vespa.QueryService, sessionOrRunID, "")
+ _, err := cli.service(target, vespa.QueryService, sessionOrRunID, cli.config.cluster())
return err
}
return nil
diff --git a/client/go/cmd/document.go b/client/go/cmd/document.go
index 32648393492..b2f71121d1a 100644
--- a/client/go/cmd/document.go
+++ b/client/go/cmd/document.go
@@ -178,7 +178,7 @@ func documentService(cli *CLI) (*vespa.Service, error) {
if err != nil {
return nil, err
}
- return cli.service(target, vespa.DocumentService, 0, "")
+ return cli.service(target, vespa.DocumentService, 0, cli.config.cluster())
}
func operationOptions(stderr io.Writer, printCurl bool, timeoutSecs int) vespa.OperationOptions {
diff --git a/client/go/cmd/logfmt/handleline.go b/client/go/cmd/logfmt/handleline.go
new file mode 100644
index 00000000000..33a1a1b386b
--- /dev/null
+++ b/client/go/cmd/logfmt/handleline.go
@@ -0,0 +1,116 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// handle a line in "vespa.log" format; do filtering and formatting as specified in opts
+
+func handleLine(opts *Options, line string) (output string, err error) {
+ fields := strings.SplitN(line, "\t", 7)
+ if len(fields) < 7 {
+ return "", fmt.Errorf("not enough fields: '%s'", line)
+ }
+ timestampfield := fields[0] // seconds, optional fractional seconds
+ hostfield := fields[1]
+ pidfield := fields[2] // pid, optional tid
+ servicefield := fields[3]
+ componentfield := fields[4]
+ levelfield := fields[5]
+ messagefields := fields[6:]
+
+ if !opts.showLevel(levelfield) {
+ return "", nil
+ }
+ if opts.OnlyHostname != "" && opts.OnlyHostname != hostfield {
+ return "", nil
+ }
+ if opts.OnlyPid != "" && opts.OnlyPid != pidfield {
+ return "", nil
+ }
+ if opts.OnlyService != "" && opts.OnlyService != servicefield {
+ return "", nil
+ }
+ if opts.OnlyInternal && !isInternal(componentfield) {
+ return "", nil
+ }
+ if opts.ComponentFilter.unmatched(componentfield) {
+ return "", nil
+ }
+ if opts.MessageFilter.unmatched(strings.Join(messagefields, "\t")) {
+ return "", nil
+ }
+
+ var buf strings.Builder
+
+ if opts.showField("fmttime") {
+ secs, err := strconv.ParseFloat(timestampfield, 64)
+ if err != nil {
+ return "", err
+ }
+ nsecs := int64(secs * 1e9)
+ timestamp := time.Unix(0, nsecs)
+ if opts.showField("usecs") {
+ buf.WriteString(timestamp.Format("[2006-01-02 15:04:05.000000] "))
+ } else if opts.showField("msecs") {
+ buf.WriteString(timestamp.Format("[2006-01-02 15:04:05.000] "))
+ } else {
+ buf.WriteString(timestamp.Format("[2006-01-02 15:04:05] "))
+ }
+ } else if opts.showField("time") {
+ buf.WriteString(timestampfield)
+ buf.WriteString(" ")
+ }
+ if opts.showField("host") {
+ buf.WriteString(fmt.Sprintf("%-8s ", hostfield))
+ }
+ if opts.showField("level") {
+ buf.WriteString(fmt.Sprintf("%-7s ", strings.ToUpper(levelfield)))
+ }
+ if opts.showField("pid") {
+ // OnlyPid, _, _ := strings.Cut(pidfield, "/")
+ buf.WriteString(fmt.Sprintf("%6s ", pidfield))
+ }
+ if opts.showField("service") {
+ if opts.TruncateService {
+ buf.WriteString(fmt.Sprintf("%-9.9s ", servicefield))
+ } else {
+ buf.WriteString(fmt.Sprintf("%-16s ", servicefield))
+ }
+ }
+ if opts.showField("component") {
+ if opts.TruncateComponent {
+ buf.WriteString(fmt.Sprintf("%-15.15s ", componentfield))
+ } else {
+ buf.WriteString(fmt.Sprintf("%s\t", componentfield))
+ }
+ }
+ if opts.showField("message") {
+ var msgBuf strings.Builder
+ for idx, message := range messagefields {
+ if idx > 0 {
+ msgBuf.WriteString("\n\t")
+ }
+ if opts.DequoteNewlines {
+ message = strings.ReplaceAll(message, "\\n\\t", "\n\t")
+ message = strings.ReplaceAll(message, "\\n", "\n\t")
+ }
+ msgBuf.WriteString(message)
+ }
+ message := msgBuf.String()
+ if strings.Contains(message, "\n") {
+ buf.WriteString("\n\t")
+ }
+ buf.WriteString(message)
+ }
+ buf.WriteString("\n")
+ output = buf.String()
+ return
+}
diff --git a/client/go/cmd/logfmt/internal.go b/client/go/cmd/logfmt/internal.go
new file mode 100644
index 00000000000..992c537f939
--- /dev/null
+++ b/client/go/cmd/logfmt/internal.go
@@ -0,0 +1,106 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "strings"
+)
+
+// is componentName a vespa-internal name?
+
+func isInternal(componentName string) bool {
+ cs := strings.Split(componentName, ".")
+ if len(cs) == 0 || cs[0] != "Container" {
+ return true
+ }
+ if len(cs) < 3 {
+ return false
+ }
+ if cs[1] == "ai" && cs[2] == "vespa" {
+ return true
+ }
+ if cs[1] == "com" && cs[2] == "yahoo" && len(cs) > 3 {
+ return internalComYahooNames[cs[3]]
+ }
+ return false
+}
+
+// a constant:
+var internalComYahooNames = map[string]bool{
+ "abicheck": true,
+ "api": true,
+ "application": true,
+ "binaryprefix": true,
+ "clientmetrics": true,
+ "cloud": true,
+ "collections": true,
+ "component": true,
+ "compress": true,
+ "concurrent": true,
+ "configtest": true,
+ "config": true,
+ "container": true,
+ "data": true,
+ "docprocs": true,
+ "docproc": true,
+ "documentapi": true,
+ "documentmodel": true,
+ "document": true,
+ "dummyreceiver": true,
+ "embedding": true,
+ "errorhandling": true,
+ "exception": true,
+ "feedapi": true,
+ "feedhandler": true,
+ "filedistribution": true,
+ "fs4": true,
+ "fsa": true,
+ "geo": true,
+ "io": true,
+ "javacc": true,
+ "jdisc": true,
+ "jrt": true,
+ "lang": true,
+ "language": true,
+ "logserver": true,
+ "log": true,
+ "messagebus": true,
+ "metrics": true,
+ "nativec": true,
+ "net": true,
+ "osgi": true,
+ "path": true,
+ "plugin": true,
+ "prelude": true,
+ "processing": true,
+ "protect": true,
+ "reflection": true,
+ "restapi": true,
+ "schema": true,
+ "searchdefinition": true,
+ "searchlib": true,
+ "search": true,
+ "security": true,
+ "slime": true,
+ "socket": true,
+ "statistics": true,
+ "stream": true,
+ "system": true,
+ "tensor": true,
+ "test": true,
+ "text": true,
+ "time": true,
+ "transaction": true,
+ "vdslib": true,
+ "vespaclient": true,
+ "vespafeeder": true,
+ "vespaget": true,
+ "vespastat": true,
+ "vespasummarybenchmark": true,
+ "vespa": true,
+ "vespavisit": true,
+ "vespaxmlparser": true,
+ "yolean": true,
+}
diff --git a/client/go/cmd/logfmt/internal_names.txt b/client/go/cmd/logfmt/internal_names.txt
new file mode 100644
index 00000000000..cc554546fcc
--- /dev/null
+++ b/client/go/cmd/logfmt/internal_names.txt
@@ -0,0 +1,782 @@
+sentinel.sentinel.config
+searchnode.eval.Test
+Container.ai.vespa.client.dsl.Test
+Container.ai.vespa.cloud.Test
+Container.ai.vespa.embedding.Test
+Container.ai.vespa.explicitversion.Test
+Container.ai.vespa.explicitversion_dep.Test
+Container.ai.vespa.feed.client.Test
+Container.ai.vespa.feed.client.impl.Test
+Container.ai.vespa.hosted.api.Test
+Container.ai.vespa.hosted.cd.Test
+Container.ai.vespa.hosted.cd.cloud.impl.Test
+Container.ai.vespa.hosted.cd.commons.Test
+Container.ai.vespa.hosted.cd.internal.Test
+Container.ai.vespa.hosted.client.Test
+Container.ai.vespa.hosted.plugin.Test
+Container.ai.vespa.http.Test
+Container.ai.vespa.intellij.schema.Test
+Container.ai.vespa.intellij.schema.findUsages.Test
+Container.ai.vespa.intellij.schema.hierarchy.Test
+Container.ai.vespa.intellij.schema.lexer.Test
+Container.ai.vespa.intellij.schema.model.Test
+Container.ai.vespa.intellij.schema.parser.Test
+Container.ai.vespa.intellij.schema.psi.Test
+Container.ai.vespa.intellij.schema.psi.impl.Test
+Container.ai.vespa.intellij.schema.structure.Test
+Container.ai.vespa.intellij.schema.utils.Test
+Container.ai.vespa.logserver.protocol.Test
+Container.ai.vespa.metricsproxy.core.Test
+Container.ai.vespa.metricsproxy.http.Test
+Container.ai.vespa.metricsproxy.http.application.Test
+Container.ai.vespa.metricsproxy.http.metrics.Test
+Container.ai.vespa.metricsproxy.http.prometheus.Test
+Container.ai.vespa.metricsproxy.http.yamas.Test
+Container.ai.vespa.metricsproxy.metric.Test
+Container.ai.vespa.metricsproxy.metric.dimensions.Test
+Container.ai.vespa.metricsproxy.metric.model.Test
+Container.ai.vespa.metricsproxy.metric.model.json.Test
+Container.ai.vespa.metricsproxy.metric.model.processing.Test
+Container.ai.vespa.metricsproxy.metric.model.prometheus.Test
+Container.ai.vespa.metricsproxy.node.Test
+Container.ai.vespa.metricsproxy.rpc.Test
+Container.ai.vespa.metricsproxy.service.Test
+Container.ai.vespa.metricsproxy.telegraf.Test
+Container.ai.vespa.modelintegration.evaluator.Test
+Container.ai.vespa.models.evaluation.Test
+Container.ai.vespa.models.handler.Test
+Container.ai.vespa.noversion.Test
+Container.ai.vespa.noversion_dep.Test
+Container.ai.vespa.rankingexpression.importer.Test
+Container.ai.vespa.rankingexpression.importer.configmodelview.Test
+Container.ai.vespa.rankingexpression.importer.lightgbm.Test
+Container.ai.vespa.rankingexpression.importer.onnx.Test
+Container.ai.vespa.rankingexpression.importer.operations.Test
+Container.ai.vespa.rankingexpression.importer.tensorflow.Test
+Container.ai.vespa.rankingexpression.importer.vespa.Test
+Container.ai.vespa.rankingexpression.importer.vespa.parser.Test
+Container.ai.vespa.rankingexpression.importer.xgboost.Test
+Container.ai.vespa.reindexing.Test
+Container.ai.vespa.reindexing.http.Test
+Container.ai.vespa.searchlib.searchprotocol.protobuf.Test
+Container.ai.vespa.util.http.hc4.Test
+Container.ai.vespa.util.http.hc4.retry.Test
+Container.ai.vespa.util.http.hc5.Test
+Container.ai.vespa.validation.Test
+Container.com.yahoo.abicheck.classtree.Test
+Container.com.yahoo.abicheck.collector.Test
+Container.com.yahoo.abicheck.mojo.Test
+Container.com.yahoo.abicheck.setmatcher.Test
+Container.com.yahoo.abicheck.signature.Test
+Container.com.yahoo.api.annotations.Test
+Container.com.yahoo.application.Test
+Container.com.yahoo.application.container.Test
+Container.com.yahoo.application.container.handler.Test
+Container.com.yahoo.application.container.impl.Test
+Container.com.yahoo.application.content.Test
+Container.com.yahoo.application.preprocessor.Test
+Container.com.yahoo.binaryprefix.Test
+Container.com.yahoo.clientmetrics.Test
+Container.com.yahoo.cloud.config.Test
+Container.com.yahoo.collections.Test
+Container.com.yahoo.component.Test
+Container.com.yahoo.component.annotation.Test
+Container.com.yahoo.component.chain.Test
+Container.com.yahoo.component.chain.dependencies.Test
+Container.com.yahoo.component.chain.dependencies.ordering.Test
+Container.com.yahoo.component.chain.model.Test
+Container.com.yahoo.component.provider.Test
+Container.com.yahoo.compress.Test
+Container.com.yahoo.concurrent.Test
+Container.com.yahoo.concurrent.classlock.Test
+Container.com.yahoo.concurrent.maintenance.Test
+Container.com.yahoo.config.Test
+Container.com.yahoo.config.application.Test
+Container.com.yahoo.config.application.api.Test
+Container.com.yahoo.config.application.api.xml.Test
+Container.com.yahoo.config.codegen.Test
+Container.com.yahoo.config.docproc.Test
+Container.com.yahoo.config.ini.Test
+Container.com.yahoo.config.model.Test
+Container.com.yahoo.config.model.admin.Test
+Container.com.yahoo.config.model.api.Test
+Container.com.yahoo.config.model.api.container.Test
+Container.com.yahoo.config.model.application.Test
+Container.com.yahoo.config.model.application.provider.Test
+Container.com.yahoo.config.model.builder.xml.Test
+Container.com.yahoo.config.model.deploy.Test
+Container.com.yahoo.config.model.graph.Test
+Container.com.yahoo.config.model.producer.Test
+Container.com.yahoo.config.model.provision.Test
+Container.com.yahoo.config.model.test.Test
+Container.com.yahoo.config.provision.Test
+Container.com.yahoo.config.provision.exception.Test
+Container.com.yahoo.config.provision.host.Test
+Container.com.yahoo.config.provisioning.Test
+Container.com.yahoo.config.provision.security.Test
+Container.com.yahoo.config.provision.serialization.Test
+Container.com.yahoo.config.provision.zone.Test
+Container.com.yahoo.config.subscription.Test
+Container.com.yahoo.config.subscription.impl.Test
+Container.com.yahoo.configtest.Test
+Container.com.yahoo.config.text.Test
+Container.com.yahoo.container.Test
+Container.com.yahoo.container.bundle.Test
+Container.com.yahoo.container.core.Test
+Container.com.yahoo.container.core.config.Test
+Container.com.yahoo.container.core.config.testutil.Test
+Container.com.yahoo.container.core.document.Test
+Container.com.yahoo.container.core.documentapi.Test
+Container.com.yahoo.container.core.http.Test
+Container.com.yahoo.container.core.identity.Test
+Container.com.yahoo.container.di.Test
+Container.com.yahoo.container.di.componentgraph.Test
+Container.com.yahoo.container.di.componentgraph.core.Test
+Container.com.yahoo.container.di.componentgraph.cycle.Test
+Container.com.yahoo.container.di.config.Test
+Container.com.yahoo.container.handler.Test
+Container.com.yahoo.container.handler.metrics.Test
+Container.com.yahoo.container.handler.observability.Test
+Container.com.yahoo.container.handler.test.Test
+Container.com.yahoo.container.handler.threadpool.Test
+Container.com.yahoo.container.http.Test
+Container.com.yahoo.container.http.filter.Test
+Container.com.yahoo.container.jdisc.Test
+Container.com.yahoo.container.jdisc.athenz.Test
+Container.com.yahoo.container.jdisc.component.Test
+Container.com.yahoo.container.jdisc.config.Test
+Container.com.yahoo.container.jdisc.messagebus.Test
+Container.com.yahoo.container.jdisc.metric.Test
+Container.com.yahoo.container.jdisc.metric.state.Test
+Container.com.yahoo.container.jdisc.secretstore.Test
+Container.com.yahoo.container.jdisc.state.Test
+Container.com.yahoo.container.jdisc.utils.Test
+Container.com.yahoo.container.logging.Test
+Container.com.yahoo.container.plugin.bundle.Test
+Container.com.yahoo.container.plugin.classanalysis.Test
+Container.com.yahoo.container.plugin.mojo.Test
+Container.com.yahoo.container.plugin.osgi.Test
+Container.com.yahoo.container.plugin.util.Test
+Container.com.yahoo.container.protect.Test
+Container.com.yahoo.container.standalone.Test
+Container.com.yahoo.container.usability.Test
+Container.com.yahoo.data.Test
+Container.com.yahoo.data.access.Test
+Container.com.yahoo.data.access.simple.Test
+Container.com.yahoo.data.access.slime.Test
+Container.com.yahoo.docproc.Test
+Container.com.yahoo.docproc.impl.Test
+Container.com.yahoo.docproc.jdisc.Test
+Container.com.yahoo.docproc.jdisc.messagebus.Test
+Container.com.yahoo.docproc.jdisc.metric.Test
+Container.com.yahoo.docproc.jdisc.observability.Test
+Container.com.yahoo.docproc.proxy.Test
+Container.com.yahoo.docprocs.indexing.Test
+Container.com.yahoo.document.Test
+Container.com.yahoo.document.annotation.Test
+Container.com.yahoo.documentapi.Test
+Container.com.yahoo.documentapi.local.Test
+Container.com.yahoo.documentapi.messagebus.Test
+Container.com.yahoo.documentapi.messagebus.protocol.Test
+Container.com.yahoo.documentapi.messagebus.systemstate.rule.Test
+Container.com.yahoo.documentapi.metrics.Test
+Container.com.yahoo.document.config.Test
+Container.com.yahoo.document.datatypes.Test
+Container.com.yahoo.document.fieldpathupdate.Test
+Container.com.yahoo.document.fieldset.Test
+Container.com.yahoo.document.idstring.Test
+Container.com.yahoo.document.internal.Test
+Container.com.yahoo.document.json.Test
+Container.com.yahoo.document.json.document.Test
+Container.com.yahoo.document.json.readers.Test
+Container.com.yahoo.documentmodel.Test
+Container.com.yahoo.document.predicate.Test
+Container.com.yahoo.document.restapi.resource.Test
+Container.com.yahoo.document.select.Test
+Container.com.yahoo.document.select.convert.Test
+Container.com.yahoo.document.select.parser.Test
+Container.com.yahoo.document.select.rule.Test
+Container.com.yahoo.document.select.simple.Test
+Container.com.yahoo.document.serialization.Test
+Container.com.yahoo.document.update.Test
+Container.com.yahoo.dummyreceiver.Test
+Container.com.yahoo.embedding.Test
+Container.com.yahoo.errorhandling.Test
+Container.com.yahoo.exception.Test
+Container.com.yahoo.feedapi.Test
+Container.com.yahoo.feedhandler.Test
+Container.com.yahoo.filedistribution.fileacquirer.Test
+Container.com.yahoo.fs4.Test
+Container.com.yahoo.fsa.Test
+Container.com.yahoo.fsa.conceptnet.Test
+Container.com.yahoo.fsa.segmenter.Test
+Container.com.yahoo.fsa.topicpredictor.Test
+Container.com.yahoo.geo.Test
+Container.com.yahoo.io.Test
+Container.com.yahoo.io.reader.Test
+Container.com.yahoo.javacc.Test
+Container.com.yahoo.jdisc.Test
+Container.com.yahoo.jdisc.application.Test
+Container.com.yahoo.jdisc.bundle.Test
+Container.com.yahoo.jdisc.bundle.a.Test
+Container.com.yahoo.jdisc.bundle.b.Test
+Container.com.yahoo.jdisc.bundle.c.Test
+Container.com.yahoo.jdisc.bundle.d.Test
+Container.com.yahoo.jdisc.bundle.e.Test
+Container.com.yahoo.jdisc.bundle.f.Test
+Container.com.yahoo.jdisc.bundle.g.Test
+Container.com.yahoo.jdisc.bundle.g_act.Test
+Container.com.yahoo.jdisc.bundle.h.Test
+Container.com.yahoo.jdisc.bundle.i.Test
+Container.com.yahoo.jdisc.bundle.j.Test
+Container.com.yahoo.jdisc.bundle.k.Test
+Container.com.yahoo.jdisc.bundle.l.Test
+Container.com.yahoo.jdisc.bundle.m.Test
+Container.com.yahoo.jdisc.bundle.my_act.Test
+Container.com.yahoo.jdisc.bundle.n.Test
+Container.com.yahoo.jdisc.bundle.o.Test
+Container.com.yahoo.jdisc.bundle.p.Test
+Container.com.yahoo.jdisc.bundle.q.Test
+Container.com.yahoo.jdisc.bundle.r.Test
+Container.com.yahoo.jdisc.bundle.s.Test
+Container.com.yahoo.jdisc.bundle.t.Test
+Container.com.yahoo.jdisc.bundle.u.Test
+Container.com.yahoo.jdisc.client.Test
+Container.com.yahoo.jdisc.cloud.aws.Test
+Container.com.yahoo.jdisc.core.Test
+Container.com.yahoo.jdisc.handler.Test
+Container.com.yahoo.jdisc.http.Test
+Container.com.yahoo.jdisc.http.cloud.Test
+Container.com.yahoo.jdisc.http.filter.Test
+Container.com.yahoo.jdisc.http.filter.chain.Test
+Container.com.yahoo.jdisc.http.filter.security.athenz.Test
+Container.com.yahoo.jdisc.http.filter.security.base.Test
+Container.com.yahoo.jdisc.http.filter.security.cors.Test
+Container.com.yahoo.jdisc.http.filter.security.csp.Test
+Container.com.yahoo.jdisc.http.filter.security.misc.Test
+Container.com.yahoo.jdisc.http.filter.security.rule.Test
+Container.com.yahoo.jdisc.http.filter.util.Test
+Container.com.yahoo.jdisc.http.server.jetty.Test
+Container.com.yahoo.jdisc.http.server.jetty.testutils.Test
+Container.com.yahoo.jdisc.http.ssl.impl.Test
+Container.com.yahoo.jdisc.metrics.yamasconsumer.cloud.Test
+Container.com.yahoo.jdisc.refcount.Test
+Container.com.yahoo.jdisc.service.Test
+Container.com.yahoo.jdisc.statistics.Test
+Container.com.yahoo.jdisc.test.Test
+Container.com.yahoo.jrt.Test
+Container.com.yahoo.jrt.slobrok.Test
+Container.com.yahoo.jrt.slobrok.api.Test
+Container.com.yahoo.jrt.slobrok.server.Test
+Container.com.yahoo.jrt.tool.Test
+Container.com.yahoo.lang.Test
+Container.com.yahoo.language.Test
+Container.com.yahoo.language.detect.Test
+Container.com.yahoo.language.opennlp.Test
+Container.com.yahoo.language.process.Test
+Container.com.yahoo.language.provider.Test
+Container.com.yahoo.language.sentencepiece.Test
+Container.com.yahoo.language.simple.Test
+Container.com.yahoo.language.simple.kstem.Test
+Container.com.yahoo.language.tools.Test
+Container.com.yahoo.language.wordpiece.Test
+Container.com.yahoo.log.Test
+Container.com.yahoo.log.event.Test
+Container.com.yahoo.log.impl.Test
+Container.com.yahoo.logserver.Test
+Container.com.yahoo.logserver.filter.Test
+Container.com.yahoo.logserver.handlers.Test
+Container.com.yahoo.logserver.handlers.archive.Test
+Container.com.yahoo.logserver.handlers.logmetrics.Test
+Container.com.yahoo.logserver.testutils.Test
+Container.com.yahoo.messagebus.Test
+Container.com.yahoo.messagebus.jdisc.Test
+Container.com.yahoo.messagebus.jdisc.test.Test
+Container.com.yahoo.messagebus.network.Test
+Container.com.yahoo.messagebus.network.local.Test
+Container.com.yahoo.messagebus.network.rpc.Test
+Container.com.yahoo.messagebus.network.rpc.test.Test
+Container.com.yahoo.messagebus.routing.Test
+Container.com.yahoo.messagebus.routing.test.Test
+Container.com.yahoo.messagebus.shared.Test
+Container.com.yahoo.messagebus.test.Test
+Container.com.yahoo.metrics.Test
+Container.com.yahoo.metrics.simple.Test
+Container.com.yahoo.metrics.simple.jdisc.Test
+Container.com.yahoo.metrics.simple.runtime.Test
+Container.com.yahoo.nativec.Test
+Container.com.yahoo.net.Test
+Container.com.yahoo.osgi.Test
+Container.com.yahoo.osgi.annotation.Test
+Container.com.yahoo.osgi.provider.model.Test
+Container.com.yahoo.path.Test
+Container.com.yahoo.plugin.Test
+Container.com.yahoo.prelude.Test
+Container.com.yahoo.prelude.cluster.Test
+Container.com.yahoo.prelude.fastsearch.Test
+Container.com.yahoo.prelude.hitfield.Test
+Container.com.yahoo.prelude.query.Test
+Container.com.yahoo.prelude.query.parser.Test
+Container.com.yahoo.prelude.query.textualrepresentation.Test
+Container.com.yahoo.prelude.querytransform.Test
+Container.com.yahoo.prelude.searcher.Test
+Container.com.yahoo.prelude.semantics.Test
+Container.com.yahoo.prelude.semantics.benchmark.Test
+Container.com.yahoo.prelude.semantics.config.Test
+Container.com.yahoo.prelude.semantics.engine.Test
+Container.com.yahoo.prelude.semantics.parser.Test
+Container.com.yahoo.prelude.semantics.rule.Test
+Container.com.yahoo.prelude.statistics.Test
+Container.com.yahoo.processing.Test
+Container.com.yahoo.processing.execution.Test
+Container.com.yahoo.processing.execution.chain.Test
+Container.com.yahoo.processing.handler.Test
+Container.com.yahoo.processing.impl.Test
+Container.com.yahoo.processing.processors.Test
+Container.com.yahoo.processing.rendering.Test
+Container.com.yahoo.processing.request.Test
+Container.com.yahoo.processing.request.properties.Test
+Container.com.yahoo.processing.response.Test
+Container.com.yahoo.processing.test.Test
+Container.com.yahoo.protect.Test
+Container.com.yahoo.reflection.Test
+Container.com.yahoo.restapi.Test
+Container.com.yahoo.schema.Test
+Container.com.yahoo.schema.derived.Test
+Container.com.yahoo.schema.derived.validation.Test
+Container.com.yahoo.schema.document.Test
+Container.com.yahoo.schema.document.annotation.Test
+Container.com.yahoo.schema.expressiontransforms.Test
+Container.com.yahoo.schema.fieldoperation.Test
+Container.com.yahoo.schema.parser.Test
+Container.com.yahoo.schema.processing.Test
+Container.com.yahoo.schema.processing.multifieldresolver.Test
+Container.com.yahoo.search.Test
+Container.com.yahoo.search.cluster.Test
+Container.com.yahoo.search.config.Test
+Container.com.yahoo.search.dispatch.Test
+Container.com.yahoo.search.dispatch.rpc.Test
+Container.com.yahoo.search.dispatch.searchcluster.Test
+Container.com.yahoo.search.federation.Test
+Container.com.yahoo.search.federation.selection.Test
+Container.com.yahoo.search.federation.sourceref.Test
+Container.com.yahoo.search.grouping.Test
+Container.com.yahoo.search.grouping.request.Test
+Container.com.yahoo.search.grouping.request.parser.Test
+Container.com.yahoo.search.grouping.result.Test
+Container.com.yahoo.search.grouping.vespa.Test
+Container.com.yahoo.search.handler.Test
+Container.com.yahoo.search.handler.observability.Test
+Container.com.yahoo.search.intent.model.Test
+Container.com.yahoo.searchlib.Test
+Container.com.yahoo.searchlib.aggregation.Test
+Container.com.yahoo.searchlib.aggregation.hll.Test
+Container.com.yahoo.searchlib.document.Test
+Container.com.yahoo.searchlib.expression.Test
+Container.com.yahoo.searchlib.gbdt.Test
+Container.com.yahoo.searchlib.rankingexpression.Test
+Container.com.yahoo.searchlib.rankingexpression.evaluation.Test
+Container.com.yahoo.searchlib.rankingexpression.evaluation.gbdtoptimization.Test
+Container.com.yahoo.searchlib.rankingexpression.evaluation.tensoroptimization.Test
+Container.com.yahoo.searchlib.rankingexpression.parser.Test
+Container.com.yahoo.searchlib.rankingexpression.rule.Test
+Container.com.yahoo.searchlib.rankingexpression.transform.Test
+Container.com.yahoo.searchlib.ranking.features.Test
+Container.com.yahoo.searchlib.ranking.features.fieldmatch.Test
+Container.com.yahoo.searchlib.tensor.Test
+Container.com.yahoo.searchlib.treenet.Test
+Container.com.yahoo.searchlib.treenet.parser.Test
+Container.com.yahoo.searchlib.treenet.rule.Test
+Container.com.yahoo.search.match.Test
+Container.com.yahoo.search.pagetemplates.Test
+Container.com.yahoo.search.pagetemplates.config.Test
+Container.com.yahoo.search.pagetemplates.engine.Test
+Container.com.yahoo.search.pagetemplates.engine.resolvers.Test
+Container.com.yahoo.search.pagetemplates.model.Test
+Container.com.yahoo.search.pagetemplates.result.Test
+Container.com.yahoo.search.predicate.Test
+Container.com.yahoo.search.predicate.annotator.Test
+Container.com.yahoo.search.predicate.benchmarks.Test
+Container.com.yahoo.search.predicate.index.Test
+Container.com.yahoo.search.predicate.index.conjunction.Test
+Container.com.yahoo.search.predicate.optimization.Test
+Container.com.yahoo.search.predicate.serialization.Test
+Container.com.yahoo.search.predicate.utils.Test
+Container.com.yahoo.search.query.Test
+Container.com.yahoo.search.query.context.Test
+Container.com.yahoo.search.query.gui.Test
+Container.com.yahoo.search.query.parser.Test
+Container.com.yahoo.search.query.profile.Test
+Container.com.yahoo.search.query.profile.compiled.Test
+Container.com.yahoo.search.query.profile.config.Test
+Container.com.yahoo.search.query.profile.types.Test
+Container.com.yahoo.search.query.properties.Test
+Container.com.yahoo.search.query.ranking.Test
+Container.com.yahoo.search.query.restapi.Test
+Container.com.yahoo.search.query.rewrite.Test
+Container.com.yahoo.search.query.rewrite.rewriters.Test
+Container.com.yahoo.search.query.textserialize.Test
+Container.com.yahoo.search.query.textserialize.item.Test
+Container.com.yahoo.search.query.textserialize.parser.Test
+Container.com.yahoo.search.query.textserialize.serializer.Test
+Container.com.yahoo.search.querytransform.Test
+Container.com.yahoo.search.rendering.Test
+Container.com.yahoo.search.result.Test
+Container.com.yahoo.search.schema.Test
+Container.com.yahoo.search.schema.internal.Test
+Container.com.yahoo.search.searchchain.Test
+Container.com.yahoo.search.searchchain.example.Test
+Container.com.yahoo.search.searchchain.model.Test
+Container.com.yahoo.search.searchchain.model.federation.Test
+Container.com.yahoo.search.searchchain.testutil.Test
+Container.com.yahoo.search.searchers.Test
+Container.com.yahoo.search.statistics.Test
+Container.com.yahoo.search.yql.Test
+Container.com.yahoo.security.Test
+Container.com.yahoo.security.tls.Test
+Container.com.yahoo.slime.Test
+Container.com.yahoo.socket.test.Test
+Container.com.yahoo.stream.Test
+Container.com.yahoo.system.Test
+Container.com.yahoo.system.execution.Test
+Container.com.yahoo.tensor.Test
+Container.com.yahoo.tensor.evaluation.Test
+Container.com.yahoo.tensor.functions.Test
+Container.com.yahoo.tensor.serialization.Test
+Container.com.yahoo.test.Test
+Container.com.yahoo.test.json.Test
+Container.com.yahoo.text.Test
+Container.com.yahoo.text.internal.Test
+Container.com.yahoo.text.interpretation.Test
+Container.com.yahoo.time.Test
+Container.com.yahoo.transaction.Test
+Container.com.yahoo.vdslib.Test
+Container.com.yahoo.vdslib.distribution.Test
+Container.com.yahoo.vdslib.state.Test
+Container.com.yahoo.vespa.Test
+Container.com.yahoo.vespa.applicationmodel.Test
+Container.com.yahoo.vespa.athenz.api.Test
+Container.com.yahoo.vespa.athenz.aws.Test
+Container.com.yahoo.vespa.athenz.client.Test
+Container.com.yahoo.vespa.athenz.client.common.Test
+Container.com.yahoo.vespa.athenz.client.common.bindings.Test
+Container.com.yahoo.vespa.athenz.client.common.serializers.Test
+Container.com.yahoo.vespa.athenz.client.zms.Test
+Container.com.yahoo.vespa.athenz.client.zms.bindings.Test
+Container.com.yahoo.vespa.athenz.client.zts.Test
+Container.com.yahoo.vespa.athenz.client.zts.bindings.Test
+Container.com.yahoo.vespa.athenz.client.zts.utils.Test
+Container.com.yahoo.vespa.athenz.identity.Test
+Container.com.yahoo.vespa.athenz.identityprovider.api.Test
+Container.com.yahoo.vespa.athenz.identityprovider.api.bindings.Test
+Container.com.yahoo.vespa.athenz.identityprovider.client.Test
+Container.com.yahoo.vespa.athenz.tls.Test
+Container.com.yahoo.vespa.athenz.utils.Test
+Container.com.yahoo.vespa.athenz.zpe.Test
+Container.com.yahoo.vespaclient.Test
+Container.com.yahoo.vespa.clustercontroller.apps.clustercontroller.Test
+Container.com.yahoo.vespa.clustercontroller.apputil.communication.http.Test
+Container.com.yahoo.vespa.clustercontroller.core.Test
+Container.com.yahoo.vespa.clustercontroller.core.database.Test
+Container.com.yahoo.vespa.clustercontroller.core.hostinfo.Test
+Container.com.yahoo.vespa.clustercontroller.core.listeners.Test
+Container.com.yahoo.vespa.clustercontroller.core.restapiv2.Test
+Container.com.yahoo.vespa.clustercontroller.core.restapiv2.requests.Test
+Container.com.yahoo.vespa.clustercontroller.core.rpc.Test
+Container.com.yahoo.vespa.clustercontroller.core.status.Test
+Container.com.yahoo.vespa.clustercontroller.core.status.statuspage.Test
+Container.com.yahoo.vespa.clustercontroller.utils.communication.async.Test
+Container.com.yahoo.vespa.clustercontroller.utils.communication.http.Test
+Container.com.yahoo.vespa.clustercontroller.utils.communication.http.writer.Test
+Container.com.yahoo.vespa.clustercontroller.utils.staterestapi.Test
+Container.com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.Test
+Container.com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.Test
+Container.com.yahoo.vespa.clustercontroller.utils.staterestapi.response.Test
+Container.com.yahoo.vespa.clustercontroller.utils.staterestapi.server.Test
+Container.com.yahoo.vespa.clustercontroller.utils.util.Test
+Container.com.yahoo.vespa.config.Test
+Container.com.yahoo.vespa.config.benchmark.Test
+Container.com.yahoo.vespa.config.buildergen.Test
+Container.com.yahoo.vespa.config.content.Test
+Container.com.yahoo.vespa.config.content.core.Test
+Container.com.yahoo.vespa.config.content.reindexing.Test
+Container.com.yahoo.vespa.config.core.Test
+Container.com.yahoo.vespa.configdefinition.Test
+Container.com.yahoo.vespa.configmodel.producers.Test
+Container.com.yahoo.vespa.config.parser.Test
+Container.com.yahoo.vespa.config.protocol.Test
+Container.com.yahoo.vespa.config.proxy.Test
+Container.com.yahoo.vespa.config.proxy.filedistribution.Test
+Container.com.yahoo.vespa.config.search.Test
+Container.com.yahoo.vespa.config.search.core.Test
+Container.com.yahoo.vespa.config.server.Test
+Container.com.yahoo.vespa.config.server.application.Test
+Container.com.yahoo.vespa.config.server.configchange.Test
+Container.com.yahoo.vespa.config.server.deploy.Test
+Container.com.yahoo.vespa.config.server.filedistribution.Test
+Container.com.yahoo.vespa.configserver.flags.Test
+Container.com.yahoo.vespa.configserver.flags.db.Test
+Container.com.yahoo.vespa.configserver.flags.http.Test
+Container.com.yahoo.vespa.config.server.host.Test
+Container.com.yahoo.vespa.config.server.http.Test
+Container.com.yahoo.vespa.config.server.http.status.Test
+Container.com.yahoo.vespa.config.server.http.v1.Test
+Container.com.yahoo.vespa.config.server.http.v2.Test
+Container.com.yahoo.vespa.config.server.http.v2.request.Test
+Container.com.yahoo.vespa.config.server.http.v2.response.Test
+Container.com.yahoo.vespa.config.server.maintenance.Test
+Container.com.yahoo.vespa.config.server.metrics.Test
+Container.com.yahoo.vespa.config.server.model.Test
+Container.com.yahoo.vespa.config.server.modelfactory.Test
+Container.com.yahoo.vespa.config.server.monitoring.Test
+Container.com.yahoo.vespa.config.server.provision.Test
+Container.com.yahoo.vespa.config.server.rpc.Test
+Container.com.yahoo.vespa.config.server.rpc.security.Test
+Container.com.yahoo.vespa.config.server.session.Test
+Container.com.yahoo.vespa.config.server.tenant.Test
+Container.com.yahoo.vespa.config.server.version.Test
+Container.com.yahoo.vespa.config.server.zookeeper.Test
+Container.com.yahoo.vespa.config.storage.Test
+Container.com.yahoo.vespa.config.util.Test
+Container.com.yahoo.vespa.curator.Test
+Container.com.yahoo.vespa.curator.api.Test
+Container.com.yahoo.vespa.curator.mock.Test
+Container.com.yahoo.vespa.curator.recipes.Test
+Container.com.yahoo.vespa.curator.stats.Test
+Container.com.yahoo.vespa.curator.transaction.Test
+Container.com.yahoo.vespa.defaults.Test
+Container.com.yahoo.vespa.document.Test
+Container.com.yahoo.vespa.document.dom.Test
+Container.com.yahoo.vespa.documentmodel.Test
+Container.com.yahoo.vespafeeder.Test
+Container.com.yahoo.vespa.feed.perf.Test
+Container.com.yahoo.vespa.filedistribution.Test
+Container.com.yahoo.vespa.filedistribution.status.Test
+Container.com.yahoo.vespa.flags.Test
+Container.com.yahoo.vespa.flags.custom.Test
+Container.com.yahoo.vespa.flags.file.Test
+Container.com.yahoo.vespa.flags.json.Test
+Container.com.yahoo.vespa.flags.json.wire.Test
+Container.com.yahoo.vespaget.Test
+Container.com.yahoo.vespa.hadoop.Test
+Container.com.yahoo.vespa.hadoop.mapreduce.Test
+Container.com.yahoo.vespa.hadoop.mapreduce.util.Test
+Container.com.yahoo.vespa.hadoop.pig.Test
+Container.com.yahoo.vespa.hosted.athenz.instanceproviderservice.Test
+Container.com.yahoo.vespa.hosted.athenz.instanceproviderservice.config.Test
+Container.com.yahoo.vespa.hosted.ca.Test
+Container.com.yahoo.vespa.hosted.ca.instance.Test
+Container.com.yahoo.vespa.hosted.ca.restapi.Test
+Container.com.yahoo.vespa.hosted.controller.Test
+Container.com.yahoo.vespa.hosted.controller.api.application.v4.Test
+Container.com.yahoo.vespa.hosted.controller.api.application.v4.model.Test
+Container.com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.Test
+Container.com.yahoo.vespa.hosted.controller.api.configserver.Test
+Container.com.yahoo.vespa.hosted.controller.api.identifiers.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.archive.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.artifact.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.athenz.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.aws.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.billing.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.certificates.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.configserver.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.deployment.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.dns.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.entity.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.horizon.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.jira.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.maven.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.noderepository.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.organization.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.repair.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.resource.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.routing.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.secrets.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.stubs.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.user.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.vcmr.Test
+Container.com.yahoo.vespa.hosted.controller.api.integration.zone.Test
+Container.com.yahoo.vespa.hosted.controller.api.role.Test
+Container.com.yahoo.vespa.hosted.controller.api.systemflags.v1.Test
+Container.com.yahoo.vespa.hosted.controller.api.systemflags.v1.wire.Test
+Container.com.yahoo.vespa.hosted.controller.application.Test
+Container.com.yahoo.vespa.hosted.controller.application.pkg.Test
+Container.com.yahoo.vespa.hosted.controller.archive.Test
+Container.com.yahoo.vespa.hosted.controller.athenz.Test
+Container.com.yahoo.vespa.hosted.controller.athenz.config.Test
+Container.com.yahoo.vespa.hosted.controller.athenz.impl.Test
+Container.com.yahoo.vespa.hosted.controller.auditlog.Test
+Container.com.yahoo.vespa.hosted.controller.certificate.Test
+Container.com.yahoo.vespa.hosted.controller.concurrent.Test
+Container.com.yahoo.vespa.hosted.controller.deployment.Test
+Container.com.yahoo.vespa.hosted.controller.dns.Test
+Container.com.yahoo.vespa.hosted.controller.maintenance.Test
+Container.com.yahoo.vespa.hosted.controller.metric.Test
+Container.com.yahoo.vespa.hosted.controller.notification.Test
+Container.com.yahoo.vespa.hosted.controller.persistence.Test
+Container.com.yahoo.vespa.hosted.controller.proxy.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.application.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.athenz.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.billing.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.changemanagement.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.configserver.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.controller.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.deployment.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.filter.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.flags.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.horizon.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.os.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.routing.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.systemflags.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.user.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.zone.v1.Test
+Container.com.yahoo.vespa.hosted.controller.restapi.zone.v2.Test
+Container.com.yahoo.vespa.hosted.controller.routing.Test
+Container.com.yahoo.vespa.hosted.controller.routing.context.Test
+Container.com.yahoo.vespa.hosted.controller.routing.rotation.Test
+Container.com.yahoo.vespa.hosted.controller.security.Test
+Container.com.yahoo.vespa.hosted.controller.support.access.Test
+Container.com.yahoo.vespa.hosted.controller.tenant.Test
+Container.com.yahoo.vespa.hosted.controller.tls.Test
+Container.com.yahoo.vespa.hosted.controller.versions.Test
+Container.com.yahoo.vespa.hosted.node.admin.Test
+Container.com.yahoo.vespa.hosted.node.admin.component.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.flags.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.noderepository.bindings.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.state.Test
+Container.com.yahoo.vespa.hosted.node.admin.configserver.state.bindings.Test
+Container.com.yahoo.vespa.hosted.node.admin.container.Test
+Container.com.yahoo.vespa.hosted.node.admin.container.image.Test
+Container.com.yahoo.vespa.hosted.node.admin.container.metrics.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.acl.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.coredump.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.disk.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.identity.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.Test
+Container.com.yahoo.vespa.hosted.node.admin.maintenance.sync.Test
+Container.com.yahoo.vespa.hosted.node.admin.nodeadmin.Test
+Container.com.yahoo.vespa.hosted.node.admin.nodeagent.Test
+Container.com.yahoo.vespa.hosted.node.admin.provider.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.editor.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.file.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.fs.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.network.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.process.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.systemd.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.template.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.text.Test
+Container.com.yahoo.vespa.hosted.node.admin.task.util.yum.Test
+Container.com.yahoo.vespa.hosted.provision.Test
+Container.com.yahoo.vespa.hosted.provision.applications.Test
+Container.com.yahoo.vespa.hosted.provision.autoscale.Test
+Container.com.yahoo.vespa.hosted.provision.lb.Test
+Container.com.yahoo.vespa.hosted.provision.maintenance.Test
+Container.com.yahoo.vespa.hosted.provision.node.Test
+Container.com.yahoo.vespa.hosted.provision.node.filter.Test
+Container.com.yahoo.vespa.hosted.provision.os.Test
+Container.com.yahoo.vespa.hosted.provision.persistence.Test
+Container.com.yahoo.vespa.hosted.provision.provisioning.Test
+Container.com.yahoo.vespa.hosted.provision.restapi.Test
+Container.com.yahoo.vespa.hosted.provision.testutils.Test
+Container.com.yahoo.vespa.hosted.routing.Test
+Container.com.yahoo.vespa.hosted.routing.nginx.Test
+Container.com.yahoo.vespa.hosted.routing.restapi.Test
+Container.com.yahoo.vespa.hosted.routing.status.Test
+Container.com.yahoo.vespa.hosted.testrunner.Test
+Container.com.yahoo.vespa.http.server.Test
+Container.com.yahoo.vespa.http.server.util.Test
+Container.com.yahoo.vespa.indexinglanguage.Test
+Container.com.yahoo.vespa.indexinglanguage.expressions.Test
+Container.com.yahoo.vespa.indexinglanguage.linguistics.Test
+Container.com.yahoo.vespa.indexinglanguage.parser.Test
+Container.com.yahoo.vespa.indexinglanguage.predicate.Test
+Container.com.yahoo.vespa.jaxrs.annotation.Test
+Container.com.yahoo.vespa.maven.plugin.enforcer.Test
+Container.com.yahoo.vespa.model.Test
+Container.com.yahoo.vespa.model.admin.Test
+Container.com.yahoo.vespa.model.admin.clustercontroller.Test
+Container.com.yahoo.vespa.model.admin.metricsproxy.Test
+Container.com.yahoo.vespa.model.admin.monitoring.Test
+Container.com.yahoo.vespa.model.admin.monitoring.builder.Test
+Container.com.yahoo.vespa.model.admin.monitoring.builder.xml.Test
+Container.com.yahoo.vespa.model.application.validation.Test
+Container.com.yahoo.vespa.model.application.validation.change.Test
+Container.com.yahoo.vespa.model.application.validation.change.search.Test
+Container.com.yahoo.vespa.model.application.validation.first.Test
+Container.com.yahoo.vespa.model.builder.Test
+Container.com.yahoo.vespa.model.builder.xml.dom.Test
+Container.com.yahoo.vespa.model.builder.xml.dom.chains.Test
+Container.com.yahoo.vespa.model.builder.xml.dom.chains.docproc.Test
+Container.com.yahoo.vespa.model.builder.xml.dom.chains.processing.Test
+Container.com.yahoo.vespa.model.builder.xml.dom.chains.search.Test
+Container.com.yahoo.vespa.model.clients.Test
+Container.com.yahoo.vespa.model.container.Test
+Container.com.yahoo.vespa.model.container.component.Test
+Container.com.yahoo.vespa.model.container.component.chain.Test
+Container.com.yahoo.vespa.model.container.configserver.Test
+Container.com.yahoo.vespa.model.container.configserver.option.Test
+Container.com.yahoo.vespa.model.container.docproc.Test
+Container.com.yahoo.vespa.model.container.docproc.model.Test
+Container.com.yahoo.vespa.model.container.http.Test
+Container.com.yahoo.vespa.model.container.http.ssl.Test
+Container.com.yahoo.vespa.model.container.http.xml.Test
+Container.com.yahoo.vespa.model.container.ml.Test
+Container.com.yahoo.vespa.model.container.processing.Test
+Container.com.yahoo.vespa.model.container.search.Test
+Container.com.yahoo.vespa.model.container.search.searchchain.Test
+Container.com.yahoo.vespa.model.container.search.searchchain.defaultsearchchains.Test
+Container.com.yahoo.vespa.model.container.xml.Test
+Container.com.yahoo.vespa.model.container.xml.document.Test
+Container.com.yahoo.vespa.model.container.xml.embedder.Test
+Container.com.yahoo.vespa.model.content.Test
+Container.com.yahoo.vespa.model.content.cluster.Test
+Container.com.yahoo.vespa.model.content.engines.Test
+Container.com.yahoo.vespa.model.content.storagecluster.Test
+Container.com.yahoo.vespa.model.filedistribution.Test
+Container.com.yahoo.vespa.model.ml.Test
+Container.com.yahoo.vespa.model.routing.Test
+Container.com.yahoo.vespa.model.search.Test
+Container.com.yahoo.vespa.model.utils.Test
+Container.com.yahoo.vespa.model.utils.internal.Test
+Container.com.yahoo.vespa.objects.Test
+Container.com.yahoo.vespa.orchestrator.Test
+Container.com.yahoo.vespa.orchestrator.config.Test
+Container.com.yahoo.vespa.orchestrator.controller.Test
+Container.com.yahoo.vespa.orchestrator.model.Test
+Container.com.yahoo.vespa.orchestrator.policy.Test
+Container.com.yahoo.vespa.orchestrator.resources.Test
+Container.com.yahoo.vespa.orchestrator.restapi.wire.Test
+Container.com.yahoo.vespa.orchestrator.status.Test
+Container.com.yahoo.vespa.orchestrator.status.json.Test
+Container.com.yahoo.vespa.security.tool.securityenv.Test
+Container.com.yahoo.vespa.service.duper.Test
+Container.com.yahoo.vespa.service.executor.Test
+Container.com.yahoo.vespa.service.health.Test
+Container.com.yahoo.vespa.service.manager.Test
+Container.com.yahoo.vespa.service.model.Test
+Container.com.yahoo.vespa.service.monitor.Test
+Container.com.yahoo.vespa.service.slobrok.Test
+Container.com.yahoo.vespastat.Test
+Container.com.yahoo.vespa.streamingvisitors.Test
+Container.com.yahoo.vespa.streamingvisitors.tracing.Test
+Container.com.yahoo.vespasummarybenchmark.Test
+Container.com.yahoo.vespa.test.file.Test
+Container.com.yahoo.vespa.testrunner.Test
+Container.com.yahoo.vespavisit.Test
+Container.com.yahoo.vespaxmlparser.Test
+Container.com.yahoo.vespa.zookeeper.Test
+Container.com.yahoo.vespa.zookeeper.cli.Test
+Container.com.yahoo.vespa.zookeeper.client.Test
+Container.com.yahoo.yolean.Test
+Container.com.yahoo.yolean.chain.Test
+Container.com.yahoo.yolean.concurrent.Test
+Container.com.yahoo.yolean.function.Test
+Container.com.yahoo.yolean.system.Test
+Container.com.yahoo.yolean.trace.Test
diff --git a/client/go/cmd/logfmt/internal_notnames.txt b/client/go/cmd/logfmt/internal_notnames.txt
new file mode 100644
index 00000000000..49543758ac3
--- /dev/null
+++ b/client/go/cmd/logfmt/internal_notnames.txt
@@ -0,0 +1,8 @@
+Container.ai.onnx.Test
+Container.com.fasterxml.jackson.jaxrs.json.Test
+Container.com.google.Test
+Container.com.yahooapis.foo.Test
+Container.com.yahoo.newssearch.Test
+Container.com.yahoo.Test
+Container.com.yahoo.testing.Test
+Container.org.apache.http.Test
diff --git a/client/go/cmd/logfmt/internal_test.go b/client/go/cmd/logfmt/internal_test.go
new file mode 100644
index 00000000000..9b6b0f8404c
--- /dev/null
+++ b/client/go/cmd/logfmt/internal_test.go
@@ -0,0 +1,34 @@
+package logfmt
+
+import (
+ "bufio"
+ "os"
+ "testing"
+)
+
+// tests: func isInternal(componentName string) bool
+
+func TestIsInternal(t *testing.T) {
+ f, err := os.Open("internal_names.txt")
+ if err != nil {
+ t.Fatal("could not read test data")
+ }
+ defer f.Close()
+ for input := bufio.NewScanner(f); input.Scan(); {
+ if name := input.Text(); !isInternal(name) {
+ t.Logf("name '%s' should be internal but was not recognized", name)
+ t.Fail()
+ }
+ }
+ f, err = os.Open("internal_notnames.txt")
+ if err != nil {
+ t.Fatal("could not read test data")
+ }
+ defer f.Close()
+ for input := bufio.NewScanner(f); input.Scan(); {
+ if name := input.Text(); isInternal(name) {
+ t.Logf("name '%s' should not be internal but was recognized", name)
+ t.Fail()
+ }
+ }
+}
diff --git a/client/go/cmd/logfmt/levelflags.go b/client/go/cmd/logfmt/levelflags.go
new file mode 100644
index 00000000000..4e6c1284753
--- /dev/null
+++ b/client/go/cmd/logfmt/levelflags.go
@@ -0,0 +1,72 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "strings"
+)
+
+// handle CLI flags for log level filtering
+
+type flagValueForLevel struct {
+ levels map[string]bool
+ changed bool
+}
+
+func defaultLevelFlags() map[string]bool {
+ return map[string]bool{
+ "fatal": true,
+ "error": true,
+ "warning": true,
+ "info": true,
+ "config": false,
+ "event": false,
+ "debug": false,
+ "spam": false,
+ }
+}
+
+func (v *flagValueForLevel) Type() string {
+ return "level flags"
+}
+
+func (v *flagValueForLevel) String() string {
+ var buf strings.Builder
+ flagNames := []string{
+ "fatal",
+ "error",
+ "warning",
+ "info",
+ "config",
+ "event",
+ "debug",
+ "spam",
+ }
+ for _, flag := range flagNames {
+ if v.levels[flag] {
+ buf.WriteString(" +")
+ } else {
+ buf.WriteString(" -")
+ }
+ buf.WriteString(flag)
+ }
+ return buf.String()
+}
+
+func (v *flagValueForLevel) flags() map[string]bool {
+ return v.levels
+}
+
+func (v *flagValueForLevel) name() string {
+ return "level"
+}
+
+func (v *flagValueForLevel) unchanged() bool {
+ return !v.changed
+}
+
+func (v *flagValueForLevel) Set(val string) error {
+ return applyPlusMinus(val, v)
+}
diff --git a/client/go/cmd/logfmt/levelflags_test.go b/client/go/cmd/logfmt/levelflags_test.go
new file mode 100644
index 00000000000..186ea2d96b0
--- /dev/null
+++ b/client/go/cmd/logfmt/levelflags_test.go
@@ -0,0 +1,74 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestLevelFlags(t *testing.T) {
+ none := " -fatal -error -warning -info -config -event -debug -spam"
+
+ var flag flagValueForLevel
+ if flag.String() != none {
+ t.Logf("unset flag displays as '%s', expected '%s'", flag.String(), none)
+ t.Fail()
+ }
+ if flag.Type() != "level flags" {
+ t.Logf("flag type was '%s'", flag.Type())
+ t.Fail()
+ }
+ check := func(expected string, texts ...string) {
+ var target flagValueForLevel
+ // target.levels = defaultLevelFlags()
+ target.levels = defaultLevelFlags()
+ for _, text := range texts {
+ err := target.Set(text)
+ if err != nil {
+ t.Fatalf("unexpected error with level flags Set('%s'): %v", text, err)
+ }
+ }
+ got := target.String()
+ if got != expected {
+ t.Logf("expected flags [%s] but got: [%s]", expected, got)
+ t.Fail()
+ }
+ }
+ check(" +fatal +error +warning +info -config -event -debug -spam")
+ check(" -fatal -error -warning -info -config -event -debug -spam", "-all")
+ check(" +fatal +error +warning +info +config +event +debug +spam", "all")
+ check(" +fatal +error +warning +info +config +event +debug +spam", "+all")
+ check(" -fatal -error -warning -info -config -event +debug -spam", "debug")
+ check(" +fatal +error +warning +info +config +event +debug -spam", "all-spam")
+ check(" +fatal +error +warning +info +config +event +debug -spam", "all", "-spam")
+ check(" +fatal +error +warning -info -config +event -debug -spam", "+event", "-info")
+ check(" +fatal +error -warning -info -config +event -debug -spam", "+event,-info,-warning,config")
+ check(" +fatal +error -warning -info +config +event -debug -spam", "+event,-info,-warning,+config")
+ check(" +fatal +error -warning -info +config +event -debug -spam", "+event,-info", "-warning,+config")
+ check(" -fatal -error -warning -info +config -event -debug -spam", "+event", "-info", "-warning", "config")
+ check = func(expectErr string, texts ...string) {
+ var target flagValueForLevel
+ target.levels = defaultLevelFlags()
+ for _, text := range texts {
+ err := target.Set(text)
+ if err != nil {
+ if err.Error() == expectErr {
+ return
+ }
+ t.Fatalf("expected error [%s] with level flags Set('%s'), but got [%v]", expectErr, text, err)
+ }
+ }
+ t.Logf("Did not get expected error '%s' from %s", expectErr, strings.Join(texts, ","))
+ t.Fail()
+ }
+ check("not a valid level flag: 'foo'", "foo")
+ check("not a valid level flag: 'foo'", "event,foo,config")
+ check("not a valid level flag: 'foo'", "-event,-foo,-config")
+ check("not a valid level flag: 'foo'", "+event,+foo,+config")
+ check("not a valid level flag: 'foo'", "event", "foo", "config")
+ check("not a valid level flag: 'foo'", "-event", "-foo", "-config")
+ check("not a valid level flag: 'foo'", "+event", "+foo", "+config")
+}
diff --git a/client/go/cmd/logfmt/options.go b/client/go/cmd/logfmt/options.go
new file mode 100644
index 00000000000..f564ffd4df0
--- /dev/null
+++ b/client/go/cmd/logfmt/options.go
@@ -0,0 +1,47 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "fmt"
+ "os"
+)
+
+// options designed for compatibility with perl version of vespa-logfmt
+
+type Options struct {
+ ShowFields flagValueForShow
+ ShowLevels flagValueForLevel
+ OnlyHostname string
+ OnlyPid string
+ OnlyService string
+ OnlyInternal bool
+ FollowTail bool
+ DequoteNewlines bool
+ TruncateService bool
+ TruncateComponent bool
+ ComponentFilter regexFlag
+ MessageFilter regexFlag
+}
+
+func NewOptions() (ret Options) {
+ ret.ShowLevels.levels = defaultLevelFlags()
+ ret.ShowFields.shown = defaultShowFlags()
+ return
+}
+
+func (o *Options) showField(field string) bool {
+ return o.ShowFields.shown[field]
+}
+
+func (o *Options) showLevel(level string) bool {
+ rv, ok := o.ShowLevels.levels[level]
+ if !ok {
+ o.ShowLevels.levels[level] = true
+ fmt.Fprintf(os.Stderr, "Warnings: unknown level '%s' in input\n", level)
+ return true
+ }
+ return rv
+}
diff --git a/client/go/cmd/logfmt/plusminusflag.go b/client/go/cmd/logfmt/plusminusflag.go
new file mode 100644
index 00000000000..1768cf0e7be
--- /dev/null
+++ b/client/go/cmd/logfmt/plusminusflag.go
@@ -0,0 +1,67 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "fmt"
+ "strings"
+)
+
+// common code for showFlags and levelFlags
+
+type plusMinusFlag interface {
+ flags() map[string]bool
+ name() string
+ unchanged() bool
+}
+
+func trimPrefix(value, prefix string) (newValue string, hadPrefix bool) {
+ hadPrefix = strings.HasPrefix(value, prefix)
+ if hadPrefix {
+ newValue = strings.TrimPrefix(value, prefix)
+ } else {
+ newValue = value
+ }
+ return
+}
+
+func applyPlusMinus(val string, target plusMinusFlag) error {
+ minus := strings.HasPrefix(val, "-")
+ plus := strings.HasPrefix(val, "+")
+ val = strings.ReplaceAll(val, "-", ",-")
+ val = strings.ReplaceAll(val, "+", ",+")
+ if target.unchanged() {
+ // user wants to reset flags?
+ if minus == false && plus == false {
+ for k, _ := range target.flags() {
+ target.flags()[k] = false
+ }
+ }
+ }
+ changeTo := !minus
+ for _, k := range strings.Split(val, ",") {
+ if suppress, minus := trimPrefix(k, "-"); minus {
+ k = suppress
+ changeTo = false
+ }
+ if surface, plus := trimPrefix(k, "+"); plus {
+ k = surface
+ changeTo = true
+ }
+ if k == "" {
+ continue
+ }
+ if k == "all" {
+ for k, _ := range target.flags() {
+ target.flags()[k] = changeTo
+ }
+ } else if _, ok := target.flags()[k]; !ok {
+ return fmt.Errorf("not a valid %s flag: '%s'", target.name(), k)
+ } else {
+ target.flags()[k] = changeTo
+ }
+ }
+ return nil
+}
diff --git a/client/go/cmd/logfmt/regexflag.go b/client/go/cmd/logfmt/regexflag.go
new file mode 100644
index 00000000000..8f7d2a91373
--- /dev/null
+++ b/client/go/cmd/logfmt/regexflag.go
@@ -0,0 +1,38 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "regexp"
+)
+
+// optional regular expression filter, as a CLI flag
+
+type regexFlag struct {
+ regex *regexp.Regexp
+}
+
+func (re regexFlag) unmatched(s string) bool {
+ if re.regex == nil {
+ return false
+ }
+ return re.regex.FindStringIndex(s) == nil
+}
+
+func (v *regexFlag) Type() string {
+ return "regular expression"
+}
+
+func (v *regexFlag) String() string {
+ if v.regex == nil {
+ return "<none>"
+ }
+ return v.regex.String()
+}
+
+func (v *regexFlag) Set(val string) (r error) {
+ v.regex, r = regexp.Compile(val)
+ return
+}
diff --git a/client/go/cmd/logfmt/regexflag_test.go b/client/go/cmd/logfmt/regexflag_test.go
new file mode 100644
index 00000000000..489439863a2
--- /dev/null
+++ b/client/go/cmd/logfmt/regexflag_test.go
@@ -0,0 +1,41 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "testing"
+)
+
+func assertMatch(t *testing.T, re string, flag *regexFlag, texts ...string) {
+ t.Helper()
+ err := flag.Set(re)
+ require.Nil(t, err, "unexpected error with flag.Set('%s'): %v", re, err)
+ assert.Equal(t, re, flag.String(), "set flag displays as '%s', expected '%s'", flag.String(), re)
+ for _, text := range texts {
+ assert.False(t, flag.unmatched(text), "flag '%s' claims a non-match for '%s'", flag.String(), text)
+ }
+}
+
+func assertUnmatch(t *testing.T, re string, flag *regexFlag, texts ...string) {
+ t.Helper()
+ err := flag.Set(re)
+ require.Nil(t, err, "unexpected error with flag.Set('%s'): %v", re, err)
+ assert.Equal(t, re, flag.String())
+ for _, text := range texts {
+ assert.True(t, flag.unmatched(text), "flag '%s' should claim a non-match for '%s'", flag.String(), text)
+ }
+}
+
+func TestRegexFlag(t *testing.T) {
+ var flag regexFlag
+ assert.Equal(t, "<none>", flag.String())
+ assert.Equal(t, "regular expression", flag.Type())
+ assert.False(t, flag.unmatched("foobar"), "unset flag claims a non-match")
+ assert.EqualError(t, flag.Set("*"), "error parsing regexp: missing argument to repetition operator: `*`")
+ assertMatch(t, "foo.*bar", new(regexFlag), "foobar", "foo bar", "x foobar y", "xfoobary", "xfooybarz")
+ assertUnmatch(t, "foo.*bar", new(regexFlag), "Foobar", "foo Bar", "fxoobar", "whatever")
+}
diff --git a/client/go/cmd/logfmt/runlogfmt.go b/client/go/cmd/logfmt/runlogfmt.go
new file mode 100644
index 00000000000..9d782692f50
--- /dev/null
+++ b/client/go/cmd/logfmt/runlogfmt.go
@@ -0,0 +1,78 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+
+ "github.com/mattn/go-isatty"
+)
+
+func inputIsTty() bool {
+ return isatty.IsTerminal(os.Stdin.Fd())
+}
+
+func vespaHome() string {
+ ev := os.Getenv("VESPA_HOME")
+ if ev == "" {
+ return "/opt/vespa"
+ }
+ return ev
+}
+
+// main entry point for vespa-logfmt
+
+func RunLogfmt(opts *Options, args []string) {
+ if len(args) == 0 {
+ if inputIsTty() {
+ args = append(args, vespaHome()+"/logs/vespa/vespa.log")
+ } else {
+ formatFile(opts, os.Stdin)
+ }
+ }
+ if opts.FollowTail {
+ if len(args) != 1 {
+ fmt.Fprintf(os.Stderr, "Must have exact 1 file for 'follow' option, got %d\n", len(args))
+ return
+ }
+ tailFile(opts, args[0])
+ return
+ }
+ for _, arg := range args {
+ file, err := os.Open(arg)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Cannot open '%s': %v\n", arg, err)
+ } else {
+ formatFile(opts, file)
+ file.Close()
+ }
+ }
+}
+
+func formatLine(opts *Options, line string) {
+ output, err := handleLine(opts, line)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "bad log line:", err)
+ } else {
+ os.Stdout.WriteString(output)
+ }
+}
+
+func tailFile(opts *Options, fn string) {
+ tailed := FollowFile(fn)
+ for line := range tailed.Lines {
+ formatLine(opts, line.Text)
+ }
+}
+
+func formatFile(opts *Options, arg *os.File) {
+ input := bufio.NewScanner(arg)
+ input.Buffer(make([]byte, 64*1024), 4*1024*1024)
+ for input.Scan() {
+ formatLine(opts, input.Text())
+ }
+}
diff --git a/client/go/cmd/logfmt/showflags.go b/client/go/cmd/logfmt/showflags.go
new file mode 100644
index 00000000000..b69860e0312
--- /dev/null
+++ b/client/go/cmd/logfmt/showflags.go
@@ -0,0 +1,76 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "strings"
+)
+
+// handle CLI flags for which fields to show when formatting a line
+
+type flagValueForShow struct {
+ shown map[string]bool
+ changed bool
+}
+
+func defaultShowFlags() map[string]bool {
+ return map[string]bool{
+ "time": true,
+ "fmttime": true,
+ "msecs": true,
+ "usecs": false,
+ "host": false,
+ "level": true,
+ "pid": false,
+ "service": true,
+ "component": true,
+ "message": true,
+ }
+}
+
+func (v *flagValueForShow) Type() string {
+ return "show flags"
+}
+
+func (v *flagValueForShow) String() string {
+ var buf strings.Builder
+ flagNames := []string{
+ "time",
+ "fmttime",
+ "msecs",
+ "usecs",
+ "host",
+ "level",
+ "pid",
+ "service",
+ "component",
+ "message",
+ }
+ for _, flag := range flagNames {
+ if v.shown[flag] {
+ buf.WriteString(" +")
+ } else {
+ buf.WriteString(" -")
+ }
+ buf.WriteString(flag)
+ }
+ return buf.String()
+}
+
+func (v *flagValueForShow) flags() map[string]bool {
+ return v.shown
+}
+
+func (v *flagValueForShow) name() string {
+ return "show"
+}
+
+func (v *flagValueForShow) unchanged() bool {
+ return !v.changed
+}
+
+func (v *flagValueForShow) Set(val string) error {
+ return applyPlusMinus(val, v)
+}
diff --git a/client/go/cmd/logfmt/showflags_test.go b/client/go/cmd/logfmt/showflags_test.go
new file mode 100644
index 00000000000..d1b66118afd
--- /dev/null
+++ b/client/go/cmd/logfmt/showflags_test.go
@@ -0,0 +1,61 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "strings"
+ "testing"
+)
+
+func TestShowFlags(t *testing.T) {
+ none := " -time -fmttime -msecs -usecs -host -level -pid -service -component -message"
+ var flag flagValueForShow
+ assert.Equal(t, none, flag.String(), "unset flag displays as '%s', expected '%s'", flag.String(), none)
+ assert.Equal(t, "show flags", flag.Type())
+ check := func(expected string, texts ...string) {
+ var target flagValueForShow
+ // target.levels = defaultLevelFlags()
+ target.shown = defaultShowFlags()
+ for _, text := range texts {
+ err := target.Set(text)
+ require.Nil(t, err, "unexpected error with show flags Set('%s'): %v", text, err)
+ }
+ assert.Equal(t, expected, target.String())
+ }
+ check(" +time +fmttime +msecs -usecs -host +level -pid +service +component +message")
+ check(" -time -fmttime -msecs -usecs -host -level -pid -service -component -message", "-all")
+ check(" +time +fmttime +msecs +usecs +host +level +pid +service +component +message", "all")
+ check(" +time +fmttime +msecs +usecs +host +level +pid +service +component +message", "+all")
+ check(" -time -fmttime -msecs -usecs -host -level +pid -service -component -message", "pid")
+ check(" +time +fmttime +msecs +usecs -host +level +pid +service +component +message", "all-host")
+ check(" +time +fmttime +msecs +usecs -host +level +pid +service +component +message", "all", "-host")
+ check(" +time +fmttime -msecs -usecs -host +level +pid +service +component +message", "+pid", "-msecs")
+ check(" +time -fmttime +msecs -usecs +host +level -pid -service +component +message", "+host,-fmttime,-service,pid")
+ check(" +time -fmttime +msecs -usecs +host +level +pid -service +component +message", "+host,-fmttime,-service,+pid")
+ check(" +time -fmttime +msecs -usecs +host +level +pid -service +component +message", "+host,-fmttime", "-service,+pid")
+ check(" -time -fmttime -msecs -usecs -host -level +pid -service -component -message", "+host", "-fmttime", "-service", "pid")
+ check = func(expectErr string, texts ...string) {
+ var target flagValueForShow
+ target.shown = defaultShowFlags()
+ for _, text := range texts {
+ err := target.Set(text)
+ if err != nil {
+ require.Equal(t, expectErr, err.Error())
+ return
+ }
+ }
+ t.Logf("Did not get expected error [%s] from %s", expectErr, strings.Join(texts, " "))
+ t.Fail()
+ }
+ check("not a valid show flag: 'foo'", "foo")
+ check("not a valid show flag: 'foo'", "level,foo,message")
+ check("not a valid show flag: 'foo'", "-level,-foo,-message")
+ check("not a valid show flag: 'foo'", "+level,+foo,+message")
+ check("not a valid show flag: 'foo'", "level", "foo", "message")
+ check("not a valid show flag: 'foo'", "-level", "-foo", "-message")
+ check("not a valid show flag: 'foo'", "+level", "+foo", "+message")
+}
diff --git a/client/go/cmd/logfmt/tail.go b/client/go/cmd/logfmt/tail.go
new file mode 100644
index 00000000000..44674012548
--- /dev/null
+++ b/client/go/cmd/logfmt/tail.go
@@ -0,0 +1,169 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa logfmt command
+// Author: arnej
+
+package logfmt
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+const lastLinesSize = 4 * 1024
+
+type Line struct {
+ Text string
+}
+
+// an active "tail -f" like object
+
+type Tail struct {
+ Lines chan Line
+ lineBuf []byte
+ curFile *os.File
+ fn string
+ reader *bufio.Reader
+ curStat unix.Stat_t
+}
+
+// API for starting to follow a log file
+
+func FollowFile(fn string) (res Tail) {
+ res.fn = fn
+ res.lineBuf = make([]byte, lastLinesSize)
+ res.openTail()
+ res.Lines = make(chan Line, 20)
+ res.lineBuf = res.lineBuf[:0]
+ go runTailWith(&res)
+ return res
+}
+
+func (t *Tail) setFile(f *os.File) {
+ if t.curFile != nil {
+ t.curFile.Close()
+ }
+ t.curFile = f
+ if f != nil {
+ err := unix.Fstat(int(f.Fd()), &t.curStat)
+ if err != nil {
+ f.Close()
+ fmt.Fprintf(os.Stderr, "unexpected failure: %v\n", err)
+ return
+ }
+ t.reader = bufio.NewReaderSize(f, 1024*1024)
+ } else {
+ t.reader = nil
+ }
+}
+
+// open log file and seek to the start of a line near the end, if possible.
+func (t *Tail) openTail() {
+ file, err := os.Open(t.fn)
+ if err != nil {
+ return
+ }
+ sz, err := file.Seek(0, os.SEEK_END)
+ if err != nil {
+ return
+ }
+ if sz < lastLinesSize {
+ sz, err = file.Seek(0, os.SEEK_SET)
+ if err == nil {
+ // just read from start of file, all OK
+ t.setFile(file)
+ }
+ return
+ }
+ sz, _ = file.Seek(-lastLinesSize, os.SEEK_END)
+ n, err := file.Read(t.lineBuf)
+ if err != nil {
+ return
+ }
+ for i := 0; i < n; i++ {
+ if t.lineBuf[i] == '\n' {
+ sz, err = file.Seek(sz+int64(i+1), os.SEEK_SET)
+ if err == nil {
+ t.setFile(file)
+ }
+ return
+ }
+ }
+}
+
+func (t *Tail) reopen(cur *unix.Stat_t) {
+ for cnt := 0; cnt < 100; cnt++ {
+ file, err := os.Open(t.fn)
+ if err != nil {
+ t.setFile(nil)
+ if cnt == 0 {
+ fmt.Fprintf(os.Stderr, "%v (waiting for log file to appear)\n", err)
+ }
+ time.Sleep(1000 * time.Millisecond)
+ continue
+ }
+ var stat unix.Stat_t
+ err = unix.Fstat(int(file.Fd()), &stat)
+ if err != nil {
+ file.Close()
+ fmt.Fprintf(os.Stderr, "unexpected failure: %v\n", err)
+ time.Sleep(5000 * time.Millisecond)
+ continue
+ }
+ if cur != nil && cur.Dev == stat.Dev && cur.Ino == stat.Ino {
+ // same file, continue following it
+ file.Close()
+ return
+ }
+ // new file, start following it
+ t.setFile(file)
+ return
+ }
+}
+
+// runs as a goroutine
+func runTailWith(t *Tail) {
+ defer t.setFile(nil)
+loop:
+ for {
+ for t.curFile == nil {
+ t.reopen(nil)
+ }
+ bytes, err := t.reader.ReadSlice('\n')
+ t.lineBuf = append(t.lineBuf, bytes...)
+ if err == bufio.ErrBufferFull {
+ continue
+ }
+ if err == nil {
+ ll := len(t.lineBuf) - 1
+ t.Lines <- Line{Text: string(t.lineBuf[:ll])}
+ t.lineBuf = t.lineBuf[:0]
+ continue
+ }
+ if err == io.EOF {
+ pos, _ := t.curFile.Seek(0, os.SEEK_CUR)
+ for cnt := 0; cnt < 100; cnt++ {
+ time.Sleep(10 * time.Millisecond)
+ sz, _ := t.curFile.Seek(0, os.SEEK_END)
+ if sz != pos {
+ if sz < pos {
+ // truncation case
+ pos = 0
+ }
+ t.curFile.Seek(pos, os.SEEK_SET)
+ continue loop
+ }
+ }
+ // no change in file size, try reopening
+ t.reopen(&t.curStat)
+ } else {
+ fmt.Fprintf(os.Stderr, "error tailing '%s': %v\n", t.fn, err)
+ close(t.Lines)
+ return
+ }
+ }
+}
diff --git a/client/go/cmd/query.go b/client/go/cmd/query.go
index 82ff5185cbd..d147e986cec 100644
--- a/client/go/cmd/query.go
+++ b/client/go/cmd/query.go
@@ -62,7 +62,7 @@ func query(cli *CLI, arguments []string, timeoutSecs int, curl bool) error {
if err != nil {
return err
}
- service, err := cli.service(target, vespa.QueryService, 0, "")
+ service, err := cli.service(target, vespa.QueryService, 0, cli.config.cluster())
if err != nil {
return err
}
diff --git a/client/go/cmd/root.go b/client/go/cmd/root.go
index 0557248cedf..e2f03cbc7ce 100644
--- a/client/go/cmd/root.go
+++ b/client/go/cmd/root.go
@@ -28,6 +28,7 @@ import (
const (
applicationFlag = "application"
instanceFlag = "instance"
+ clusterFlag = "cluster"
zoneFlag = "zone"
targetFlag = "target"
waitFlag = "wait"
@@ -178,14 +179,16 @@ func (c *CLI) configureFlags() map[string]*pflag.Flag {
target string
application string
instance string
+ cluster string
zone string
waitSecs int
color string
quiet bool
)
c.cmd.PersistentFlags().StringVarP(&target, targetFlag, "t", "local", `The target platform to use. Must be "local", "cloud", "hosted" or an URL`)
- c.cmd.PersistentFlags().StringVarP(&application, applicationFlag, "a", "", "The application to manage")
- c.cmd.PersistentFlags().StringVarP(&instance, instanceFlag, "i", "", "The instance of the application to manage")
+ c.cmd.PersistentFlags().StringVarP(&application, applicationFlag, "a", "", "The application to use")
+ c.cmd.PersistentFlags().StringVarP(&instance, instanceFlag, "i", "", "The instance of the application to use")
+ c.cmd.PersistentFlags().StringVarP(&cluster, clusterFlag, "C", "", "The container cluster to use. This is only required for applications with multiple clusters")
c.cmd.PersistentFlags().StringVarP(&zone, zoneFlag, "z", "", "The zone to use. This defaults to a dev zone")
c.cmd.PersistentFlags().IntVarP(&waitSecs, waitFlag, "w", 0, "Number of seconds to wait for a service to become ready")
c.cmd.PersistentFlags().StringVarP(&color, colorFlag, "c", "auto", `Whether to use colors in output. Must be "auto", "never", or "always"`)
@@ -213,19 +216,17 @@ func (c *CLI) configureSpinner() {
func (c *CLI) configureCommands() {
rootCmd := c.cmd
authCmd := newAuthCmd()
- certCmd := newCertCmd(c, false)
+ certCmd := newCertCmd(c)
configCmd := newConfigCmd()
documentCmd := newDocumentCmd(c)
prodCmd := newProdCmd()
statusCmd := newStatusCmd(c)
certCmd.AddCommand(newCertAddCmd(c)) // auth cert add
authCmd.AddCommand(certCmd) // auth cert
- authCmd.AddCommand(newAPIKeyCmd(c, false)) // auth api-key
+ authCmd.AddCommand(newAPIKeyCmd(c)) // auth api-key
authCmd.AddCommand(newLoginCmd(c)) // auth login
authCmd.AddCommand(newLogoutCmd(c)) // auth logout
rootCmd.AddCommand(authCmd) // auth
- rootCmd.AddCommand(newCertCmd(c, true)) // cert TODO: Remove this after 2022-06-01
- rootCmd.AddCommand(newAPIKeyCmd(c, true)) // api-key TODO: Remove this after 2022-06-01
rootCmd.AddCommand(newCloneCmd(c)) // clone
configCmd.AddCommand(newConfigGetCmd(c)) // config get
configCmd.AddCommand(newConfigSetCmd(c)) // config set
diff --git a/client/go/cmd/status.go b/client/go/cmd/status.go
index 65da8f8f1c0..c44bbddb98a 100644
--- a/client/go/cmd/status.go
+++ b/client/go/cmd/status.go
@@ -81,7 +81,7 @@ func printServiceStatus(cli *CLI, name string) error {
if timeout > 0 {
log.Printf("Waiting up to %s for service to become ready ...", color.CyanString(timeout.String()))
}
- s, err := t.Service(name, timeout, 0, "")
+ s, err := t.Service(name, timeout, 0, cli.config.cluster())
if err != nil {
return err
}
diff --git a/client/go/vespa-logfmt/cmd.go b/client/go/vespa-logfmt/cmd.go
new file mode 100644
index 00000000000..749cac5fa56
--- /dev/null
+++ b/client/go/vespa-logfmt/cmd.go
@@ -0,0 +1,45 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// vespa-logfmt command
+// Author: arnej
+
+package main
+
+import (
+ "github.com/spf13/cobra"
+ "github.com/vespa-engine/vespa/client/go/build"
+ "github.com/vespa-engine/vespa/client/go/cmd/logfmt"
+)
+
+func NewLogfmtCmd() *cobra.Command {
+ var (
+ curOptions logfmt.Options = logfmt.NewOptions()
+ )
+ cmd := &cobra.Command{
+ Use: "vespa-logfmt",
+ Short: "convert vespa.log to human-readable format",
+ Long: `vespa-logfmt takes input in the internal vespa format
+and converts it to something human-readable`,
+ Version: build.Version,
+ Run: func(cmd *cobra.Command, args []string) {
+ logfmt.RunLogfmt(&curOptions, args)
+ },
+ Args: cobra.MaximumNArgs(1),
+ }
+ cmd.Flags().VarP(&curOptions.ShowLevels, "level", "l", "turn levels on/off\n")
+ cmd.Flags().VarP(&curOptions.ShowFields, "show", "s", "turn fields shown on/off\n")
+ cmd.Flags().VarP(&curOptions.ComponentFilter, "component", "c", "select components by regexp")
+ cmd.Flags().VarP(&curOptions.MessageFilter, "message", "m", "select messages by regexp")
+ cmd.Flags().BoolVarP(&curOptions.OnlyInternal, "internal", "i", false, "select only internal components")
+ cmd.Flags().BoolVar(&curOptions.TruncateService, "truncateservice", false, "truncate service name")
+ cmd.Flags().BoolVar(&curOptions.TruncateService, "ts", false, "")
+ cmd.Flags().BoolVarP(&curOptions.FollowTail, "follow", "f", false, "follow logfile with tail -f")
+ cmd.Flags().BoolVarP(&curOptions.DequoteNewlines, "nldequote", "N", false, "dequote newlines embedded in message")
+ cmd.Flags().BoolVarP(&curOptions.TruncateComponent, "truncatecomponent", "t", false, "truncate component name")
+ cmd.Flags().BoolVar(&curOptions.TruncateComponent, "tc", false, "")
+ cmd.Flags().StringVarP(&curOptions.OnlyHostname, "host", "H", "", "select only one host")
+ cmd.Flags().StringVarP(&curOptions.OnlyPid, "pid", "p", "", "select only one process ID")
+ cmd.Flags().StringVarP(&curOptions.OnlyService, "service", "S", "", "select only one service")
+ cmd.Flags().MarkHidden("tc")
+ cmd.Flags().MarkHidden("ts")
+ return cmd
+}
diff --git a/client/go/vespa-logfmt/main.go b/client/go/vespa-logfmt/main.go
new file mode 100644
index 00000000000..90a7719a1ef
--- /dev/null
+++ b/client/go/vespa-logfmt/main.go
@@ -0,0 +1,9 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+// Author: arnej
+
+package main
+
+func main() {
+ cobra := NewLogfmtCmd()
+ cobra.Execute()
+}
diff --git a/client/go/vespa/target_cloud.go b/client/go/vespa/target_cloud.go
index 696d5109015..1076724a252 100644
--- a/client/go/vespa/target_cloud.go
+++ b/client/go/vespa/target_cloud.go
@@ -9,6 +9,7 @@ import (
"net/http"
"sort"
"strconv"
+ "strings"
"time"
"github.com/vespa-engine/vespa/client/go/auth/auth0"
@@ -82,28 +83,27 @@ func CloudTarget(httpClient util.HTTPClient, apiOptions APIOptions, deploymentOp
}, nil
}
-func (t *cloudTarget) resolveEndpoint(cluster string) (string, error) {
+func (t *cloudTarget) findClusterURL(cluster string) (string, error) {
+ clusters := make([]string, 0, len(t.deploymentOptions.ClusterURLs))
+ for c := range t.deploymentOptions.ClusterURLs {
+ clusters = append(clusters, c)
+ }
if cluster == "" {
- for _, u := range t.deploymentOptions.ClusterURLs {
+ for _, url := range t.deploymentOptions.ClusterURLs {
if len(t.deploymentOptions.ClusterURLs) == 1 {
- return u, nil
+ return url, nil
} else {
- return "", fmt.Errorf("multiple clusters, none chosen: %v", t.deploymentOptions.ClusterURLs)
+ return "", fmt.Errorf("no cluster specified: found multiple clusters '%s'", strings.Join(clusters, "', '"))
}
}
} else {
- u := t.deploymentOptions.ClusterURLs[cluster]
- if u == "" {
- clusters := make([]string, len(t.deploymentOptions.ClusterURLs))
- for c := range t.deploymentOptions.ClusterURLs {
- clusters = append(clusters, c)
- }
- return "", fmt.Errorf("unknown cluster '%s': must be one of %v", cluster, clusters)
+ url, ok := t.deploymentOptions.ClusterURLs[cluster]
+ if !ok {
+ return "", fmt.Errorf("invalid cluster '%s': must be one of '%s'", cluster, strings.Join(clusters, "', '"))
}
- return u, nil
+ return url, nil
}
-
- return "", fmt.Errorf("no endpoints")
+ return "", fmt.Errorf("no endpoints found")
}
func (t *cloudTarget) Type() string {
@@ -142,7 +142,7 @@ func (t *cloudTarget) Service(name string, timeout time.Duration, runID int64, c
return nil, err
}
}
- url, err := t.resolveEndpoint(cluster)
+ url, err := t.findClusterURL(cluster)
if err != nil {
return nil, err
}
diff --git a/client/js/app/README.md b/client/js/app/README.md
new file mode 100644
index 00000000000..ae6a8d1cc25
--- /dev/null
+++ b/client/js/app/README.md
@@ -0,0 +1,57 @@
+<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+
+![Vespa logo](https://vespa.ai/assets/vespa-logo-color.png)
+
+# Vespa client
+
+This app is work in progress.
+It currently contains the **Query Builder** and the **Trace Visualizer**.
+
+
+
+## Query Builder
+The Query Builder is a tool for creating Vespa queries to send to a local backend.
+The tool provides all of the options for query parameters from dropdowns.
+The input fields provide hints to what is the expected type of value.
+
+
+
+## Trace Visualizer
+The Trace Visualizer is a tool for converting and visualizing traces from Vespa in a flame graph.
+To use the visualizer, a [Jaeger](https://www.jaegertracing.io/) instance must be run locally with Docker:
+
+ docker run -d --rm \
+ -p 16685:16685 \
+ -p 16686:16686 \
+ -p 16687:16687 \
+ -e SPAN_STORAGE_TYPE=memory \
+ jaegertracing/jaeger-query:latest
+
+The Jaeger UI can then be reached at **localhost:16686/search**
+
+To use the visualizer,
+paste the Vespa trace into the text box
+and press the button to convert the trace to a format supported by Jaeger and download it.
+Only traces using _trace.timestamps=true_ **and** _traceLevel_ between 3 and 5 (inclusive) will work correctly -
+see [query tracing](https://docs.vespa.ai/en/query-api.html#query-tracing):
+
+![Trace Converter](img/TraceConverter.png)
+
+After downloading the converted trace, it can be used with the Jaeger UI.
+Press the _JSON File_ button as shown in the image, and drag and drop the trace you just downloaded:
+
+![Jaeger Image](img/JaegerExample.png)
+
+Then click on the newly added trace and see it displayed as a flame graph:
+
+![Example Image](img/result.png)
+
+
+
+## Client install and start
+
+ nvm install --lts node # in case your current node.js is too old
+ yarn install
+ yarn dev # then open link, like http://127.0.0.1:3000/
+
+<!-- ToDo: publish a Docker image with all the clients ... -->
diff --git a/client/js/app/img/JaegerExample.png b/client/js/app/img/JaegerExample.png
new file mode 100644
index 00000000000..646123962ad
--- /dev/null
+++ b/client/js/app/img/JaegerExample.png
Binary files differ
diff --git a/client/js/app/img/TraceConverter.png b/client/js/app/img/TraceConverter.png
new file mode 100644
index 00000000000..9d7146556a1
--- /dev/null
+++ b/client/js/app/img/TraceConverter.png
Binary files differ
diff --git a/client/js/app/img/result.png b/client/js/app/img/result.png
new file mode 100644
index 00000000000..17655daacaf
--- /dev/null
+++ b/client/js/app/img/result.png
Binary files differ
diff --git a/client/js/app/package.json b/client/js/app/package.json
index 5459608197c..f2f8f6cb433 100644
--- a/client/js/app/package.json
+++ b/client/js/app/package.json
@@ -7,6 +7,7 @@
"build": "vite build",
"preview": "vite preview",
"prepare": "cd ../../../ && husky install client/js/app/.husky",
+ "test": "jest",
"lint": "eslint '{**/*,*}.{js,jsx}'"
},
"dependencies": {
@@ -14,12 +15,18 @@
"react-dom": "^18"
},
"devDependencies": {
- "@mantine/core": "^4",
- "@mantine/hooks": "^4",
- "@reach/router": "^1",
+ "@emotion/react": "^11",
+ "@fortawesome/fontawesome-svg-core": "^6",
+ "@fortawesome/free-regular-svg-icons": "^6",
+ "@fortawesome/free-solid-svg-icons": "^6",
+ "@fortawesome/react-fontawesome": "^0",
+ "@mantine/core": "^5",
+ "@mantine/hooks": "^5",
+ "@mantine/notifications": "^5",
"@types/react": "^18",
"@types/react-dom": "^18",
"@vitejs/plugin-react": "^1",
+ "esbuild-jest": "^0",
"eslint": "^8",
"eslint-plugin-import": "^2",
"eslint-plugin-prettier": "^4",
@@ -28,8 +35,31 @@
"eslint-plugin-react-perf": "^3",
"eslint-plugin-unused-imports": "^2",
"husky": "^7",
+ "jest": "^28",
+ "lodash": "^4",
"prettier": "2",
"pretty-quick": "^3",
+ "react-router-dom": "^6",
+ "use-context-selector": "^1",
"vite": "^2"
+ },
+ "jest": {
+ "testMatch": [
+ "<rootDir>/src/**/*.test.{js,jsx,ts,tsx}"
+ ],
+ "transform": {
+ "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": [
+ "esbuild-jest"
+ ]
+ },
+ "transformIgnorePatterns": [
+ "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$"
+ ],
+ "moduleNameMapper": {
+ "^app/(.*)$": [
+ "<rootDir>/src/app/$1"
+ ]
+ },
+ "resetMocks": true
}
}
diff --git a/client/js/app/src/app/app.jsx b/client/js/app/src/app/app.jsx
index 57eba3ea95d..704a5bcbeeb 100644
--- a/client/js/app/src/app/app.jsx
+++ b/client/js/app/src/app/app.jsx
@@ -1,16 +1,27 @@
import React from 'react';
+import { BrowserRouter } from 'react-router-dom';
+import { NotificationsProvider as MantineNotificationsProvider } from '@mantine/notifications';
import { Layout } from 'app/components';
-import { AppRouter } from 'app/libs/app-router';
import { Home } from 'app/pages/home/home';
-import { QueryBuilder } from 'app/pages/querybuilder/query-builder';
+import { QueryBuilder } from 'app/pages/querybuilder';
+import { QueryTracer } from 'app/pages/querytracer/query-tracer';
+import { ThemeProvider } from 'app/libs/theme-provider';
+import { Router } from 'app/libs/router';
export function App() {
return (
- <Layout>
- <AppRouter>
- <Home path="/" />
- <QueryBuilder path="querybuilder" />
- </AppRouter>
- </Layout>
+ <BrowserRouter>
+ <ThemeProvider>
+ <MantineNotificationsProvider>
+ <Layout>
+ <Router>
+ <Home path="/" title="Home" />
+ <QueryBuilder path="querybuilder" title="Query Builder" />
+ <QueryTracer path="querytracer" title="Query Tracer" />
+ </Router>
+ </Layout>
+ </MantineNotificationsProvider>
+ </ThemeProvider>
+ </BrowserRouter>
);
}
diff --git a/client/js/app/src/app/assets/img/vespa-logo.svg b/client/js/app/src/app/assets/img/vespa-logo.svg
index 239a2a0fc13..96f8167d790 100644
--- a/client/js/app/src/app/assets/img/vespa-logo.svg
+++ b/client/js/app/src/app/assets/img/vespa-logo.svg
@@ -1,235 +1,37 @@
-<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 426.73 157">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 195.67 57.59">
<defs>
<style>
.cls-1 {
- fill: none;
- clip-rule: evenodd;
+ fill: none;
}
+
.cls-2 {
- clip-path: url(#clip-path);
- }
- .cls-3 {
- clip-path: url(#clip-path-2);
- }
- .cls-4 {
- clip-path: url(#clip-path-3);
- }
- .cls-5 {
- clip-path: url(#clip-path-4);
- }
- .cls-6 {
- clip-path: url(#clip-path-5);
- }
- .cls-7 {
- clip-path: url(#clip-path-6);
- }
- .cls-8 {
- clip-path: url(#clip-path-7);
- }
- .cls-9 {
- clip-path: url(#clip-path-8);
- }
- .cls-10 {
- clip-path: url(#clip-path-9);
- }
- .cls-11 {
- clip-path: url(#clip-path-10);
- }
- .cls-12 {
- clip-path: url(#clip-path-11);
- }
- .cls-13 {
- clip-path: url(#clip-path-12);
- }
- .cls-14 {
- clip-path: url(#clip-path-13);
- }
- .cls-15 {
- clip-path: url(#clip-path-14);
- }
- .cls-16 {
- clip-path: url(#clip-path-15);
- }
- .cls-17 {
- clip-path: url(#clip-path-16);
- }
- .cls-18 {
- clip-path: url(#clip-path-17);
- }
- .cls-19 {
- clip-path: url(#clip-path-18);
- }
- .cls-20 {
- clip-path: url(#clip-path-19);
- }
- .cls-21 {
- clip-path: url(#clip-path-20);
- }
- .cls-22 {
- clip-path: url(#clip-path-21);
- }
- .cls-23 {
- clip-path: url(#clip-path-22);
- }
- .cls-24 {
- clip-path: url(#clip-path-23);
- }
- .cls-25 {
- clip-path: url(#clip-path-24);
- }
- .cls-26 {
- clip-path: url(#clip-path-25);
- }
- .cls-27 {
- fill: #ff9d4b;
- }
- .cls-28 {
- fill: url(#linear-gradient);
- }
- .cls-29 {
- fill: #1a7db6;
- }
- .cls-30 {
- fill: url(#linear-gradient-2);
- }
- .cls-31 {
- fill: #fff;
+ fill: #e9e9e9;
}
</style>
- <clipPath id="clip-path">
- <polygon class="cls-1"
- points="-126.52 -1487.49 133.48 -1388.16 133.48 -1648.82 -126.52 -1748.16 -126.52 -1487.49" />
- </clipPath>
- <clipPath id="clip-path-2">
- <path class="cls-1"
- d="M-1.82-1672.51a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.33,6.31,6.31,0,0,1,6.3,6.33,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-3">
- <path class="cls-1"
- d="M-1.82-1616a6.31,6.31,0,0,1-6.3-6.33,6.3,6.3,0,0,1,6.3-6.31,6.3,6.3,0,0,1,6.3,6.31,6.31,6.31,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-4">
- <path class="cls-1"
- d="M-1.82-1559.57a6.31,6.31,0,0,1-6.3-6.32,6.3,6.3,0,0,1,6.3-6.32,6.3,6.3,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-5">
- <path class="cls-1"
- d="M-1.82-1504.78a6.32,6.32,0,0,1-6.3-6.33,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.32,6.32,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-6">
- <path class="cls-1"
- d="M-1.82-1446.63a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-7">
- <path class="cls-1"
- d="M-1.82-1390.16a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-8">
- <path class="cls-1"
- d="M-55.58-1672.51a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.33,6.31,6.31,0,0,1,6.3,6.33,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-9">
- <path class="cls-1"
- d="M-55.58-1616a6.31,6.31,0,0,1-6.3-6.33,6.3,6.3,0,0,1,6.3-6.31,6.3,6.3,0,0,1,6.3,6.31,6.31,6.31,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-10">
- <path class="cls-1"
- d="M-55.58-1559.57a6.31,6.31,0,0,1-6.3-6.32,6.3,6.3,0,0,1,6.3-6.32,6.3,6.3,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-11">
- <path class="cls-1"
- d="M-55.58-1504.78a6.32,6.32,0,0,1-6.3-6.33,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.32,6.32,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-12">
- <path class="cls-1"
- d="M-55.58-1446.63a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-13">
- <path class="cls-1"
- d="M-55.58-1390.16a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-14">
- <path class="cls-1"
- d="M-106-1672.51a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.33,6.31,6.31,0,0,1,6.3,6.33,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-15">
- <path class="cls-1"
- d="M-106-1616a6.31,6.31,0,0,1-6.3-6.33,6.3,6.3,0,0,1,6.3-6.31,6.3,6.3,0,0,1,6.3,6.31A6.31,6.31,0,0,1-106-1616" />
- </clipPath>
- <clipPath id="clip-path-16">
- <path class="cls-1"
- d="M-106-1559.57a6.31,6.31,0,0,1-6.3-6.32,6.3,6.3,0,0,1,6.3-6.32,6.3,6.3,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-17">
- <path class="cls-1"
- d="M-106-1504.78a6.32,6.32,0,0,1-6.3-6.33,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.32,6.32,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-18">
- <path class="cls-1"
- d="M-106-1446.63a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-19">
- <path class="cls-1"
- d="M-106-1390.16a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-20">
- <path class="cls-1"
- d="M-157.22-1672.51a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.33,6.31,6.31,0,0,1,6.3,6.33,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-21">
- <path class="cls-1"
- d="M-157.22-1616a6.31,6.31,0,0,1-6.3-6.33,6.3,6.3,0,0,1,6.3-6.31,6.3,6.3,0,0,1,6.3,6.31,6.31,6.31,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-22">
- <path class="cls-1"
- d="M-157.22-1559.57a6.31,6.31,0,0,1-6.3-6.32,6.3,6.3,0,0,1,6.3-6.32,6.3,6.3,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-23">
- <path class="cls-1"
- d="M-157.22-1504.78a6.32,6.32,0,0,1-6.3-6.33,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.32,6.32,0,0,1-6.3,6.33" />
- </clipPath>
- <clipPath id="clip-path-24">
- <path class="cls-1"
- d="M-157.22-1446.63a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <clipPath id="clip-path-25">
- <path class="cls-1"
- d="M-157.22-1390.16a6.31,6.31,0,0,1-6.3-6.32,6.31,6.31,0,0,1,6.3-6.32,6.31,6.31,0,0,1,6.3,6.32,6.31,6.31,0,0,1-6.3,6.32" />
- </clipPath>
- <linearGradient id="linear-gradient" x1="838.35" y1="43.03" x2="793.28" y2="71.6"
- gradientTransform="matrix(-1, 0, 0, 1, 920.21, 0)" gradientUnits="userSpaceOnUse">
- <stop offset="0.01" stop-color="#c6783e" />
- <stop offset="0.54" stop-color="#ff9750" />
- </linearGradient>
- <linearGradient id="linear-gradient-2" x1="51.41" y1="102.76" x2="-24.85" y2="61.2" gradientUnits="userSpaceOnUse">
- <stop offset="0" stop-color="#005a8e" />
- <stop offset="0.54" stop-color="#1a7db6" />
- </linearGradient>
</defs>
- <polygon class="cls-27"
- points="75.53 8.2 24.79 42.66 24.79 101.98 75.53 66.22 126.27 101.98 126.27 42.66 75.53 8.2" />
- <polygon class="cls-28" points="75.53 66.22 75.53 8.2 126.27 42.66 126.27 101.98 75.53 66.22" />
- <polygon class="cls-29"
- points="55.77 80.19 5.03 44.42 5.03 103.74 55.77 138.2 106.51 103.74 106.51 44.42 55.77 80.19" />
- <polygon class="cls-30" points="55.77 80.19 55.77 138.2 5.03 103.74 5.03 44.42 55.77 80.19" />
- <path class="cls-31"
- d="M186.09,100.33H171a.91.91,0,0,1-.85-.61L151.62,46.43a.9.9,0,0,1,.85-1.2h7.89a8.49,8.49,0,0,1,8.19,6.22l10,35.82h.3l9.93-35.81A8.5,8.5,0,0,1,197,45.23h7.54a.9.9,0,0,1,.85,1.2L187,99.72A.92.92,0,0,1,186.09,100.33Z" />
- <path class="cls-31"
- d="M283.73,44.28c13.18,0,22.09,6.53,22.82,16.49a.91.91,0,0,1-.9,1H293.88A.89.89,0,0,1,293,61c-.65-3.92-4.2-6.36-9.47-6.36s-8.76,2.35-8.76,5.9c0,2.76,2.4,4.61,7.35,5.76l10.36,2.25c11.06,2.5,15.46,6.76,15.46,15,0,10.71-9.85,17.77-24.26,17.77-14.05,0-23-6.56-24.28-16.6a.92.92,0,0,1,.9-1h12.52a.91.91,0,0,1,.88.69c.95,4.22,4.63,6.57,10.38,6.57s9.35-2.25,9.35-5.86c0-2.85-1.9-4.35-6.9-5.55l-10.16-2.3C266,74.86,260.66,69.5,260.66,61.44,260.66,51.09,269.76,44.28,283.73,44.28Z" />
- <path class="cls-31"
- d="M367.47,72.75c0,17.52-8.6,28.23-22.41,28.23-8,0-14.11-3.66-17.12-9.91h-.3v18.77a8.49,8.49,0,0,1-8.5,8.5h-5.21a.9.9,0,0,1-.9-.9V46.13a.9.9,0,0,1,.9-.9h12.61a.9.9,0,0,1,.9.9v8.51h.3c2.9-6.21,9.36-10.06,17.12-10.06C358.82,44.58,367.47,55.24,367.47,72.75Zm-15,0c0-9.9-4.95-16.36-12.51-16.36S327.59,63,327.59,72.8s5,16.37,12.41,16.37S352.51,82.76,352.51,72.75Z" />
- <path class="cls-31"
- d="M371.86,84.46c0-10,7.66-15.66,21.72-16.51l12.91-.8a.9.9,0,0,0,.85-.9v-2.8c0-5.31-3.65-8.21-9.66-8.21-5,0-8.59,2.5-9.56,6.15a.94.94,0,0,1-.9.66H375.58a.89.89,0,0,1-.9-1c.92-10,10.26-16.8,23.6-16.8,14.16,0,23.42,7.26,23.42,18.27V99.43a.9.9,0,0,1-.9.9h-4.7a8.51,8.51,0,0,1-8.51-8.51h-.3c-3,5.75-9.81,9.16-16.86,9.16C379.82,101,371.86,94.32,371.86,84.46Zm35.48-4.35v-4l-11.56.8c-6.11.4-9.36,2.8-9.36,6.85s3.46,6.61,8.76,6.61C401.93,90.32,407.34,86.11,407.34,80.11Z" />
- <path class="cls-31"
- d="M229.48,44.28C213.32,44.28,203,55.49,203,73s10.26,28.27,27,28.27c12.47,0,22-6.16,24.51-15.6a1.71,1.71,0,0,0-1.64-2.17H242.68a1.87,1.87,0,0,0-1.53,1c-1.71,3.67-5.8,5.88-10.87,5.88A12.63,12.63,0,0,1,221,86.7a13.58,13.58,0,0,1-3.54-9.64v-.9h36.33a1.7,1.7,0,0,0,1.7-1.7V71.65C255.45,54.89,245.34,44.28,229.48,44.28ZM217.57,67.1c.51-7.06,5.4-11.91,12.07-11.91s11.45,4.7,11.7,11.91Z" />
- <path class="cls-31"
- d="M188.47,127c-.55-2.91-2.64-4.83-6.08-4.83-4.36,0-6.81,3.25-6.81,9.28s2.47,9.42,6.81,9.42c3.3,0,5.47-1.61,6.08-4.64H196c-.67,6.86-5.67,11.28-13.64,11.28-9.56,0-15-5.78-15-16.06s5.39-15.92,15-15.92c8.11,0,13,4.5,13.64,11.47Z" />
- <path class="cls-31" d="M199.21,104.5h0a8.08,8.08,0,0,1,8.08,8.08v34.26h0a8.08,8.08,0,0,1-8.08-8.08Z" />
- <path class="cls-31"
- d="M210.18,131.5c0-9.92,5.75-16,15.09-16s15.09,6,15.09,16-5.67,16-15.09,16S210.18,141.53,210.18,131.5Zm21.87,0c0-5.89-2.5-9.36-6.78-9.36s-6.78,3.47-6.78,9.36,2.44,9.4,6.78,9.4S232.05,137.45,232.05,131.5Z" />
- <path class="cls-31"
- d="M271.83,146.84H264v-4.92h-.5c-1.45,3.56-4.31,5.59-8.95,5.59-6.61,0-10.72-4.22-10.72-11.34v-20h8.08v17.9c0,4.22,1.92,6.39,5.64,6.39,4,0,6.2-2.53,6.2-6.61V116.19h8.08Z" />
- <path class="cls-31"
- d="M274.62,131.48c0-9.76,4.78-15.79,12.47-15.79,4.14,0,7.56,2,9.15,5.39h.47V104.5h0a8.08,8.08,0,0,1,8.08,8.08v34.26h-3A4.81,4.81,0,0,1,297,142h-.5c-1.64,3.31-5.11,5.28-9.37,5.28C279.37,147.31,274.62,141.26,274.62,131.48Zm8.31,0c0,5.67,2.58,9.06,6.91,9.06s7-3.42,7-9-2.64-9.06-7-9.06S282.93,125.89,282.93,131.5Z" />
+ <g id="Layer_2">
+ <g id="Layer_1-2">
+ <path class="cls-1"
+ d="M179,33.76c0,1.91,1.63,3.11,4.13,3.11,3.19,0,5.74-2,5.74-4.81V30.14l-5.46.38C180.55,30.71,179,31.84,179,33.76Z" />
+ <path class="cls-1" d="M105,20.29c-3.14,0-5.45,2.3-5.69,5.63h11.22C110.42,22.51,108.2,20.29,105,20.29Z" />
+ <path class="cls-1"
+ d="M157.11,20.86c-3.52,0-5.86,3.1-5.86,7.75s2.34,7.72,5.86,7.72,5.9-3,5.9-7.75S160.67,20.86,157.11,20.86Z" />
+ <polygon class="cls-2" points="31.27 24.98 31.27 0 9.32 14.91 9.32 21.27 22.93 30.86 31.27 24.98" />
+ <polygon class="cls-2" points="33.27 23.59 47.9 13.28 47.9 35.28 55.23 40.45 55.23 14.91 33.27 0 33.27 23.59" />
+ <path class="cls-2"
+ d="M93.14,15.59H89.59a4,4,0,0,0-3.87,2.94L81,35.43h-.14l-4.71-16.9a4,4,0,0,0-3.86-2.94H68.59a.43.43,0,0,0-.4.57l8.73,25.15a.43.43,0,0,0,.4.29h7.14a.43.43,0,0,0,.4-.29l8.69-25.15A.43.43,0,0,0,93.14,15.59Z" />
+ <path class="cls-2"
+ d="M134.68,26.6l-4.89-1.06c-2.34-.55-3.47-1.42-3.47-2.72,0-1.68,1.65-2.79,4.13-2.79s4.16,1.16,4.47,3a.42.42,0,0,0,.42.36h5.55a.43.43,0,0,0,.43-.46c-.35-4.7-4.55-7.78-10.78-7.78-6.59,0-10.88,3.21-10.88,8.1,0,3.8,2.52,6.33,7.41,7.44l4.8,1.08c2.36.57,3.26,1.28,3.26,2.62,0,1.71-1.68,2.77-4.42,2.77s-4.45-1.11-4.9-3.1a.43.43,0,0,0-.41-.33h-5.91a.42.42,0,0,0-.42.48c.58,4.74,4.82,7.84,11.45,7.84,6.8,0,11.46-3.33,11.46-8.39C142,29.79,139.9,27.78,134.68,26.6Z" />
+ <path class="cls-2"
+ d="M159.4,15.29A8.63,8.63,0,0,0,151.32,20h-.14V16a.43.43,0,0,0-.43-.43H144.8a.42.42,0,0,0-.42.43V49.68a.42.42,0,0,0,.42.42h2.46a4,4,0,0,0,4-4V37.23h.15c1.41,3,4.32,4.68,8.07,4.68,6.52,0,10.58-5.06,10.58-13.33S166,15.29,159.4,15.29Zm-2.29,21c-3.52,0-5.86-3-5.86-7.72s2.34-7.75,5.86-7.75,5.9,3.05,5.9,7.72S160.67,36.33,157.11,36.33Z" />
+ <path class="cls-2"
+ d="M184.62,15.15c-6.3,0-10.71,3.21-11.15,7.93a.43.43,0,0,0,.43.45h5.5a.43.43,0,0,0,.42-.31c.46-1.72,2.15-2.9,4.51-2.9,2.84,0,4.56,1.37,4.56,3.87v1.33a.42.42,0,0,1-.4.42l-6.09.38c-6.64.4-10.26,3.07-10.26,7.79s3.76,7.8,8.77,7.8c3.33,0,6.54-1.61,8-4.33H189a4,4,0,0,0,4,4h2.22a.43.43,0,0,0,.43-.43V23.77C195.67,18.57,191.3,15.15,184.62,15.15Zm4.27,16.91c0,2.83-2.55,4.81-5.74,4.81-2.5,0-4.13-1.2-4.13-3.11s1.53-3,4.41-3.24l5.46-.38Z" />
+ <path class="cls-2"
+ d="M104.94,15.14c-7.63,0-12.5,5.29-12.5,13.56s4.85,13.35,12.76,13.35c5.89,0,10.37-2.91,11.57-7.36a.81.81,0,0,0-.77-1h-4.83a.89.89,0,0,0-.72.46c-.81,1.74-2.74,2.78-5.13,2.78a6,6,0,0,1-4.4-1.73,6.43,6.43,0,0,1-1.67-4.55v-.43H116.4a.8.8,0,0,0,.8-.8V28.07C117.2,20.15,112.43,15.14,104.94,15.14ZM99.32,25.92c.24-3.33,2.55-5.63,5.69-5.63s5.41,2.22,5.53,5.63Z" />
+ <polygon class="cls-2"
+ points="34.27 25.51 24.2 32.61 24.2 57.59 46.15 42.68 46.15 33.88 46.15 17.14 34.27 25.51" />
+ <polygon class="cls-2" points="21.2 32.08 9.32 23.71 0 17.14 0 42.68 21.95 57.59 21.95 32.61 21.2 32.08" />
+ </g>
+ </g>
</svg>
diff --git a/client/js/app/src/app/assets/index.js b/client/js/app/src/app/assets/index.js
index a62869fa71b..bf132dd86a7 100644
--- a/client/js/app/src/app/assets/index.js
+++ b/client/js/app/src/app/assets/index.js
@@ -1,2 +1 @@
export { default as VespaLogo } from 'app/assets/img/vespa-logo.svg';
-export { default as VespaIcon } from 'app/assets/img/vespa-icon.svg';
diff --git a/client/js/app/src/app/components/card-link/card-link.jsx b/client/js/app/src/app/components/card-link/card-link.jsx
new file mode 100644
index 00000000000..636c8e35e15
--- /dev/null
+++ b/client/js/app/src/app/components/card-link/card-link.jsx
@@ -0,0 +1,36 @@
+import React from 'react';
+import { Box } from '@mantine/core';
+
+export function CardLink({
+ sx,
+ withBorder = true,
+ borderStyle = 'solid',
+ minHeight = '89px',
+ minWidth = 'auto',
+ ...props
+}) {
+ return (
+ <Box
+ sx={(theme) => ({
+ minHeight,
+ minWidth,
+ display: 'grid',
+ placeContent: 'center',
+ justifyItems: 'center',
+ rowGap: '8px',
+ ...theme.fn.hover({
+ cursor: 'pointer',
+ background: theme.cr.getSubtleBackground(),
+ border: withBorder
+ ? `1px ${borderStyle} ${theme.cr.getUiElementBorderAndFocus()}`
+ : 0,
+ }),
+ border: withBorder
+ ? `1px ${borderStyle} ${theme.cr.getSubtleBorderAndSeparator()}`
+ : 0,
+ ...sx,
+ })}
+ {...props}
+ />
+ );
+}
diff --git a/client/js/app/src/app/components/containers/container.jsx b/client/js/app/src/app/components/containers/container.jsx
new file mode 100644
index 00000000000..fb30b180a3d
--- /dev/null
+++ b/client/js/app/src/app/components/containers/container.jsx
@@ -0,0 +1,14 @@
+import React from 'react';
+import { Box } from '@mantine/core';
+
+export function Container({ sx, ...props }) {
+ return (
+ <Box
+ sx={() => ({
+ display: 'grid',
+ ...sx,
+ })}
+ {...props}
+ />
+ );
+}
diff --git a/client/js/app/src/app/components/containers/content.jsx b/client/js/app/src/app/components/containers/content.jsx
new file mode 100644
index 00000000000..bbf51a063f2
--- /dev/null
+++ b/client/js/app/src/app/components/containers/content.jsx
@@ -0,0 +1,32 @@
+import React from 'react';
+import { Paper, Stack, Box } from '@mantine/core';
+
+export function Content({
+ transparent,
+ withBorder,
+ padding,
+ borderStyle = 'solid',
+ stack = true,
+ sx,
+ ...props
+}) {
+ const Wrapper = stack ? Stack : Box;
+ return (
+ <Paper
+ sx={(theme) => ({
+ background: transparent && 'transparent',
+ border: withBorder
+ ? `1px ${borderStyle} ${theme.cr.getSubtleBorderAndSeparator()}`
+ : 0,
+ })}
+ >
+ <Wrapper
+ sx={(theme) => ({
+ padding: padding ?? theme.spacing.md,
+ ...sx,
+ })}
+ {...props}
+ />
+ </Paper>
+ );
+}
diff --git a/client/js/app/src/app/components/containers/message.jsx b/client/js/app/src/app/components/containers/message.jsx
new file mode 100644
index 00000000000..abe3286c021
--- /dev/null
+++ b/client/js/app/src/app/components/containers/message.jsx
@@ -0,0 +1,16 @@
+import React from 'react';
+import { Box } from '@mantine/core';
+
+export function Message({ sx, ...props }) {
+ return (
+ <Box
+ sx={() => ({
+ display: 'grid',
+ placeContent: 'center',
+ minHeight: '89px',
+ ...sx,
+ })}
+ {...props}
+ />
+ );
+}
diff --git a/client/js/app/src/app/components/containers/section.jsx b/client/js/app/src/app/components/containers/section.jsx
new file mode 100644
index 00000000000..d9d43a7aa5a
--- /dev/null
+++ b/client/js/app/src/app/components/containers/section.jsx
@@ -0,0 +1,17 @@
+import React from 'react';
+import { Stack } from '@mantine/core';
+
+export function Section({ transparent, sx, ...props }) {
+ return (
+ <Stack
+ sx={(theme) => ({
+ padding: theme.spacing.md,
+ background: transparent
+ ? 'transparent'
+ : theme.cr.getSubtleBackground(),
+ ...sx,
+ })}
+ {...props}
+ />
+ );
+}
diff --git a/client/js/app/src/app/components/icon/icon.jsx b/client/js/app/src/app/components/icon/icon.jsx
new file mode 100644
index 00000000000..edc86250b01
--- /dev/null
+++ b/client/js/app/src/app/components/icon/icon.jsx
@@ -0,0 +1,47 @@
+import React from 'react';
+import { library } from '@fortawesome/fontawesome-svg-core';
+import { Box } from '@mantine/core';
+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import {
+ faArrowsToDot,
+ faChartGantt,
+ faCheck,
+ faCircleMinus,
+ faCopy,
+ faDownload,
+ faPaste,
+ faPlus,
+ faXmark,
+ faInfo,
+ faExclamation,
+} from '@fortawesome/free-solid-svg-icons';
+
+// TODO: use dynamic import
+
+library.add(
+ faArrowsToDot,
+ faChartGantt,
+ faCircleMinus,
+ faPlus,
+ faPaste,
+ faDownload,
+ faCopy,
+ faCheck,
+ faXmark,
+ faInfo,
+ faExclamation
+);
+
+export function Icon({ name, type = 'solid', color, ...rest }) {
+ const icon = `fa-${type} fa-${name}`;
+ return (
+ <Box
+ sx={(theme) => ({
+ ...(color && { color: theme.cr.getSolidBackground(color) }),
+ })}
+ component={FontAwesomeIcon}
+ icon={icon}
+ {...rest}
+ />
+ );
+}
diff --git a/client/js/app/src/app/components/index.js b/client/js/app/src/app/components/index.js
index 488fc1b23fa..83ac39bc932 100644
--- a/client/js/app/src/app/components/index.js
+++ b/client/js/app/src/app/components/index.js
@@ -1,2 +1,9 @@
export { Error } from 'app/components/layout/error';
export { Layout } from 'app/components/layout/layout';
+export { Message } from 'app/components/containers/message';
+export { Container } from 'app/components/containers/container';
+export { Content } from 'app/components/containers/content';
+export { Section } from 'app/components/containers/section';
+export { Link } from 'app/components/link/link';
+export { CardLink } from 'app/components/card-link/card-link';
+export { Icon } from 'app/components/icon/icon';
diff --git a/client/js/app/src/app/components/layout/header-logo.jsx b/client/js/app/src/app/components/layout/header-logo.jsx
index 42b03af4bf6..09c0fcd1334 100644
--- a/client/js/app/src/app/components/layout/header-logo.jsx
+++ b/client/js/app/src/app/components/layout/header-logo.jsx
@@ -1,7 +1,12 @@
import React from 'react';
import { Image } from '@mantine/core';
+import { Link } from 'react-router-dom';
import { VespaLogo } from 'app/assets';
export function HeaderLogo() {
- return <Image height={34} src={VespaLogo} />;
+ return (
+ <Link to="/">
+ <Image height={34} src={VespaLogo} />
+ </Link>
+ );
}
diff --git a/client/js/app/src/app/components/layout/header.jsx b/client/js/app/src/app/components/layout/header.jsx
index 2ddc3943445..b4eac293826 100644
--- a/client/js/app/src/app/components/layout/header.jsx
+++ b/client/js/app/src/app/components/layout/header.jsx
@@ -4,7 +4,17 @@ import { HeaderLogo } from 'app/components/layout/header-logo';
export function Header() {
return (
- <MantineHeader height={55} sx={{ display: 'flex', alignItems: 'center' }}>
+ <MantineHeader
+ height={55}
+ sx={(theme) => ({
+ display: 'flex',
+ alignItems: 'center',
+ paddingLeft: theme.spacing.md,
+ paddingRight: theme.spacing.md,
+ background: theme.cr.getSolidBackground(),
+ borderBottom: `1px solid ${theme.cr.getSubtleBorderAndSeparator()}`,
+ })}
+ >
<HeaderLogo />
</MantineHeader>
);
diff --git a/client/js/app/src/app/components/layout/layout.jsx b/client/js/app/src/app/components/layout/layout.jsx
index f0f5a0594c0..532a9ce3630 100644
--- a/client/js/app/src/app/components/layout/layout.jsx
+++ b/client/js/app/src/app/components/layout/layout.jsx
@@ -3,9 +3,5 @@ import { AppShell } from '@mantine/core';
import { Header } from 'app/components/layout/header';
export function Layout({ children }) {
- return (
- <AppShell header={<Header />} fixed>
- {children}
- </AppShell>
- );
+ return <AppShell header={<Header />}>{children}</AppShell>;
}
diff --git a/client/js/app/src/app/components/link/link.jsx b/client/js/app/src/app/components/link/link.jsx
new file mode 100644
index 00000000000..288174d21be
--- /dev/null
+++ b/client/js/app/src/app/components/link/link.jsx
@@ -0,0 +1,23 @@
+import React from 'react';
+import { Link as InternalLink } from 'react-router-dom';
+import { Anchor } from '@mantine/core';
+
+export const isInternalLink = (link) => {
+ if (!link) return false;
+ return !/^[a-z]+:\/\//.test(link);
+};
+
+export function Link({ to, api = false, ...props }) {
+ const internal = !api && isInternalLink(to);
+
+ if (!props.download && to && internal)
+ return <Anchor component={InternalLink} to={to} {...props} />;
+
+ const fixedProps = Object.assign(
+ to ? { href: (api ? window.config.api : '') + to } : {},
+ to && !internal && { target: '_blank', rel: 'noopener noreferrer' },
+ props
+ );
+
+ return <Anchor {...fixedProps} />;
+}
diff --git a/client/js/app/src/app/libs/app-router.jsx b/client/js/app/src/app/libs/app-router.jsx
deleted file mode 100644
index 0f196c5d58b..00000000000
--- a/client/js/app/src/app/libs/app-router.jsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import React from 'react';
-import { Redirect, Router } from '@reach/router';
-import { Error } from 'app/components';
-
-const mainTitle = 'Vespa App';
-
-function AppRoute({ element, title, default: isDefault, ...props }) {
- const clone = React.cloneElement(element, props, props.children);
- if (title != null) {
- const titleStr = typeof title === 'function' ? title(props) : title;
- document.title = titleStr.endsWith(mainTitle)
- ? titleStr
- : `${titleStr} - ${mainTitle}`;
- } else if (isDefault) {
- // Reset the title if title is not set and this is a default router
- document.title = mainTitle;
- }
- return clone;
-}
-
-export function AppRouter({ children, props: inParentProps }) {
- const newProps = Object.assign(
- { primary: false, component: React.Fragment },
- inParentProps
- );
-
- // If there is only one route then this comes as an object.
- if (!Array.isArray(children)) children = [children];
- const hasDefault = children.some((child) => child.props.default);
-
- return (
- <Router {...newProps}>
- {children
- .filter(({ props }) => props.enabled ?? true)
- .map((e, i) => {
- if (e.type === Redirect) return e;
- return <AppRoute key={i} element={e} {...e.props} />;
- })}
- {!hasDefault && <Error code={404} default />}
- </Router>
- );
-}
diff --git a/client/js/app/src/app/libs/notification/index.jsx b/client/js/app/src/app/libs/notification/index.jsx
new file mode 100644
index 00000000000..9313e3c9adf
--- /dev/null
+++ b/client/js/app/src/app/libs/notification/index.jsx
@@ -0,0 +1,2 @@
+export * from 'app/libs/notification/rest-message';
+export * from 'app/libs/notification/messages';
diff --git a/client/js/app/src/app/libs/notification/messages.jsx b/client/js/app/src/app/libs/notification/messages.jsx
new file mode 100644
index 00000000000..87f94b0dda0
--- /dev/null
+++ b/client/js/app/src/app/libs/notification/messages.jsx
@@ -0,0 +1,77 @@
+import React from 'react';
+import { showNotification } from '@mantine/notifications';
+import { Icon } from 'app/components';
+import { SHADE } from 'app/styles/theme/colors';
+
+function getStyles(color) {
+ return (theme) => ({
+ root: {
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ background: theme.fn.themeColor(color, SHADE.UI_ELEMENT_BACKGROUND),
+ borderColor: theme.fn.themeColor(
+ color,
+ SHADE.UI_ELEMENT_BORDER_AND_FOCUS
+ ),
+ },
+ title: {
+ fontWeight: 700,
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ '&:hover': {
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ },
+ },
+ description: {
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ '&:hover': {
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ },
+ },
+ closeButton: {
+ color: theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ '&:hover': {
+ backgroundColor: theme.fn.themeColor(
+ color,
+ SHADE.HOVERED_UI_ELEMENT_BACKGROUND
+ ),
+ },
+ },
+ });
+}
+
+const commonMessage = ({ title, icon, color, message }) => {
+ return showNotification({
+ styles: getStyles(color),
+ icon: <Icon name={icon} />,
+ title,
+ color,
+ message,
+ });
+};
+
+export const infoMessage = (
+ message,
+ title = 'Info',
+ icon = 'info',
+ color = 'blue'
+) => commonMessage({ title, icon, color, message });
+
+export const warningMessage = (
+ message,
+ title = 'Warning',
+ icon = 'exclamation',
+ color = 'orange'
+) => commonMessage({ title, icon, color, message });
+
+export const errorMessage = (
+ message,
+ title = 'Error',
+ icon = 'xmark',
+ color = 'red'
+) => commonMessage({ title, icon, color, message });
+
+export const successMessage = (
+ message,
+ title = 'Success',
+ icon = 'check',
+ color = 'green'
+) => commonMessage({ title, icon, color, message });
diff --git a/client/js/app/src/app/libs/notification/rest-message.jsx b/client/js/app/src/app/libs/notification/rest-message.jsx
new file mode 100644
index 00000000000..d05d28754b8
--- /dev/null
+++ b/client/js/app/src/app/libs/notification/rest-message.jsx
@@ -0,0 +1,43 @@
+import {
+ errorMessage,
+ infoMessage,
+ successMessage,
+} from 'app/libs/notification/index';
+
+export const restMessage = (response, prefix, code = 200) => {
+ // Gracefully handle various types of rest responses input
+ // Response can be a raw fetch request, an already decoded object or a plain string
+ if (typeof response === 'object') {
+ if (typeof response.text === 'function') {
+ Promise.resolve(response.text()).then((text) => {
+ restMessageContent(response.status || code, text, prefix);
+ });
+ } else {
+ restMessageContent(
+ response.code || 200,
+ response.message || JSON.stringify(response),
+ prefix
+ );
+ }
+ } else if (typeof response === 'string') {
+ restMessageContent(code, response, prefix);
+ }
+};
+
+const restMessageContent = (code, message, prefix) => {
+ // Trunk long messages
+ if (message.length > 200) message = message.substring(0, 200) + '...';
+
+ // Add pre-message if given
+ // Most of the time the message is just "Success" - so you would like
+ // to prefix it with eg. 'Adding user: '
+ message = prefix ? prefix + message : message;
+
+ if (code < 300) {
+ successMessage(message);
+ } else if (code < 400) {
+ infoMessage(message);
+ } else {
+ errorMessage(message);
+ }
+};
diff --git a/client/js/app/src/app/libs/router.jsx b/client/js/app/src/app/libs/router.jsx
new file mode 100644
index 00000000000..c942470d057
--- /dev/null
+++ b/client/js/app/src/app/libs/router.jsx
@@ -0,0 +1,52 @@
+import React from 'react';
+import { Routes, Route, useParams, Navigate } from 'react-router-dom';
+import { Error } from 'app/components';
+
+const mainTitle = 'Vespa App';
+
+function TitledRoute({ element, title, default: isDefault, ...props }) {
+ const params = useParams();
+ const clone = React.cloneElement(element, Object.assign(props, params));
+ if (title != null) {
+ const titleStr = typeof title === 'function' ? title(params) : title;
+ document.title = titleStr.endsWith(mainTitle)
+ ? titleStr
+ : `${titleStr} - ${mainTitle}`;
+ } else if (isDefault) {
+ // Reset the title if title is not set and this is a default router
+ document.title = mainTitle;
+ }
+
+ return clone;
+}
+
+export function Router({ children }) {
+ // If there is only one route then this comes as an object.
+ if (!Array.isArray(children)) children = [children];
+ children = children.filter(({ props }) => props.enabled ?? true);
+
+ if (!children.some((child) => child.props.default))
+ children.push(<Error code={404} default />);
+
+ return (
+ <Routes>
+ {children.map(({ props, ...element }, i) => (
+ <Route
+ key={`${i}-${props.path}`}
+ path={props.default ? '*' : props.path}
+ element={
+ element.type === Redirect ? (
+ Object.assign({ props }, element)
+ ) : (
+ <TitledRoute element={element} {...props} />
+ )
+ }
+ />
+ ))}
+ </Routes>
+ );
+}
+
+export function Redirect({ to, replace }) {
+ return <Navigate {...{ to, replace }} />;
+}
diff --git a/client/js/app/src/app/libs/theme-provider.jsx b/client/js/app/src/app/libs/theme-provider.jsx
new file mode 100644
index 00000000000..c5e9cbee963
--- /dev/null
+++ b/client/js/app/src/app/libs/theme-provider.jsx
@@ -0,0 +1,19 @@
+import React from 'react';
+import { Global, MantineProvider } from '@mantine/core';
+import { Colors } from 'app/styles/theme/colors';
+import { styles } from 'app/styles/global';
+import { getTheme } from 'app/styles/theme';
+
+function setColorResolver(theme) {
+ if (!theme.cr) theme.cr = new Colors(theme);
+ return theme;
+}
+
+export function ThemeProvider({ children }) {
+ return (
+ <MantineProvider theme={getTheme()}>
+ <Global styles={(theme) => styles(setColorResolver(theme))} />
+ {children}
+ </MantineProvider>
+ );
+}
diff --git a/client/js/app/src/app/pages/home/home.jsx b/client/js/app/src/app/pages/home/home.jsx
index d39b696bf08..737b07acf3a 100644
--- a/client/js/app/src/app/pages/home/home.jsx
+++ b/client/js/app/src/app/pages/home/home.jsx
@@ -1,5 +1,31 @@
import React from 'react';
+import { Container, SimpleGrid, Space } from '@mantine/core';
+import { Link, CardLink, Icon } from 'app/components';
+
+// TODO: move SimpleGrid to components
export function Home() {
- return <>home</>;
+ return (
+ <Container>
+ <Space h={55} />
+ <SimpleGrid
+ style={{ gridAutoRows: 'minmax(0, 144px)' }}
+ breakpoints={[
+ { maxWidth: 'sm', cols: 2, spacing: 'sm' },
+ { maxWidth: 'xs', cols: 1, spacing: 'sm' },
+ ]}
+ spacing="lg"
+ cols={2}
+ >
+ <CardLink component={Link} to="/querybuilder">
+ <Icon name="arrows-to-dot" size="2x" />
+ query builder
+ </CardLink>
+ <CardLink component={Link} to="/querytracer">
+ <Icon name="chart-gantt" size="2x" />
+ query tracer
+ </CardLink>
+ </SimpleGrid>
+ </Container>
+ );
}
diff --git a/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx b/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx
new file mode 100644
index 00000000000..7299f1cb777
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx
@@ -0,0 +1,349 @@
+// Generates a random hex string of size "size"
+const genRanHex = (size) =>
+ [...Array(size)]
+ .map(() => Math.floor(Math.random() * 16).toString(16))
+ .join('');
+
+const traceID = genRanHex(32);
+const output = { data: [{ traceID: traceID, spans: [], processes: {} }] };
+const processes = output['data'][0]['processes'];
+const processMap = new Map();
+const data = output['data'][0]['spans'];
+let traceStartTimestamp = 0;
+let processID = 1;
+
+export default function transform(trace) {
+ let temp = trace['trace']['children'];
+ let message = temp[0]['message'].split(' ');
+ processes.p0 = { serviceName: message[3], tags: [] };
+ let spans = digDownInTrace(temp);
+ traceStartTimestamp = findTraceStartTime(spans);
+ let firstSpan = createNewSpan(traceStartTimestamp, 0, 'p0', message[6]);
+ const totalDuration = findTotalDuration(spans);
+ firstSpan['duration'] = totalDuration;
+ data.push(firstSpan);
+
+ traverseSpans(spans, firstSpan);
+ return output;
+}
+
+function traverseChildren(span, parent) {
+ let logSpan;
+ if (span.hasOwnProperty('children')) {
+ let duration =
+ (span['children'][span['children'].length - 1]['timestamp'] -
+ span['children'][0]['timestamp']) *
+ 1000;
+ if (isNaN(duration) || duration <= 0) {
+ duration = 1;
+ }
+ parent['duration'] = duration;
+ for (let i = 0; i < span['children'].length; i++) {
+ let x = span['children'][i];
+ if (x.hasOwnProperty('children')) {
+ // Create a new parent span so that the timeline for the spans are correct
+ let message = findProcessName(parent['operationName']);
+ let processKey = message === '' ? 'p0' : getProcess(message);
+ logSpan = createNewSpan(
+ traceStartTimestamp + x['timestamp'] * 1000,
+ duration,
+ processKey,
+ parent['operationName'],
+ [{ refType: 'CHILD_OF', traceID: traceID, spanID: parent['spanID'] }]
+ );
+ data.push(logSpan);
+ traverseChildren(x, logSpan);
+ } else if (Array.isArray(x['message'])) {
+ createProtonSpans(x['message'], parent['spanID']);
+ } else if (x.hasOwnProperty('message') && x.hasOwnProperty('timestamp')) {
+ // only add logs with a timestamp
+ let logPointDuration;
+ if (i >= span['children'].length - 1) {
+ logPointDuration = 1;
+ } else {
+ logPointDuration =
+ findDuration(span['children'], i) - x['timestamp'] * 1000;
+ }
+ if (isNaN(logPointDuration) || logPointDuration <= 0) {
+ logPointDuration = 1;
+ }
+ addLogSpan(data, x, logPointDuration, parent);
+ }
+ }
+ }
+}
+
+function traverseSpans(spans, firstSpan) {
+ for (let i = 0; i < spans.length; i++) {
+ if (spans[i].hasOwnProperty('children')) {
+ traverseChildren(spans[i], data[data.length - 1]);
+ } else if (
+ spans[i].hasOwnProperty('message') &&
+ spans[i].hasOwnProperty('timestamp')
+ ) {
+ let duration;
+ if (i >= spans.length - 1) {
+ duration = 1;
+ } else {
+ duration = findDuration(spans, i) - spans[i]['timestamp'] * 1000;
+ }
+ if (isNaN(duration) || duration <= 0) {
+ duration = 1;
+ }
+ addLogSpan(data, spans[i], duration, firstSpan);
+ }
+ }
+}
+
+function addLogSpan(data, span, duration, parent) {
+ let logPointStart = traceStartTimestamp + span['timestamp'] * 1000;
+ let message = findProcessName(span['message']);
+ let processKey = message === '' ? 'p0' : getProcess(message);
+ let logSpan = createNewSpan(
+ logPointStart,
+ duration,
+ processKey,
+ span['message'],
+ [
+ {
+ refType: 'CHILD_OF',
+ traceID: traceID,
+ spanID: parent['spanID'],
+ },
+ ]
+ );
+ data.push(logSpan);
+}
+
+function createProtonSpans(children, parentID) {
+ let child = children[0];
+ let processKey = genRanHex(5);
+ processes[processKey] = { serviceName: 'Proton:' + genRanHex(3), tags: [] };
+ let startTimestamp = Date.parse(child['start_time']) * 1000;
+ let newSpan = createNewSpan(
+ startTimestamp,
+ child['duration_ms'] * 1000,
+ processKey,
+ 'Search Dispatch',
+ [{ refType: 'CHILD_OF', traceID: traceID, spanID: parentID }]
+ );
+ data.push(newSpan);
+ let traces = child['traces'];
+ for (let k = 0; k < traces.length; k++) {
+ let trace = traces[k];
+ let traceTimestamp = trace['timestamp_ms'];
+ let events;
+ let firstEvent;
+ let duration;
+ processKey = getProcessID();
+ processes[processKey] = { serviceName: trace['tag'], tags: [] };
+ if (trace['tag'] === 'query_execution') {
+ traverseQueryExecution(
+ trace,
+ traceTimestamp,
+ startTimestamp,
+ processKey,
+ newSpan['spanID']
+ );
+ } else {
+ if (trace['tag'] === 'query_execution_plan') {
+ events = [];
+ let nextTrace = traces[k + 1];
+ firstEvent = trace;
+ // query execution plan has no events, duration must therefore be found using the next trace
+ if (nextTrace['tag'] === 'query_execution') {
+ duration =
+ (nextTrace['threads'][0]['traces'][0]['timestamp_ms'] -
+ traceTimestamp) *
+ 1000;
+ } else {
+ duration = (nextTrace['timestamp_ms'] - traceTimestamp) * 1000;
+ }
+ } else {
+ events = trace['traces'];
+ firstEvent = events[0];
+ duration = (traceTimestamp - firstEvent['timestamp_ms']) * 1000;
+ }
+ let childSpan = createNewSpan(
+ startTimestamp + firstEvent['timestamp_ms'] * 1000,
+ duration,
+ processKey,
+ trace['tag'],
+ [{ refType: 'CHILD_OF', traceID: traceID, spanID: newSpan['spanID'] }]
+ );
+ data.push(childSpan);
+ traverseEvents(events, childSpan, startTimestamp, traceTimestamp);
+ }
+ }
+}
+
+// the query execution tag might have several threads
+function traverseQueryExecution(
+ trace,
+ traceTimestamp,
+ startTimestamp,
+ processKey,
+ spanID
+) {
+ let threads = trace['threads'];
+ for (let i = 0; i < threads.length; i++) {
+ let events = threads[i]['traces'];
+ let firstEvent = events[0];
+ let duration = (traceTimestamp - firstEvent['timestamp_ms']) * 1000;
+ let span = createNewSpan(
+ startTimestamp + firstEvent['timestamp_ms'] * 1000,
+ duration,
+ processKey,
+ trace['tag'],
+ [{ refType: 'CHILD_OF', traceID: traceID, spanID: spanID }]
+ );
+ data.push(span);
+ traverseEvents(events, span, startTimestamp, traceTimestamp);
+ }
+}
+
+function traverseEvents(events, parent, startTimestamp, traceTimestamp) {
+ for (let i = 0; i < events.length; i++) {
+ let event = events[i];
+ let eventStart = event['timestamp_ms'];
+ let operationName;
+ let duration;
+ if (event.hasOwnProperty('event')) {
+ operationName = event['event'];
+ if (
+ operationName === 'Complete query setup' ||
+ operationName === 'MatchThread::run Done'
+ ) {
+ duration = (traceTimestamp - eventStart) * 1000;
+ } else {
+ duration = (events[i + 1]['timestamp_ms'] - eventStart) * 1000;
+ }
+ } else {
+ operationName = event['tag'];
+ duration = (events[i + 1]['timestamp_ms'] - eventStart) * 1000;
+ }
+ let eventSpan = createNewSpan(
+ startTimestamp + eventStart * 1000,
+ duration,
+ parent['processID'],
+ operationName,
+ [
+ {
+ refType: 'CHILD_OF',
+ traceID: traceID,
+ spanID: parent['spanID'],
+ },
+ ]
+ );
+ data.push(eventSpan);
+ }
+}
+
+function digDownInTrace(traces) {
+ for (let trace of traces) {
+ if (trace.hasOwnProperty('children')) {
+ return trace['children'];
+ }
+ }
+}
+
+// Get an estimated start time by using the start time of the query and subtracting the current run time
+function getTraceStartTime(trace) {
+ if (Array.isArray(trace['message'])) {
+ let timestamp = Date.parse(trace['message'][0]['start_time']) * 1000;
+ let currentTimestamp = trace['timestamp'] * 1000;
+ return timestamp - currentTimestamp;
+ }
+}
+
+function findTraceStartTime(spans) {
+ let startTime = 0;
+ for (let span of spans) {
+ if (span.hasOwnProperty('children')) {
+ startTime = findTraceStartTime(span['children']);
+ } else if (span.hasOwnProperty('message')) {
+ if (Array.isArray(span['message'])) {
+ return getTraceStartTime(span);
+ }
+ }
+ if (startTime !== 0) {
+ return startTime;
+ }
+ }
+ return startTime;
+}
+
+// Finds the total duration of the entire trace
+function findTotalDuration(spans) {
+ let i = spans.length - 1;
+ while (i >= 0) {
+ if (spans[i].hasOwnProperty('timestamp')) {
+ return spans[i]['timestamp'] * 1000;
+ }
+ i--;
+ }
+ return 0;
+}
+
+// Finds the duration of a single span
+function findDuration(span, i) {
+ i = i + 1;
+ while (i < span.length) {
+ if (span[i].hasOwnProperty('timestamp')) {
+ return span[i]['timestamp'] * 1000;
+ }
+ i++;
+ }
+ return 0;
+}
+
+function createNewSpan(
+ startTime = 0,
+ duration = 1,
+ processID = 'p0',
+ operationName = 'Complete',
+ references = []
+) {
+ let spanID = genRanHex(16);
+ let newSpan = {
+ traceID: traceID,
+ spanID: spanID,
+ operationName: operationName,
+ startTime: startTime,
+ duration: duration,
+ references: references,
+ tags: [],
+ logs: [],
+ processID: processID,
+ };
+ return newSpan;
+}
+
+function getProcess(key) {
+ if (processMap.has(key)) {
+ return processMap.get(key);
+ } else {
+ let id = 'p' + getProcessID();
+ processes[id] = { serviceName: key, tags: [] };
+ processMap.set(key, id);
+ return id;
+ }
+}
+
+function getProcessID() {
+ processID += 1;
+ return processID;
+}
+
+// find a name to use for a process using the operationName from a span
+function findProcessName(string) {
+ let regex = /(?:[a-z]+\.)+[a-zA-Z]+/gm;
+ let match = string.match(regex);
+ if (match != null && match.length > 0) {
+ let temp = match[0];
+ temp = temp.split('.');
+ return temp[temp.length - 1];
+ } else {
+ return '';
+ }
+}
diff --git a/client/js/app/src/app/pages/querybuilder/context/__test__/query-builder-provider.test.jsx b/client/js/app/src/app/pages/querybuilder/context/__test__/query-builder-provider.test.jsx
new file mode 100644
index 00000000000..5ccad2a054e
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/context/__test__/query-builder-provider.test.jsx
@@ -0,0 +1,179 @@
+import {
+ ACTION,
+ reducer,
+} from 'app/pages/querybuilder/context/query-builder-provider';
+import parameters from 'app/pages/querybuilder/context/parameters';
+import { cloneDeep, omitBy } from 'lodash';
+
+const state = reducer();
+
+test('default state', () => {
+ const fixed = { ...state, params: hideTypes(state.params) };
+ expect(fixed).toEqual({
+ http: {},
+ params: {
+ value: [{ id: '0', value: '', type: 'yql' }],
+ },
+ query: {
+ input: '{\n "yql": ""\n}',
+ },
+ request: {
+ body: '{\n "yql": ""\n}',
+ fullUrl: 'http://localhost:8080/search/',
+ method: 'POST',
+ url: 'http://localhost:8080/search/',
+ },
+ });
+});
+
+test('manipulates inputs', () => {
+ function assert(state, queryJson, querySearchParams, params) {
+ expect(hideTypes(state.params).value).toEqual(params);
+ expect({ ...state.query, input: JSON.parse(state.query.input) }).toEqual(
+ queryJson
+ );
+
+ const spState = reducer(state, { action: ACTION.SET_METHOD, data: 'GET' });
+ expect(hideTypes(spState.params).value).toEqual(params);
+ expect(spState.query).toEqual(querySearchParams);
+ }
+
+ const s1 = reduce(state, [[ACTION.INPUT_ADD, { type: 'hits' }]]);
+ assert(s1, { input: { yql: '', hits: null } }, { input: 'yql=&hits=' }, [
+ { id: '0', value: '', type: 'yql' },
+ { id: '1', value: '', type: 'hits' },
+ ]);
+
+ const s2 = reduce(s1, [
+ [ACTION.INPUT_UPDATE, { id: '1', value: '12' }],
+ [ACTION.INPUT_ADD, { type: 'ranking' }],
+ [ACTION.INPUT_UPDATE, { id: '1', type: 'offset' }],
+ [ACTION.INPUT_REMOVE, '0'],
+ [ACTION.INPUT_ADD, { id: '2', type: 'location' }],
+ [ACTION.INPUT_ADD, { id: '2', type: 'matchPhase' }],
+ [ACTION.INPUT_UPDATE, { id: '2.0', value: 'us' }],
+ ]);
+ assert(
+ s2,
+ { input: { offset: 12, ranking: { location: 'us', matchPhase: {} } } },
+ { input: 'offset=12&ranking.location=us' },
+ [
+ { id: '1', value: '12', type: 'offset' },
+ {
+ id: '2',
+ type: 'ranking',
+ value: [
+ { id: '2.0', value: 'us', type: 'location' },
+ { id: '2.1', type: 'matchPhase', value: [] },
+ ],
+ },
+ ]
+ );
+
+ assert(
+ reduce(s2, [[ACTION.INPUT_UPDATE, { id: '2', type: 'noCache' }]]),
+ { input: { offset: 12, noCache: false } },
+ { input: 'offset=12&noCache=' },
+ [
+ { id: '1', value: '12', type: 'offset' },
+ { id: '2', value: '', type: 'noCache' },
+ ]
+ );
+
+ assert(
+ reduce(s2, [[ACTION.INPUT_REMOVE, '2']]),
+ { input: { offset: 12 } },
+ { input: 'offset=12' },
+ [{ id: '1', value: '12', type: 'offset' }]
+ );
+});
+
+test('set query', () => {
+ const query = (method, input) =>
+ reduce(state, [
+ [ACTION.INPUT_REMOVE, '0'],
+ [ACTION.SET_METHOD, method],
+ [ACTION.SET_QUERY, input],
+ ]);
+ function assert(inputJson, inputSearchParams, params) {
+ const s2 = query('POST', inputJson);
+ expect(hideTypes(s2.params).value).toEqual(params);
+ expect(s2.query.input).toEqual(inputJson);
+ expect(s2.query.error).toBeUndefined();
+
+ if (inputSearchParams == null) return;
+ const s3 = query('GET', inputSearchParams);
+ expect(hideTypes(s3.params).value).toEqual(params);
+ expect(s3.query.input).toEqual(inputSearchParams);
+ expect(s3.query.error).toBeUndefined();
+ }
+
+ function error(method, input, error) {
+ const s = query(method, input);
+ expect(s.params.value).toEqual([]);
+ expect(s.query.input).toEqual(input);
+ expect(s.query.error).toEqual(error);
+ }
+
+ assert('{"yql":"abc"}', '?yql=abc', [{ id: '0', value: 'abc', type: 'yql' }]);
+
+ assert(
+ '{"hits":12,"ranking":{"location":"us","matchPhase":{"attribute":"[\\"a b\\"]"}},"noCache":true,"offset":""}',
+ 'hits=12&ranking.location=us&noCache=true&ranking.matchPhase.attribute=%5B%22a+b%22%5D&offset',
+ [
+ { id: '0', value: '12', type: 'hits' },
+ {
+ id: '1',
+ type: 'ranking',
+ value: [
+ { id: '1.0', value: 'us', type: 'location' },
+ {
+ id: '1.1',
+ type: 'matchPhase',
+ value: [{ id: '1.1.0', value: '["a b"]', type: 'attribute' }],
+ },
+ ],
+ },
+ { id: '2', value: 'true', type: 'noCache' },
+ { id: '3', value: '', type: 'offset' },
+ ]
+ );
+
+ assert('{"ranking":{"matchPhase":{}}}', null, [
+ {
+ id: '0',
+ type: 'ranking',
+ value: [{ id: '0.0', type: 'matchPhase', value: [] }],
+ },
+ ]);
+
+ let msg = "Unknown property 'asd' on root level";
+ error('POST', '{"asd":123}', msg);
+ error('GET', 'asd=123', msg);
+
+ msg = "Unknown property 'asd' under 'matchPhase'";
+ error('POST', '{"ranking":{"matchPhase":{"asd":123}}}', msg);
+ error('GET', 'ranking.matchPhase.asd=123', msg);
+
+ error('POST', '{"yql":"test}', 'Unexpected end of JSON input');
+
+ msg =
+ "Property 'ranking' cannot have a value, supported children: features,freshness,listFeatures,location,matchPhase,profile,properties,queryCache,sorting";
+ error('POST', '{"ranking":123}', msg);
+ error('GET', 'ranking=123', msg);
+
+ error('POST', '{"yql":{}}', "Expected property 'yql' to be String");
+});
+
+function hideTypes({ type, value, ...copy }) {
+ if (type.name) copy.type = type.name;
+ copy.value = type.children ? value.map(hideTypes) : value;
+ return copy;
+}
+
+function reduce(state, operations) {
+ return operations.reduce(
+ (acc, [action, data]) => reducer(acc, { action, data }),
+ state
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/context/parameters.jsx b/client/js/app/src/app/pages/querybuilder/context/parameters.jsx
new file mode 100644
index 00000000000..b3ca2425c9c
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/context/parameters.jsx
@@ -0,0 +1,120 @@
+export default {
+ yql: { name: 'yql', type: 'String' },
+ hits: { name: 'hits', type: 'Integer' },
+ offset: { name: 'offset', type: 'Integer' },
+ queryProfile: { name: 'queryProfile', type: 'String' },
+ noCache: { name: 'noCache', type: 'Boolean' },
+ groupingSessionCache: { name: 'groupingSessionCache', type: 'Boolean' },
+ searchChain: { name: 'searchChain', type: 'String' },
+ timeout: { name: 'timeout', type: 'Float' },
+ trace: {
+ name: 'trace',
+ type: 'Parent',
+ children: {
+ timestamps: { name: 'timestamps', type: 'Boolean' },
+ },
+ },
+ tracelevel: {
+ name: 'tracelevel',
+ type: 'Parent',
+ children: {
+ rules: { name: 'rules', type: 'Integer' },
+ },
+ },
+ traceLevel: { name: 'traceLevel', type: 'Integer' },
+ explainLevel: { name: 'explainLevel', type: 'Integer' },
+ explainlevel: { name: 'explainlevel', type: 'Integer' },
+ model: {
+ name: 'model',
+ type: 'Parent',
+ children: {
+ defaultIndex: { name: 'defaultIndex', type: 'String' },
+ encoding: { name: 'encoding', type: 'String' },
+ language: { name: 'language', type: 'String' },
+ queryString: { name: 'queryString', type: 'String' },
+ restrict: { name: 'restrict', type: 'List' },
+ searchPath: { name: 'searchPath', type: 'String' },
+ sources: { name: 'sources', type: 'List' },
+ type: { name: 'type', type: 'String' },
+ },
+ },
+ ranking: {
+ name: 'ranking',
+ type: 'Parent',
+ children: {
+ location: { name: 'location', type: 'String' },
+ features: { name: 'features', type: 'String' },
+ listFeatures: { name: 'listFeatures', type: 'Boolean' },
+ profile: { name: 'profile', type: 'String' },
+ properties: { name: 'properties', type: 'String' },
+ sorting: { name: 'sorting', type: 'String' },
+ freshness: { name: 'freshness', type: 'String' },
+ queryCache: { name: 'queryCache', type: 'Boolean' },
+ matchPhase: {
+ name: 'matchPhase',
+ type: 'Parent',
+ children: {
+ maxHits: { name: 'maxHits', type: 'Long' },
+ attribute: { name: 'attribute', type: 'String' },
+ ascending: { name: 'ascending', type: 'Boolean' },
+ diversity: {
+ name: 'diversity',
+ type: 'Parent',
+ children: {
+ attribute: { name: 'attribute', type: 'String' },
+ minGroups: { name: 'minGroups', type: 'Long' },
+ },
+ },
+ },
+ },
+ },
+ },
+ collapse: {
+ name: 'collapse',
+ type: 'Parent',
+ children: {
+ summary: { name: 'summary', type: 'String' },
+ },
+ },
+ collapsesize: { name: 'collapsesize', type: 'Integer' },
+ collapsefield: { name: 'collapsefield', type: 'String' },
+ presentation: {
+ name: 'presentation',
+ type: 'Parent',
+ children: {
+ bolding: { name: 'bolding', type: 'Boolean' },
+ format: { name: 'format', type: 'String' },
+ summary: { name: 'summary', type: 'String' },
+ template: { name: 'template', type: 'String' },
+ timing: { name: 'timing', type: 'Boolean' },
+ },
+ },
+ streaming: {
+ name: 'streaming',
+ type: 'Parent',
+ children: {
+ userid: { name: 'userid', type: 'Integer' },
+ groupname: { name: 'groupname', type: 'String' },
+ selection: { name: 'selection', type: 'String' },
+ priority: { name: 'priority', type: 'String' },
+ maxbucketspervisitor: { name: 'maxbucketspervisitor', type: 'Integer' },
+ },
+ },
+ rules: {
+ name: 'rules',
+ type: 'Parent',
+ children: {
+ off: { name: 'off', type: 'Boolean' },
+ rulebase: { name: 'rulebase', type: 'String' },
+ },
+ },
+ recall: { name: 'recall', type: 'List' },
+ user: { name: 'user', type: 'String' },
+ metrics: {
+ name: 'metrics',
+ type: 'Parent',
+ children: {
+ ignore: { name: 'ignore', type: 'Boolean' },
+ },
+ },
+};
diff --git a/client/js/app/src/app/pages/querybuilder/context/query-builder-provider.jsx b/client/js/app/src/app/pages/querybuilder/context/query-builder-provider.jsx
new file mode 100644
index 00000000000..74585e1340c
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/context/query-builder-provider.jsx
@@ -0,0 +1,217 @@
+import { last, set } from 'lodash';
+import React, { useReducer } from 'react';
+import { createContext, useContextSelector } from 'use-context-selector';
+import parameters from 'app/pages/querybuilder/context/parameters';
+
+let _dispatch;
+const root = { type: { children: parameters } };
+const context = createContext(null);
+
+export const ACTION = Object.freeze({
+ SET_QUERY: 0,
+ SET_HTTP: 1,
+ SET_METHOD: 2,
+ SET_URL: 3,
+
+ INPUT_ADD: 10,
+ INPUT_UPDATE: 11,
+ INPUT_REMOVE: 12,
+});
+
+function cloneParams(params) {
+ if (!Array.isArray(params.value)) return { ...params };
+ return { ...params, value: params.value.map(cloneParams) };
+}
+
+function inputsToQuery(method, inputs) {
+ if (method === 'POST') {
+ const inputsToJson = (inputs, parent) =>
+ Object.fromEntries(
+ inputs.map(({ value, type: { name, type, children } }) => [
+ name,
+ children ? inputsToJson(value) : parseInput(value, type),
+ ])
+ );
+ return JSON.stringify(inputsToJson(inputs), null, 4);
+ }
+
+ const inputsToSearchParams = (inputs, parent) =>
+ inputs.reduce((acc, { value, type: { name, children } }) => {
+ const key = parent ? `${parent}.${name}` : name;
+ return Object.assign(
+ acc,
+ children ? inputsToSearchParams(value, key) : { [key]: value }
+ );
+ }, {});
+ return new URLSearchParams(inputsToSearchParams(inputs)).toString();
+}
+
+function queryToInputs(method, query) {
+ if (method === 'POST') return jsonToInputs(JSON.parse(query));
+
+ const json = [...new URLSearchParams(query).entries()].reduce(
+ (acc, [key, value]) => set(acc, key, value),
+ {}
+ );
+ return jsonToInputs(json);
+}
+
+function jsonToInputs(json, parent = root) {
+ return Object.entries(json).map(([key, value], i) => {
+ const node = {
+ id: parent.id ? `${parent.id}.${i}` : i.toString(),
+ type: parent.type.children[key],
+ };
+ if (!node.type) {
+ const location = parent.type.name
+ ? `under '${parent.type.name}'`
+ : 'on root level';
+ throw new Error(`Unknown property '${key}' ${location}`);
+ }
+ if (value != null && typeof value === 'object') {
+ if (!node.type.children)
+ throw new Error(`Expected property '${key}' to be ${node.type.type}`);
+ node.value = jsonToInputs(value, node);
+ } else {
+ if (node.type.children)
+ throw new Error(
+ `Property '${key}' cannot have a value, supported children: ${Object.keys(
+ node.type.children
+ ).sort()}`
+ );
+ node.value = value?.toString();
+ }
+ return node;
+ });
+}
+
+function parseInput(value, type) {
+ if (type === 'Integer' || type === 'Long') return parseInt(value);
+ if (type === 'Float') return parseFloat(value);
+ if (type === 'Boolean') return value.toLowerCase() === 'true';
+ return value;
+}
+
+function inputAdd(params, { id: parentId, type: typeName }) {
+ const cloned = cloneParams(params);
+ const parent = findInput(cloned, parentId);
+
+ const nextId = parseInt(last(last(parent.value)?.id?.split('.')) ?? -1) + 1;
+ const id = parentId ? `${parentId}.${nextId}` : nextId.toString();
+ const type = parent.type.children[typeName];
+
+ parent.value.push({ id, value: type.children ? [] : '', type });
+
+ return cloned;
+}
+
+function inputUpdate(params, { id, type, value }) {
+ const cloned = cloneParams(params);
+ const node = findInput(cloned, id);
+ if (type) {
+ const parent = findInput(cloned, id.substring(0, id.lastIndexOf('.')));
+ const newType = parent.type.children[type];
+ if ((node.type.children != null) !== (newType.children != null))
+ node.value = newType.children ? [] : '';
+ node.type = newType;
+ }
+ if (value) node.value = value;
+
+ return cloned;
+}
+
+function findInput(params, id, Delete = false) {
+ if (!id) return params;
+ let end = -1;
+ while ((end = id.indexOf('.', end + 1)) > 0)
+ params = params.value.find((input) => input.id === id.substring(0, end));
+ const index = params.value.findIndex((input) => input.id === id);
+ return Delete ? params.value.splice(index, 1)[0] : params.value[index];
+}
+
+export function reducer(state, action) {
+ if (state == null) {
+ state = { http: {}, params: {}, query: {}, request: {} };
+
+ return [
+ [ACTION.SET_URL, 'http://localhost:8080/search/'],
+ [ACTION.SET_QUERY, 'yql='],
+ [ACTION.SET_METHOD, 'POST'],
+ ].reduce((s, [action, data]) => reducer(s, { action, data }), state);
+ }
+
+ const result = preReducer(state, action);
+ const { request: sr, params: sp, query: sq } = state;
+ const { request: rr, params: rp, query: rq } = result;
+
+ if ((sp.value !== rp.value && sq === rq) || sr.method !== rr.method)
+ result.query = { input: inputsToQuery(rr.method, rp.value) };
+
+ const input = result.query.input;
+ if (sr.url !== rr.url || sq.input !== input || sr.method !== rr.method) {
+ if (rr.method === 'POST') {
+ result.request = { ...result.request, fullUrl: rr.url, body: input };
+ } else {
+ const url = new URL(rr.url);
+ url.search = input;
+ result.request = {
+ ...result.request,
+ fullUrl: url.toString(),
+ body: null,
+ };
+ }
+ }
+
+ return result;
+}
+
+function preReducer(state, { action, data }) {
+ switch (action) {
+ case ACTION.SET_QUERY: {
+ try {
+ const value = queryToInputs(state.request.method, data);
+ return {
+ ...state,
+ params: { ...root, value },
+ query: { input: data },
+ };
+ } catch (error) {
+ return { ...state, query: { input: data, error: error.message } };
+ }
+ }
+ case ACTION.SET_HTTP:
+ return { ...state, http: data };
+ case ACTION.SET_METHOD:
+ return { ...state, request: { ...state.request, method: data } };
+ case ACTION.SET_URL:
+ return { ...state, request: { ...state.request, url: data } };
+
+ case ACTION.INPUT_ADD:
+ return { ...state, params: inputAdd(state.params, data) };
+ case ACTION.INPUT_UPDATE:
+ return { ...state, params: inputUpdate(state.params, data) };
+ case ACTION.INPUT_REMOVE: {
+ const cloned = cloneParams(state.params);
+ findInput(cloned, data, true);
+ return { ...state, params: cloned };
+ }
+
+ default:
+ throw new Error(`Unknown action ${action}`);
+ }
+}
+
+export function QueryBuilderProvider({ children }) {
+ const [value, dispatch] = useReducer(reducer, null, reducer);
+ _dispatch = dispatch;
+ return <context.Provider value={value}>{children}</context.Provider>;
+}
+
+export function useQueryBuilderContext(selector) {
+ const func = typeof selector === 'string' ? (c) => c[selector] : selector;
+ return useContextSelector(context, func);
+}
+
+export function dispatch(action, data) {
+ _dispatch({ action, data });
+}
diff --git a/client/js/app/src/app/pages/querybuilder/index.jsx b/client/js/app/src/app/pages/querybuilder/index.jsx
new file mode 100644
index 00000000000..b8889dfd7c5
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/index.jsx
@@ -0,0 +1,36 @@
+import React from 'react';
+import { SimpleGrid, Title } from '@mantine/core';
+import { Container, Content, Icon } from 'app/components';
+import { QueryBuilderProvider } from 'app/pages/querybuilder/context/query-builder-provider';
+import { QueryFilters } from 'app/pages/querybuilder/query-filters/query-filters';
+import { QueryDerived } from 'app/pages/querybuilder/query-derived/query-derived';
+import { QueryResponse } from 'app/pages/querybuilder/query-response/query-response';
+import QueryEndpoint from 'app/pages/querybuilder/query-endpoint/query-endpoint';
+
+export function QueryBuilder() {
+ return (
+ <QueryBuilderProvider>
+ <Container sx={{ rowGap: '21px' }}>
+ <Title order={2}>
+ <Icon name="arrows-to-dot" /> Query Builder
+ </Title>
+ <QueryEndpoint />
+ <SimpleGrid
+ breakpoints={[{ maxWidth: 'sm', cols: 1 }]}
+ cols={3}
+ spacing="lg"
+ >
+ <Content>
+ <QueryFilters />
+ </Content>
+ <Content>
+ <QueryDerived />
+ </Content>
+ <Content>
+ <QueryResponse />
+ </Content>
+ </SimpleGrid>
+ </Container>
+ </QueryBuilderProvider>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-builder.jsx b/client/js/app/src/app/pages/querybuilder/query-builder.jsx
deleted file mode 100644
index 7e8f133f9ec..00000000000
--- a/client/js/app/src/app/pages/querybuilder/query-builder.jsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import React from 'react';
-
-export function QueryBuilder() {
- return <>query builder</>;
-}
diff --git a/client/js/app/src/app/pages/querybuilder/query-derived/query-derived.jsx b/client/js/app/src/app/pages/querybuilder/query-derived/query-derived.jsx
new file mode 100644
index 00000000000..fca06defc5d
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/query-derived/query-derived.jsx
@@ -0,0 +1,57 @@
+import React from 'react';
+import {
+ Badge,
+ Group,
+ Stack,
+ Button,
+ CopyButton,
+ Textarea,
+} from '@mantine/core';
+import {
+ ACTION,
+ dispatch,
+ useQueryBuilderContext,
+} from 'app/pages/querybuilder/context/query-builder-provider';
+import { Icon } from 'app/components';
+
+export function QueryDerived() {
+ const { input, error } = useQueryBuilderContext('query');
+
+ return (
+ <Stack>
+ <Group position="apart">
+ <Badge variant="filled">Query</Badge>
+ <Group spacing="xs">
+ <CopyButton value={input}>
+ {({ copied, copy }) => (
+ <Button
+ leftIcon={<Icon name={copied ? 'check' : 'copy'} />}
+ color={copied ? 'teal' : 'blue'}
+ variant="outline"
+ onClick={copy}
+ size="xs"
+ compact
+ >
+ Copy
+ </Button>
+ )}
+ </CopyButton>
+ </Group>
+ </Group>
+ <Textarea
+ styles={(theme) => ({
+ input: {
+ fontFamily: theme.fontFamilyMonospace,
+ fontSize: theme.fontSizes.xs,
+ },
+ })}
+ value={input}
+ error={error}
+ onChange={({ target }) => dispatch(ACTION.SET_QUERY, target.value)}
+ variant="unstyled"
+ minRows={21}
+ autosize
+ />
+ </Stack>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-endpoint/query-endpoint.jsx b/client/js/app/src/app/pages/querybuilder/query-endpoint/query-endpoint.jsx
new file mode 100644
index 00000000000..09d52640936
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/query-endpoint/query-endpoint.jsx
@@ -0,0 +1,63 @@
+import React from 'react';
+import { Select, TextInput, Button } from '@mantine/core';
+import { errorMessage } from 'app/libs/notification';
+import {
+ ACTION,
+ dispatch,
+ useQueryBuilderContext,
+} from 'app/pages/querybuilder/context/query-builder-provider';
+import { Container, Content } from 'app/components';
+
+function send(event, method, url, body) {
+ event.preventDefault();
+ dispatch(ACTION.SET_HTTP, { loading: true });
+ fetch(url, {
+ method,
+ headers: { 'Content-Type': 'application/json;charset=utf-8' },
+ body,
+ })
+ .then((response) => response.json())
+ .then((result) =>
+ dispatch(ACTION.SET_HTTP, {
+ response: JSON.stringify(result, null, 4),
+ })
+ )
+ .catch((error) => {
+ errorMessage(error.message);
+ dispatch(ACTION.SET_HTTP, {});
+ });
+}
+
+export default function QueryEndpoint() {
+ const { method, url, fullUrl, body } = useQueryBuilderContext('request');
+ const hasError = useQueryBuilderContext((ctx) => ctx.query.error != null);
+ const loading = useQueryBuilderContext((ctx) => ctx.http.loading);
+
+ return (
+ <Content>
+ <form onSubmit={(event) => send(event, method, fullUrl, body)}>
+ <Container sx={{ gridTemplateColumns: 'max-content auto max-content' }}>
+ <Select
+ data={['POST', 'GET']}
+ onChange={(value) => dispatch(ACTION.SET_METHOD, value)}
+ value={method}
+ radius={0}
+ />
+ <TextInput
+ onChange={(e) => dispatch(ACTION.SET_URL, e.currentTarget.value)}
+ value={url}
+ radius={0}
+ />
+ <Button
+ radius={0}
+ type="submit"
+ loading={loading}
+ disabled={hasError}
+ >
+ Send
+ </Button>
+ </Container>
+ </form>
+ </Content>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-filters/query-filters.jsx b/client/js/app/src/app/pages/querybuilder/query-filters/query-filters.jsx
new file mode 100644
index 00000000000..178270eb71f
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/query-filters/query-filters.jsx
@@ -0,0 +1,128 @@
+import React from 'react';
+import {
+ Select,
+ TextInput,
+ ActionIcon,
+ Button,
+ Box,
+ Stack,
+ Badge,
+ Group,
+} from '@mantine/core';
+import { Container, Content, Icon } from 'app/components';
+import {
+ ACTION,
+ dispatch,
+ useQueryBuilderContext,
+} from 'app/pages/querybuilder/context/query-builder-provider';
+import { SHADE } from 'app/styles/theme/colors';
+
+function AddProperty(props) {
+ return (
+ <Button leftIcon={<Icon name="plus" />} {...props}>
+ Add property
+ </Button>
+ );
+}
+
+function Input({ id, value, types, type }) {
+ const options = { [type.name]: type, ...types };
+ return (
+ <>
+ <Box sx={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
+ <Select
+ sx={{ flex: 1 }}
+ data={Object.values(options).map(({ name }) => name)}
+ onChange={(type) => dispatch(ACTION.INPUT_UPDATE, { id, type })}
+ value={type.name}
+ searchable
+ />
+ {!type.children && (
+ <TextInput
+ sx={{ flex: 1 }}
+ onChange={(event) =>
+ dispatch(ACTION.INPUT_UPDATE, {
+ id,
+ value: event.currentTarget.value,
+ })
+ }
+ placeholder={type.type}
+ value={value}
+ />
+ )}
+ <ActionIcon onClick={() => dispatch(ACTION.INPUT_REMOVE, id)}>
+ <Icon name="circle-minus" />
+ </ActionIcon>
+ </Box>
+ {type.children && (
+ <Box
+ py={8}
+ sx={(theme) => ({
+ borderLeft: `1px dashed ${theme.fn.themeColor(
+ 'gray',
+ SHADE.UI_ELEMENT_BORDER_AND_FOCUS
+ )}`,
+ marginLeft: '13px',
+ paddingLeft: '13px',
+ })}
+ >
+ <Inputs id={id} type={type.children} inputs={value} />
+ </Box>
+ )}
+ </>
+ );
+}
+
+function Inputs({ id, type, inputs }) {
+ const usedTypes = inputs.map(({ type }) => type.name);
+ const remainingTypes = Object.fromEntries(
+ Object.entries(type).filter(([name]) => !usedTypes.includes(name))
+ );
+ const firstRemaining = Object.keys(remainingTypes)[0];
+ return (
+ <Container sx={{ rowGap: '5px' }}>
+ {inputs.map(({ id, value, type }) => (
+ <Input key={id} types={remainingTypes} {...{ id, value, type }} />
+ ))}
+ {firstRemaining && (
+ <>
+ {id != null ? (
+ <Container sx={{ justifyContent: 'start' }}>
+ <AddProperty
+ onClick={() =>
+ dispatch(ACTION.INPUT_ADD, { id, type: firstRemaining })
+ }
+ variant="subtle"
+ size="xs"
+ compact
+ />
+ </Container>
+ ) : (
+ <AddProperty
+ onClick={() =>
+ dispatch(ACTION.INPUT_ADD, { id, type: firstRemaining })
+ }
+ mt={13}
+ />
+ )}
+ </>
+ )}
+ </Container>
+ );
+}
+
+export function QueryFilters() {
+ const { value, type } = useQueryBuilderContext('params');
+ return (
+ <Stack>
+ <Group>
+ <Badge variant="filled">Parameters</Badge>
+ </Group>
+ <Container sx={{ alignContent: 'start' }}>
+ <Content padding={0}>
+ <Inputs type={type.children} inputs={value} />
+ </Content>
+ </Container>
+ </Stack>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-response/download-jeager.jsx b/client/js/app/src/app/pages/querybuilder/query-response/download-jeager.jsx
new file mode 100644
index 00000000000..4130172a329
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/query-response/download-jeager.jsx
@@ -0,0 +1,55 @@
+import { Button } from '@mantine/core';
+import React from 'react';
+import { errorMessage } from 'app/libs/notification';
+import { Icon } from 'app/components';
+import transform from 'app/pages/querybuilder/TransformVespaTrace';
+
+// copied from safakeskin´s answer on SO, link: https://stackoverflow.com/questions/55613438/reactwrite-to-json-file-or-export-download-no-server
+function downloadFile(filename, blob) {
+ const href = URL.createObjectURL(blob);
+
+ // create "a" HTML element with href to file
+ const link = document.createElement('a');
+ link.href = href;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+
+ // clean up "a" element & remove ObjectURL
+ document.body.removeChild(link);
+ URL.revokeObjectURL(href);
+}
+
+export function DownloadJeager({ response, ...props }) {
+ const handleClick = () => {
+ try {
+ const json = JSON.parse(response);
+
+ try {
+ const content = JSON.stringify(transform(json), null, 4);
+ downloadFile(
+ 'vespa-response.json',
+ new Blob([content], { type: 'application/json' })
+ );
+ } catch (error) {
+ errorMessage(
+ 'Request must be made with tracelevel ≥ 4',
+ 'Failed to transform response to Jaeger format'
+ );
+ }
+ } catch (error) {
+ errorMessage(error.message);
+ }
+ };
+
+ return (
+ <Button
+ {...props}
+ leftIcon={<Icon name="download" />}
+ onClick={handleClick}
+ disabled={!(response?.length > 0)}
+ >
+ Jaeger Format
+ </Button>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-response/query-response.jsx b/client/js/app/src/app/pages/querybuilder/query-response/query-response.jsx
new file mode 100644
index 00000000000..56562ae1717
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/query-response/query-response.jsx
@@ -0,0 +1,58 @@
+import React from 'react';
+import {
+ Badge,
+ Button,
+ Group,
+ Stack,
+ CopyButton,
+ Textarea,
+} from '@mantine/core';
+import { DownloadJeager } from 'app/pages/querybuilder/query-response/download-jeager';
+import { useQueryBuilderContext } from 'app/pages/querybuilder/context/query-builder-provider';
+import { Icon } from 'app/components';
+
+export function QueryResponse() {
+ const response = useQueryBuilderContext((ctx) => ctx.http.response);
+
+ return (
+ <Stack>
+ <Group position="apart">
+ <Badge variant="filled">Response</Badge>
+ <Group spacing="xs">
+ <CopyButton value={response}>
+ {({ copied, copy }) => (
+ <Button
+ leftIcon={<Icon name={copied ? 'check' : 'copy'} />}
+ color={copied ? 'teal' : 'blue'}
+ variant="outline"
+ onClick={copy}
+ size="xs"
+ compact
+ >
+ Copy
+ </Button>
+ )}
+ </CopyButton>
+ <DownloadJeager
+ variant="outline"
+ size="xs"
+ compact
+ response={response}
+ />
+ </Group>
+ </Group>
+ <Textarea
+ styles={(theme) => ({
+ input: {
+ fontFamily: theme.fontFamilyMonospace,
+ fontSize: theme.fontSizes.xs,
+ },
+ })}
+ value={response ?? ''}
+ variant="unstyled"
+ minRows={21}
+ autosize
+ />
+ </Stack>
+ );
+}
diff --git a/client/js/app/src/app/pages/querytracer/query-tracer.jsx b/client/js/app/src/app/pages/querytracer/query-tracer.jsx
new file mode 100644
index 00000000000..758182d4f3f
--- /dev/null
+++ b/client/js/app/src/app/pages/querytracer/query-tracer.jsx
@@ -0,0 +1,25 @@
+import React, { useState } from 'react';
+import { Stack, Textarea } from '@mantine/core';
+import { DownloadJeager } from 'app/pages/querybuilder/query-response/download-jeager';
+
+export function QueryTracer() {
+ const [response, setResponse] = useState('');
+
+ return (
+ <Stack>
+ <Textarea
+ styles={(theme) => ({
+ input: {
+ fontFamily: theme.fontFamilyMonospace,
+ fontSize: theme.fontSizes.xs,
+ },
+ })}
+ minRows={21}
+ autosize
+ value={response}
+ onChange={({ target }) => setResponse(target.value)}
+ />
+ <DownloadJeager fullWidth response={response} />
+ </Stack>
+ );
+}
diff --git a/client/js/app/src/app/styles/default/default-props.js b/client/js/app/src/app/styles/default/default-props.js
new file mode 100644
index 00000000000..c25d9009da9
--- /dev/null
+++ b/client/js/app/src/app/styles/default/default-props.js
@@ -0,0 +1,9 @@
+export const defaultProps = {
+ Button: { radius: 2 },
+ Badge: { size: 'sm' },
+ Group: { spacing: 'xs' },
+ Paper: { radius: 0 },
+ Tooltip: { withArrow: true },
+ Table: { verticalSpacing: 8 },
+ ActionIcon: { size: 'sm' },
+};
diff --git a/client/js/app/src/app/styles/default/default-styles.js b/client/js/app/src/app/styles/default/default-styles.js
new file mode 100644
index 00000000000..d65e4eecaef
--- /dev/null
+++ b/client/js/app/src/app/styles/default/default-styles.js
@@ -0,0 +1,393 @@
+import { SHADE } from 'app/styles/theme/colors';
+
+const inputSizes = Object.freeze({
+ xs: 28,
+ sm: 34,
+ md: 40,
+ lg: 48,
+ xl: 58,
+});
+
+const buttonSizes = Object.freeze({
+ xs: { height: inputSizes.xs, padding: '0 13px' },
+ sm: { height: inputSizes.sm, padding: '0 17px' },
+ md: { height: inputSizes.md, padding: '0 21px' },
+ lg: { height: inputSizes.lg, padding: '0 26px' },
+ xl: { height: inputSizes.xl, padding: '0 34px' },
+ 'compact-xs': { height: 'initial', padding: '2px 5px' },
+ 'compact-sm': { height: 'initial', padding: '3px 8px' },
+ 'compact-md': { height: 'initial', padding: '5px 8px' },
+ 'compact-lg': { height: 'initial', padding: '5px 13px' },
+ 'compact-xl': { height: 'initial', padding: '8px 13px' },
+});
+
+export const segmentedControlSizes = Object.freeze({
+ xs: '1px 8px',
+ sm: '1px 13px',
+ md: '3px 13px',
+ lg: '5px 21px',
+ xl: '8px 21px',
+});
+
+const titleStyles = Object.freeze({
+ h1: {
+ wordBreak: 'break-word',
+ lineHeight: 'calc(1.5 / var(--space) * var(--vspace))',
+ },
+ h2: {
+ wordBreak: 'break-word',
+ fontWeight: 'normal',
+ lineHeight: '1rem',
+ },
+ h3: {
+ fontWeight: 'normal',
+ textTransform: 'uppercase',
+ letterSpacing: '0.1rem',
+ lineHeight: '1rem',
+ },
+ h4: {
+ textTransform: 'capitalize',
+ lineHeight: 'var(--vspace)',
+ },
+ h5: {
+ fontWeight: 'lighter',
+ textTransform: 'uppercase',
+ letterSpacing: '0.15rem',
+ lineHeight: 'var(--vspace)',
+ },
+ h6: {
+ fontWeight: 'normal',
+ fontStyle: 'italic',
+ letterSpacing: '0 !important',
+ lineHeight: 'var(--vspace)',
+ },
+});
+
+const getButtonStyles = ({ compact, size }) => {
+ if (!compact) return buttonSizes[size];
+ return buttonSizes[`compact-${size}`];
+};
+
+const getTitleStyles = ({ element = 'h1' }) => titleStyles[element];
+
+export function getVariantStyles({ fn, white }, color, variant) {
+ if (variant === 'hover' || variant === 'transparent') {
+ return {
+ color: fn.themeColor(color, SHADE.SOLID_BACKGROUND),
+ backgroundColor: 'transparent',
+ border: '1px solid transparent',
+ ...fn.hover(
+ variant === 'hover'
+ ? {
+ backgroundColor: fn.themeColor(
+ color,
+ SHADE.UI_ELEMENT_BACKGROUND
+ ),
+ }
+ : {}
+ ),
+ };
+ }
+ if (variant === 'light') {
+ return {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor(color, SHADE.HOVERED_ELEMENT_BACKGROUND),
+ border: '1px solid transparent',
+ '&:hover': {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor(
+ color,
+ SHADE.SUBTLE_BORDER_AND_SEPARATOR
+ ),
+ },
+ };
+ }
+ if (variant === 'outline') {
+ return {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor(color, SHADE.APP_BACKGROUND),
+ border: `1px solid ${fn.themeColor(color, SHADE.SOLID_BACKGROUND)}`,
+ '&:hover': {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ borderColor: fn.themeColor(color, SHADE.HOVERED_SOLID_BACKGROUND),
+ },
+ };
+ }
+ if (variant === 'dot') {
+ return {
+ color: fn.themeColor('gray', SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: 'transparent',
+ border: `1px solid ${fn.themeColor(
+ 'gray',
+ SHADE.UI_ELEMENT_BORDER_AND_FOCUS
+ )}`,
+ '&:hover': {
+ color: fn.themeColor('gray', SHADE.LOW_CONTRAST_TEXT),
+ borderColor: fn.themeColor('gray', SHADE.UI_ELEMENT_BORDER_AND_FOCUS),
+ },
+ '&::before': {
+ backgroundColor: fn.themeColor(color, SHADE.SOLID_BACKGROUND),
+ },
+ };
+ }
+ if (variant === 'subtle') {
+ return {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: 'transparent',
+ border: 'transparent',
+ '&:hover': {
+ color: fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor(color, SHADE.HOVERED_ELEMENT_BACKGROUND),
+ },
+ };
+ }
+ if (variant === 'default') {
+ return {
+ color: fn.themeColor('gray', SHADE.HIGH_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor('gray', SHADE.SUBTLE_BACKGROUND),
+ border: `1px solid ${fn.themeColor(
+ 'gray',
+ SHADE.UI_ELEMENT_BORDER_AND_FOCUS
+ )}`,
+ '&:hover': {
+ color: fn.themeColor('gray', SHADE.HIGH_CONTRAST_TEXT),
+ backgroundColor: fn.themeColor(
+ 'gray',
+ SHADE.HOVERED_ELEMENT_BACKGROUND
+ ),
+ },
+ };
+ }
+ if (variant === 'basic') {
+ return {
+ color: fn.themeColor('gray', SHADE.HIGH_CONTRAST_TEXT),
+ backgroundColor: 'transparent',
+ border: '1px solid transparent',
+ '&:hover': {
+ color: fn.themeColor('gray', SHADE.HIGH_CONTRAST_TEXT),
+ backgroundColor: 'transparent',
+ },
+ };
+ }
+ return {
+ color: white,
+ backgroundColor: fn.themeColor(color, SHADE.SOLID_BACKGROUND),
+ border: '1px solid transparent',
+ '&:hover': {
+ color: white,
+ backgroundColor: fn.themeColor(color, SHADE.HOVERED_SOLID_BACKGROUND),
+ },
+ };
+}
+
+function getInputSizes({ fn, size }) {
+ return {
+ minHeight: fn.size({ size, sizes: inputSizes }),
+ height: fn.size({ size, sizes: inputSizes }),
+ lineHeight: `${fn.size({ size, sizes: inputSizes }) - 2}px`,
+ };
+}
+
+function getInputVariantStyles({ fn, cr }, variant, size) {
+ if (variant === 'unstyled') {
+ return {
+ color: cr.getHighContrastText(),
+ };
+ }
+ if (variant === 'filled') {
+ return {
+ backgroundColor: cr.getUiElementBackground(),
+ '&:focus, &:focus-within': {
+ borderColor: `${cr.getUiElementBorderAndFocus()} !important`,
+ },
+ ...getInputSizes({ fn, size }),
+ };
+ }
+ return {
+ border: `1px solid ${cr.getSubtleBorderAndSeparator()}`,
+ backgroundColor: cr.getSubtleBackground(),
+ '&:focus, &:focus-within': {
+ borderColor: cr.getUiElementBorderAndFocus(),
+ },
+ ...getInputSizes({ fn, size }),
+ };
+}
+
+export const defaultStyles = {
+ AppShell: () => ({
+ main: {
+ maxWidth: '1920px',
+ margin: '0 auto',
+ },
+ }),
+ ActionIcon: (theme, { color }) => ({
+ root: {
+ '&:disabled': {
+ color: theme.fn.themeColor('gray', SHADE.SOLID_BACKGROUND),
+ backgroundColor: 'transparent',
+ borderColor: 'transparent',
+ opacity: 0.55,
+ },
+ },
+ light: getVariantStyles(theme, color, 'light'),
+ filled: getVariantStyles(theme, color, 'filled'),
+ outline: getVariantStyles(theme, color, 'outline'),
+ default: getVariantStyles(theme, color, 'default'),
+ hover: getVariantStyles(theme, color, 'hover'),
+ transparent: getVariantStyles(theme, color, 'transparent'),
+ }),
+ Badge: (theme, { color }) => ({
+ light: getVariantStyles(theme, color, 'light'),
+ filled: getVariantStyles(theme, color, 'filled'),
+ outline: getVariantStyles(theme, color, 'outline'),
+ dot: getVariantStyles(theme, color, 'dot'),
+ }),
+ Button: (theme, { color, compact, size }) => ({
+ root: getButtonStyles({ compact, size }),
+ light: getVariantStyles(theme, color, 'light'),
+ filled: getVariantStyles(theme, color, 'filled'),
+ outline: getVariantStyles(theme, color, 'outline'),
+ subtle: getVariantStyles(theme, color, 'subtle'),
+ default: getVariantStyles(theme, color, 'default'),
+ leftIcon: { marginRight: 3 },
+ rightIcon: { marginLeft: 3 },
+ }),
+ Divider: (theme) => ({
+ horizontal: {
+ borderTopColor: theme.cr.getSubtleBorderAndSeparator(),
+ },
+ }),
+ Input: (theme, { invalid, size }) => ({
+ defaultVariant: { ...getInputVariantStyles(theme, 'default', size) },
+ filledVariant: { ...getInputVariantStyles(theme, 'filled', size) },
+ unstyledVariant: { ...getInputVariantStyles(theme, 'unstyled', size) },
+ invalid: {
+ color: theme.fn.themeColor('red', SHADE.SOLID_BACKGROUND),
+ borderColor: theme.fn.themeColor('red', SHADE.SOLID_BACKGROUND),
+ '&::placeholder': {
+ color: theme.fn.themeColor('red', SHADE.SOLID_BACKGROUND),
+ },
+ },
+ disabled: {
+ backgroundColor: theme.fn.themeColor('gray', SHADE.SOLID_BACKGROUND),
+ color: theme.fn.themeColor('gray', SHADE.LOW_CONTRAST_TEXT),
+ '&::placeholder': {
+ color: theme.fn.themeColor('gray', SHADE.LOW_CONTRAST_TEXT),
+ },
+ },
+ icon: {
+ color: invalid
+ ? theme.fn.themeColor('red', SHADE.SOLID_BACKGROUND)
+ : theme.cr.getUiElementBorderAndFocus(),
+ },
+ }),
+ Paper: (theme) => ({
+ root: {
+ color: theme.cr.getHighContrastText(),
+ backgroundColor: theme.cr.getUiElementBackground(),
+ },
+ }),
+ Popover: (theme) => ({
+ arrow: {
+ borderColor: theme.cr.getUiElementBorderAndFocus(),
+ background: theme.cr.getSubtleBackground(),
+ },
+ popover: {
+ background: theme.cr.getSubtleBackground(),
+ },
+ body: {
+ border: `1px solid ${theme.cr.getUiElementBorderAndFocus()}`,
+ whiteSpace: 'nowrap',
+ },
+ header: {
+ borderBottom: `1px solid ${theme.cr.getUiElementBorderAndFocus()}`,
+ },
+ }),
+ Progress: (theme) => ({
+ root: {
+ display: 'flex',
+ backgroundColor: theme.fn.themeColor(
+ 'gray',
+ SHADE.SUBTLE_BORDER_AND_SEPARATOR
+ ),
+ },
+ bar: {
+ position: 'unset',
+ minWidth: '2em',
+ },
+ }),
+ SegmentedControl: (theme, { size }) => ({
+ root: {
+ backgroundColor: theme.cr.getUiElementBackground(),
+ },
+ label: {
+ color: theme.cr.getLowContrastText(),
+ padding:
+ segmentedControlSizes[size in segmentedControlSizes ? size : 'sm'],
+ },
+ control: {
+ '&:not(:first-of-type)': {
+ borderColor: theme.cr.getUiElementBorderAndFocus(),
+ },
+ },
+ }),
+ Select: (theme, { variant, size }) => ({
+ input: { ...getInputVariantStyles(theme, variant, size) },
+ dropdown: {
+ backgroundColor: theme.cr.getSubtleBackground(),
+ border: `1px solid ${theme.cr.getUiElementBorderAndFocus()}`,
+ borderRadius: theme.radius.xs,
+ },
+ item: {
+ color: theme.cr.getHighContrastText(),
+ borderRadius: 0,
+ },
+ selected: {
+ backgroundColor: theme.cr.getUiElementBackground(),
+ color: theme.cr.getHighContrastText(),
+ },
+ hovered: {
+ backgroundColor: theme.cr.getHoveredUiElementBackground(),
+ },
+ }),
+ Table: (theme) => ({
+ root: {
+ color: theme.cr.getHighContrastText(),
+ '& thead tr th': {
+ textTransform: 'uppercase',
+ fontSize: theme.fontSizes.xs,
+ color: theme.cr.getLowContrastText(),
+ borderBottom: `1px solid ${theme.cr.getSubtleBorderAndSeparator()}`,
+ },
+ '& tbody tr td': {
+ borderBottom: `1px solid ${theme.cr.getSubtleBorderAndSeparator()}`,
+ },
+ '& thead tr:hover': {
+ backgroundColor: 'transparent !important',
+ },
+ },
+ }),
+ Text: (theme, { color, variant }) => ({
+ root: {
+ color: theme.cr.getText(color, variant),
+ ...theme.fn.hover({
+ color: theme.cr.getText(color, variant),
+ textDecorationColor: theme.fn.themeColor(
+ color,
+ SHADE.UI_ELEMENT_BORDER_AND_FOCUS
+ ),
+ }),
+ },
+ }),
+ Title: (theme, { element }) => ({
+ root: {
+ '--space': theme.lineHeight,
+ '--vspace': 'calc(var(--space) * 1rem)',
+ ...getTitleStyles({ element }),
+ },
+ }),
+ Tooltip: (theme) => ({
+ body: { ...theme.cr.getTooltip() },
+ arrow: { ...theme.cr.getTooltip() },
+ }),
+};
diff --git a/client/js/app/src/app/styles/default/index.js b/client/js/app/src/app/styles/default/index.js
new file mode 100644
index 00000000000..5ffc102d3d4
--- /dev/null
+++ b/client/js/app/src/app/styles/default/index.js
@@ -0,0 +1,2 @@
+export { defaultProps } from 'app/styles/default/default-props';
+export { defaultStyles } from 'app/styles/default/default-styles';
diff --git a/client/js/app/src/app/styles/global.js b/client/js/app/src/app/styles/global.js
new file mode 100644
index 00000000000..900ae5d9304
--- /dev/null
+++ b/client/js/app/src/app/styles/global.js
@@ -0,0 +1,39 @@
+export const styles = (theme) => ({
+ '*, *::before, *::after': {
+ boxSizing: 'border-box',
+ },
+
+ '*': {
+ margin: '0',
+ },
+
+ html: {
+ height: '100%',
+ },
+
+ body: {
+ height: '100%',
+ WebkitFontSmoothing: 'antialiased',
+ lineHeight: theme.lineHeight,
+ background: theme.cr.getAppBackground(),
+ color: theme.cr.getHighContrastText(),
+ ...theme.fn.fontStyles(),
+ },
+
+ 'img, picture, video, canvas, svg': {
+ display: 'block',
+ },
+
+ 'input, button, textarea, select': {
+ font: 'inherit',
+ },
+
+ 'p, h1, h2, h3, h4, h5, h6': {
+ overflowWrap: 'break-word',
+ },
+
+ '#root': {
+ height: '100%',
+ isolation: 'isolate',
+ },
+});
diff --git a/client/js/app/src/app/styles/theme/colors.js b/client/js/app/src/app/styles/theme/colors.js
new file mode 100644
index 00000000000..5736b514329
--- /dev/null
+++ b/client/js/app/src/app/styles/theme/colors.js
@@ -0,0 +1,69 @@
+export const SHADE = Object.freeze({
+ APP_BACKGROUND: 0,
+ SUBTLE_BACKGROUND: 1,
+ UI_ELEMENT_BACKGROUND: 2,
+ HOVERED_ELEMENT_BACKGROUND: 3,
+ SUBTLE_BORDER_AND_SEPARATOR: 4,
+ UI_ELEMENT_BORDER_AND_FOCUS: 5,
+ SOLID_BACKGROUND: 6,
+ HOVERED_SOLID_BACKGROUND: 7,
+ LOW_CONTRAST_TEXT: 8,
+ HIGH_CONTRAST_TEXT: 9,
+});
+
+export class Colors {
+ constructor(theme) {
+ this.theme = theme;
+ this.themeColor = theme.colors['blue'];
+ }
+
+ getAppBackground() {
+ return this.themeColor[SHADE.APP_BACKGROUND];
+ }
+
+ getSubtleBackground() {
+ return this.themeColor[SHADE.SUBTLE_BACKGROUND];
+ }
+
+ getUiElementBackground() {
+ return this.themeColor[SHADE.UI_ELEMENT_BACKGROUND];
+ }
+
+ getHoveredUiElementBackground() {
+ return this.themeColor[SHADE.HOVERED_ELEMENT_BACKGROUND];
+ }
+
+ getSubtleBorderAndSeparator() {
+ return this.themeColor[SHADE.SUBTLE_BORDER_AND_SEPARATOR];
+ }
+
+ getUiElementBorderAndFocus() {
+ return this.themeColor[SHADE.UI_ELEMENT_BORDER_AND_FOCUS];
+ }
+
+ getSolidBackground(color) {
+ return this.theme.fn.themeColor(color, SHADE.SOLID_BACKGROUND);
+ }
+
+ getHoveredSolidBackground(color) {
+ return this.theme.fn.themeColor(color, SHADE.HOVERED_SOLID_BACKGROUND);
+ }
+
+ getLowContrastText() {
+ return this.theme.colors.gray[SHADE.LOW_CONTRAST_TEXT];
+ }
+
+ getHighContrastText() {
+ return this.theme.colors.gray[SHADE.HIGH_CONTRAST_TEXT];
+ }
+
+ getText(color, variant) {
+ return color === 'dimmed'
+ ? this.theme.fn.themeColor('gray', SHADE.SOLID_BACKGROUND)
+ : color in this.theme.colors
+ ? this.theme.fn.themeColor(color, SHADE.LOW_CONTRAST_TEXT)
+ : variant === 'link'
+ ? this.theme.fn.themeColor(color, SHADE.SOLID_BACKGROUND)
+ : color || 'inherit';
+ }
+}
diff --git a/client/js/app/src/app/styles/theme/common-colors.js b/client/js/app/src/app/styles/theme/common-colors.js
new file mode 100644
index 00000000000..fa942d3abff
--- /dev/null
+++ b/client/js/app/src/app/styles/theme/common-colors.js
@@ -0,0 +1,158 @@
+export const commonColors = {
+ gray: [
+ '#fcfcfc',
+ '#f8f8f8',
+ '#f3f3f3',
+ '#ededed',
+ '#e8e8e8',
+ '#e2e2e2',
+ '#8f8f8f',
+ '#858585',
+ '#6f6f6f',
+ '#171717',
+ ],
+ red: [
+ '#fffcfc',
+ '#fff8f8',
+ '#ffefef',
+ '#ffe5e5',
+ '#fdd8d8',
+ '#f9c6c6',
+ '#e5484d',
+ '#dc3d43',
+ '#cd2b31',
+ '#381316',
+ ],
+ pink: [
+ '#fffcfe',
+ '#fff7fc',
+ '#feeef8',
+ '#fce5f3',
+ '#f9d8ec',
+ '#f3c6e2',
+ '#d6409f',
+ '#d23197',
+ '#cd1d8d',
+ '#3b0a2a',
+ ],
+ grape: [
+ '#fefcfe',
+ '#fdfaff',
+ '#f9f1fe',
+ '#f3e7fc',
+ '#eddbf9',
+ '#e3ccf4',
+ '#8e4ec6',
+ '#8445bc',
+ '#793aaf',
+ '#2b0e44',
+ ],
+ violet: [
+ '#fdfcfe',
+ '#fbfaff',
+ '#f5f2ff',
+ '#ede9fe',
+ '#e4defc',
+ '#d7cff9',
+ '#6e56cf',
+ '#644fc1',
+ '#5746af',
+ '#20134b',
+ ],
+ indigo: [
+ '#fdfdfe',
+ '#f8faff',
+ '#f0f4ff',
+ '#e6edfe',
+ '#d9e2fc',
+ '#c6d4f9',
+ '#3e63dd',
+ '#3a5ccc',
+ '#3451b2',
+ '#101d46',
+ ],
+ blue: [
+ '#f5fbff',
+ '#feffff',
+ '#edf8ff',
+ '#e1f4ff',
+ '#ceecfe',
+ '#b7e0f8',
+ '#00598c',
+ '#00507e',
+ '#00436a',
+ '#002033',
+ ],
+ cyan: [
+ '#fafdfe',
+ '#f2fcfd',
+ '#e7f9fb',
+ '#d8f3f6',
+ '#c4eaef',
+ '#aadee6',
+ '#05a2c2',
+ '#0894b3',
+ '#0c7792',
+ '#04313c',
+ ],
+ teal: [
+ '#fafefd',
+ '#f1fcfa',
+ '#e7f9f5',
+ '#d9f3ee',
+ '#c7ebe5',
+ '#afdfd7',
+ '#12a594',
+ '#0e9888',
+ '#067a6f',
+ '#10302b',
+ ],
+ green: [
+ '#fbfefc',
+ '#f2fcf5',
+ '#e9f9ee',
+ '#ddf3e4',
+ '#ccebd7',
+ '#b4dfc4',
+ '#30a46c',
+ '#299764',
+ '#18794e',
+ '#153226',
+ ],
+ lime: [
+ '#fcfdfa',
+ '#f7fcf0',
+ '#eefadc',
+ '#e4f7c7',
+ '#d7f2b0',
+ '#c9e894',
+ '#99d52a',
+ '#93c926',
+ '#5d770d',
+ '#263209',
+ ],
+ yellow: [
+ '#fdfdf9',
+ '#fffce8',
+ '#fffbd1',
+ '#fff8bb',
+ '#fef2a4',
+ '#f9e68c',
+ '#f5d90a',
+ '#f7ce00',
+ '#946800',
+ '#35290f',
+ ],
+ orange: [
+ '#fefcfb',
+ '#fef8f4',
+ '#fff1e7',
+ '#ffe8d7',
+ '#ffdcc3',
+ '#ffcca7',
+ '#f76808',
+ '#ed5f00',
+ '#bd4b00',
+ '#451e11',
+ ],
+};
diff --git a/client/js/app/src/app/styles/theme/common.js b/client/js/app/src/app/styles/theme/common.js
new file mode 100644
index 00000000000..93a08721e5c
--- /dev/null
+++ b/client/js/app/src/app/styles/theme/common.js
@@ -0,0 +1,35 @@
+export const common = {
+ primaryShade: 6,
+ loader: 'oval',
+ white: '#fff',
+ black: '#303030',
+ defaultRadius: 'xs',
+ primaryColor: 'blue',
+ lineHeight: 1.5,
+ fontFamily: 'Lato, sans-serif',
+ shadows: {
+ xs: '0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 2px rgba(0, 0, 0, 0.1)',
+ sm: '0 1px 3px rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0px 10px 15px -5px, rgba(0, 0, 0, 0.04) 0px 7px 7px -5px',
+ md: '0 1px 3px rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0px 20px 25px -5px, rgba(0, 0, 0, 0.04) 0px 10px 10px -5px',
+ lg: '0 1px 3px rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0px 28px 23px -7px, rgba(0, 0, 0, 0.04) 0px 12px 12px -7px',
+ xl: '0 1px 3px rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0px 36px 28px -7px, rgba(0, 0, 0, 0.04) 0px 17px 17px -7px',
+ },
+ fontSizes: { xs: 12, sm: 14, md: 16, lg: 18, xl: 20 },
+ radius: { xs: 5, sm: 8, md: 13, lg: 21, xl: 34 },
+ spacing: { xs: 5, sm: 8, md: 13, lg: 21, xl: 34 },
+ breakpoints: { xs: 576, sm: 768, md: 992, lg: 1200, xl: 1400 },
+ headings: {
+ fontFamily: 'Lato, sans-serif',
+ sizes: {
+ h1: { fontSize: '1.5rem' },
+ h2: { fontSize: '1.3333rem' },
+ h3: { fontSize: '1.125rem' },
+ h4: { fontSize: '1rem' },
+ h5: { fontSize: '0.9375rem' },
+ h6: { fontSize: '0.875rem' },
+ },
+ },
+ other: {},
+ datesLocale: 'en',
+ fn: {},
+};
diff --git a/client/js/app/src/app/styles/theme/components.js b/client/js/app/src/app/styles/theme/components.js
new file mode 100644
index 00000000000..0994ad322d0
--- /dev/null
+++ b/client/js/app/src/app/styles/theme/components.js
@@ -0,0 +1,10 @@
+export const components = {
+ AppShell: {
+ styles: () => ({
+ main: {
+ maxWidth: '1920px',
+ margin: '0 auto',
+ },
+ }),
+ },
+};
diff --git a/client/js/app/src/app/styles/theme/index.js b/client/js/app/src/app/styles/theme/index.js
new file mode 100644
index 00000000000..2c69eb2af81
--- /dev/null
+++ b/client/js/app/src/app/styles/theme/index.js
@@ -0,0 +1,7 @@
+import { common } from 'app/styles/theme/common';
+import { components } from 'app/styles/theme/components';
+import { commonColors } from 'app/styles/theme/common-colors';
+
+export const getTheme = () => {
+ return { ...common, components, colors: commonColors };
+};
diff --git a/client/js/app/yarn.lock b/client/js/app/yarn.lock
index 90377962003..39a2213d77c 100644
--- a/client/js/app/yarn.lock
+++ b/client/js/app/yarn.lock
@@ -10,328 +10,444 @@
"@jridgewell/gen-mapping" "^0.1.0"
"@jridgewell/trace-mapping" "^0.3.9"
-"@babel/code-frame@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.16.7.tgz#44416b6bd7624b998f5b1af5d470856c40138789"
- integrity sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==
+"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13", "@babel/code-frame@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.18.6.tgz#3b25d38c89600baa2dcc219edfa88a74eb2c427a"
+ integrity sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==
dependencies:
- "@babel/highlight" "^7.16.7"
+ "@babel/highlight" "^7.18.6"
-"@babel/compat-data@^7.17.10":
- version "7.18.5"
- resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.18.5.tgz#acac0c839e317038c73137fbb6ef71a1d6238471"
- integrity sha512-BxhE40PVCBxVEJsSBhB6UWyAuqJRxGsAw8BdHMJ3AKGydcwuWW4kOO3HmqBQAdcq/OP+/DlTVxLvsCzRTnZuGg==
+"@babel/compat-data@^7.18.8":
+ version "7.18.8"
+ resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.18.8.tgz#2483f565faca607b8535590e84e7de323f27764d"
+ integrity sha512-HSmX4WZPPK3FUxYp7g2T6EyO8j96HlZJlxmKPSh6KAcqwyDrfx7hKjXpAW/0FhFfTJsR0Yt4lAjLI2coMptIHQ==
-"@babel/core@^7.17.10":
- version "7.18.5"
- resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.18.5.tgz#c597fa680e58d571c28dda9827669c78cdd7f000"
- integrity sha512-MGY8vg3DxMnctw0LdvSEojOsumc70g0t18gNyUdAZqB1Rpd1Bqo/svHGvt+UJ6JcGX+DIekGFDxxIWofBxLCnQ==
+"@babel/core@^7.1.0", "@babel/core@^7.11.6", "@babel/core@^7.12.17", "@babel/core@^7.12.3", "@babel/core@^7.17.10":
+ version "7.18.10"
+ resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.18.10.tgz#39ad504991d77f1f3da91be0b8b949a5bc466fb8"
+ integrity sha512-JQM6k6ENcBFKVtWvLavlvi/mPcpYZ3+R+2EySDEMSMbp7Mn4FexlbbJVrx2R7Ijhr01T8gyqrOaABWIOgxeUyw==
dependencies:
"@ampproject/remapping" "^2.1.0"
- "@babel/code-frame" "^7.16.7"
- "@babel/generator" "^7.18.2"
- "@babel/helper-compilation-targets" "^7.18.2"
- "@babel/helper-module-transforms" "^7.18.0"
- "@babel/helpers" "^7.18.2"
- "@babel/parser" "^7.18.5"
- "@babel/template" "^7.16.7"
- "@babel/traverse" "^7.18.5"
- "@babel/types" "^7.18.4"
+ "@babel/code-frame" "^7.18.6"
+ "@babel/generator" "^7.18.10"
+ "@babel/helper-compilation-targets" "^7.18.9"
+ "@babel/helper-module-transforms" "^7.18.9"
+ "@babel/helpers" "^7.18.9"
+ "@babel/parser" "^7.18.10"
+ "@babel/template" "^7.18.10"
+ "@babel/traverse" "^7.18.10"
+ "@babel/types" "^7.18.10"
convert-source-map "^1.7.0"
debug "^4.1.0"
gensync "^1.0.0-beta.2"
json5 "^2.2.1"
semver "^6.3.0"
-"@babel/generator@^7.18.2":
- version "7.18.2"
- resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.18.2.tgz#33873d6f89b21efe2da63fe554460f3df1c5880d"
- integrity sha512-W1lG5vUwFvfMd8HVXqdfbuG7RuaSrTCCD8cl8fP8wOivdbtbIg2Db3IWUcgvfxKbbn6ZBGYRW/Zk1MIwK49mgw==
+"@babel/generator@^7.18.10", "@babel/generator@^7.7.2":
+ version "7.18.12"
+ resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.18.12.tgz#fa58daa303757bd6f5e4bbca91b342040463d9f4"
+ integrity sha512-dfQ8ebCN98SvyL7IxNMCUtZQSq5R7kxgN+r8qYTGDmmSion1hX2C0zq2yo1bsCDhXixokv1SAWTZUMYbO/V5zg==
dependencies:
- "@babel/types" "^7.18.2"
- "@jridgewell/gen-mapping" "^0.3.0"
+ "@babel/types" "^7.18.10"
+ "@jridgewell/gen-mapping" "^0.3.2"
jsesc "^2.5.1"
-"@babel/helper-annotate-as-pure@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz#bb2339a7534a9c128e3102024c60760a3a7f3862"
- integrity sha512-s6t2w/IPQVTAET1HitoowRGXooX8mCgtuP5195wD/QJPV6wYjpujCGF7JuMODVX2ZAJOf1GT6DT9MHEZvLOFSw==
+"@babel/helper-annotate-as-pure@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.18.6.tgz#eaa49f6f80d5a33f9a5dd2276e6d6e451be0a6bb"
+ integrity sha512-duORpUiYrEpzKIop6iNbjnwKLAKnJ47csTyRACyEmWj0QdUrm5aqNJGHSSEQSUAvNW0ojX0dOmK9dZduvkfeXA==
dependencies:
- "@babel/types" "^7.16.7"
+ "@babel/types" "^7.18.6"
-"@babel/helper-compilation-targets@^7.18.2":
- version "7.18.2"
- resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.18.2.tgz#67a85a10cbd5fc7f1457fec2e7f45441dc6c754b"
- integrity sha512-s1jnPotJS9uQnzFtiZVBUxe67CuBa679oWFHpxYYnTpRL/1ffhyX44R9uYiXoa/pLXcY9H2moJta0iaanlk/rQ==
+"@babel/helper-compilation-targets@^7.18.9":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.18.9.tgz#69e64f57b524cde3e5ff6cc5a9f4a387ee5563bf"
+ integrity sha512-tzLCyVmqUiFlcFoAPLA/gL9TeYrF61VLNtb+hvkuVaB5SUjW7jcfrglBIX1vUIoT7CLP3bBlIMeyEsIl2eFQNg==
dependencies:
- "@babel/compat-data" "^7.17.10"
- "@babel/helper-validator-option" "^7.16.7"
+ "@babel/compat-data" "^7.18.8"
+ "@babel/helper-validator-option" "^7.18.6"
browserslist "^4.20.2"
semver "^6.3.0"
-"@babel/helper-environment-visitor@^7.16.7", "@babel/helper-environment-visitor@^7.18.2":
- version "7.18.2"
- resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.2.tgz#8a6d2dedb53f6bf248e31b4baf38739ee4a637bd"
- integrity sha512-14GQKWkX9oJzPiQQ7/J36FTXcD4kSp8egKjO9nINlSKiHITRA9q/R74qu8S9xlc/b/yjsJItQUeeh3xnGN0voQ==
+"@babel/helper-environment-visitor@^7.18.9":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz#0c0cee9b35d2ca190478756865bb3528422f51be"
+ integrity sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==
+
+"@babel/helper-function-name@^7.18.9":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.18.9.tgz#940e6084a55dee867d33b4e487da2676365e86b0"
+ integrity sha512-fJgWlZt7nxGksJS9a0XdSaI4XvpExnNIgRP+rVefWh5U7BL8pPuir6SJUmFKRfjWQ51OtWSzwOxhaH/EBWWc0A==
+ dependencies:
+ "@babel/template" "^7.18.6"
+ "@babel/types" "^7.18.9"
+
+"@babel/helper-hoist-variables@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz#d4d2c8fb4baeaa5c68b99cc8245c56554f926678"
+ integrity sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==
+ dependencies:
+ "@babel/types" "^7.18.6"
+
+"@babel/helper-module-imports@^7.16.7", "@babel/helper-module-imports@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz#1e3ebdbbd08aad1437b428c50204db13c5a3ca6e"
+ integrity sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==
+ dependencies:
+ "@babel/types" "^7.18.6"
+
+"@babel/helper-module-transforms@^7.18.6", "@babel/helper-module-transforms@^7.18.9":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.18.9.tgz#5a1079c005135ed627442df31a42887e80fcb712"
+ integrity sha512-KYNqY0ICwfv19b31XzvmI/mfcylOzbLtowkw+mfvGPAQ3kfCnMLYbED3YecL5tPd8nAYFQFAd6JHp2LxZk/J1g==
+ dependencies:
+ "@babel/helper-environment-visitor" "^7.18.9"
+ "@babel/helper-module-imports" "^7.18.6"
+ "@babel/helper-simple-access" "^7.18.6"
+ "@babel/helper-split-export-declaration" "^7.18.6"
+ "@babel/helper-validator-identifier" "^7.18.6"
+ "@babel/template" "^7.18.6"
+ "@babel/traverse" "^7.18.9"
+ "@babel/types" "^7.18.9"
+
+"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.18.9", "@babel/helper-plugin-utils@^7.8.0":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.18.9.tgz#4b8aea3b069d8cb8a72cdfe28ddf5ceca695ef2f"
+ integrity sha512-aBXPT3bmtLryXaoJLyYPXPlSD4p1ld9aYeR+sJNOZjJJGiOpb+fKfh3NkcCu7J54nUJwCERPBExCCpyCOHnu/w==
+
+"@babel/helper-simple-access@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.18.6.tgz#d6d8f51f4ac2978068df934b569f08f29788c7ea"
+ integrity sha512-iNpIgTgyAvDQpDj76POqg+YEt8fPxx3yaNBg3S30dxNKm2SWfYhD0TGrK/Eu9wHpUW63VQU894TsTg+GLbUa1g==
+ dependencies:
+ "@babel/types" "^7.18.6"
+
+"@babel/helper-split-export-declaration@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz#7367949bc75b20c6d5a5d4a97bba2824ae8ef075"
+ integrity sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==
+ dependencies:
+ "@babel/types" "^7.18.6"
+
+"@babel/helper-string-parser@^7.18.10":
+ version "7.18.10"
+ resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.18.10.tgz#181f22d28ebe1b3857fa575f5c290b1aaf659b56"
+ integrity sha512-XtIfWmeNY3i4t7t4D2t02q50HvqHybPqW2ki1kosnvWCwuCMeo81Jf0gwr85jy/neUdg5XDdeFE/80DXiO+njw==
+
+"@babel/helper-validator-identifier@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.18.6.tgz#9c97e30d31b2b8c72a1d08984f2ca9b574d7a076"
+ integrity sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g==
+
+"@babel/helper-validator-option@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz#bf0d2b5a509b1f336099e4ff36e1a63aa5db4db8"
+ integrity sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==
+
+"@babel/helpers@^7.18.9":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.18.9.tgz#4bef3b893f253a1eced04516824ede94dcfe7ff9"
+ integrity sha512-Jf5a+rbrLoR4eNdUmnFu8cN5eNJT6qdTdOg5IHIzq87WwyRw9PwguLFOWYgktN/60IP4fgDUawJvs7PjQIzELQ==
+ dependencies:
+ "@babel/template" "^7.18.6"
+ "@babel/traverse" "^7.18.9"
+ "@babel/types" "^7.18.9"
+
+"@babel/highlight@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.18.6.tgz#81158601e93e2563795adcbfbdf5d64be3f2ecdf"
+ integrity sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==
+ dependencies:
+ "@babel/helper-validator-identifier" "^7.18.6"
+ chalk "^2.0.0"
+ js-tokens "^4.0.0"
+
+"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.18.10", "@babel/parser@^7.18.11":
+ version "7.18.11"
+ resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.18.11.tgz#68bb07ab3d380affa9a3f96728df07969645d2d9"
+ integrity sha512-9JKn5vN+hDt0Hdqn1PiJ2guflwP+B6Ga8qbDuoF0PzzVhrzsKIJo8yGqVk6CmMHiMei9w1C1Bp9IMJSIK+HPIQ==
-"@babel/helper-function-name@^7.17.9":
- version "7.17.9"
- resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.17.9.tgz#136fcd54bc1da82fcb47565cf16fd8e444b1ff12"
- integrity sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg==
+"@babel/plugin-syntax-async-generators@^7.8.4":
+ version "7.8.4"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d"
+ integrity sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==
dependencies:
- "@babel/template" "^7.16.7"
- "@babel/types" "^7.17.0"
+ "@babel/helper-plugin-utils" "^7.8.0"
-"@babel/helper-hoist-variables@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.7.tgz#86bcb19a77a509c7b77d0e22323ef588fa58c246"
- integrity sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==
+"@babel/plugin-syntax-bigint@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz#4c9a6f669f5d0cdf1b90a1671e9a146be5300cea"
+ integrity sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==
dependencies:
- "@babel/types" "^7.16.7"
+ "@babel/helper-plugin-utils" "^7.8.0"
-"@babel/helper-module-imports@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.16.7.tgz#25612a8091a999704461c8a222d0efec5d091437"
- integrity sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==
+"@babel/plugin-syntax-class-properties@^7.8.3":
+ version "7.12.13"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz#b5c987274c4a3a82b89714796931a6b53544ae10"
+ integrity sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==
dependencies:
- "@babel/types" "^7.16.7"
+ "@babel/helper-plugin-utils" "^7.12.13"
-"@babel/helper-module-transforms@^7.18.0":
- version "7.18.0"
- resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.18.0.tgz#baf05dec7a5875fb9235bd34ca18bad4e21221cd"
- integrity sha512-kclUYSUBIjlvnzN2++K9f2qzYKFgjmnmjwL4zlmU5f8ZtzgWe8s0rUPSTGy2HmK4P8T52MQsS+HTQAgZd3dMEA==
+"@babel/plugin-syntax-import-meta@^7.8.3":
+ version "7.10.4"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz#ee601348c370fa334d2207be158777496521fd51"
+ integrity sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==
dependencies:
- "@babel/helper-environment-visitor" "^7.16.7"
- "@babel/helper-module-imports" "^7.16.7"
- "@babel/helper-simple-access" "^7.17.7"
- "@babel/helper-split-export-declaration" "^7.16.7"
- "@babel/helper-validator-identifier" "^7.16.7"
- "@babel/template" "^7.16.7"
- "@babel/traverse" "^7.18.0"
- "@babel/types" "^7.18.0"
-
-"@babel/helper-plugin-utils@^7.16.7", "@babel/helper-plugin-utils@^7.17.12":
- version "7.17.12"
- resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.17.12.tgz#86c2347da5acbf5583ba0a10aed4c9bf9da9cf96"
- integrity sha512-JDkf04mqtN3y4iAbO1hv9U2ARpPyPL1zqyWs/2WG1pgSq9llHFjStX5jdxb84himgJm+8Ng+x0oiWF/nw/XQKA==
-
-"@babel/helper-simple-access@^7.17.7":
- version "7.18.2"
- resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.18.2.tgz#4dc473c2169ac3a1c9f4a51cfcd091d1c36fcff9"
- integrity sha512-7LIrjYzndorDY88MycupkpQLKS1AFfsVRm2k/9PtKScSy5tZq0McZTj+DiMRynboZfIqOKvo03pmhTaUgiD6fQ==
- dependencies:
- "@babel/types" "^7.18.2"
-
-"@babel/helper-split-export-declaration@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.7.tgz#0b648c0c42da9d3920d85ad585f2778620b8726b"
- integrity sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==
- dependencies:
- "@babel/types" "^7.16.7"
-
-"@babel/helper-validator-identifier@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz#e8c602438c4a8195751243da9031d1607d247cad"
- integrity sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==
-
-"@babel/helper-validator-option@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz#b203ce62ce5fe153899b617c08957de860de4d23"
- integrity sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==
-
-"@babel/helpers@^7.18.2":
- version "7.18.2"
- resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.18.2.tgz#970d74f0deadc3f5a938bfa250738eb4ac889384"
- integrity sha512-j+d+u5xT5utcQSzrh9p+PaJX94h++KN+ng9b9WEJq7pkUPAd61FGqhjuUEdfknb3E/uDBb7ruwEeKkIxNJPIrg==
- dependencies:
- "@babel/template" "^7.16.7"
- "@babel/traverse" "^7.18.2"
- "@babel/types" "^7.18.2"
-
-"@babel/highlight@^7.16.7":
- version "7.17.12"
- resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.17.12.tgz#257de56ee5afbd20451ac0a75686b6b404257351"
- integrity sha512-7yykMVF3hfZY2jsHZEEgLc+3x4o1O+fYyULu11GynEUQNwB6lua+IIQn1FiJxNucd5UlyJryrwsOh8PL9Sn8Qg==
- dependencies:
- "@babel/helper-validator-identifier" "^7.16.7"
- chalk "^2.0.0"
- js-tokens "^4.0.0"
+ "@babel/helper-plugin-utils" "^7.10.4"
+
+"@babel/plugin-syntax-json-strings@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a"
+ integrity sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.8.0"
+
+"@babel/plugin-syntax-jsx@^7.17.12", "@babel/plugin-syntax-jsx@^7.18.6":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz#a8feef63b010150abd97f1649ec296e849943ca0"
+ integrity sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.18.6"
+
+"@babel/plugin-syntax-logical-assignment-operators@^7.8.3":
+ version "7.10.4"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699"
+ integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.10.4"
+
+"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9"
+ integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.8.0"
+
+"@babel/plugin-syntax-numeric-separator@^7.8.3":
+ version "7.10.4"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz#b9b070b3e33570cd9fd07ba7fa91c0dd37b9af97"
+ integrity sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.10.4"
+
+"@babel/plugin-syntax-object-rest-spread@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz#60e225edcbd98a640332a2e72dd3e66f1af55871"
+ integrity sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.8.0"
+
+"@babel/plugin-syntax-optional-catch-binding@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz#6111a265bcfb020eb9efd0fdfd7d26402b9ed6c1"
+ integrity sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.8.0"
+
+"@babel/plugin-syntax-optional-chaining@^7.8.3":
+ version "7.8.3"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz#4f69c2ab95167e0180cd5336613f8c5788f7d48a"
+ integrity sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.8.0"
+
+"@babel/plugin-syntax-top-level-await@^7.8.3":
+ version "7.14.5"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz#c1cfdadc35a646240001f06138247b741c34d94c"
+ integrity sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.14.5"
-"@babel/parser@^7.16.7", "@babel/parser@^7.18.5":
- version "7.18.5"
- resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.18.5.tgz#337062363436a893a2d22faa60be5bb37091c83c"
- integrity sha512-YZWVaglMiplo7v8f1oMQ5ZPQr0vn7HPeZXxXWsxXJRjGVrzUFn9OxFQl1sb5wzfootjA/yChhW84BV+383FSOw==
+"@babel/plugin-syntax-typescript@^7.7.2":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.18.6.tgz#1c09cd25795c7c2b8a4ba9ae49394576d4133285"
+ integrity sha512-mAWAuq4rvOepWCBid55JuRNvpTNf2UGVgoz4JV0fXEKolsVZDzsa4NqCef758WZJj/GDu0gVGItjKFiClTAmZA==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.18.6"
-"@babel/plugin-syntax-jsx@^7.17.12":
- version "7.17.12"
- resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.17.12.tgz#834035b45061983a491f60096f61a2e7c5674a47"
- integrity sha512-spyY3E3AURfxh/RHtjx5j6hs8am5NbUBGfcZ2vB3uShSpZdQyXSf5rR5Mk76vbtlAZOelyVQ71Fg0x9SG4fsog==
+"@babel/plugin-transform-modules-commonjs@^7.12.13":
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.18.6.tgz#afd243afba166cca69892e24a8fd8c9f2ca87883"
+ integrity sha512-Qfv2ZOWikpvmedXQJDSbxNqy7Xr/j2Y8/KfijM0iJyKkBTmWuvCA1yeH1yDM7NJhBW/2aXxeucLj6i80/LAJ/Q==
dependencies:
- "@babel/helper-plugin-utils" "^7.17.12"
+ "@babel/helper-module-transforms" "^7.18.6"
+ "@babel/helper-plugin-utils" "^7.18.6"
+ "@babel/helper-simple-access" "^7.18.6"
+ babel-plugin-dynamic-import-node "^2.3.3"
"@babel/plugin-transform-react-jsx-development@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.16.7.tgz#43a00724a3ed2557ed3f276a01a929e6686ac7b8"
- integrity sha512-RMvQWvpla+xy6MlBpPlrKZCMRs2AGiHOGHY3xRwl0pEeim348dDyxeH4xBsMPbIMhujeq7ihE702eM2Ew0Wo+A==
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.18.6.tgz#dbe5c972811e49c7405b630e4d0d2e1380c0ddc5"
+ integrity sha512-SA6HEjwYFKF7WDjWcMcMGUimmw/nhNRDWxr+KaLSCrkD/LMDBvWRmHAYgE1HDeF8KUuI8OAu+RT6EOtKxSW2qA==
dependencies:
- "@babel/plugin-transform-react-jsx" "^7.16.7"
+ "@babel/plugin-transform-react-jsx" "^7.18.6"
"@babel/plugin-transform-react-jsx-self@^7.16.7":
- version "7.17.12"
- resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.17.12.tgz#7f2e9b8c08d6a4204733138d8c29d4dba4bb66c2"
- integrity sha512-7S9G2B44EnYOx74mue02t1uD8ckWZ/ee6Uz/qfdzc35uWHX5NgRy9i+iJSb2LFRgMd+QV9zNcStQaazzzZ3n3Q==
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.18.6.tgz#3849401bab7ae8ffa1e3e5687c94a753fc75bda7"
+ integrity sha512-A0LQGx4+4Jv7u/tWzoJF7alZwnBDQd6cGLh9P+Ttk4dpiL+J5p7NSNv/9tlEFFJDq3kjxOavWmbm6t0Gk+A3Ig==
dependencies:
- "@babel/helper-plugin-utils" "^7.17.12"
+ "@babel/helper-plugin-utils" "^7.18.6"
"@babel/plugin-transform-react-jsx-source@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.16.7.tgz#1879c3f23629d287cc6186a6c683154509ec70c0"
- integrity sha512-rONFiQz9vgbsnaMtQlZCjIRwhJvlrPET8TabIUK2hzlXw9B9s2Ieaxte1SCOOXMbWRHodbKixNf3BLcWVOQ8Bw==
+ version "7.18.6"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.18.6.tgz#06e9ae8a14d2bc19ce6e3c447d842032a50598fc"
+ integrity sha512-utZmlASneDfdaMh0m/WausbjUjEdGrQJz0vFK93d7wD3xf5wBtX219+q6IlCNZeguIcxS2f/CvLZrlLSvSHQXw==
dependencies:
- "@babel/helper-plugin-utils" "^7.16.7"
+ "@babel/helper-plugin-utils" "^7.18.6"
-"@babel/plugin-transform-react-jsx@^7.16.7", "@babel/plugin-transform-react-jsx@^7.17.3":
- version "7.17.12"
- resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.17.12.tgz#2aa20022709cd6a3f40b45d60603d5f269586dba"
- integrity sha512-Lcaw8bxd1DKht3thfD4A12dqo1X16he1Lm8rIv8sTwjAYNInRS1qHa9aJoqvzpscItXvftKDCfaEQzwoVyXpEQ==
+"@babel/plugin-transform-react-jsx@^7.17.3", "@babel/plugin-transform-react-jsx@^7.18.6":
+ version "7.18.10"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.18.10.tgz#ea47b2c4197102c196cbd10db9b3bb20daa820f1"
+ integrity sha512-gCy7Iikrpu3IZjYZolFE4M1Sm+nrh1/6za2Ewj77Z+XirT4TsbJcvOFOyF+fRPwU6AKKK136CZxx6L8AbSFG6A==
dependencies:
- "@babel/helper-annotate-as-pure" "^7.16.7"
- "@babel/helper-module-imports" "^7.16.7"
- "@babel/helper-plugin-utils" "^7.17.12"
- "@babel/plugin-syntax-jsx" "^7.17.12"
- "@babel/types" "^7.17.12"
+ "@babel/helper-annotate-as-pure" "^7.18.6"
+ "@babel/helper-module-imports" "^7.18.6"
+ "@babel/helper-plugin-utils" "^7.18.9"
+ "@babel/plugin-syntax-jsx" "^7.18.6"
+ "@babel/types" "^7.18.10"
-"@babel/runtime@^7.10.2", "@babel/runtime@^7.13.10":
- version "7.18.3"
- resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.18.3.tgz#c7b654b57f6f63cf7f8b418ac9ca04408c4579f4"
- integrity sha512-38Y8f7YUhce/K7RMwTp7m0uCumpv9hZkitCbBClqQIow1qSbCvGkcegKOXpEWCQLfWmevgRiWokZ1GkpfhbZug==
+"@babel/runtime@^7.10.2", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.18.3", "@babel/runtime@^7.5.5", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.7":
+ version "7.18.9"
+ resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.18.9.tgz#b4fcfce55db3d2e5e080d2490f608a3b9f407f4a"
+ integrity sha512-lkqXDcvlFT5rvEjiu6+QYO+1GXrEHRo2LOtS7E4GtX5ESIZOgepqsZBVIj6Pv+a6zqsya9VCgiK1KAK4BvJDAw==
dependencies:
regenerator-runtime "^0.13.4"
-"@babel/template@^7.16.7":
- version "7.16.7"
- resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.16.7.tgz#8d126c8701fde4d66b264b3eba3d96f07666d155"
- integrity sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==
- dependencies:
- "@babel/code-frame" "^7.16.7"
- "@babel/parser" "^7.16.7"
- "@babel/types" "^7.16.7"
-
-"@babel/traverse@^7.18.0", "@babel/traverse@^7.18.2", "@babel/traverse@^7.18.5":
- version "7.18.5"
- resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.18.5.tgz#94a8195ad9642801837988ab77f36e992d9a20cd"
- integrity sha512-aKXj1KT66sBj0vVzk6rEeAO6Z9aiiQ68wfDgge3nHhA/my6xMM/7HGQUNumKZaoa2qUPQ5whJG9aAifsxUKfLA==
- dependencies:
- "@babel/code-frame" "^7.16.7"
- "@babel/generator" "^7.18.2"
- "@babel/helper-environment-visitor" "^7.18.2"
- "@babel/helper-function-name" "^7.17.9"
- "@babel/helper-hoist-variables" "^7.16.7"
- "@babel/helper-split-export-declaration" "^7.16.7"
- "@babel/parser" "^7.18.5"
- "@babel/types" "^7.18.4"
+"@babel/template@^7.18.10", "@babel/template@^7.18.6", "@babel/template@^7.3.3":
+ version "7.18.10"
+ resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.18.10.tgz#6f9134835970d1dbf0835c0d100c9f38de0c5e71"
+ integrity sha512-TI+rCtooWHr3QJ27kJxfjutghu44DLnasDMwpDqCXVTal9RLp3RSYNh4NdBrRP2cQAoG9A8juOQl6P6oZG4JxA==
+ dependencies:
+ "@babel/code-frame" "^7.18.6"
+ "@babel/parser" "^7.18.10"
+ "@babel/types" "^7.18.10"
+
+"@babel/traverse@^7.18.10", "@babel/traverse@^7.18.9", "@babel/traverse@^7.7.2":
+ version "7.18.11"
+ resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.18.11.tgz#3d51f2afbd83ecf9912bcbb5c4d94e3d2ddaa16f"
+ integrity sha512-TG9PiM2R/cWCAy6BPJKeHzNbu4lPzOSZpeMfeNErskGpTJx6trEvFaVCbDvpcxwy49BKWmEPwiW8mrysNiDvIQ==
+ dependencies:
+ "@babel/code-frame" "^7.18.6"
+ "@babel/generator" "^7.18.10"
+ "@babel/helper-environment-visitor" "^7.18.9"
+ "@babel/helper-function-name" "^7.18.9"
+ "@babel/helper-hoist-variables" "^7.18.6"
+ "@babel/helper-split-export-declaration" "^7.18.6"
+ "@babel/parser" "^7.18.11"
+ "@babel/types" "^7.18.10"
debug "^4.1.0"
globals "^11.1.0"
-"@babel/types@^7.16.7", "@babel/types@^7.17.0", "@babel/types@^7.17.12", "@babel/types@^7.18.0", "@babel/types@^7.18.2", "@babel/types@^7.18.4":
- version "7.18.4"
- resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.18.4.tgz#27eae9b9fd18e9dccc3f9d6ad051336f307be354"
- integrity sha512-ThN1mBcMq5pG/Vm2IcBmPPfyPXbd8S02rS+OBIDENdufvqC7Z/jHPCv9IcP01277aKtDI8g/2XysBN4hA8niiw==
+"@babel/types@^7.0.0", "@babel/types@^7.18.10", "@babel/types@^7.18.6", "@babel/types@^7.18.9", "@babel/types@^7.3.0", "@babel/types@^7.3.3":
+ version "7.18.10"
+ resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.18.10.tgz#4908e81b6b339ca7c6b7a555a5fc29446f26dde6"
+ integrity sha512-MJvnbEiiNkpjo+LknnmRrqbY1GPUUggjv+wQVjetM/AONoupqRALB7I6jGqNUAZsKcRIEu2J6FRFvsczljjsaQ==
dependencies:
- "@babel/helper-validator-identifier" "^7.16.7"
+ "@babel/helper-string-parser" "^7.18.10"
+ "@babel/helper-validator-identifier" "^7.18.6"
to-fast-properties "^2.0.0"
-"@emotion/cache@11.7.1":
- version "11.7.1"
- resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.7.1.tgz#08d080e396a42e0037848214e8aa7bf879065539"
- integrity sha512-r65Zy4Iljb8oyjtLeCuBH8Qjiy107dOYC6SJq7g7GV5UCQWMObY4SJDPGFjiiVpPrOJ2hmJOoBiYTC7hwx9E2A==
+"@bcoe/v8-coverage@^0.2.3":
+ version "0.2.3"
+ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39"
+ integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==
+
+"@cnakazawa/watch@^1.0.3":
+ version "1.0.4"
+ resolved "https://registry.yarnpkg.com/@cnakazawa/watch/-/watch-1.0.4.tgz#f864ae85004d0fcab6f50be9141c4da368d1656a"
+ integrity sha512-v9kIhKwjeZThiWrLmj0y17CWoyddASLj9O2yvbZkbvw/N3rWOYy9zkV66ursAoVr0mV15bL8g0c4QZUE6cdDoQ==
dependencies:
- "@emotion/memoize" "^0.7.4"
- "@emotion/sheet" "^1.1.0"
- "@emotion/utils" "^1.0.0"
- "@emotion/weak-memoize" "^0.2.5"
- stylis "4.0.13"
+ exec-sh "^0.3.2"
+ minimist "^1.2.0"
-"@emotion/cache@^11.7.1":
- version "11.9.3"
- resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.9.3.tgz#96638449f6929fd18062cfe04d79b29b44c0d6cb"
- integrity sha512-0dgkI/JKlCXa+lEXviaMtGBL0ynpx4osh7rjOXE71q9bIF8G+XhJgvi+wDu0B0IdCVx37BffiwXlN9I3UuzFvg==
+"@emotion/babel-plugin@^11.10.0":
+ version "11.10.0"
+ resolved "https://registry.yarnpkg.com/@emotion/babel-plugin/-/babel-plugin-11.10.0.tgz#ae545b8faa6b42d3a50ec86b70b758296f3c4467"
+ integrity sha512-xVnpDAAbtxL1dsuSelU5A7BnY/lftws0wUexNJZTPsvX/1tM4GZJbclgODhvW4E+NH7E5VFcH0bBn30NvniPJA==
dependencies:
- "@emotion/memoize" "^0.7.4"
- "@emotion/sheet" "^1.1.1"
- "@emotion/utils" "^1.0.0"
- "@emotion/weak-memoize" "^0.2.5"
+ "@babel/helper-module-imports" "^7.16.7"
+ "@babel/plugin-syntax-jsx" "^7.17.12"
+ "@babel/runtime" "^7.18.3"
+ "@emotion/hash" "^0.9.0"
+ "@emotion/memoize" "^0.8.0"
+ "@emotion/serialize" "^1.1.0"
+ babel-plugin-macros "^3.1.0"
+ convert-source-map "^1.5.0"
+ escape-string-regexp "^4.0.0"
+ find-root "^1.1.0"
+ source-map "^0.5.7"
stylis "4.0.13"
-"@emotion/hash@^0.8.0":
- version "0.8.0"
- resolved "https://registry.yarnpkg.com/@emotion/hash/-/hash-0.8.0.tgz#bbbff68978fefdbe68ccb533bc8cbe1d1afb5413"
- integrity sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==
+"@emotion/cache@^11.10.0":
+ version "11.10.1"
+ resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.10.1.tgz#75a157c2a6bb9220450f73ebef1df2e1467dc65d"
+ integrity sha512-uZTj3Yz5D69GE25iFZcIQtibnVCFsc/6+XIozyL3ycgWvEdif2uEw9wlUt6umjLr4Keg9K6xRPHmD8LGi+6p1A==
+ dependencies:
+ "@emotion/memoize" "^0.8.0"
+ "@emotion/sheet" "^1.2.0"
+ "@emotion/utils" "^1.2.0"
+ "@emotion/weak-memoize" "^0.3.0"
+ stylis "4.0.13"
-"@emotion/memoize@^0.7.4":
- version "0.7.5"
- resolved "https://registry.yarnpkg.com/@emotion/memoize/-/memoize-0.7.5.tgz#2c40f81449a4e554e9fc6396910ed4843ec2be50"
- integrity sha512-igX9a37DR2ZPGYtV6suZ6whr8pTFtyHL3K/oLUotxpSVO2ASaprmAe2Dkq7tBo7CRY7MMDrAa9nuQP9/YG8FxQ==
+"@emotion/hash@^0.9.0":
+ version "0.9.0"
+ resolved "https://registry.yarnpkg.com/@emotion/hash/-/hash-0.9.0.tgz#c5153d50401ee3c027a57a177bc269b16d889cb7"
+ integrity sha512-14FtKiHhy2QoPIzdTcvh//8OyBlknNs2nXRwIhG904opCby3l+9Xaf/wuPvICBF0rc1ZCNBd3nKe9cd2mecVkQ==
-"@emotion/react@11.7.1":
- version "11.7.1"
- resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.7.1.tgz#3f800ce9b20317c13e77b8489ac4a0b922b2fe07"
- integrity sha512-DV2Xe3yhkF1yT4uAUoJcYL1AmrnO5SVsdfvu+fBuS7IbByDeTVx9+wFmvx9Idzv7/78+9Mgx2Hcmr7Fex3tIyw==
- dependencies:
- "@babel/runtime" "^7.13.10"
- "@emotion/cache" "^11.7.1"
- "@emotion/serialize" "^1.0.2"
- "@emotion/sheet" "^1.1.0"
- "@emotion/utils" "^1.0.0"
- "@emotion/weak-memoize" "^0.2.5"
+"@emotion/memoize@^0.8.0":
+ version "0.8.0"
+ resolved "https://registry.yarnpkg.com/@emotion/memoize/-/memoize-0.8.0.tgz#f580f9beb67176fa57aae70b08ed510e1b18980f"
+ integrity sha512-G/YwXTkv7Den9mXDO7AhLWkE3q+I92B+VqAE+dYG4NGPaHZGvt3G8Q0p9vmE+sq7rTGphUbAvmQ9YpbfMQGGlA==
+
+"@emotion/react@^11":
+ version "11.10.0"
+ resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.10.0.tgz#53c577f063f26493f68a05188fb87528d912ff2e"
+ integrity sha512-K6z9zlHxxBXwN8TcpwBKcEsBsOw4JWCCmR+BeeOWgqp8GIU1yA2Odd41bwdAAr0ssbQrbJbVnndvv7oiv1bZeQ==
+ dependencies:
+ "@babel/runtime" "^7.18.3"
+ "@emotion/babel-plugin" "^11.10.0"
+ "@emotion/cache" "^11.10.0"
+ "@emotion/serialize" "^1.1.0"
+ "@emotion/utils" "^1.2.0"
+ "@emotion/weak-memoize" "^0.3.0"
hoist-non-react-statics "^3.3.1"
-"@emotion/serialize@1.0.2":
- version "1.0.2"
- resolved "https://registry.yarnpkg.com/@emotion/serialize/-/serialize-1.0.2.tgz#77cb21a0571c9f68eb66087754a65fa97bfcd965"
- integrity sha512-95MgNJ9+/ajxU7QIAruiOAdYNjxZX7G2mhgrtDWswA21VviYIRP1R5QilZ/bDY42xiKsaktP4egJb3QdYQZi1A==
- dependencies:
- "@emotion/hash" "^0.8.0"
- "@emotion/memoize" "^0.7.4"
- "@emotion/unitless" "^0.7.5"
- "@emotion/utils" "^1.0.0"
- csstype "^3.0.2"
-
-"@emotion/serialize@^1.0.2":
- version "1.0.4"
- resolved "https://registry.yarnpkg.com/@emotion/serialize/-/serialize-1.0.4.tgz#ff31fd11bb07999611199c2229e152faadc21a3c"
- integrity sha512-1JHamSpH8PIfFwAMryO2bNka+y8+KA5yga5Ocf2d7ZEiJjb7xlLW7aknBGZqJLajuLOvJ+72vN+IBSwPlXD1Pg==
+"@emotion/serialize@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@emotion/serialize/-/serialize-1.1.0.tgz#b1f97b1011b09346a40e9796c37a3397b4ea8ea8"
+ integrity sha512-F1ZZZW51T/fx+wKbVlwsfchr5q97iW8brAnXmsskz4d0hVB4O3M/SiA3SaeH06x02lSNzkkQv+n3AX3kCXKSFA==
dependencies:
- "@emotion/hash" "^0.8.0"
- "@emotion/memoize" "^0.7.4"
- "@emotion/unitless" "^0.7.5"
- "@emotion/utils" "^1.0.0"
+ "@emotion/hash" "^0.9.0"
+ "@emotion/memoize" "^0.8.0"
+ "@emotion/unitless" "^0.8.0"
+ "@emotion/utils" "^1.2.0"
csstype "^3.0.2"
-"@emotion/sheet@^1.1.0", "@emotion/sheet@^1.1.1":
- version "1.1.1"
- resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-1.1.1.tgz#015756e2a9a3c7c5f11d8ec22966a8dbfbfac787"
- integrity sha512-J3YPccVRMiTZxYAY0IOq3kd+hUP8idY8Kz6B/Cyo+JuXq52Ek+zbPbSQUrVQp95aJ+lsAW7DPL1P2Z+U1jGkKA==
+"@emotion/sheet@^1.2.0":
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-1.2.0.tgz#771b1987855839e214fc1741bde43089397f7be5"
+ integrity sha512-OiTkRgpxescko+M51tZsMq7Puu/KP55wMT8BgpcXVG2hqXc0Vo0mfymJ/Uj24Hp0i083ji/o0aLddh08UEjq8w==
-"@emotion/unitless@^0.7.5":
- version "0.7.5"
- resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.7.5.tgz#77211291c1900a700b8a78cfafda3160d76949ed"
- integrity sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==
+"@emotion/unitless@^0.8.0":
+ version "0.8.0"
+ resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.8.0.tgz#a4a36e9cbdc6903737cd20d38033241e1b8833db"
+ integrity sha512-VINS5vEYAscRl2ZUDiT3uMPlrFQupiKgHz5AA4bCH1miKBg4qtwkim1qPmJj/4WG6TreYMY111rEFsjupcOKHw==
-"@emotion/utils@1.0.0":
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.0.0.tgz#abe06a83160b10570816c913990245813a2fd6af"
- integrity sha512-mQC2b3XLDs6QCW+pDQDiyO/EdGZYOygE8s5N5rrzjSI4M3IejPE/JPndCBwRT9z982aqQNi6beWs1UeayrQxxA==
+"@emotion/utils@^1.2.0":
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.2.0.tgz#9716eaccbc6b5ded2ea5a90d65562609aab0f561"
+ integrity sha512-sn3WH53Kzpw8oQ5mgMmIzzyAaH2ZqFEbozVVBSYp538E06OSE6ytOp7pRAjNQR+Q/orwqdQYJSe2m3hCOeznkw==
-"@emotion/utils@^1.0.0":
- version "1.1.0"
- resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.1.0.tgz#86b0b297f3f1a0f2bdb08eeac9a2f49afd40d0cf"
- integrity sha512-iRLa/Y4Rs5H/f2nimczYmS5kFJEbpiVvgN3XVfZ022IYhuNA1IRSHEizcof88LtCTXtl9S2Cxt32KgaXEu72JQ==
+"@emotion/weak-memoize@^0.3.0":
+ version "0.3.0"
+ resolved "https://registry.yarnpkg.com/@emotion/weak-memoize/-/weak-memoize-0.3.0.tgz#ea89004119dc42db2e1dba0f97d553f7372f6fcb"
+ integrity sha512-AHPmaAx+RYfZz0eYu6Gviiagpmiyw98ySSlQvCUhVGDRtDFe4DBS0x1bSjdF3gqUDYOczB+yYvBTtEylYSdRhg==
-"@emotion/weak-memoize@^0.2.5":
- version "0.2.5"
- resolved "https://registry.yarnpkg.com/@emotion/weak-memoize/-/weak-memoize-0.2.5.tgz#8eed982e2ee6f7f4e44c253e12962980791efd46"
- integrity sha512-6U71C2Wp7r5XtFtQzYrW5iKFT67OixrSxjI4MptCHzdSVlgabczzqLe0ZSgnub/5Kp4hSbpDB1tMytZY9pwxxA==
+"@esbuild/linux-loong64@0.14.54":
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz#de2a4be678bd4d0d1ffbb86e6de779cde5999028"
+ integrity sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==
"@eslint/eslintrc@^1.3.0":
version "1.3.0"
@@ -348,20 +464,328 @@
minimatch "^3.1.2"
strip-json-comments "^3.1.1"
-"@humanwhocodes/config-array@^0.9.2":
- version "0.9.5"
- resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.9.5.tgz#2cbaf9a89460da24b5ca6531b8bbfc23e1df50c7"
- integrity sha512-ObyMyWxZiCu/yTisA7uzx81s40xR2fD5Cg/2Kq7G02ajkNubJf6BopgDTmDyc3U7sXpNKM8cYOw7s7Tyr+DnCw==
+"@floating-ui/core@^0.7.3":
+ version "0.7.3"
+ resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-0.7.3.tgz#d274116678ffae87f6b60e90f88cc4083eefab86"
+ integrity sha512-buc8BXHmG9l82+OQXOFU3Kr2XQx9ys01U/Q9HMIrZ300iLc8HLMgh7dcCqgYzAzf4BkoQvDcXf5Y+CuEZ5JBYg==
+
+"@floating-ui/dom@^0.5.3":
+ version "0.5.4"
+ resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-0.5.4.tgz#4eae73f78bcd4bd553ae2ade30e6f1f9c73fe3f1"
+ integrity sha512-419BMceRLq0RrmTSDxn8hf9R3VCJv2K9PUfugh5JyEFmdjzDo+e8U5EdR8nzKq8Yj1htzLm3b6eQEEam3/rrtg==
+ dependencies:
+ "@floating-ui/core" "^0.7.3"
+
+"@floating-ui/react-dom-interactions@0.6.6":
+ version "0.6.6"
+ resolved "https://registry.yarnpkg.com/@floating-ui/react-dom-interactions/-/react-dom-interactions-0.6.6.tgz#8542e8c4bcbee2cd0d512de676c6a493e0a2d168"
+ integrity sha512-qnao6UPjSZNHnXrF+u4/n92qVroQkx0Umlhy3Avk1oIebm/5ee6yvDm4xbHob0OjY7ya8WmUnV3rQlPwX3Atwg==
+ dependencies:
+ "@floating-ui/react-dom" "^0.7.2"
+ aria-hidden "^1.1.3"
+ use-isomorphic-layout-effect "^1.1.1"
+
+"@floating-ui/react-dom@^0.7.2":
+ version "0.7.2"
+ resolved "https://registry.yarnpkg.com/@floating-ui/react-dom/-/react-dom-0.7.2.tgz#0bf4ceccb777a140fc535c87eb5d6241c8e89864"
+ integrity sha512-1T0sJcpHgX/u4I1OzIEhlcrvkUN8ln39nz7fMoE/2HDHrPiMFoOGR7++GYyfUmIQHkkrTinaeQsO3XWubjSvGg==
+ dependencies:
+ "@floating-ui/dom" "^0.5.3"
+ use-isomorphic-layout-effect "^1.1.1"
+
+"@fortawesome/fontawesome-common-types@6.1.2":
+ version "6.1.2"
+ resolved "https://registry.yarnpkg.com/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.1.2.tgz#c1095b1bbabf19f37f9ff0719db38d92a410bcfe"
+ integrity sha512-wBaAPGz1Awxg05e0PBRkDRuTsy4B3dpBm+zreTTyd9TH4uUM27cAL4xWyWR0rLJCrRwzVsQ4hF3FvM6rqydKPA==
+
+"@fortawesome/fontawesome-svg-core@^6":
+ version "6.1.2"
+ resolved "https://registry.yarnpkg.com/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.1.2.tgz#11e2e8583a7dea75d734e4d0e53d91c63fae7511"
+ integrity sha512-853G/Htp0BOdXnPoeCPTjFrVwyrJHpe8MhjB/DYE9XjwhnNDfuBCd3aKc2YUYbEfHEcBws4UAA0kA9dymZKGjA==
+ dependencies:
+ "@fortawesome/fontawesome-common-types" "6.1.2"
+
+"@fortawesome/free-regular-svg-icons@^6":
+ version "6.1.2"
+ resolved "https://registry.yarnpkg.com/@fortawesome/free-regular-svg-icons/-/free-regular-svg-icons-6.1.2.tgz#9f04009098addcc11d0d185126f058ed042c3099"
+ integrity sha512-xR4hA+tAwsaTHGfb+25H1gVU/aJ0Rzu+xIUfnyrhaL13yNQ7TWiI2RvzniAaB+VGHDU2a+Pk96Ve+pkN3/+TTQ==
+ dependencies:
+ "@fortawesome/fontawesome-common-types" "6.1.2"
+
+"@fortawesome/free-solid-svg-icons@^6":
+ version "6.1.2"
+ resolved "https://registry.yarnpkg.com/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.1.2.tgz#491d668b8a6603698d0ce1ac620f66fd22b74c84"
+ integrity sha512-lTgZz+cMpzjkHmCwOG3E1ilUZrnINYdqMmrkv30EC3XbRsGlbIOL8H9LaNp5SV4g0pNJDfQ4EdTWWaMvdwyLiQ==
+ dependencies:
+ "@fortawesome/fontawesome-common-types" "6.1.2"
+
+"@fortawesome/react-fontawesome@^0":
+ version "0.2.0"
+ resolved "https://registry.yarnpkg.com/@fortawesome/react-fontawesome/-/react-fontawesome-0.2.0.tgz#d90dd8a9211830b4e3c08e94b63a0ba7291ddcf4"
+ integrity sha512-uHg75Rb/XORTtVt7OS9WoK8uM276Ufi7gCzshVWkUJbHhh3svsUUeqXerrM96Wm7fRiDzfKRwSoahhMIkGAYHw==
+ dependencies:
+ prop-types "^15.8.1"
+
+"@humanwhocodes/config-array@^0.10.4":
+ version "0.10.4"
+ resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.10.4.tgz#01e7366e57d2ad104feea63e72248f22015c520c"
+ integrity sha512-mXAIHxZT3Vcpg83opl1wGlVZ9xydbfZO3r5YfRSH6Gpp2J/PfdBP0wbDa2sO6/qRbcalpoevVyW6A/fI6LfeMw==
dependencies:
"@humanwhocodes/object-schema" "^1.2.1"
debug "^4.1.1"
minimatch "^3.0.4"
+"@humanwhocodes/gitignore-to-minimatch@^1.0.2":
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/@humanwhocodes/gitignore-to-minimatch/-/gitignore-to-minimatch-1.0.2.tgz#316b0a63b91c10e53f242efb4ace5c3b34e8728d"
+ integrity sha512-rSqmMJDdLFUsyxR6FMtD00nfQKKLFb1kv+qBbOVKqErvloEIJLo5bDTJTQNTYgeyp78JsA7u/NPi5jT1GR/MuA==
+
"@humanwhocodes/object-schema@^1.2.1":
version "1.2.1"
resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz#b520529ec21d8e5945a1851dfd1c32e94e39ff45"
integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==
+"@istanbuljs/load-nyc-config@^1.0.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced"
+ integrity sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==
+ dependencies:
+ camelcase "^5.3.1"
+ find-up "^4.1.0"
+ get-package-type "^0.1.0"
+ js-yaml "^3.13.1"
+ resolve-from "^5.0.0"
+
+"@istanbuljs/schema@^0.1.2":
+ version "0.1.3"
+ resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.3.tgz#e45e384e4b8ec16bce2fd903af78450f6bf7ec98"
+ integrity sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==
+
+"@jest/console@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/console/-/console-28.1.3.tgz#2030606ec03a18c31803b8a36382762e447655df"
+ integrity sha512-QPAkP5EwKdK/bxIr6C1I4Vs0rm2nHiANzj/Z5X2JQkrZo6IqvC4ldZ9K95tF0HdidhA8Bo6egxSzUFPYKcEXLw==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ jest-message-util "^28.1.3"
+ jest-util "^28.1.3"
+ slash "^3.0.0"
+
+"@jest/core@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/core/-/core-28.1.3.tgz#0ebf2bd39840f1233cd5f2d1e6fc8b71bd5a1ac7"
+ integrity sha512-CIKBrlaKOzA7YG19BEqCw3SLIsEwjZkeJzf5bdooVnW4bH5cktqe3JX+G2YV1aK5vP8N9na1IGWFzYaTp6k6NA==
+ dependencies:
+ "@jest/console" "^28.1.3"
+ "@jest/reporters" "^28.1.3"
+ "@jest/test-result" "^28.1.3"
+ "@jest/transform" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ ansi-escapes "^4.2.1"
+ chalk "^4.0.0"
+ ci-info "^3.2.0"
+ exit "^0.1.2"
+ graceful-fs "^4.2.9"
+ jest-changed-files "^28.1.3"
+ jest-config "^28.1.3"
+ jest-haste-map "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-regex-util "^28.0.2"
+ jest-resolve "^28.1.3"
+ jest-resolve-dependencies "^28.1.3"
+ jest-runner "^28.1.3"
+ jest-runtime "^28.1.3"
+ jest-snapshot "^28.1.3"
+ jest-util "^28.1.3"
+ jest-validate "^28.1.3"
+ jest-watcher "^28.1.3"
+ micromatch "^4.0.4"
+ pretty-format "^28.1.3"
+ rimraf "^3.0.0"
+ slash "^3.0.0"
+ strip-ansi "^6.0.0"
+
+"@jest/environment@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-28.1.3.tgz#abed43a6b040a4c24fdcb69eab1f97589b2d663e"
+ integrity sha512-1bf40cMFTEkKyEf585R9Iz1WayDjHoHqvts0XFYEqyKM3cFWDpeMoqKKTAF9LSYQModPUlh8FKptoM2YcMWAXA==
+ dependencies:
+ "@jest/fake-timers" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ jest-mock "^28.1.3"
+
+"@jest/expect-utils@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-28.1.3.tgz#58561ce5db7cd253a7edddbc051fb39dda50f525"
+ integrity sha512-wvbi9LUrHJLn3NlDW6wF2hvIMtd4JUl2QNVrjq+IBSHirgfrR3o9RnVtxzdEGO2n9JyIWwHnLfby5KzqBGg2YA==
+ dependencies:
+ jest-get-type "^28.0.2"
+
+"@jest/expect@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/expect/-/expect-28.1.3.tgz#9ac57e1d4491baca550f6bdbd232487177ad6a72"
+ integrity sha512-lzc8CpUbSoE4dqT0U+g1qODQjBRHPpCPXissXD4mS9+sWQdmmpeJ9zSH1rS1HEkrsMN0fb7nKrJ9giAR1d3wBw==
+ dependencies:
+ expect "^28.1.3"
+ jest-snapshot "^28.1.3"
+
+"@jest/fake-timers@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-28.1.3.tgz#230255b3ad0a3d4978f1d06f70685baea91c640e"
+ integrity sha512-D/wOkL2POHv52h+ok5Oj/1gOG9HSywdoPtFsRCUmlCILXNn5eIWmcnd3DIiWlJnpGvQtmajqBP95Ei0EimxfLw==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ "@sinonjs/fake-timers" "^9.1.2"
+ "@types/node" "*"
+ jest-message-util "^28.1.3"
+ jest-mock "^28.1.3"
+ jest-util "^28.1.3"
+
+"@jest/globals@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-28.1.3.tgz#a601d78ddc5fdef542728309894895b4a42dc333"
+ integrity sha512-XFU4P4phyryCXu1pbcqMO0GSQcYe1IsalYCDzRNyhetyeyxMcIxa11qPNDpVNLeretItNqEmYYQn1UYz/5x1NA==
+ dependencies:
+ "@jest/environment" "^28.1.3"
+ "@jest/expect" "^28.1.3"
+ "@jest/types" "^28.1.3"
+
+"@jest/reporters@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-28.1.3.tgz#9adf6d265edafc5fc4a434cfb31e2df5a67a369a"
+ integrity sha512-JuAy7wkxQZVNU/V6g9xKzCGC5LVXx9FDcABKsSXp5MiKPEE2144a/vXTEDoyzjUpZKfVwp08Wqg5A4WfTMAzjg==
+ dependencies:
+ "@bcoe/v8-coverage" "^0.2.3"
+ "@jest/console" "^28.1.3"
+ "@jest/test-result" "^28.1.3"
+ "@jest/transform" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@jridgewell/trace-mapping" "^0.3.13"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ collect-v8-coverage "^1.0.0"
+ exit "^0.1.2"
+ glob "^7.1.3"
+ graceful-fs "^4.2.9"
+ istanbul-lib-coverage "^3.0.0"
+ istanbul-lib-instrument "^5.1.0"
+ istanbul-lib-report "^3.0.0"
+ istanbul-lib-source-maps "^4.0.0"
+ istanbul-reports "^3.1.3"
+ jest-message-util "^28.1.3"
+ jest-util "^28.1.3"
+ jest-worker "^28.1.3"
+ slash "^3.0.0"
+ string-length "^4.0.1"
+ strip-ansi "^6.0.0"
+ terminal-link "^2.0.0"
+ v8-to-istanbul "^9.0.1"
+
+"@jest/schemas@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-28.1.3.tgz#ad8b86a66f11f33619e3d7e1dcddd7f2d40ff905"
+ integrity sha512-/l/VWsdt/aBXgjshLWOFyFt3IVdYypu5y2Wn2rOO1un6nkqIn8SLXzgIMYXFyYsRWDyF5EthmKJMIdJvk08grg==
+ dependencies:
+ "@sinclair/typebox" "^0.24.1"
+
+"@jest/source-map@^28.1.2":
+ version "28.1.2"
+ resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-28.1.2.tgz#7fe832b172b497d6663cdff6c13b0a920e139e24"
+ integrity sha512-cV8Lx3BeStJb8ipPHnqVw/IM2VCMWO3crWZzYodSIkxXnRcXJipCdx1JCK0K5MsJJouZQTH73mzf4vgxRaH9ww==
+ dependencies:
+ "@jridgewell/trace-mapping" "^0.3.13"
+ callsites "^3.0.0"
+ graceful-fs "^4.2.9"
+
+"@jest/test-result@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-28.1.3.tgz#5eae945fd9f4b8fcfce74d239e6f725b6bf076c5"
+ integrity sha512-kZAkxnSE+FqE8YjW8gNuoVkkC9I7S1qmenl8sGcDOLropASP+BkcGKwhXoyqQuGOGeYY0y/ixjrd/iERpEXHNg==
+ dependencies:
+ "@jest/console" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/istanbul-lib-coverage" "^2.0.0"
+ collect-v8-coverage "^1.0.0"
+
+"@jest/test-sequencer@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-28.1.3.tgz#9d0c283d906ac599c74bde464bc0d7e6a82886c3"
+ integrity sha512-NIMPEqqa59MWnDi1kvXXpYbqsfQmSJsIbnd85mdVGkiDfQ9WQQTXOLsvISUfonmnBT+w85WEgneCigEEdHDFxw==
+ dependencies:
+ "@jest/test-result" "^28.1.3"
+ graceful-fs "^4.2.9"
+ jest-haste-map "^28.1.3"
+ slash "^3.0.0"
+
+"@jest/transform@^26.6.2":
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-26.6.2.tgz#5ac57c5fa1ad17b2aae83e73e45813894dcf2e4b"
+ integrity sha512-E9JjhUgNzvuQ+vVAL21vlyfy12gP0GhazGgJC4h6qUt1jSdUXGWJ1wfu/X7Sd8etSgxV4ovT1pb9v5D6QW4XgA==
+ dependencies:
+ "@babel/core" "^7.1.0"
+ "@jest/types" "^26.6.2"
+ babel-plugin-istanbul "^6.0.0"
+ chalk "^4.0.0"
+ convert-source-map "^1.4.0"
+ fast-json-stable-stringify "^2.0.0"
+ graceful-fs "^4.2.4"
+ jest-haste-map "^26.6.2"
+ jest-regex-util "^26.0.0"
+ jest-util "^26.6.2"
+ micromatch "^4.0.2"
+ pirates "^4.0.1"
+ slash "^3.0.0"
+ source-map "^0.6.1"
+ write-file-atomic "^3.0.0"
+
+"@jest/transform@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-28.1.3.tgz#59d8098e50ab07950e0f2fc0fc7ec462371281b0"
+ integrity sha512-u5dT5di+oFI6hfcLOHGTAfmUxFRrjK+vnaP0kkVow9Md/M7V/MxqQMOz/VV25UZO8pzeA9PjfTpOu6BDuwSPQA==
+ dependencies:
+ "@babel/core" "^7.11.6"
+ "@jest/types" "^28.1.3"
+ "@jridgewell/trace-mapping" "^0.3.13"
+ babel-plugin-istanbul "^6.1.1"
+ chalk "^4.0.0"
+ convert-source-map "^1.4.0"
+ fast-json-stable-stringify "^2.0.0"
+ graceful-fs "^4.2.9"
+ jest-haste-map "^28.1.3"
+ jest-regex-util "^28.0.2"
+ jest-util "^28.1.3"
+ micromatch "^4.0.4"
+ pirates "^4.0.4"
+ slash "^3.0.0"
+ write-file-atomic "^4.0.1"
+
+"@jest/types@^26.6.2":
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/@jest/types/-/types-26.6.2.tgz#bef5a532030e1d88a2f5a6d933f84e97226ed48e"
+ integrity sha512-fC6QCp7Sc5sX6g8Tvbmj4XUTbyrik0akgRy03yjXbQaBWWNWGE7SGtJk98m0N8nzegD/7SggrUlivxo5ax4KWQ==
+ dependencies:
+ "@types/istanbul-lib-coverage" "^2.0.0"
+ "@types/istanbul-reports" "^3.0.0"
+ "@types/node" "*"
+ "@types/yargs" "^15.0.0"
+ chalk "^4.0.0"
+
+"@jest/types@^28.1.3":
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/@jest/types/-/types-28.1.3.tgz#b05de80996ff12512bc5ceb1d208285a7d11748b"
+ integrity sha512-RyjiyMUZrKz/c+zlMFO1pm70DcIlST8AeWTkoUdZevew44wcNZQHsEVOiCVtgVnlFFD82FPaXycys58cf2muVQ==
+ dependencies:
+ "@jest/schemas" "^28.1.3"
+ "@types/istanbul-lib-coverage" "^2.0.0"
+ "@types/istanbul-reports" "^3.0.0"
+ "@types/node" "*"
+ "@types/yargs" "^17.0.8"
+ chalk "^4.0.0"
+
"@jridgewell/gen-mapping@^0.1.0":
version "0.1.1"
resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz#e5d2e450306a9491e3bd77e323e38d7aff315996"
@@ -370,170 +794,185 @@
"@jridgewell/set-array" "^1.0.0"
"@jridgewell/sourcemap-codec" "^1.4.10"
-"@jridgewell/gen-mapping@^0.3.0":
- version "0.3.1"
- resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.1.tgz#cf92a983c83466b8c0ce9124fadeaf09f7c66ea9"
- integrity sha512-GcHwniMlA2z+WFPWuY8lp3fsza0I8xPFMWL5+n8LYyP6PSvPrXf4+n8stDHZY2DM0zy9sVkRDy1jDI4XGzYVqg==
+"@jridgewell/gen-mapping@^0.3.2":
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9"
+ integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==
dependencies:
- "@jridgewell/set-array" "^1.0.0"
+ "@jridgewell/set-array" "^1.0.1"
"@jridgewell/sourcemap-codec" "^1.4.10"
"@jridgewell/trace-mapping" "^0.3.9"
"@jridgewell/resolve-uri@^3.0.3":
- version "3.0.7"
- resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.7.tgz#30cd49820a962aff48c8fffc5cd760151fca61fe"
- integrity sha512-8cXDaBBHOr2pQ7j77Y6Vp5VDT2sIqWyWQ56TjEq4ih/a4iST3dItRe8Q9fp0rrIl9DoKhWQtUQz/YpOxLkXbNA==
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78"
+ integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==
-"@jridgewell/set-array@^1.0.0":
- version "1.1.1"
- resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.1.tgz#36a6acc93987adcf0ba50c66908bd0b70de8afea"
- integrity sha512-Ct5MqZkLGEXTVmQYbGtx9SVqD2fqwvdubdps5D3djjAkgkKwT918VNOz65pEHFaYTeWcukmJmH5SwsA9Tn2ObQ==
+"@jridgewell/set-array@^1.0.0", "@jridgewell/set-array@^1.0.1":
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72"
+ integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==
"@jridgewell/sourcemap-codec@^1.4.10":
- version "1.4.13"
- resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.13.tgz#b6461fb0c2964356c469e115f504c95ad97ab88c"
- integrity sha512-GryiOJmNcWbovBxTfZSF71V/mXbgcV3MewDe3kIMCLyIh5e7SKAeUZs+rMnJ8jkMolZ/4/VsdBmMrw3l+VdZ3w==
+ version "1.4.14"
+ resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24"
+ integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==
-"@jridgewell/trace-mapping@^0.3.9":
- version "0.3.13"
- resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.13.tgz#dcfe3e95f224c8fe97a87a5235defec999aa92ea"
- integrity sha512-o1xbKhp9qnIAoHJSWd6KlCZfqslL4valSF81H8ImioOAxluWYWOpWkpyktY2vnt4tbrX9XYaxovq6cgowaJp2w==
+"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.13", "@jridgewell/trace-mapping@^0.3.9":
+ version "0.3.15"
+ resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.15.tgz#aba35c48a38d3fd84b37e66c9c0423f9744f9774"
+ integrity sha512-oWZNOULl+UbhsgB51uuZzglikfIKSUBO/M9W2OfEjn7cmqoAiCgmv9lyACTUacZwBz0ITnJ2NqjU8Tx0DHL88g==
dependencies:
"@jridgewell/resolve-uri" "^3.0.3"
"@jridgewell/sourcemap-codec" "^1.4.10"
-"@mantine/core@^4":
- version "4.2.10"
- resolved "https://registry.yarnpkg.com/@mantine/core/-/core-4.2.10.tgz#6b4973bc5c79cd077341ab2bbe327749ca3ed8c4"
- integrity sha512-UCPhDcumygfBvik64VkMnBvqy0ZN9q+1AQ0fPdK8aAUvjRBWSyH0dJPL55vsK1ODboKktSEsyjHtb09DroL7fA==
+"@mantine/core@^5":
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/@mantine/core/-/core-5.1.6.tgz#98c984bf08ceeb8684a8dc7146034c85e35de9f7"
+ integrity sha512-ZG/ccTc+LcxcUahxMu4m3hOkAss8LetETFbZ5zsDotJTvij2lzMzNcuPebLeyxNt714VEWIXNzIUotNtGXDSGg==
dependencies:
- "@mantine/styles" "4.2.10"
- "@popperjs/core" "^2.9.3"
- "@radix-ui/react-scroll-area" "^0.1.1"
- react-popper "^2.2.5"
- react-textarea-autosize "^8.3.2"
+ "@floating-ui/react-dom-interactions" "0.6.6"
+ "@mantine/styles" "5.1.6"
+ "@mantine/utils" "5.1.6"
+ "@radix-ui/react-scroll-area" "1.0.0"
+ react-textarea-autosize "8.3.4"
-"@mantine/hooks@^4":
- version "4.2.10"
- resolved "https://registry.yarnpkg.com/@mantine/hooks/-/hooks-4.2.10.tgz#ad55d5ad3c5814eab924dfb6fd04f9ffd44e3d30"
- integrity sha512-gVYWeE4Ieu6FBwh9h/3FjcrrNzKx1k6Yw07/LSngJP0uT3fLt1gvY2p4PtPpOh7z2/RpTXBR1x+dOgEUKomYUQ==
+"@mantine/hooks@^5":
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/@mantine/hooks/-/hooks-5.1.6.tgz#07d4850d3444526268a749c965ce64eea8cb7583"
+ integrity sha512-wD+Cx9W00YQchudIvkiEy52e/UCB0EhTkJs2fr2JbTlfKCWfWSilE/CPbLz6NWmK58bbyB/qjdKUDwXV6qyasw==
-"@mantine/styles@4.2.10":
- version "4.2.10"
- resolved "https://registry.yarnpkg.com/@mantine/styles/-/styles-4.2.10.tgz#967f0b09f4b3adaa23e650f9112be362ed07e953"
- integrity sha512-dWwCzBLYE8CwPJSPlV3MyIuR4ET3u6O+T+VmxY0lab6w/bqflseNSh9UBIW2AUoIYtxPVDjbZfzeTw32aV8CxA==
- dependencies:
- "@emotion/cache" "11.7.1"
- "@emotion/react" "11.7.1"
- "@emotion/serialize" "1.0.2"
- "@emotion/utils" "1.0.0"
- clsx "^1.1.1"
+"@mantine/notifications@^5":
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/@mantine/notifications/-/notifications-5.1.6.tgz#6311c928e821fdee6963048a698fce465482a589"
+ integrity sha512-JT0nLOoNO/NDuB2Xn4kVOSo+4Y4F+ogrWLN7qHgpmZlRsxc/8S1DFwgubTMwvJR38AHrOVaqp1hFsqdHDww0Ow==
+ dependencies:
+ "@mantine/utils" "5.1.6"
+ react-transition-group "4.4.2"
+
+"@mantine/styles@5.1.6":
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/@mantine/styles/-/styles-5.1.6.tgz#cfb4a33d4c38ffb499d51cd0af35abd436ebe831"
+ integrity sha512-7d112DIHauP+X0JaVh0uzlpVndWqw/muaz77C5hLlA8yP7gVuRWOhEqJDuTnZzNtj/utIJJDAyVM2+DHFqtQtg==
+ dependencies:
+ clsx "1.1.1"
csstype "3.0.9"
-"@popperjs/core@^2.9.3":
- version "2.11.5"
- resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
- integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
+"@mantine/utils@5.1.6":
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/@mantine/utils/-/utils-5.1.6.tgz#992cd1e8850467533aa88dc5fd933650674abf5e"
+ integrity sha512-y7va2keQ+TPwn2j668r889NhQWO0OhSvaxT5P8n2iBaTyPg+Xp5Jm2IE5UjI+OrZErrgmQq1sxbfg6v5vdK+0A==
-"@radix-ui/number@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/number/-/number-0.1.0.tgz#73ad13d5cc5f75fa5e147d72e5d5d5e50d688256"
- integrity sha512-rpf6QiOWLHAkM4FEMYu9i+5Jr8cKT893+R4mPpcdsy4LD7omr9JfdOqj/h/xPA5+EcVrpMMlU6rrRYpUB5UI8g==
+"@nodelib/fs.scandir@2.1.5":
+ version "2.1.5"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5"
+ integrity sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==
dependencies:
- "@babel/runtime" "^7.13.10"
+ "@nodelib/fs.stat" "2.0.5"
+ run-parallel "^1.1.9"
-"@radix-ui/primitive@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/primitive/-/primitive-0.1.0.tgz#6206b97d379994f0d1929809db035733b337e543"
- integrity sha512-tqxZKybwN5Fa3VzZry4G6mXAAb9aAqKmPtnVbZpL0vsBwvOHTBwsjHVPXylocYLwEtBY9SCe665bYnNB515uoA==
+"@nodelib/fs.stat@2.0.5", "@nodelib/fs.stat@^2.0.2":
+ version "2.0.5"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b"
+ integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==
+
+"@nodelib/fs.walk@^1.2.3":
+ version "1.2.8"
+ resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a"
+ integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==
dependencies:
- "@babel/runtime" "^7.13.10"
+ "@nodelib/fs.scandir" "2.1.5"
+ fastq "^1.6.0"
-"@radix-ui/react-compose-refs@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-compose-refs/-/react-compose-refs-0.1.0.tgz#cff6e780a0f73778b976acff2c2a5b6551caab95"
- integrity sha512-eyclbh+b77k+69Dk72q3694OHrn9B3QsoIRx7ywX341U9RK1ThgQjMFZoPtmZNQTksXHLNEiefR8hGVeFyInGg==
+"@radix-ui/number@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/number/-/number-1.0.0.tgz#4c536161d0de750b3f5d55860fc3de46264f897b"
+ integrity sha512-Ofwh/1HX69ZfJRiRBMTy7rgjAzHmwe4kW9C9Y99HTRUcYLUuVT0KESFj15rPjRgKJs20GPq8Bm5aEDJ8DuA3vA==
dependencies:
"@babel/runtime" "^7.13.10"
-"@radix-ui/react-context@0.1.1":
- version "0.1.1"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-context/-/react-context-0.1.1.tgz#06996829ea124d9a1bc1dbe3e51f33588fab0875"
- integrity sha512-PkyVX1JsLBioeu0jB9WvRpDBBLtLZohVDT3BB5CTSJqActma8S8030P57mWZb4baZifMvN7KKWPAA40UmWKkQg==
+"@radix-ui/primitive@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/primitive/-/primitive-1.0.0.tgz#e1d8ef30b10ea10e69c76e896f608d9276352253"
+ integrity sha512-3e7rn8FDMin4CgeL7Z/49smCA3rFYY3Ha2rUQ7HRWFadS5iCRw08ZgVT1LaNTCNqgvrUiyczLflrVrF0SRQtNA==
dependencies:
"@babel/runtime" "^7.13.10"
-"@radix-ui/react-presence@0.1.2":
- version "0.1.2"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-presence/-/react-presence-0.1.2.tgz#9f11cce3df73cf65bc348e8b76d891f0d54c1fe3"
- integrity sha512-3BRlFZraooIUfRlyN+b/Xs5hq1lanOOo/+3h6Pwu2GMFjkGKKa4Rd51fcqGqnVlbr3jYg+WLuGyAV4KlgqwrQw==
+"@radix-ui/react-compose-refs@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-compose-refs/-/react-compose-refs-1.0.0.tgz#37595b1f16ec7f228d698590e78eeed18ff218ae"
+ integrity sha512-0KaSv6sx787/hK3eF53iOkiSLwAGlFMx5lotrqD2pTjB18KbybKoEIgkNZTKC60YECDQTKGTRcDBILwZVqVKvA==
dependencies:
"@babel/runtime" "^7.13.10"
- "@radix-ui/react-compose-refs" "0.1.0"
- "@radix-ui/react-use-layout-effect" "0.1.0"
-"@radix-ui/react-primitive@0.1.4":
- version "0.1.4"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-primitive/-/react-primitive-0.1.4.tgz#6c233cf08b0cb87fecd107e9efecb3f21861edc1"
- integrity sha512-6gSl2IidySupIMJFjYnDIkIWRyQdbu/AHK7rbICPani+LW4b0XdxBXc46og/iZvuwW8pjCS8I2SadIerv84xYA==
+"@radix-ui/react-context@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-context/-/react-context-1.0.0.tgz#f38e30c5859a9fb5e9aa9a9da452ee3ed9e0aee0"
+ integrity sha512-1pVM9RfOQ+n/N5PJK33kRSKsr1glNxomxONs5c49MliinBY6Yw2Q995qfBUUo0/Mbg05B/sGA0gkgPI7kmSHBg==
dependencies:
"@babel/runtime" "^7.13.10"
- "@radix-ui/react-slot" "0.1.2"
-"@radix-ui/react-scroll-area@^0.1.1":
- version "0.1.4"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-scroll-area/-/react-scroll-area-0.1.4.tgz#be1d32c113ee9f64e3d2e7ee3983d98f00b42038"
- integrity sha512-QHxRsjy+hsHwQYJ9cCNgSJ5+6ioZu1KhwD1UOXoHNciuFGMX08v+uJPKXIz+ySv03Rx6cOz6f/Fk5aPHRMFi/A==
+"@radix-ui/react-direction@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-direction/-/react-direction-1.0.0.tgz#a2e0b552352459ecf96342c79949dd833c1e6e45"
+ integrity sha512-2HV05lGUgYcA6xgLQ4BKPDmtL+QbIZYH5fCOTAOOcJ5O0QbWS3i9lKaurLzliYUDhORI2Qr3pyjhJh44lKA3rQ==
dependencies:
"@babel/runtime" "^7.13.10"
- "@radix-ui/number" "0.1.0"
- "@radix-ui/primitive" "0.1.0"
- "@radix-ui/react-compose-refs" "0.1.0"
- "@radix-ui/react-context" "0.1.1"
- "@radix-ui/react-presence" "0.1.2"
- "@radix-ui/react-primitive" "0.1.4"
- "@radix-ui/react-use-callback-ref" "0.1.0"
- "@radix-ui/react-use-direction" "0.1.0"
- "@radix-ui/react-use-layout-effect" "0.1.0"
-
-"@radix-ui/react-slot@0.1.2":
- version "0.1.2"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-slot/-/react-slot-0.1.2.tgz#e6f7ad9caa8ce81cc8d532c854c56f9b8b6307c8"
- integrity sha512-ADkqfL+agEzEguU3yS26jfB50hRrwf7U4VTwAOZEmi/g+ITcBWe12yM46ueS/UCIMI9Py+gFUaAdxgxafFvY2Q==
+
+"@radix-ui/react-presence@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-presence/-/react-presence-1.0.0.tgz#814fe46df11f9a468808a6010e3f3ca7e0b2e84a"
+ integrity sha512-A+6XEvN01NfVWiKu38ybawfHsBjWum42MRPnEuqPsBZ4eV7e/7K321B5VgYMPv3Xx5An6o1/l9ZuDBgmcmWK3w==
dependencies:
"@babel/runtime" "^7.13.10"
- "@radix-ui/react-compose-refs" "0.1.0"
+ "@radix-ui/react-compose-refs" "1.0.0"
+ "@radix-ui/react-use-layout-effect" "1.0.0"
-"@radix-ui/react-use-callback-ref@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-0.1.0.tgz#934b6e123330f5b3a6b116460e6662cbc663493f"
- integrity sha512-Va041McOFFl+aV+sejvl0BS2aeHx86ND9X/rVFmEFQKTXCp6xgUK0NGUAGcgBlIjnJSbMYPGEk1xKSSlVcN2Aw==
+"@radix-ui/react-primitive@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-primitive/-/react-primitive-1.0.0.tgz#376cd72b0fcd5e0e04d252ed33eb1b1f025af2b0"
+ integrity sha512-EyXe6mnRlHZ8b6f4ilTDrXmkLShICIuOTTj0GX4w1rp+wSxf3+TD05u1UOITC8VsJ2a9nwHvdXtOXEOl0Cw/zQ==
dependencies:
"@babel/runtime" "^7.13.10"
+ "@radix-ui/react-slot" "1.0.0"
-"@radix-ui/react-use-direction@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-use-direction/-/react-use-direction-0.1.0.tgz#97ac1d52e497c974389e7988f809238ed72e7df7"
- integrity sha512-NajpY/An9TCPSfOVkgWIdXJV+VuWl67PxB6kOKYmtNAFHvObzIoh8o0n9sAuwSAyFCZVq211FEf9gvVDRhOyiA==
+"@radix-ui/react-scroll-area@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-scroll-area/-/react-scroll-area-1.0.0.tgz#10d0262a52266af528798f36947145f7e3a3a52c"
+ integrity sha512-3SNFukAjS5remgtpAVR9m3Zgo23ZojBZ8V3TCyR3A+56x2mtVqKlPV4+e8rScZUFMuvtbjIdQCmsJBFBazKZig==
dependencies:
"@babel/runtime" "^7.13.10"
+ "@radix-ui/number" "1.0.0"
+ "@radix-ui/primitive" "1.0.0"
+ "@radix-ui/react-compose-refs" "1.0.0"
+ "@radix-ui/react-context" "1.0.0"
+ "@radix-ui/react-direction" "1.0.0"
+ "@radix-ui/react-presence" "1.0.0"
+ "@radix-ui/react-primitive" "1.0.0"
+ "@radix-ui/react-use-callback-ref" "1.0.0"
+ "@radix-ui/react-use-layout-effect" "1.0.0"
+
+"@radix-ui/react-slot@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-slot/-/react-slot-1.0.0.tgz#7fa805b99891dea1e862d8f8fbe07f4d6d0fd698"
+ integrity sha512-3mrKauI/tWXo1Ll+gN5dHcxDPdm/Df1ufcDLCecn+pnCIVcdWE7CujXo8QaXOWRJyZyQWWbpB8eFwHzWXlv5mQ==
+ dependencies:
+ "@babel/runtime" "^7.13.10"
+ "@radix-ui/react-compose-refs" "1.0.0"
-"@radix-ui/react-use-layout-effect@0.1.0":
- version "0.1.0"
- resolved "https://registry.yarnpkg.com/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-0.1.0.tgz#ebf71bd6d2825de8f1fbb984abf2293823f0f223"
- integrity sha512-+wdeS51Y+E1q1Wmd+1xSSbesZkpVj4jsg0BojCbopWvgq5iBvixw5vgemscdh58ep98BwUbsFYnrywFhV9yrVg==
+"@radix-ui/react-use-callback-ref@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.0.0.tgz#9e7b8b6b4946fe3cbe8f748c82a2cce54e7b6a90"
+ integrity sha512-GZtyzoHz95Rhs6S63D2t/eqvdFCm7I+yHMLVQheKM7nBD8mbZIt+ct1jz4536MDnaOGKIxynJ8eHTkVGVVkoTg==
dependencies:
"@babel/runtime" "^7.13.10"
-"@reach/router@^1":
- version "1.3.4"
- resolved "https://registry.yarnpkg.com/@reach/router/-/router-1.3.4.tgz#d2574b19370a70c80480ed91f3da840136d10f8c"
- integrity sha512-+mtn9wjlB9NN2CNnnC/BRYtwdKBfSyyasPYraNAyvaV1occr/5NnB4CVzjEZipNHwYebQwcndGUmpFzxAUoqSA==
+"@radix-ui/react-use-layout-effect@1.0.0":
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.0.0.tgz#2fc19e97223a81de64cd3ba1dc42ceffd82374dc"
+ integrity sha512-6Tpkq+R6LOlmQb1R5NNETLG0B4YP0wc+klfXafpUCj6JGyaUc8il7/kUZ7m59rGbXGczE9Bs+iz2qloqsZBduQ==
dependencies:
- create-react-context "0.3.0"
- invariant "^2.2.3"
- prop-types "^15.6.1"
- react-lifecycles-compat "^3.0.4"
+ "@babel/runtime" "^7.13.10"
"@rollup/pluginutils@^4.2.1":
version "4.2.1"
@@ -543,6 +982,84 @@
estree-walker "^2.0.1"
picomatch "^2.2.2"
+"@sinclair/typebox@^0.24.1":
+ version "0.24.28"
+ resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.24.28.tgz#15aa0b416f82c268b1573ab653e4413c965fe794"
+ integrity sha512-dgJd3HLOkLmz4Bw50eZx/zJwtBq65nms3N9VBYu5LTjJ883oBFkTyXRlCB/ZGGwqYpJJHA5zW2Ibhl5ngITfow==
+
+"@sinonjs/commons@^1.7.0":
+ version "1.8.3"
+ resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d"
+ integrity sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==
+ dependencies:
+ type-detect "4.0.8"
+
+"@sinonjs/fake-timers@^9.1.2":
+ version "9.1.2"
+ resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-9.1.2.tgz#4eaab737fab77332ab132d396a3c0d364bd0ea8c"
+ integrity sha512-BPS4ynJW/o92PUR4wgriz2Ud5gpST5vz6GQfMixEDK0Z8ZCUv2M7SkBLykH56T++Xs+8ln9zTGbOvNGIe02/jw==
+ dependencies:
+ "@sinonjs/commons" "^1.7.0"
+
+"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.14", "@types/babel__core@^7.1.7":
+ version "7.1.19"
+ resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.19.tgz#7b497495b7d1b4812bdb9d02804d0576f43ee460"
+ integrity sha512-WEOTgRsbYkvA/KCsDwVEGkd7WAr1e3g31VHQ8zy5gul/V1qKullU/BU5I68X5v7V3GnB9eotmom4v5a5gjxorw==
+ dependencies:
+ "@babel/parser" "^7.1.0"
+ "@babel/types" "^7.0.0"
+ "@types/babel__generator" "*"
+ "@types/babel__template" "*"
+ "@types/babel__traverse" "*"
+
+"@types/babel__generator@*":
+ version "7.6.4"
+ resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.6.4.tgz#1f20ce4c5b1990b37900b63f050182d28c2439b7"
+ integrity sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==
+ dependencies:
+ "@babel/types" "^7.0.0"
+
+"@types/babel__template@*":
+ version "7.4.1"
+ resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.4.1.tgz#3d1a48fd9d6c0edfd56f2ff578daed48f36c8969"
+ integrity sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==
+ dependencies:
+ "@babel/parser" "^7.1.0"
+ "@babel/types" "^7.0.0"
+
+"@types/babel__traverse@*", "@types/babel__traverse@^7.0.6":
+ version "7.18.0"
+ resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.18.0.tgz#8134fd78cb39567465be65b9fdc16d378095f41f"
+ integrity sha512-v4Vwdko+pgymgS+A2UIaJru93zQd85vIGWObM5ekZNdXCKtDYqATlEYnWgfo86Q6I1Lh0oXnksDnMU1cwmlPDw==
+ dependencies:
+ "@babel/types" "^7.3.0"
+
+"@types/graceful-fs@^4.1.2", "@types/graceful-fs@^4.1.3":
+ version "4.1.5"
+ resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.5.tgz#21ffba0d98da4350db64891f92a9e5db3cdb4e15"
+ integrity sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==
+ dependencies:
+ "@types/node" "*"
+
+"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1":
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz#8467d4b3c087805d63580480890791277ce35c44"
+ integrity sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==
+
+"@types/istanbul-lib-report@*":
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#c14c24f18ea8190c118ee7562b7ff99a36552686"
+ integrity sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==
+ dependencies:
+ "@types/istanbul-lib-coverage" "*"
+
+"@types/istanbul-reports@^3.0.0":
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz#9153fe98bba2bd565a63add9436d6f0d7f8468ff"
+ integrity sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==
+ dependencies:
+ "@types/istanbul-lib-report" "*"
+
"@types/json5@^0.0.29":
version "0.0.29"
resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee"
@@ -553,31 +1070,37 @@
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.5.tgz#1001cc5e6a3704b83c236027e77f2f58ea010f40"
integrity sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==
+"@types/node@*":
+ version "18.7.3"
+ resolved "https://registry.yarnpkg.com/@types/node/-/node-18.7.3.tgz#432c89796eab539b7a30b7b8801a727b585238a4"
+ integrity sha512-LJgzOEwWuMTBxHzgBR/fhhBOWrvBjvO+zPteUgbbuQi80rYIZHrk1mNbRUqPZqSLP2H7Rwt1EFLL/tNLD1Xx/w==
+
+"@types/parse-json@^4.0.0":
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0"
+ integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==
+
+"@types/prettier@^2.1.5":
+ version "2.7.0"
+ resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.7.0.tgz#ea03e9f0376a4446f44797ca19d9c46c36e352dc"
+ integrity sha512-RI1L7N4JnW5gQw2spvL7Sllfuf1SaHdrZpCHiBlCXjIlufi1SMNnbu2teze3/QE67Fg2tBlH7W+mi4hVNk4p0A==
+
"@types/prop-types@*":
version "15.7.5"
resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.5.tgz#5f19d2b85a98e9558036f6a3cacc8819420f05cf"
integrity sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==
"@types/react-dom@^18":
- version "18.0.5"
- resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.0.5.tgz#330b2d472c22f796e5531446939eacef8378444a"
- integrity sha512-OWPWTUrY/NIrjsAPkAk1wW9LZeIjSvkXRhclsFO8CZcZGCOg2G0YZy4ft+rOyYxy8B7ui5iZzi9OkDebZ7/QSA==
+ version "18.0.6"
+ resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.0.6.tgz#36652900024842b74607a17786b6662dd1e103a1"
+ integrity sha512-/5OFZgfIPSwy+YuIBP/FgJnQnsxhZhjjrnxudMddeblOouIodEQ75X14Rr4wGSG/bknL+Omy9iWlLo1u/9GzAA==
dependencies:
"@types/react" "*"
-"@types/react@*":
- version "18.0.13"
- resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.13.tgz#0f5bd24a5f26593e04e450fe85ff43f51c1524ff"
- integrity sha512-psqptIYQxGUFuGYwP3KCFVtPTkMpIcrqFmtKblWEUQhLuYLpHBwJkXhjp6eHfDM5IbyskY4x7qQpLedEsPkHlA==
- dependencies:
- "@types/prop-types" "*"
- "@types/scheduler" "*"
- csstype "^3.0.2"
-
-"@types/react@^18":
- version "18.0.14"
- resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.14.tgz#e016616ffff51dba01b04945610fe3671fdbe06d"
- integrity sha512-x4gGuASSiWmo0xjDLpm5mPb52syZHJx02VKbqUKdLmKtAwIh63XClGsiTI1K6DO5q7ox4xAsQrU+Gl3+gGXF9Q==
+"@types/react@*", "@types/react@^18":
+ version "18.0.17"
+ resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.17.tgz#4583d9c322d67efe4b39a935d223edcc7050ccf4"
+ integrity sha512-38ETy4tL+rn4uQQi7mB81G7V1g0u2ryquNmsVIOKUAEIDK+3CUjZ6rSRpdvS99dNBnkLFL83qfmtLacGOTIhwQ==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
@@ -588,6 +1111,30 @@
resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.2.tgz#1a62f89525723dde24ba1b01b092bf5df8ad4d39"
integrity sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew==
+"@types/stack-utils@^2.0.0":
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.1.tgz#20f18294f797f2209b5f65c8e3b5c8e8261d127c"
+ integrity sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==
+
+"@types/yargs-parser@*":
+ version "21.0.0"
+ resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.0.tgz#0c60e537fa790f5f9472ed2776c2b71ec117351b"
+ integrity sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==
+
+"@types/yargs@^15.0.0":
+ version "15.0.14"
+ resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-15.0.14.tgz#26d821ddb89e70492160b66d10a0eb6df8f6fb06"
+ integrity sha512-yEJzHoxf6SyQGhBhIYGXQDSCkJjB6HohDShto7m8vaKg9Yp0Yn8+71J9eakh2bnPg6BfsH9PRMhiRTZnd4eXGQ==
+ dependencies:
+ "@types/yargs-parser" "*"
+
+"@types/yargs@^17.0.8":
+ version "17.0.11"
+ resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-17.0.11.tgz#5e10ca33e219807c0eee0f08b5efcba9b6a42c06"
+ integrity sha512-aB4y9UDUXTSMxmM4MH+YnuR0g5Cph3FLQBoWoMB21DSvFVAxRVEHEMx3TLh+zUZYMCQtKiqazz0Q4Rre31f/OA==
+ dependencies:
+ "@types/yargs-parser" "*"
+
"@vitejs/plugin-react@^1":
version "1.3.2"
resolved "https://registry.yarnpkg.com/@vitejs/plugin-react/-/plugin-react-1.3.2.tgz#2fcf0b6ce9bcdcd4cec5c760c199779d5657ece1"
@@ -607,10 +1154,10 @@ acorn-jsx@^5.3.2:
resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"
integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==
-acorn@^8.7.1:
- version "8.7.1"
- resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.7.1.tgz#0197122c843d1bf6d0a5e83220a788f278f63c30"
- integrity sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==
+acorn@^8.8.0:
+ version "8.8.0"
+ resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.0.tgz#88c0187620435c7f6015803f5539dae05a9dbea8"
+ integrity sha512-QOxyigPVrpZ2GXT+PFyZTl6TtOFc5egxHIP9IlQ+RbupQuX4RkT/Bee4/kQuC02Xkzg84JcT7oLYtDIQxp+v7w==
ajv@^6.10.0, ajv@^6.12.4:
version "6.12.6"
@@ -622,6 +1169,13 @@ ajv@^6.10.0, ajv@^6.12.4:
json-schema-traverse "^0.4.1"
uri-js "^4.2.2"
+ansi-escapes@^4.2.1:
+ version "4.3.2"
+ resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e"
+ integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==
+ dependencies:
+ type-fest "^0.21.3"
+
ansi-regex@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
@@ -634,18 +1188,68 @@ ansi-styles@^3.2.1:
dependencies:
color-convert "^1.9.0"
-ansi-styles@^4.1.0:
+ansi-styles@^4.0.0, ansi-styles@^4.1.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937"
integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
dependencies:
color-convert "^2.0.1"
+ansi-styles@^5.0.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b"
+ integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==
+
+anymatch@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb"
+ integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==
+ dependencies:
+ micromatch "^3.1.4"
+ normalize-path "^2.1.1"
+
+anymatch@^3.0.3:
+ version "3.1.2"
+ resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716"
+ integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==
+ dependencies:
+ normalize-path "^3.0.0"
+ picomatch "^2.0.4"
+
+argparse@^1.0.7:
+ version "1.0.10"
+ resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
+ integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==
+ dependencies:
+ sprintf-js "~1.0.2"
+
argparse@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38"
integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==
+aria-hidden@^1.1.3:
+ version "1.1.3"
+ resolved "https://registry.yarnpkg.com/aria-hidden/-/aria-hidden-1.1.3.tgz#bb48de18dc84787a3c6eee113709c473c64ec254"
+ integrity sha512-RhVWFtKH5BiGMycI72q2RAFMLQi8JP9bLuQXgR5a8Znp7P5KOIADSJeyfI8PCVxLEp067B2HbP5JIiI/PXIZeA==
+ dependencies:
+ tslib "^1.0.0"
+
+arr-diff@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520"
+ integrity sha512-YVIQ82gZPGBebQV/a8dar4AitzCQs0jjXwMPZllpXMaGjXPYVUawSxQrRsjhjupyVxEvbHgUmIhKVlND+j02kA==
+
+arr-flatten@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
+ integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==
+
+arr-union@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4"
+ integrity sha512-sKpyeERZ02v1FeCZT8lrfJq5u6goHCtpTAzPwJYe7c8SPFOboNjNg1vz2L4VTn9T4PQxEx13TbXLmYUcS6Ug7Q==
+
array-differ@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/array-differ/-/array-differ-3.0.0.tgz#3cbb3d0f316810eafcc47624734237d6aee4ae6b"
@@ -667,6 +1271,11 @@ array-union@^2.1.0:
resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d"
integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==
+array-unique@^0.3.2:
+ version "0.3.2"
+ resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428"
+ integrity sha512-SleRWjh9JUud2wH1hPs9rZBZ33H6T9HOiL0uwGnGx9FpE6wKGyfWugmbkEOIs6qWrZhg0LWeLziLrEwQJhs5mQ==
+
array.prototype.flat@^1.2.5:
version "1.3.0"
resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.3.0.tgz#0b0c1567bf57b38b56b4c97b8aa72ab45e4adc7b"
@@ -692,11 +1301,142 @@ arrify@^2.0.1:
resolved "https://registry.yarnpkg.com/arrify/-/arrify-2.0.1.tgz#c9655e9331e0abcd588d2a7cad7e9956f66701fa"
integrity sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==
+assign-symbols@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367"
+ integrity sha512-Q+JC7Whu8HhmTdBph/Tq59IoRtoy6KAm5zzPv00WdujX82lbAL8K7WVjne7vdCsAmbF4AYaDOPyO3k0kl8qIrw==
+
+atob@^2.1.2:
+ version "2.1.2"
+ resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9"
+ integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==
+
+babel-jest@^26.6.3:
+ version "26.6.3"
+ resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-26.6.3.tgz#d87d25cb0037577a0c89f82e5755c5d293c01056"
+ integrity sha512-pl4Q+GAVOHwvjrck6jKjvmGhnO3jHX/xuB9d27f+EJZ/6k+6nMuPjorrYp7s++bKKdANwzElBWnLWaObvTnaZA==
+ dependencies:
+ "@jest/transform" "^26.6.2"
+ "@jest/types" "^26.6.2"
+ "@types/babel__core" "^7.1.7"
+ babel-plugin-istanbul "^6.0.0"
+ babel-preset-jest "^26.6.2"
+ chalk "^4.0.0"
+ graceful-fs "^4.2.4"
+ slash "^3.0.0"
+
+babel-jest@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-28.1.3.tgz#c1187258197c099072156a0a121c11ee1e3917d5"
+ integrity sha512-epUaPOEWMk3cWX0M/sPvCHHCe9fMFAa/9hXEgKP8nFfNl/jlGkE9ucq9NqkZGXLDduCJYS0UvSlPUwC0S+rH6Q==
+ dependencies:
+ "@jest/transform" "^28.1.3"
+ "@types/babel__core" "^7.1.14"
+ babel-plugin-istanbul "^6.1.1"
+ babel-preset-jest "^28.1.3"
+ chalk "^4.0.0"
+ graceful-fs "^4.2.9"
+ slash "^3.0.0"
+
+babel-plugin-dynamic-import-node@^2.3.3:
+ version "2.3.3"
+ resolved "https://registry.yarnpkg.com/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.3.tgz#84fda19c976ec5c6defef57f9427b3def66e17a3"
+ integrity sha512-jZVI+s9Zg3IqA/kdi0i6UDCybUI3aSBLnglhYbSSjKlV7yF1F/5LWv8MakQmvYpnbJDS6fcBL2KzHSxNCMtWSQ==
+ dependencies:
+ object.assign "^4.1.0"
+
+babel-plugin-istanbul@^6.0.0, babel-plugin-istanbul@^6.1.1:
+ version "6.1.1"
+ resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz#fa88ec59232fd9b4e36dbbc540a8ec9a9b47da73"
+ integrity sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.0.0"
+ "@istanbuljs/load-nyc-config" "^1.0.0"
+ "@istanbuljs/schema" "^0.1.2"
+ istanbul-lib-instrument "^5.0.4"
+ test-exclude "^6.0.0"
+
+babel-plugin-jest-hoist@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-26.6.2.tgz#8185bd030348d254c6d7dd974355e6a28b21e62d"
+ integrity sha512-PO9t0697lNTmcEHH69mdtYiOIkkOlj9fySqfO3K1eCcdISevLAE0xY59VLLUj0SoiPiTX/JU2CYFpILydUa5Lw==
+ dependencies:
+ "@babel/template" "^7.3.3"
+ "@babel/types" "^7.3.3"
+ "@types/babel__core" "^7.0.0"
+ "@types/babel__traverse" "^7.0.6"
+
+babel-plugin-jest-hoist@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-28.1.3.tgz#1952c4d0ea50f2d6d794353762278d1d8cca3fbe"
+ integrity sha512-Ys3tUKAmfnkRUpPdpa98eYrAR0nV+sSFUZZEGuQ2EbFd1y4SOLtD5QDNHAq+bb9a+bbXvYQC4b+ID/THIMcU6Q==
+ dependencies:
+ "@babel/template" "^7.3.3"
+ "@babel/types" "^7.3.3"
+ "@types/babel__core" "^7.1.14"
+ "@types/babel__traverse" "^7.0.6"
+
+babel-plugin-macros@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz#9ef6dc74deb934b4db344dc973ee851d148c50c1"
+ integrity sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==
+ dependencies:
+ "@babel/runtime" "^7.12.5"
+ cosmiconfig "^7.0.0"
+ resolve "^1.19.0"
+
+babel-preset-current-node-syntax@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz#b4399239b89b2a011f9ddbe3e4f401fc40cff73b"
+ integrity sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==
+ dependencies:
+ "@babel/plugin-syntax-async-generators" "^7.8.4"
+ "@babel/plugin-syntax-bigint" "^7.8.3"
+ "@babel/plugin-syntax-class-properties" "^7.8.3"
+ "@babel/plugin-syntax-import-meta" "^7.8.3"
+ "@babel/plugin-syntax-json-strings" "^7.8.3"
+ "@babel/plugin-syntax-logical-assignment-operators" "^7.8.3"
+ "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3"
+ "@babel/plugin-syntax-numeric-separator" "^7.8.3"
+ "@babel/plugin-syntax-object-rest-spread" "^7.8.3"
+ "@babel/plugin-syntax-optional-catch-binding" "^7.8.3"
+ "@babel/plugin-syntax-optional-chaining" "^7.8.3"
+ "@babel/plugin-syntax-top-level-await" "^7.8.3"
+
+babel-preset-jest@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-26.6.2.tgz#747872b1171df032252426586881d62d31798fee"
+ integrity sha512-YvdtlVm9t3k777c5NPQIv6cxFFFapys25HiUmuSgHwIZhfifweR5c5Sf5nwE3MAbfu327CYSvps8Yx6ANLyleQ==
+ dependencies:
+ babel-plugin-jest-hoist "^26.6.2"
+ babel-preset-current-node-syntax "^1.0.0"
+
+babel-preset-jest@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-28.1.3.tgz#5dfc20b99abed5db994406c2b9ab94c73aaa419d"
+ integrity sha512-L+fupJvlWAHbQfn74coNX3zf60LXMJsezNvvx8eIh7iOR1luJ1poxYgQk1F8PYtNq/6QODDHCqsSnTFSWC491A==
+ dependencies:
+ babel-plugin-jest-hoist "^28.1.3"
+ babel-preset-current-node-syntax "^1.0.0"
+
balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
+base@^0.11.1:
+ version "0.11.2"
+ resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f"
+ integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==
+ dependencies:
+ cache-base "^1.0.1"
+ class-utils "^0.3.5"
+ component-emitter "^1.2.1"
+ define-property "^1.0.0"
+ isobject "^3.0.1"
+ mixin-deep "^1.2.0"
+ pascalcase "^0.1.1"
+
brace-expansion@^1.1.7:
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
@@ -705,16 +1445,65 @@ brace-expansion@^1.1.7:
balanced-match "^1.0.0"
concat-map "0.0.1"
+braces@^2.3.1:
+ version "2.3.2"
+ resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729"
+ integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==
+ dependencies:
+ arr-flatten "^1.1.0"
+ array-unique "^0.3.2"
+ extend-shallow "^2.0.1"
+ fill-range "^4.0.0"
+ isobject "^3.0.1"
+ repeat-element "^1.1.2"
+ snapdragon "^0.8.1"
+ snapdragon-node "^2.0.1"
+ split-string "^3.0.2"
+ to-regex "^3.0.1"
+
+braces@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107"
+ integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==
+ dependencies:
+ fill-range "^7.0.1"
+
browserslist@^4.20.2:
- version "4.20.4"
- resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.20.4.tgz#98096c9042af689ee1e0271333dbc564b8ce4477"
- integrity sha512-ok1d+1WpnU24XYN7oC3QWgTyMhY/avPJ/r9T00xxvUOIparA/gc+UPUMaod3i+G6s+nI2nUb9xZ5k794uIwShw==
+ version "4.21.3"
+ resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.3.tgz#5df277694eb3c48bc5c4b05af3e8b7e09c5a6d1a"
+ integrity sha512-898rgRXLAyRkM1GryrrBHGkqA5hlpkV5MhtZwg9QXeiyLUYs2k00Un05aX5l2/yJIOObYKOpS2JNo8nJDE7fWQ==
dependencies:
- caniuse-lite "^1.0.30001349"
- electron-to-chromium "^1.4.147"
- escalade "^3.1.1"
- node-releases "^2.0.5"
- picocolors "^1.0.0"
+ caniuse-lite "^1.0.30001370"
+ electron-to-chromium "^1.4.202"
+ node-releases "^2.0.6"
+ update-browserslist-db "^1.0.5"
+
+bser@2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05"
+ integrity sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==
+ dependencies:
+ node-int64 "^0.4.0"
+
+buffer-from@^1.0.0:
+ version "1.1.2"
+ resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"
+ integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==
+
+cache-base@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2"
+ integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==
+ dependencies:
+ collection-visit "^1.0.0"
+ component-emitter "^1.2.1"
+ get-value "^2.0.6"
+ has-value "^1.0.0"
+ isobject "^3.0.1"
+ set-value "^2.0.0"
+ to-object-path "^0.3.0"
+ union-value "^1.0.0"
+ unset-value "^1.0.0"
call-bind@^1.0.0, call-bind@^1.0.2:
version "1.0.2"
@@ -729,10 +1518,27 @@ callsites@^3.0.0:
resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73"
integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==
-caniuse-lite@^1.0.30001349:
- version "1.0.30001355"
- resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001355.tgz#e240b7177443ed0198c737a7f609536976701c77"
- integrity sha512-Sd6pjJHF27LzCB7pT7qs+kuX2ndurzCzkpJl6Qct7LPSZ9jn0bkOA8mdgMgmqnQAWLVOOGjLpc+66V57eLtb1g==
+camelcase@^5.3.1:
+ version "5.3.1"
+ resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320"
+ integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==
+
+camelcase@^6.2.0:
+ version "6.3.0"
+ resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a"
+ integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==
+
+caniuse-lite@^1.0.30001370:
+ version "1.0.30001375"
+ resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001375.tgz#8e73bc3d1a4c800beb39f3163bf0190d7e5d7672"
+ integrity sha512-kWIMkNzLYxSvnjy0hL8w1NOaWNr2rn39RTAVyIwcw8juu60bZDWiF1/loOYANzjtJmy6qPgNmn38ro5Pygagdw==
+
+capture-exit@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/capture-exit/-/capture-exit-2.0.0.tgz#fb953bfaebeb781f62898239dabb426d08a509a4"
+ integrity sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==
+ dependencies:
+ rsvp "^4.8.4"
chalk@^2.0.0:
version "2.4.2"
@@ -759,11 +1565,68 @@ chalk@^4.0.0:
ansi-styles "^4.1.0"
supports-color "^7.1.0"
-clsx@^1.1.1:
+char-regex@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf"
+ integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==
+
+ci-info@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"
+ integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==
+
+ci-info@^3.2.0:
+ version "3.3.2"
+ resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.3.2.tgz#6d2967ffa407466481c6c90b6e16b3098f080128"
+ integrity sha512-xmDt/QIAdeZ9+nfdPsaBCpMvHNLFiLdjj59qjqn+6iPe6YmHGQ35sBnQ8uslRBXFmXkiZQOJRjvQeoGppoTjjg==
+
+cjs-module-lexer@^1.0.0:
+ version "1.2.2"
+ resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz#9f84ba3244a512f3a54e5277e8eef4c489864e40"
+ integrity sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==
+
+class-utils@^0.3.5:
+ version "0.3.6"
+ resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463"
+ integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==
+ dependencies:
+ arr-union "^3.1.0"
+ define-property "^0.2.5"
+ isobject "^3.0.0"
+ static-extend "^0.1.1"
+
+cliui@^7.0.2:
+ version "7.0.4"
+ resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f"
+ integrity sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==
+ dependencies:
+ string-width "^4.2.0"
+ strip-ansi "^6.0.0"
+ wrap-ansi "^7.0.0"
+
+clsx@1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.1.1.tgz#98b3134f9abbdf23b2663491ace13c5c03a73188"
integrity sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA==
+co@^4.6.0:
+ version "4.6.0"
+ resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"
+ integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==
+
+collect-v8-coverage@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz#cc2c8e94fc18bbdffe64d6534570c8a673b27f59"
+ integrity sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==
+
+collection-visit@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0"
+ integrity sha512-lNkKvzEeMBBjUGHZ+q6z9pSJla0KWAQPvtzhEV9+iGyQYG+pBpl7xKDhxoNSOZH2hhv0v5k0y2yAM4o4SjoSkw==
+ dependencies:
+ map-visit "^1.0.0"
+ object-visit "^1.0.0"
+
color-convert@^1.9.0:
version "1.9.3"
resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
@@ -788,27 +1651,51 @@ color-name@~1.1.4:
resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
+component-emitter@^1.2.1:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0"
+ integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==
+
concat-map@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==
-convert-source-map@^1.7.0:
+convert-source-map@^1.4.0, convert-source-map@^1.5.0, convert-source-map@^1.6.0, convert-source-map@^1.7.0:
version "1.8.0"
resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.8.0.tgz#f3373c32d21b4d780dd8004514684fb791ca4369"
integrity sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==
dependencies:
safe-buffer "~5.1.1"
-create-react-context@0.3.0:
- version "0.3.0"
- resolved "https://registry.yarnpkg.com/create-react-context/-/create-react-context-0.3.0.tgz#546dede9dc422def0d3fc2fe03afe0bc0f4f7d8c"
- integrity sha512-dNldIoSuNSvlTJ7slIKC/ZFGKexBMBrrcc+TTe1NdmROnaASuLPvqpwj9v4XS4uXZ8+YPu0sNmShX2rXI5LNsw==
- dependencies:
- gud "^1.0.0"
- warning "^4.0.3"
+copy-descriptor@^0.1.0:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d"
+ integrity sha512-XgZ0pFcakEUlbwQEVNg3+QAis1FyTL3Qel9FYy8pSkQqoG3PNoT0bOCQtOXcOkur21r2Eq2kI+IE+gsmAEVlYw==
-cross-spawn@^7.0.0, cross-spawn@^7.0.2:
+cosmiconfig@^7.0.0:
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-7.0.1.tgz#714d756522cace867867ccb4474c5d01bbae5d6d"
+ integrity sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==
+ dependencies:
+ "@types/parse-json" "^4.0.0"
+ import-fresh "^3.2.1"
+ parse-json "^5.0.0"
+ path-type "^4.0.0"
+ yaml "^1.10.0"
+
+cross-spawn@^6.0.0:
+ version "6.0.5"
+ resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4"
+ integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==
+ dependencies:
+ nice-try "^1.0.4"
+ path-key "^2.0.1"
+ semver "^5.5.0"
+ shebang-command "^1.2.0"
+ which "^1.2.9"
+
+cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3:
version "7.0.3"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==
@@ -827,7 +1714,7 @@ csstype@^3.0.2:
resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.0.tgz#4ddcac3718d787cf9df0d1b7d15033925c8f29f2"
integrity sha512-uX1KG+x9h5hIJsaKR9xHUeUraxf8IODOwq9JLNPq6BwB04a/xgpq3rcx47l5BZu5zBPlgD342tdke3Hom/nJRA==
-debug@^2.6.9:
+debug@^2.2.0, debug@^2.3.3, debug@^2.6.9:
version "2.6.9"
resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==
@@ -848,11 +1735,26 @@ debug@^4.1.0, debug@^4.1.1, debug@^4.3.2:
dependencies:
ms "2.1.2"
+decode-uri-component@^0.2.0:
+ version "0.2.0"
+ resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545"
+ integrity sha512-hjf+xovcEn31w/EUYdTXQh/8smFL/dzYjohQGEIgjyNavaJfBY2p5F527Bo1VPATxv0VYTUC2bOcXvqFwk78Og==
+
+dedent@^0.7.0:
+ version "0.7.0"
+ resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c"
+ integrity sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==
+
deep-is@^0.1.3:
version "0.1.4"
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==
+deepmerge@^4.2.2:
+ version "4.2.2"
+ resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955"
+ integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==
+
define-properties@^1.1.3, define-properties@^1.1.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.4.tgz#0b14d7bd7fbeb2f3572c3a7eda80ea5d57fb05b1"
@@ -861,6 +1763,45 @@ define-properties@^1.1.3, define-properties@^1.1.4:
has-property-descriptors "^1.0.0"
object-keys "^1.1.1"
+define-property@^0.2.5:
+ version "0.2.5"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116"
+ integrity sha512-Rr7ADjQZenceVOAKop6ALkkRAmH1A4Gx9hV/7ZujPUN2rkATqFO0JZLZInbAjpZYoJ1gUx8MRMQVkYemcbMSTA==
+ dependencies:
+ is-descriptor "^0.1.0"
+
+define-property@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6"
+ integrity sha512-cZTYKFWspt9jZsMscWo8sc/5lbPC9Q0N5nBLgb+Yd915iL3udB1uFgS3B8YCx66UVHq018DAVFoee7x+gxggeA==
+ dependencies:
+ is-descriptor "^1.0.0"
+
+define-property@^2.0.2:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d"
+ integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==
+ dependencies:
+ is-descriptor "^1.0.2"
+ isobject "^3.0.1"
+
+detect-newline@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651"
+ integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==
+
+diff-sequences@^28.1.1:
+ version "28.1.1"
+ resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-28.1.1.tgz#9989dc731266dc2903457a70e996f3a041913ac6"
+ integrity sha512-FU0iFaH/E23a+a718l8Qa/19bF9p06kgE0KipMOMadwa3SjnaElKzPaUC0vnibs6/B/9ni97s61mcejk8W1fQw==
+
+dir-glob@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f"
+ integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==
+ dependencies:
+ path-type "^4.0.0"
+
doctrine@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d"
@@ -875,10 +1816,28 @@ doctrine@^3.0.0:
dependencies:
esutils "^2.0.2"
-electron-to-chromium@^1.4.147:
- version "1.4.158"
- resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.158.tgz#abbdaaf64676bfa4bc0307522125db34424a0ada"
- integrity sha512-gppO3/+Y6sP432HtvwvuU8S+YYYLH4PmAYvQwqUtt9HDOmEsBwQfLnK9T8+1NIKwAS1BEygIjTaATC4H5EzvxQ==
+dom-helpers@^5.0.1:
+ version "5.2.1"
+ resolved "https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-5.2.1.tgz#d9400536b2bf8225ad98fe052e029451ac40e902"
+ integrity sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==
+ dependencies:
+ "@babel/runtime" "^7.8.7"
+ csstype "^3.0.2"
+
+electron-to-chromium@^1.4.202:
+ version "1.4.219"
+ resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.219.tgz#a7a672304b6aa4f376918d3f63a47f2c3906009a"
+ integrity sha512-zoQJsXOUw0ZA0YxbjkmzBumAJRtr6je5JySuL/bAoFs0DuLiLJ+5FzRF7/ZayihxR2QcewlRZVm5QZdUhwjOgA==
+
+emittery@^0.10.2:
+ version "0.10.2"
+ resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.10.2.tgz#902eec8aedb8c41938c46e9385e9db7e03182933"
+ integrity sha512-aITqOwnLanpHLNXZJENbOgjUBeHocD+xsSJmNrjovKBW5HbSpW3d1pEls7GFQPUWXiwG9+0P4GtHfEqC/4M0Iw==
+
+emoji-regex@^8.0.0:
+ version "8.0.0"
+ resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
+ integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
end-of-stream@^1.1.0:
version "1.4.4"
@@ -887,6 +1846,13 @@ end-of-stream@^1.1.0:
dependencies:
once "^1.4.0"
+error-ex@^1.3.1:
+ version "1.3.2"
+ resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf"
+ integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==
+ dependencies:
+ is-arrayish "^0.2.1"
+
es-abstract@^1.19.0, es-abstract@^1.19.1, es-abstract@^1.19.2, es-abstract@^1.19.5:
version "1.20.1"
resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.20.1.tgz#027292cd6ef44bd12b1913b828116f54787d1814"
@@ -932,131 +1898,141 @@ es-to-primitive@^1.2.1:
is-date-object "^1.0.1"
is-symbol "^1.0.2"
-esbuild-android-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-android-64/-/esbuild-android-64-0.14.44.tgz#62f5cb563d0ba318d898b6eb230c61ad3dc93619"
- integrity sha512-dFPHBXmx385zuJULAD/Cmq/LyPRXiAWbf9ylZtY0wJ8iVyWfKYaCYxeJx8OAZUuj46ZwNa7MzW2GBAQLOeiemg==
-
-esbuild-android-arm64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-android-arm64/-/esbuild-android-arm64-0.14.44.tgz#ee7fcc9f47855b3395dfd1abcc2c43d8c53e57db"
- integrity sha512-qqaqqyxHXjZ/0ddKU3I3Nb7lAvVM69ELMhb8+91FyomAUmQPlHtxe+TTiWxXGHE72XEzcgTEGq4VauqLNkN22g==
-
-esbuild-darwin-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-darwin-64/-/esbuild-darwin-64-0.14.44.tgz#75ea7f594687a7189a8ba62070d42f13178e68d0"
- integrity sha512-RBmtGKGY06+AW6IOJ1LE/dEeF7HH34C1/Ces9FSitU4bIbIpL4KEuQpTFoxwb4ry5s2hyw7vbPhhtyOd18FH9g==
-
-esbuild-darwin-arm64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.44.tgz#550631fd135688abda042f4039b962a27f3a5f78"
- integrity sha512-Bmhx5Cfo4Hdb7WyyyDupTB8HPmnFZ8baLfPlzLdYvF6OzsIbV+CY+m/AWf0OQvY40BlkzCLJ/7Lfwbb71Tngmg==
-
-esbuild-freebsd-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.44.tgz#f98069b964266ca79bb361cfb9d7454a05b7e8ca"
- integrity sha512-O4HpWa5ZgxbNPQTF7URicLzYa+TidGlmGT/RAC3GjbGEQQYkd0R1Slyh69Yrmb2qmcOcPAgWHbNo1UhK4WmZ4w==
-
-esbuild-freebsd-arm64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.44.tgz#247a8553d6033a58b6c3ba4d539216300497d7f6"
- integrity sha512-f0/jkAKccnDY7mg1F9l/AMzEm+VXWXK6c3IrOEmd13jyKfpTZKTIlt+yI04THPDCDZTzXHTRUBLozqp+m8Mg5Q==
-
-esbuild-linux-32@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-32/-/esbuild-linux-32-0.14.44.tgz#4b72747f9f367d3ee3c1d80bf75c617e6b109821"
- integrity sha512-WSIhzLldMR7YUoEL7Ix319tC+NFmW9Pu7NgFWxUfOXeWsT0Wg484hm6bNgs7+oY2pGzg715y/Wrqi1uNOMmZJw==
-
-esbuild-linux-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-64/-/esbuild-linux-64-0.14.44.tgz#6cd158fdd11f8d037c45139ccddb4fa5966f7ab6"
- integrity sha512-zgscTrCMcRZRIsVugqBTP/B5lPLNchBlWjQ8sQq2Epnv+UDtYKgXEq1ctWAmibZNy2E9QRCItKMeIEqeTUT5kA==
-
-esbuild-linux-arm64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.44.tgz#f14f3c8c3501067f5b2cef7a79c9a0058092cb22"
- integrity sha512-H0H/2/wgiScTwBve/JR8/o+Zhabx5KPk8T2mkYZFKQGl1hpUgC+AOmRyqy/Js3p66Wim4F4Akv3I3sJA1sKg0w==
-
-esbuild-linux-arm@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-arm/-/esbuild-linux-arm-0.14.44.tgz#625478cc6ea4f64f5335e7fb07f80d6f659aeb5c"
- integrity sha512-laPBPwGfsbBxGw6F6jnqic2CPXLyC1bPrmnSOeJ9oEnx1rcKkizd4HWCRUc0xv+l4z/USRfx/sEfYlWSLeqoJQ==
-
-esbuild-linux-mips64le@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.44.tgz#593c909bb612998300af7f7db2809a63a0d62eec"
- integrity sha512-ri3Okw0aleYy7o5n9zlIq+FCtq3tcMlctN6X1H1ucILjBJuH8pan2trJPKWeb8ppntFvE28I9eEXhwkWh6wYKg==
-
-esbuild-linux-ppc64le@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.44.tgz#8fc2fcee671e322a5d44fcf8da6889095a187df9"
- integrity sha512-96TqL/MvFRuIVXz+GtCIXzRQ43ZwEk4XTn0RWUNJduXXMDQ/V1iOV28U6x6Oe3NesK4xkoKSaK2+F3VHcU8ZrA==
-
-esbuild-linux-riscv64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.14.44.tgz#cc2b7158c8345b67e74458a0ec020c80ca777046"
- integrity sha512-rrK9qEp2M8dhilsPn4T9gxUsAumkITc1kqYbpyNMr9EWo+J5ZBj04n3GYldULrcCw4ZCHAJ+qPjqr8b6kG2inA==
-
-esbuild-linux-s390x@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.44.tgz#5a1e87d5d6236a8791026820936478f3b9cf8e35"
- integrity sha512-2YmTm9BrW5aUwBSe8wIEARd9EcnOQmkHp4+IVaO09Ez/C5T866x+ABzhG0bwx0b+QRo9q97CRMaQx2Ngb6/hfw==
-
-esbuild-netbsd-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.44.tgz#8afb16880b530264ce2ed9fb3df26071eb841312"
- integrity sha512-zypdzPmZTCqYS30WHxbcvtC0E6e/ECvl4WueUdbdWhs2dfWJt5RtCBME664EpTznixR3lSN1MQ2NhwQF8MQryw==
-
-esbuild-openbsd-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.44.tgz#a87455be446d6f5b07a60f060e1eafad454c9d4b"
- integrity sha512-8J43ab9ByYl7KteC03HGQjr2HY1ge7sN04lFnwMFWYk2NCn8IuaeeThvLeNjzOYhyT3I6K8puJP0uVXUu+D1xw==
-
-esbuild-sunos-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-sunos-64/-/esbuild-sunos-64-0.14.44.tgz#74ce7d5fd815fa60fe0a85b9db7549b1dcb32804"
- integrity sha512-OH1/09CGUJwffA+HNM6mqPkSIyHVC3ZnURU/4CCIx7IqWUBn1Sh1HRLQC8/TWNgcs0/1u7ygnc2pgf/AHZJ/Ow==
-
-esbuild-windows-32@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-windows-32/-/esbuild-windows-32-0.14.44.tgz#499e1c6cb46c216bdcb62f5b006fec3999bb06a7"
- integrity sha512-mCAOL9/rRqwfOfxTu2sjq/eAIs7eAXGiU6sPBnowggI7QS953Iq6o3/uDu010LwfN7zr18c/lEj6/PTwwTB3AA==
-
-esbuild-windows-64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-windows-64/-/esbuild-windows-64-0.14.44.tgz#a8dae69a4615b17f62375859ce9536dd96940a06"
- integrity sha512-AG6BH3+YG0s2Q/IfB1cm68FdyFnoE1P+GFbmgFO3tA4UIP8+BKsmKGGZ5I3+ZjcnzOwvT74bQRVrfnQow2KO5Q==
-
-esbuild-windows-arm64@0.14.44:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.44.tgz#db73bb68aa75a880bdaa938ccacc0f17e7a4bfea"
- integrity sha512-ygYPfYE5By4Sd6szsNr10B0RtWVNOSGmZABSaj4YQBLqh9b9i45VAjVWa8tyIy+UAbKF7WGwybi2wTbSVliO8A==
+esbuild-android-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-android-64/-/esbuild-android-64-0.14.54.tgz#505f41832884313bbaffb27704b8bcaa2d8616be"
+ integrity sha512-Tz2++Aqqz0rJ7kYBfz+iqyE3QMycD4vk7LBRyWaAVFgFtQ/O8EJOnVmTOiDWYZ/uYzB4kvP+bqejYdVKzE5lAQ==
+
+esbuild-android-arm64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-android-arm64/-/esbuild-android-arm64-0.14.54.tgz#8ce69d7caba49646e009968fe5754a21a9871771"
+ integrity sha512-F9E+/QDi9sSkLaClO8SOV6etqPd+5DgJje1F9lOWoNncDdOBL2YF59IhsWATSt0TLZbYCf3pNlTHvVV5VfHdvg==
+
+esbuild-darwin-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-darwin-64/-/esbuild-darwin-64-0.14.54.tgz#24ba67b9a8cb890a3c08d9018f887cc221cdda25"
+ integrity sha512-jtdKWV3nBviOd5v4hOpkVmpxsBy90CGzebpbO9beiqUYVMBtSc0AL9zGftFuBon7PNDcdvNCEuQqw2x0wP9yug==
+
+esbuild-darwin-arm64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.54.tgz#3f7cdb78888ee05e488d250a2bdaab1fa671bf73"
+ integrity sha512-OPafJHD2oUPyvJMrsCvDGkRrVCar5aVyHfWGQzY1dWnzErjrDuSETxwA2HSsyg2jORLY8yBfzc1MIpUkXlctmw==
+
+esbuild-freebsd-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.54.tgz#09250f997a56ed4650f3e1979c905ffc40bbe94d"
+ integrity sha512-OKwd4gmwHqOTp4mOGZKe/XUlbDJ4Q9TjX0hMPIDBUWWu/kwhBAudJdBoxnjNf9ocIB6GN6CPowYpR/hRCbSYAg==
+
+esbuild-freebsd-arm64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.54.tgz#bafb46ed04fc5f97cbdb016d86947a79579f8e48"
+ integrity sha512-sFwueGr7OvIFiQT6WeG0jRLjkjdqWWSrfbVwZp8iMP+8UHEHRBvlaxL6IuKNDwAozNUmbb8nIMXa7oAOARGs1Q==
+
+esbuild-jest@^0:
+ version "0.5.0"
+ resolved "https://registry.yarnpkg.com/esbuild-jest/-/esbuild-jest-0.5.0.tgz#7a9964bfdecafca3b675a8aeb08193bcdba8b9d7"
+ integrity sha512-AMZZCdEpXfNVOIDvURlqYyHwC8qC1/BFjgsrOiSL1eyiIArVtHL8YAC83Shhn16cYYoAWEW17yZn0W/RJKJKHQ==
+ dependencies:
+ "@babel/core" "^7.12.17"
+ "@babel/plugin-transform-modules-commonjs" "^7.12.13"
+ babel-jest "^26.6.3"
+
+esbuild-linux-32@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-32/-/esbuild-linux-32-0.14.54.tgz#e2a8c4a8efdc355405325033fcebeb941f781fe5"
+ integrity sha512-1ZuY+JDI//WmklKlBgJnglpUL1owm2OX+8E1syCD6UAxcMM/XoWd76OHSjl/0MR0LisSAXDqgjT3uJqT67O3qw==
+
+esbuild-linux-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-64/-/esbuild-linux-64-0.14.54.tgz#de5fdba1c95666cf72369f52b40b03be71226652"
+ integrity sha512-EgjAgH5HwTbtNsTqQOXWApBaPVdDn7XcK+/PtJwZLT1UmpLoznPd8c5CxqsH2dQK3j05YsB3L17T8vE7cp4cCg==
+
+esbuild-linux-arm64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.54.tgz#dae4cd42ae9787468b6a5c158da4c84e83b0ce8b"
+ integrity sha512-WL71L+0Rwv+Gv/HTmxTEmpv0UgmxYa5ftZILVi2QmZBgX3q7+tDeOQNqGtdXSdsL8TQi1vIaVFHUPDe0O0kdig==
+
+esbuild-linux-arm@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-arm/-/esbuild-linux-arm-0.14.54.tgz#a2c1dff6d0f21dbe8fc6998a122675533ddfcd59"
+ integrity sha512-qqz/SjemQhVMTnvcLGoLOdFpCYbz4v4fUo+TfsWG+1aOu70/80RV6bgNpR2JCrppV2moUQkww+6bWxXRL9YMGw==
+
+esbuild-linux-mips64le@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.54.tgz#d9918e9e4cb972f8d6dae8e8655bf9ee131eda34"
+ integrity sha512-qTHGQB8D1etd0u1+sB6p0ikLKRVuCWhYQhAHRPkO+OF3I/iSlTKNNS0Lh2Oc0g0UFGguaFZZiPJdJey3AGpAlw==
+
+esbuild-linux-ppc64le@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.54.tgz#3f9a0f6d41073fb1a640680845c7de52995f137e"
+ integrity sha512-j3OMlzHiqwZBDPRCDFKcx595XVfOfOnv68Ax3U4UKZ3MTYQB5Yz3X1mn5GnodEVYzhtZgxEBidLWeIs8FDSfrQ==
+
+esbuild-linux-riscv64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.14.54.tgz#618853c028178a61837bc799d2013d4695e451c8"
+ integrity sha512-y7Vt7Wl9dkOGZjxQZnDAqqn+XOqFD7IMWiewY5SPlNlzMX39ocPQlOaoxvT4FllA5viyV26/QzHtvTjVNOxHZg==
+
+esbuild-linux-s390x@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.54.tgz#d1885c4c5a76bbb5a0fe182e2c8c60eb9e29f2a6"
+ integrity sha512-zaHpW9dziAsi7lRcyV4r8dhfG1qBidQWUXweUjnw+lliChJqQr+6XD71K41oEIC3Mx1KStovEmlzm+MkGZHnHA==
+
+esbuild-netbsd-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.54.tgz#69ae917a2ff241b7df1dbf22baf04bd330349e81"
+ integrity sha512-PR01lmIMnfJTgeU9VJTDY9ZerDWVFIUzAtJuDHwwceppW7cQWjBBqP48NdeRtoP04/AtO9a7w3viI+PIDr6d+w==
+
+esbuild-openbsd-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.54.tgz#db4c8495287a350a6790de22edea247a57c5d47b"
+ integrity sha512-Qyk7ikT2o7Wu76UsvvDS5q0amJvmRzDyVlL0qf5VLsLchjCa1+IAvd8kTBgUxD7VBUUVgItLkk609ZHUc1oCaw==
+
+esbuild-sunos-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-sunos-64/-/esbuild-sunos-64-0.14.54.tgz#54287ee3da73d3844b721c21bc80c1dc7e1bf7da"
+ integrity sha512-28GZ24KmMSeKi5ueWzMcco6EBHStL3B6ubM7M51RmPwXQGLe0teBGJocmWhgwccA1GeFXqxzILIxXpHbl9Q/Kw==
+
+esbuild-windows-32@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-windows-32/-/esbuild-windows-32-0.14.54.tgz#f8aaf9a5667630b40f0fb3aa37bf01bbd340ce31"
+ integrity sha512-T+rdZW19ql9MjS7pixmZYVObd9G7kcaZo+sETqNH4RCkuuYSuv9AGHUVnPoP9hhuE1WM1ZimHz1CIBHBboLU7w==
+
+esbuild-windows-64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-windows-64/-/esbuild-windows-64-0.14.54.tgz#bf54b51bd3e9b0f1886ffdb224a4176031ea0af4"
+ integrity sha512-AoHTRBUuYwXtZhjXZbA1pGfTo8cJo3vZIcWGLiUcTNgHpJJMC1rVA44ZereBHMJtotyN71S8Qw0npiCIkW96cQ==
+
+esbuild-windows-arm64@0.14.54:
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.54.tgz#937d15675a15e4b0e4fafdbaa3a01a776a2be982"
+ integrity sha512-M0kuUvXhot1zOISQGXwWn6YtS+Y/1RT9WrVIOywZnJHo3jCDyewAc79aKNQWFCQm+xNHVTq9h8dZKvygoXQQRg==
esbuild@^0.14.27:
- version "0.14.44"
- resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.14.44.tgz#27fa3cd4f55d36780650c7f32cab581abc7a4473"
- integrity sha512-Rn+lRRfj60r/3svI6NgAVnetzp3vMOj17BThuhshSj/gS1LR03xrjkDYyfPmrYG/0c3D68rC6FNYMQ3yRbiXeQ==
+ version "0.14.54"
+ resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.14.54.tgz#8b44dcf2b0f1a66fc22459943dccf477535e9aa2"
+ integrity sha512-Cy9llcy8DvET5uznocPyqL3BFRrFXSVqbgpMJ9Wz8oVjZlh/zUSNbPRbov0VX7VxN2JH1Oa0uNxZ7eLRb62pJA==
optionalDependencies:
- esbuild-android-64 "0.14.44"
- esbuild-android-arm64 "0.14.44"
- esbuild-darwin-64 "0.14.44"
- esbuild-darwin-arm64 "0.14.44"
- esbuild-freebsd-64 "0.14.44"
- esbuild-freebsd-arm64 "0.14.44"
- esbuild-linux-32 "0.14.44"
- esbuild-linux-64 "0.14.44"
- esbuild-linux-arm "0.14.44"
- esbuild-linux-arm64 "0.14.44"
- esbuild-linux-mips64le "0.14.44"
- esbuild-linux-ppc64le "0.14.44"
- esbuild-linux-riscv64 "0.14.44"
- esbuild-linux-s390x "0.14.44"
- esbuild-netbsd-64 "0.14.44"
- esbuild-openbsd-64 "0.14.44"
- esbuild-sunos-64 "0.14.44"
- esbuild-windows-32 "0.14.44"
- esbuild-windows-64 "0.14.44"
- esbuild-windows-arm64 "0.14.44"
+ "@esbuild/linux-loong64" "0.14.54"
+ esbuild-android-64 "0.14.54"
+ esbuild-android-arm64 "0.14.54"
+ esbuild-darwin-64 "0.14.54"
+ esbuild-darwin-arm64 "0.14.54"
+ esbuild-freebsd-64 "0.14.54"
+ esbuild-freebsd-arm64 "0.14.54"
+ esbuild-linux-32 "0.14.54"
+ esbuild-linux-64 "0.14.54"
+ esbuild-linux-arm "0.14.54"
+ esbuild-linux-arm64 "0.14.54"
+ esbuild-linux-mips64le "0.14.54"
+ esbuild-linux-ppc64le "0.14.54"
+ esbuild-linux-riscv64 "0.14.54"
+ esbuild-linux-s390x "0.14.54"
+ esbuild-netbsd-64 "0.14.54"
+ esbuild-openbsd-64 "0.14.54"
+ esbuild-sunos-64 "0.14.54"
+ esbuild-windows-32 "0.14.54"
+ esbuild-windows-64 "0.14.54"
+ esbuild-windows-arm64 "0.14.54"
escalade@^3.1.1:
version "3.1.1"
@@ -1068,6 +2044,11 @@ escape-string-regexp@^1.0.5:
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==
+escape-string-regexp@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344"
+ integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==
+
escape-string-regexp@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34"
@@ -1082,12 +2063,11 @@ eslint-import-resolver-node@^0.3.6:
resolve "^1.20.0"
eslint-module-utils@^2.7.3:
- version "2.7.3"
- resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.7.3.tgz#ad7e3a10552fdd0642e1e55292781bd6e34876ee"
- integrity sha512-088JEC7O3lDZM9xGe0RerkOMd0EjFl+Yvd1jPWIkMT5u3H9+HC34mWWPnqPrN13gieT9pBOO+Qt07Nb/6TresQ==
+ version "2.7.4"
+ resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.7.4.tgz#4f3e41116aaf13a20792261e61d3a2e7e0583974"
+ integrity sha512-j4GT+rqzCoRKHwURX7pddtIPGySnX9Si/cgMI5ztrcqOPtk5dDEeZ34CQVPphnqkJytlc97Vuk05Um2mJ3gEQA==
dependencies:
debug "^3.2.7"
- find-up "^2.1.0"
eslint-plugin-import@^2:
version "2.26.0"
@@ -1109,9 +2089,9 @@ eslint-plugin-import@^2:
tsconfig-paths "^3.14.1"
eslint-plugin-prettier@^4:
- version "4.0.0"
- resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.0.0.tgz#8b99d1e4b8b24a762472b4567992023619cb98e0"
- integrity sha512-98MqmCJ7vJodoQK359bqQWaxOE0CS8paAz/GgjaZLyex4TTk3g9HugoO89EqWCrFiOqn9EVvcoo7gZzONCWVwQ==
+ version "4.2.1"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.2.1.tgz#651cbb88b1dab98bfd42f017a12fa6b2d993f94b"
+ integrity sha512-f/0rXLXUt0oFYs8ra4w49wYZBG5GKZpAYsJSm6rnYL5uVDjd+zowwMwVZHnAjf4edNrKpCDYfXDgmRE/Ak7QyQ==
dependencies:
prettier-linter-helpers "^1.0.0"
@@ -1126,9 +2106,9 @@ eslint-plugin-react-perf@^3:
integrity sha512-iOx2UtEOH50TmQhezTS4jbBAj/2gbrUdX+ZM28c2K9mwTvtRX6gdnd2P4WPQrejITDsAMNTCz95zu5HcjCD0xg==
eslint-plugin-react@^7:
- version "7.30.0"
- resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.30.0.tgz#8e7b1b2934b8426ac067a0febade1b13bd7064e3"
- integrity sha512-RgwH7hjW48BleKsYyHK5vUAvxtE9SMPDKmcPRQgtRCYaZA0XQPt5FSkrU3nhz5ifzMZcA8opwmRJ2cmOO8tr5A==
+ version "7.30.1"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.30.1.tgz#2be4ab23ce09b5949c6631413ba64b2810fd3e22"
+ integrity sha512-NbEvI9jtqO46yJA3wcRF9Mo0lF9T/jhdHqhCHXiXtD+Zcb98812wvokjWpU7Q4QH5edo6dmqrukxVvWWXHlsUg==
dependencies:
array-includes "^3.1.5"
array.prototype.flatmap "^1.3.0"
@@ -1183,12 +2163,13 @@ eslint-visitor-keys@^3.3.0:
integrity sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==
eslint@^8:
- version "8.18.0"
- resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.18.0.tgz#78d565d16c993d0b73968c523c0446b13da784fd"
- integrity sha512-As1EfFMVk7Xc6/CvhssHUjsAQSkpfXvUGMFC3ce8JDe6WvqCgRrLOBQbVpsBFr1X1V+RACOadnzVvcUS5ni2bA==
+ version "8.22.0"
+ resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.22.0.tgz#78fcb044196dfa7eef30a9d65944f6f980402c48"
+ integrity sha512-ci4t0sz6vSRKdmkOGmprBo6fmI4PrphDFMy5JEq/fNS0gQkJM3rLmrqcp8ipMcdobH3KtUP40KniAE9W19S4wA==
dependencies:
"@eslint/eslintrc" "^1.3.0"
- "@humanwhocodes/config-array" "^0.9.2"
+ "@humanwhocodes/config-array" "^0.10.4"
+ "@humanwhocodes/gitignore-to-minimatch" "^1.0.2"
ajv "^6.10.0"
chalk "^4.0.0"
cross-spawn "^7.0.2"
@@ -1198,14 +2179,17 @@ eslint@^8:
eslint-scope "^7.1.1"
eslint-utils "^3.0.0"
eslint-visitor-keys "^3.3.0"
- espree "^9.3.2"
+ espree "^9.3.3"
esquery "^1.4.0"
esutils "^2.0.2"
fast-deep-equal "^3.1.3"
file-entry-cache "^6.0.1"
+ find-up "^5.0.0"
functional-red-black-tree "^1.0.1"
glob-parent "^6.0.1"
globals "^13.15.0"
+ globby "^11.1.0"
+ grapheme-splitter "^1.0.4"
ignore "^5.2.0"
import-fresh "^3.0.0"
imurmurhash "^0.1.4"
@@ -1223,15 +2207,20 @@ eslint@^8:
text-table "^0.2.0"
v8-compile-cache "^2.0.3"
-espree@^9.3.2:
- version "9.3.2"
- resolved "https://registry.yarnpkg.com/espree/-/espree-9.3.2.tgz#f58f77bd334731182801ced3380a8cc859091596"
- integrity sha512-D211tC7ZwouTIuY5x9XnS0E9sWNChB7IYKX/Xp5eQj3nFXhqmiUDB9q27y76oFl8jTg3pXcQx/bpxMfs3CIZbA==
+espree@^9.3.2, espree@^9.3.3:
+ version "9.3.3"
+ resolved "https://registry.yarnpkg.com/espree/-/espree-9.3.3.tgz#2dd37c4162bb05f433ad3c1a52ddf8a49dc08e9d"
+ integrity sha512-ORs1Rt/uQTqUKjDdGCyrtYxbazf5umATSf/K4qxjmZHORR6HJk+2s/2Pqe+Kk49HHINC/xNIrGfgh8sZcll0ng==
dependencies:
- acorn "^8.7.1"
+ acorn "^8.8.0"
acorn-jsx "^5.3.2"
eslint-visitor-keys "^3.3.0"
+esprima@^4.0.0:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71"
+ integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==
+
esquery@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.4.0.tgz#2148ffc38b82e8c7057dfed48425b3e61f0f24a5"
@@ -1261,6 +2250,24 @@ esutils@^2.0.2:
resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64"
integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==
+exec-sh@^0.3.2:
+ version "0.3.6"
+ resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.3.6.tgz#ff264f9e325519a60cb5e273692943483cca63bc"
+ integrity sha512-nQn+hI3yp+oD0huYhKwvYI32+JFeq+XkNcD1GAo3Y/MjxsfVGmrrzrnzjWiNY6f+pUCP440fThsFh5gZrRAU/w==
+
+execa@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8"
+ integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==
+ dependencies:
+ cross-spawn "^6.0.0"
+ get-stream "^4.0.0"
+ is-stream "^1.1.0"
+ npm-run-path "^2.0.0"
+ p-finally "^1.0.0"
+ signal-exit "^3.0.0"
+ strip-eof "^1.0.0"
+
execa@^4.0.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/execa/-/execa-4.1.0.tgz#4e5491ad1572f2f17a77d388c6c857135b22847a"
@@ -1276,6 +2283,79 @@ execa@^4.0.0:
signal-exit "^3.0.2"
strip-final-newline "^2.0.0"
+execa@^5.0.0:
+ version "5.1.1"
+ resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd"
+ integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==
+ dependencies:
+ cross-spawn "^7.0.3"
+ get-stream "^6.0.0"
+ human-signals "^2.1.0"
+ is-stream "^2.0.0"
+ merge-stream "^2.0.0"
+ npm-run-path "^4.0.1"
+ onetime "^5.1.2"
+ signal-exit "^3.0.3"
+ strip-final-newline "^2.0.0"
+
+exit@^0.1.2:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c"
+ integrity sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==
+
+expand-brackets@^2.1.4:
+ version "2.1.4"
+ resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622"
+ integrity sha512-w/ozOKR9Obk3qoWeY/WDi6MFta9AoMR+zud60mdnbniMcBxRuFJyDt2LdX/14A1UABeqk+Uk+LDfUpvoGKppZA==
+ dependencies:
+ debug "^2.3.3"
+ define-property "^0.2.5"
+ extend-shallow "^2.0.1"
+ posix-character-classes "^0.1.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
+expect@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/expect/-/expect-28.1.3.tgz#90a7c1a124f1824133dd4533cce2d2bdcb6603ec"
+ integrity sha512-eEh0xn8HlsuOBxFgIss+2mX85VAS4Qy3OSkjV7rlBWljtA4oWH37glVGyOZSZvErDT/yBywZdPGwCXuTvSG85g==
+ dependencies:
+ "@jest/expect-utils" "^28.1.3"
+ jest-get-type "^28.0.2"
+ jest-matcher-utils "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-util "^28.1.3"
+
+extend-shallow@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f"
+ integrity sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==
+ dependencies:
+ is-extendable "^0.1.0"
+
+extend-shallow@^3.0.0, extend-shallow@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8"
+ integrity sha512-BwY5b5Ql4+qZoefgMj2NUmx+tehVTH/Kf4k1ZEtOHNFcm2wSxMRo992l6X3TIgni2eZVTZ85xMOjF31fwZAj6Q==
+ dependencies:
+ assign-symbols "^1.0.0"
+ is-extendable "^1.0.1"
+
+extglob@^2.0.4:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543"
+ integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==
+ dependencies:
+ array-unique "^0.3.2"
+ define-property "^1.0.0"
+ expand-brackets "^2.1.4"
+ extend-shallow "^2.0.1"
+ fragment-cache "^0.2.1"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:
version "3.1.3"
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"
@@ -1286,6 +2366,17 @@ fast-diff@^1.1.2:
resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03"
integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==
+fast-glob@^3.2.9:
+ version "3.2.11"
+ resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.11.tgz#a1172ad95ceb8a16e20caa5c5e56480e5129c1d9"
+ integrity sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==
+ dependencies:
+ "@nodelib/fs.stat" "^2.0.2"
+ "@nodelib/fs.walk" "^1.2.3"
+ glob-parent "^5.1.2"
+ merge2 "^1.3.0"
+ micromatch "^4.0.4"
+
fast-json-stable-stringify@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633"
@@ -1296,6 +2387,20 @@ fast-levenshtein@^2.0.6:
resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917"
integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==
+fastq@^1.6.0:
+ version "1.13.0"
+ resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.13.0.tgz#616760f88a7526bdfc596b7cab8c18938c36b98c"
+ integrity sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==
+ dependencies:
+ reusify "^1.0.4"
+
+fb-watchman@^2.0.0:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.1.tgz#fc84fb39d2709cf3ff6d743706157bb5708a8a85"
+ integrity sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg==
+ dependencies:
+ bser "2.1.1"
+
file-entry-cache@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027"
@@ -1303,14 +2408,29 @@ file-entry-cache@^6.0.1:
dependencies:
flat-cache "^3.0.4"
-find-up@^2.1.0:
- version "2.1.0"
- resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7"
- integrity sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ==
+fill-range@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7"
+ integrity sha512-VcpLTWqWDiTerugjj8e3+esbg+skS3M9e54UuR3iCeIDMXCLTsAH8hTSzDQU/X6/6t3eYkOKoZSef2PlU6U1XQ==
dependencies:
- locate-path "^2.0.0"
+ extend-shallow "^2.0.1"
+ is-number "^3.0.0"
+ repeat-string "^1.6.1"
+ to-regex-range "^2.1.0"
-find-up@^4.1.0:
+fill-range@^7.0.1:
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40"
+ integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==
+ dependencies:
+ to-regex-range "^5.0.1"
+
+find-root@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4"
+ integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==
+
+find-up@^4.0.0, find-up@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19"
integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==
@@ -1318,6 +2438,14 @@ find-up@^4.1.0:
locate-path "^5.0.0"
path-exists "^4.0.0"
+find-up@^5.0.0:
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc"
+ integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==
+ dependencies:
+ locate-path "^6.0.0"
+ path-exists "^4.0.0"
+
flat-cache@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.0.4.tgz#61b0338302b2fe9f957dcc32fc2a87f1c3048b11"
@@ -1327,16 +2455,28 @@ flat-cache@^3.0.4:
rimraf "^3.0.2"
flatted@^3.1.0:
- version "3.2.5"
- resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"
- integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==
+ version "3.2.6"
+ resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.6.tgz#022e9218c637f9f3fc9c35ab9c9193f05add60b2"
+ integrity sha512-0sQoMh9s0BYsm+12Huy/rkKxVu4R1+r96YX5cG44rHV0pQ6iC3Q+mkoMFaGWObMFYQxCVT+ssG1ksneA2MI9KQ==
+
+for-in@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
+ integrity sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==
+
+fragment-cache@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19"
+ integrity sha512-GMBAbW9antB8iZRHLoGw0b3HANt57diZYFO/HL1JGIC1MjKrdmhxvrJbupnVvpys0zsz7yBApXdQyfepKly2kA==
+ dependencies:
+ map-cache "^0.2.2"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==
-fsevents@~2.3.2:
+fsevents@^2.1.2, fsevents@^2.3.2, fsevents@~2.3.2:
version "2.3.2"
resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a"
integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==
@@ -1371,6 +2511,11 @@ gensync@^1.0.0-beta.2:
resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0"
integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==
+get-caller-file@^2.0.5:
+ version "2.0.5"
+ resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e"
+ integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==
+
get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1:
version "1.1.2"
resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.2.tgz#336975123e05ad0b7ba41f152ee4aadbea6cf598"
@@ -1380,6 +2525,18 @@ get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1:
has "^1.0.3"
has-symbols "^1.0.3"
+get-package-type@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a"
+ integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==
+
+get-stream@^4.0.0:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-4.1.0.tgz#c1b255575f3dc21d59bfc79cd3d2b46b1c3a54b5"
+ integrity sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==
+ dependencies:
+ pump "^3.0.0"
+
get-stream@^5.0.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3"
@@ -1387,6 +2544,11 @@ get-stream@^5.0.0:
dependencies:
pump "^3.0.0"
+get-stream@^6.0.0:
+ version "6.0.1"
+ resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7"
+ integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==
+
get-symbol-description@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.0.0.tgz#7fdb81c900101fbd564dd5f1a30af5aadc1e58d6"
@@ -1395,6 +2557,18 @@ get-symbol-description@^1.0.0:
call-bind "^1.0.2"
get-intrinsic "^1.1.1"
+get-value@^2.0.3, get-value@^2.0.6:
+ version "2.0.6"
+ resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
+ integrity sha512-Ln0UQDlxH1BapMu3GPtf7CuYNwRZf2gwCuPqbyG6pB8WfmFpzqcy4xtAaAMUhnNqjMKTiCPZG2oMT3YSx8U2NA==
+
+glob-parent@^5.1.2:
+ version "5.1.2"
+ resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"
+ integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==
+ dependencies:
+ is-glob "^4.0.1"
+
glob-parent@^6.0.1:
version "6.0.2"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3"
@@ -1402,7 +2576,7 @@ glob-parent@^6.0.1:
dependencies:
is-glob "^4.0.3"
-glob@^7.1.3:
+glob@^7.1.3, glob@^7.1.4:
version "7.2.3"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b"
integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==
@@ -1420,16 +2594,33 @@ globals@^11.1.0:
integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==
globals@^13.15.0:
- version "13.15.0"
- resolved "https://registry.yarnpkg.com/globals/-/globals-13.15.0.tgz#38113218c907d2f7e98658af246cef8b77e90bac"
- integrity sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==
+ version "13.17.0"
+ resolved "https://registry.yarnpkg.com/globals/-/globals-13.17.0.tgz#902eb1e680a41da93945adbdcb5a9f361ba69bd4"
+ integrity sha512-1C+6nQRb1GwGMKm2dH/E7enFAMxGTmGI7/dEdhy/DNelv85w9B72t3uc5frtMNXIbzrarJJ/lTCjcaZwbLJmyw==
dependencies:
type-fest "^0.20.2"
-gud@^1.0.0:
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/gud/-/gud-1.0.0.tgz#a489581b17e6a70beca9abe3ae57de7a499852c0"
- integrity sha512-zGEOVKFM5sVPPrYs7J5/hYEw2Pof8KCyOwyhG8sAF26mCAeUFAcYPu1mwB7hhpIP29zOIBaDqwuHdLp0jvZXjw==
+globby@^11.1.0:
+ version "11.1.0"
+ resolved "https://registry.yarnpkg.com/globby/-/globby-11.1.0.tgz#bd4be98bb042f83d796f7e3811991fbe82a0d34b"
+ integrity sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==
+ dependencies:
+ array-union "^2.1.0"
+ dir-glob "^3.0.1"
+ fast-glob "^3.2.9"
+ ignore "^5.2.0"
+ merge2 "^1.4.1"
+ slash "^3.0.0"
+
+graceful-fs@^4.2.4, graceful-fs@^4.2.9:
+ version "4.2.10"
+ resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c"
+ integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==
+
+grapheme-splitter@^1.0.4:
+ version "1.0.4"
+ resolved "https://registry.yarnpkg.com/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz#9cf3a665c6247479896834af35cf1dbb4400767e"
+ integrity sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==
has-bigints@^1.0.1, has-bigints@^1.0.2:
version "1.0.2"
@@ -1453,7 +2644,7 @@ has-property-descriptors@^1.0.0:
dependencies:
get-intrinsic "^1.1.1"
-has-symbols@^1.0.1, has-symbols@^1.0.2, has-symbols@^1.0.3:
+has-symbols@^1.0.2, has-symbols@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8"
integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==
@@ -1465,6 +2656,37 @@ has-tostringtag@^1.0.0:
dependencies:
has-symbols "^1.0.2"
+has-value@^0.3.1:
+ version "0.3.1"
+ resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f"
+ integrity sha512-gpG936j8/MzaeID5Yif+577c17TxaDmhuyVgSwtnL/q8UUTySg8Mecb+8Cf1otgLoD7DDH75axp86ER7LFsf3Q==
+ dependencies:
+ get-value "^2.0.3"
+ has-values "^0.1.4"
+ isobject "^2.0.0"
+
+has-value@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177"
+ integrity sha512-IBXk4GTsLYdQ7Rvt+GRBrFSVEkmuOUy4re0Xjd9kJSUQpnTrWR4/y9RpfexN9vkAPMFuQoeWKwqzPozRTlasGw==
+ dependencies:
+ get-value "^2.0.6"
+ has-values "^1.0.0"
+ isobject "^3.0.0"
+
+has-values@^0.1.4:
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771"
+ integrity sha512-J8S0cEdWuQbqD9//tlZxiMuMNmxB8PlEwvYwuxsTmR1G5RXUePEX/SJn7aD0GMLieuZYSwNH0cQuJGwnYunXRQ==
+
+has-values@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f"
+ integrity sha512-ODYZC64uqzmtfGMEAX/FvZiRyWLpAC3vYnNunURUnkGVTS+mI0smVsWaPydRBsE3g+ok7h960jChO8mFcWlHaQ==
+ dependencies:
+ is-number "^3.0.0"
+ kind-of "^4.0.0"
+
has@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796"
@@ -1472,6 +2694,13 @@ has@^1.0.3:
dependencies:
function-bind "^1.1.1"
+history@^5.2.0:
+ version "5.3.0"
+ resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b"
+ integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==
+ dependencies:
+ "@babel/runtime" "^7.7.6"
+
hoist-non-react-statics@^3.3.1:
version "3.3.2"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"
@@ -1479,11 +2708,21 @@ hoist-non-react-statics@^3.3.1:
dependencies:
react-is "^16.7.0"
+html-escaper@^2.0.0:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453"
+ integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==
+
human-signals@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==
+human-signals@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0"
+ integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==
+
husky@^7:
version "7.0.4"
resolved "https://registry.yarnpkg.com/husky/-/husky-7.0.4.tgz#242048245dc49c8fb1bf0cc7cfb98dd722531535"
@@ -1502,6 +2741,14 @@ import-fresh@^3.0.0, import-fresh@^3.2.1:
parent-module "^1.0.0"
resolve-from "^4.0.0"
+import-local@^3.0.2:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4"
+ integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==
+ dependencies:
+ pkg-dir "^4.2.0"
+ resolve-cwd "^3.0.0"
+
imurmurhash@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
@@ -1529,12 +2776,24 @@ internal-slot@^1.0.3:
has "^1.0.3"
side-channel "^1.0.4"
-invariant@^2.2.3:
- version "2.2.4"
- resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6"
- integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==
+is-accessor-descriptor@^0.1.6:
+ version "0.1.6"
+ resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"
+ integrity sha512-e1BM1qnDbMRG3ll2U9dSK0UMHuWOs3pY3AtcFsmvwPtKL3MML/Q86i+GilLfvqEs4GW+ExB91tQ3Ig9noDIZ+A==
dependencies:
- loose-envify "^1.0.0"
+ kind-of "^3.0.2"
+
+is-accessor-descriptor@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656"
+ integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==
+ dependencies:
+ kind-of "^6.0.0"
+
+is-arrayish@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d"
+ integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==
is-bigint@^1.0.1:
version "1.0.4"
@@ -1551,18 +2810,44 @@ is-boolean-object@^1.1.0:
call-bind "^1.0.2"
has-tostringtag "^1.0.0"
+is-buffer@^1.1.5:
+ version "1.1.6"
+ resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
+ integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==
+
is-callable@^1.1.4, is-callable@^1.2.4:
version "1.2.4"
resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945"
integrity sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==
+is-ci@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c"
+ integrity sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==
+ dependencies:
+ ci-info "^2.0.0"
+
is-core-module@^2.8.1, is-core-module@^2.9.0:
- version "2.9.0"
- resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69"
- integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==
+ version "2.10.0"
+ resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.10.0.tgz#9012ede0a91c69587e647514e1d5277019e728ed"
+ integrity sha512-Erxj2n/LDAZ7H8WNJXd9tw38GYM3dv8rk8Zcs+jJuxYTW7sozH+SS8NtrSjVL1/vpLvWi1hxy96IzjJ3EHTJJg==
dependencies:
has "^1.0.3"
+is-data-descriptor@^0.1.4:
+ version "0.1.4"
+ resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56"
+ integrity sha512-+w9D5ulSoBNlmw9OHn3U2v51SyoCd0he+bB3xMl62oijhrspxowjU+AIcDY0N3iEJbUEkB15IlMASQsxYigvXg==
+ dependencies:
+ kind-of "^3.0.2"
+
+is-data-descriptor@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7"
+ integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==
+ dependencies:
+ kind-of "^6.0.0"
+
is-date-object@^1.0.1:
version "1.0.5"
resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.5.tgz#0841d5536e724c25597bf6ea62e1bd38298df31f"
@@ -1570,12 +2855,52 @@ is-date-object@^1.0.1:
dependencies:
has-tostringtag "^1.0.0"
+is-descriptor@^0.1.0:
+ version "0.1.6"
+ resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca"
+ integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==
+ dependencies:
+ is-accessor-descriptor "^0.1.6"
+ is-data-descriptor "^0.1.4"
+ kind-of "^5.0.0"
+
+is-descriptor@^1.0.0, is-descriptor@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec"
+ integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==
+ dependencies:
+ is-accessor-descriptor "^1.0.0"
+ is-data-descriptor "^1.0.0"
+ kind-of "^6.0.2"
+
+is-extendable@^0.1.0, is-extendable@^0.1.1:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
+ integrity sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==
+
+is-extendable@^1.0.1:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4"
+ integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==
+ dependencies:
+ is-plain-object "^2.0.4"
+
is-extglob@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"
integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==
-is-glob@^4.0.0, is-glob@^4.0.3:
+is-fullwidth-code-point@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
+ integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
+
+is-generator-fn@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118"
+ integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==
+
+is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3:
version "4.0.3"
resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084"
integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==
@@ -1594,6 +2919,25 @@ is-number-object@^1.0.4:
dependencies:
has-tostringtag "^1.0.0"
+is-number@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
+ integrity sha512-4cboCqIpliH+mAvFNegjZQ4kgKc3ZUhQVr3HvWbSh5q3WH2v82ct+T2Y1hdU5Gdtorx/cLifQjqCbL7bpznLTg==
+ dependencies:
+ kind-of "^3.0.2"
+
+is-number@^7.0.0:
+ version "7.0.0"
+ resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b"
+ integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==
+
+is-plain-object@^2.0.3, is-plain-object@^2.0.4:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
+ integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==
+ dependencies:
+ isobject "^3.0.1"
+
is-regex@^1.1.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.4.tgz#eef5663cd59fa4c0ae339505323df6854bb15958"
@@ -1609,6 +2953,11 @@ is-shared-array-buffer@^1.0.2:
dependencies:
call-bind "^1.0.2"
+is-stream@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
+ integrity sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==
+
is-stream@^2.0.0:
version "2.0.1"
resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077"
@@ -1628,6 +2977,11 @@ is-symbol@^1.0.2, is-symbol@^1.0.3:
dependencies:
has-symbols "^1.0.2"
+is-typedarray@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a"
+ integrity sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==
+
is-weakref@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.0.2.tgz#9529f383a9338205e89765e0392efc2f100f06f2"
@@ -1635,16 +2989,501 @@ is-weakref@^1.0.2:
dependencies:
call-bind "^1.0.2"
+is-windows@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
+ integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==
+
+isarray@1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
+ integrity sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==
+
isexe@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==
+isobject@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
+ integrity sha512-+OUdGJlgjOBZDfxnDjYYG6zp487z0JGNQq3cYQYg5f5hKR+syHMsaztzGeml/4kGG55CSpKSpWTY+jYGgsHLgA==
+ dependencies:
+ isarray "1.0.0"
+
+isobject@^3.0.0, isobject@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
+ integrity sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==
+
+istanbul-lib-coverage@^3.0.0, istanbul-lib-coverage@^3.2.0:
+ version "3.2.0"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz#189e7909d0a39fa5a3dfad5b03f71947770191d3"
+ integrity sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==
+
+istanbul-lib-instrument@^5.0.4, istanbul-lib-instrument@^5.1.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.0.tgz#31d18bdd127f825dd02ea7bfdfd906f8ab840e9f"
+ integrity sha512-6Lthe1hqXHBNsqvgDzGO6l03XNeu3CrG4RqQ1KM9+l5+jNGpEJfIELx1NS3SEHmJQA8np/u+E4EPRKRiu6m19A==
+ dependencies:
+ "@babel/core" "^7.12.3"
+ "@babel/parser" "^7.14.7"
+ "@istanbuljs/schema" "^0.1.2"
+ istanbul-lib-coverage "^3.2.0"
+ semver "^6.3.0"
+
+istanbul-lib-report@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz#7518fe52ea44de372f460a76b5ecda9ffb73d8a6"
+ integrity sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==
+ dependencies:
+ istanbul-lib-coverage "^3.0.0"
+ make-dir "^3.0.0"
+ supports-color "^7.1.0"
+
+istanbul-lib-source-maps@^4.0.0:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz#895f3a709fcfba34c6de5a42939022f3e4358551"
+ integrity sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==
+ dependencies:
+ debug "^4.1.1"
+ istanbul-lib-coverage "^3.0.0"
+ source-map "^0.6.1"
+
+istanbul-reports@^3.1.3:
+ version "3.1.5"
+ resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.1.5.tgz#cc9a6ab25cb25659810e4785ed9d9fb742578bae"
+ integrity sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==
+ dependencies:
+ html-escaper "^2.0.0"
+ istanbul-lib-report "^3.0.0"
+
+jest-changed-files@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-28.1.3.tgz#d9aeee6792be3686c47cb988a8eaf82ff4238831"
+ integrity sha512-esaOfUWJXk2nfZt9SPyC8gA1kNfdKLkQWyzsMlqq8msYSlNKfmZxfRgZn4Cd4MGVUF+7v6dBs0d5TOAKa7iIiA==
+ dependencies:
+ execa "^5.0.0"
+ p-limit "^3.1.0"
+
+jest-circus@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-28.1.3.tgz#d14bd11cf8ee1a03d69902dc47b6bd4634ee00e4"
+ integrity sha512-cZ+eS5zc79MBwt+IhQhiEp0OeBddpc1n8MBo1nMB8A7oPMKEO+Sre+wHaLJexQUj9Ya/8NOBY0RESUgYjB6fow==
+ dependencies:
+ "@jest/environment" "^28.1.3"
+ "@jest/expect" "^28.1.3"
+ "@jest/test-result" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ co "^4.6.0"
+ dedent "^0.7.0"
+ is-generator-fn "^2.0.0"
+ jest-each "^28.1.3"
+ jest-matcher-utils "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-runtime "^28.1.3"
+ jest-snapshot "^28.1.3"
+ jest-util "^28.1.3"
+ p-limit "^3.1.0"
+ pretty-format "^28.1.3"
+ slash "^3.0.0"
+ stack-utils "^2.0.3"
+
+jest-cli@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-28.1.3.tgz#558b33c577d06de55087b8448d373b9f654e46b2"
+ integrity sha512-roY3kvrv57Azn1yPgdTebPAXvdR2xfezaKKYzVxZ6It/5NCxzJym6tUI5P1zkdWhfUYkxEI9uZWcQdaFLo8mJQ==
+ dependencies:
+ "@jest/core" "^28.1.3"
+ "@jest/test-result" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ chalk "^4.0.0"
+ exit "^0.1.2"
+ graceful-fs "^4.2.9"
+ import-local "^3.0.2"
+ jest-config "^28.1.3"
+ jest-util "^28.1.3"
+ jest-validate "^28.1.3"
+ prompts "^2.0.1"
+ yargs "^17.3.1"
+
+jest-config@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-28.1.3.tgz#e315e1f73df3cac31447eed8b8740a477392ec60"
+ integrity sha512-MG3INjByJ0J4AsNBm7T3hsuxKQqFIiRo/AUqb1q9LRKI5UU6Aar9JHbr9Ivn1TVwfUD9KirRoM/T6u8XlcQPHQ==
+ dependencies:
+ "@babel/core" "^7.11.6"
+ "@jest/test-sequencer" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ babel-jest "^28.1.3"
+ chalk "^4.0.0"
+ ci-info "^3.2.0"
+ deepmerge "^4.2.2"
+ glob "^7.1.3"
+ graceful-fs "^4.2.9"
+ jest-circus "^28.1.3"
+ jest-environment-node "^28.1.3"
+ jest-get-type "^28.0.2"
+ jest-regex-util "^28.0.2"
+ jest-resolve "^28.1.3"
+ jest-runner "^28.1.3"
+ jest-util "^28.1.3"
+ jest-validate "^28.1.3"
+ micromatch "^4.0.4"
+ parse-json "^5.2.0"
+ pretty-format "^28.1.3"
+ slash "^3.0.0"
+ strip-json-comments "^3.1.1"
+
+jest-diff@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-28.1.3.tgz#948a192d86f4e7a64c5264ad4da4877133d8792f"
+ integrity sha512-8RqP1B/OXzjjTWkqMX67iqgwBVJRgCyKD3L9nq+6ZqJMdvjE8RgHktqZ6jNrkdMT+dJuYNI3rhQpxaz7drJHfw==
+ dependencies:
+ chalk "^4.0.0"
+ diff-sequences "^28.1.1"
+ jest-get-type "^28.0.2"
+ pretty-format "^28.1.3"
+
+jest-docblock@^28.1.1:
+ version "28.1.1"
+ resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-28.1.1.tgz#6f515c3bf841516d82ecd57a62eed9204c2f42a8"
+ integrity sha512-3wayBVNiOYx0cwAbl9rwm5kKFP8yHH3d/fkEaL02NPTkDojPtheGB7HZSFY4wzX+DxyrvhXz0KSCVksmCknCuA==
+ dependencies:
+ detect-newline "^3.0.0"
+
+jest-each@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-28.1.3.tgz#bdd1516edbe2b1f3569cfdad9acd543040028f81"
+ integrity sha512-arT1z4sg2yABU5uogObVPvSlSMQlDA48owx07BDPAiasW0yYpYHYOo4HHLz9q0BVzDVU4hILFjzJw0So9aCL/g==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ chalk "^4.0.0"
+ jest-get-type "^28.0.2"
+ jest-util "^28.1.3"
+ pretty-format "^28.1.3"
+
+jest-environment-node@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-28.1.3.tgz#7e74fe40eb645b9d56c0c4b70ca4357faa349be5"
+ integrity sha512-ugP6XOhEpjAEhGYvp5Xj989ns5cB1K6ZdjBYuS30umT4CQEETaxSiPcZ/E1kFktX4GkrcM4qu07IIlDYX1gp+A==
+ dependencies:
+ "@jest/environment" "^28.1.3"
+ "@jest/fake-timers" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ jest-mock "^28.1.3"
+ jest-util "^28.1.3"
+
+jest-get-type@^28.0.2:
+ version "28.0.2"
+ resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-28.0.2.tgz#34622e628e4fdcd793d46db8a242227901fcf203"
+ integrity sha512-ioj2w9/DxSYHfOm5lJKCdcAmPJzQXmbM/Url3rhlghrPvT3tt+7a/+oXc9azkKmLvoiXjtV83bEWqi+vs5nlPA==
+
+jest-haste-map@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-26.6.2.tgz#dd7e60fe7dc0e9f911a23d79c5ff7fb5c2cafeaa"
+ integrity sha512-easWIJXIw71B2RdR8kgqpjQrbMRWQBgiBwXYEhtGUTaX+doCjBheluShdDMeR8IMfJiTqH4+zfhtg29apJf/8w==
+ dependencies:
+ "@jest/types" "^26.6.2"
+ "@types/graceful-fs" "^4.1.2"
+ "@types/node" "*"
+ anymatch "^3.0.3"
+ fb-watchman "^2.0.0"
+ graceful-fs "^4.2.4"
+ jest-regex-util "^26.0.0"
+ jest-serializer "^26.6.2"
+ jest-util "^26.6.2"
+ jest-worker "^26.6.2"
+ micromatch "^4.0.2"
+ sane "^4.0.3"
+ walker "^1.0.7"
+ optionalDependencies:
+ fsevents "^2.1.2"
+
+jest-haste-map@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-28.1.3.tgz#abd5451129a38d9841049644f34b034308944e2b"
+ integrity sha512-3S+RQWDXccXDKSWnkHa/dPwt+2qwA8CJzR61w3FoYCvoo3Pn8tvGcysmMF0Bj0EX5RYvAI2EIvC57OmotfdtKA==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ "@types/graceful-fs" "^4.1.3"
+ "@types/node" "*"
+ anymatch "^3.0.3"
+ fb-watchman "^2.0.0"
+ graceful-fs "^4.2.9"
+ jest-regex-util "^28.0.2"
+ jest-util "^28.1.3"
+ jest-worker "^28.1.3"
+ micromatch "^4.0.4"
+ walker "^1.0.8"
+ optionalDependencies:
+ fsevents "^2.3.2"
+
+jest-leak-detector@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-28.1.3.tgz#a6685d9b074be99e3adee816ce84fd30795e654d"
+ integrity sha512-WFVJhnQsiKtDEo5lG2mM0v40QWnBM+zMdHHyJs8AWZ7J0QZJS59MsyKeJHWhpBZBH32S48FOVvGyOFT1h0DlqA==
+ dependencies:
+ jest-get-type "^28.0.2"
+ pretty-format "^28.1.3"
+
+jest-matcher-utils@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-28.1.3.tgz#5a77f1c129dd5ba3b4d7fc20728806c78893146e"
+ integrity sha512-kQeJ7qHemKfbzKoGjHHrRKH6atgxMk8Enkk2iPQ3XwO6oE/KYD8lMYOziCkeSB9G4adPM4nR1DE8Tf5JeWH6Bw==
+ dependencies:
+ chalk "^4.0.0"
+ jest-diff "^28.1.3"
+ jest-get-type "^28.0.2"
+ pretty-format "^28.1.3"
+
+jest-message-util@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-28.1.3.tgz#232def7f2e333f1eecc90649b5b94b0055e7c43d"
+ integrity sha512-PFdn9Iewbt575zKPf1286Ht9EPoJmYT7P0kY+RibeYZ2XtOr53pDLEFoTWXbd1h4JiGiWpTBC84fc8xMXQMb7g==
+ dependencies:
+ "@babel/code-frame" "^7.12.13"
+ "@jest/types" "^28.1.3"
+ "@types/stack-utils" "^2.0.0"
+ chalk "^4.0.0"
+ graceful-fs "^4.2.9"
+ micromatch "^4.0.4"
+ pretty-format "^28.1.3"
+ slash "^3.0.0"
+ stack-utils "^2.0.3"
+
+jest-mock@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-28.1.3.tgz#d4e9b1fc838bea595c77ab73672ebf513ab249da"
+ integrity sha512-o3J2jr6dMMWYVH4Lh/NKmDXdosrsJgi4AviS8oXLujcjpCMBb1FMsblDnOXKZKfSiHLxYub1eS0IHuRXsio9eA==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+
+jest-pnp-resolver@^1.2.2:
+ version "1.2.2"
+ resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c"
+ integrity sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==
+
+jest-regex-util@^26.0.0:
+ version "26.0.0"
+ resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-26.0.0.tgz#d25e7184b36e39fd466c3bc41be0971e821fee28"
+ integrity sha512-Gv3ZIs/nA48/Zvjrl34bf+oD76JHiGDUxNOVgUjh3j890sblXryjY4rss71fPtD/njchl6PSE2hIhvyWa1eT0A==
+
+jest-regex-util@^28.0.2:
+ version "28.0.2"
+ resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-28.0.2.tgz#afdc377a3b25fb6e80825adcf76c854e5bf47ead"
+ integrity sha512-4s0IgyNIy0y9FK+cjoVYoxamT7Zeo7MhzqRGx7YDYmaQn1wucY9rotiGkBzzcMXTtjrCAP/f7f+E0F7+fxPNdw==
+
+jest-resolve-dependencies@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-28.1.3.tgz#8c65d7583460df7275c6ea2791901fa975c1fe66"
+ integrity sha512-qa0QO2Q0XzQoNPouMbCc7Bvtsem8eQgVPNkwn9LnS+R2n8DaVDPL/U1gngC0LTl1RYXJU0uJa2BMC2DbTfFrHA==
+ dependencies:
+ jest-regex-util "^28.0.2"
+ jest-snapshot "^28.1.3"
+
+jest-resolve@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-28.1.3.tgz#cfb36100341ddbb061ec781426b3c31eb51aa0a8"
+ integrity sha512-Z1W3tTjE6QaNI90qo/BJpfnvpxtaFTFw5CDgwpyE/Kz8U/06N1Hjf4ia9quUhCh39qIGWF1ZuxFiBiJQwSEYKQ==
+ dependencies:
+ chalk "^4.0.0"
+ graceful-fs "^4.2.9"
+ jest-haste-map "^28.1.3"
+ jest-pnp-resolver "^1.2.2"
+ jest-util "^28.1.3"
+ jest-validate "^28.1.3"
+ resolve "^1.20.0"
+ resolve.exports "^1.1.0"
+ slash "^3.0.0"
+
+jest-runner@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-28.1.3.tgz#5eee25febd730b4713a2cdfd76bdd5557840f9a1"
+ integrity sha512-GkMw4D/0USd62OVO0oEgjn23TM+YJa2U2Wu5zz9xsQB1MxWKDOlrnykPxnMsN0tnJllfLPinHTka61u0QhaxBA==
+ dependencies:
+ "@jest/console" "^28.1.3"
+ "@jest/environment" "^28.1.3"
+ "@jest/test-result" "^28.1.3"
+ "@jest/transform" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ emittery "^0.10.2"
+ graceful-fs "^4.2.9"
+ jest-docblock "^28.1.1"
+ jest-environment-node "^28.1.3"
+ jest-haste-map "^28.1.3"
+ jest-leak-detector "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-resolve "^28.1.3"
+ jest-runtime "^28.1.3"
+ jest-util "^28.1.3"
+ jest-watcher "^28.1.3"
+ jest-worker "^28.1.3"
+ p-limit "^3.1.0"
+ source-map-support "0.5.13"
+
+jest-runtime@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-28.1.3.tgz#a57643458235aa53e8ec7821949e728960d0605f"
+ integrity sha512-NU+881ScBQQLc1JHG5eJGU7Ui3kLKrmwCPPtYsJtBykixrM2OhVQlpMmFWJjMyDfdkGgBMNjXCGB/ebzsgNGQw==
+ dependencies:
+ "@jest/environment" "^28.1.3"
+ "@jest/fake-timers" "^28.1.3"
+ "@jest/globals" "^28.1.3"
+ "@jest/source-map" "^28.1.2"
+ "@jest/test-result" "^28.1.3"
+ "@jest/transform" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ chalk "^4.0.0"
+ cjs-module-lexer "^1.0.0"
+ collect-v8-coverage "^1.0.0"
+ execa "^5.0.0"
+ glob "^7.1.3"
+ graceful-fs "^4.2.9"
+ jest-haste-map "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-mock "^28.1.3"
+ jest-regex-util "^28.0.2"
+ jest-resolve "^28.1.3"
+ jest-snapshot "^28.1.3"
+ jest-util "^28.1.3"
+ slash "^3.0.0"
+ strip-bom "^4.0.0"
+
+jest-serializer@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/jest-serializer/-/jest-serializer-26.6.2.tgz#d139aafd46957d3a448f3a6cdabe2919ba0742d1"
+ integrity sha512-S5wqyz0DXnNJPd/xfIzZ5Xnp1HrJWBczg8mMfMpN78OJ5eDxXyf+Ygld9wX1DnUWbIbhM1YDY95NjR4CBXkb2g==
+ dependencies:
+ "@types/node" "*"
+ graceful-fs "^4.2.4"
+
+jest-snapshot@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-28.1.3.tgz#17467b3ab8ddb81e2f605db05583d69388fc0668"
+ integrity sha512-4lzMgtiNlc3DU/8lZfmqxN3AYD6GGLbl+72rdBpXvcV+whX7mDrREzkPdp2RnmfIiWBg1YbuFSkXduF2JcafJg==
+ dependencies:
+ "@babel/core" "^7.11.6"
+ "@babel/generator" "^7.7.2"
+ "@babel/plugin-syntax-typescript" "^7.7.2"
+ "@babel/traverse" "^7.7.2"
+ "@babel/types" "^7.3.3"
+ "@jest/expect-utils" "^28.1.3"
+ "@jest/transform" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/babel__traverse" "^7.0.6"
+ "@types/prettier" "^2.1.5"
+ babel-preset-current-node-syntax "^1.0.0"
+ chalk "^4.0.0"
+ expect "^28.1.3"
+ graceful-fs "^4.2.9"
+ jest-diff "^28.1.3"
+ jest-get-type "^28.0.2"
+ jest-haste-map "^28.1.3"
+ jest-matcher-utils "^28.1.3"
+ jest-message-util "^28.1.3"
+ jest-util "^28.1.3"
+ natural-compare "^1.4.0"
+ pretty-format "^28.1.3"
+ semver "^7.3.5"
+
+jest-util@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-26.6.2.tgz#907535dbe4d5a6cb4c47ac9b926f6af29576cbc1"
+ integrity sha512-MDW0fKfsn0OI7MS7Euz6h8HNDXVQ0gaM9uW6RjfDmd1DAFcaxX9OqIakHIqhbnmF08Cf2DLDG+ulq8YQQ0Lp0Q==
+ dependencies:
+ "@jest/types" "^26.6.2"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ graceful-fs "^4.2.4"
+ is-ci "^2.0.0"
+ micromatch "^4.0.2"
+
+jest-util@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-28.1.3.tgz#f4f932aa0074f0679943220ff9cbba7e497028b0"
+ integrity sha512-XdqfpHwpcSRko/C35uLYFM2emRAltIIKZiJ9eAmhjsj0CqZMa0p1ib0R5fWIqGhn1a103DebTbpqIaP1qCQ6tQ==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ chalk "^4.0.0"
+ ci-info "^3.2.0"
+ graceful-fs "^4.2.9"
+ picomatch "^2.2.3"
+
+jest-validate@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-28.1.3.tgz#e322267fd5e7c64cea4629612c357bbda96229df"
+ integrity sha512-SZbOGBWEsaTxBGCOpsRWlXlvNkvTkY0XxRfh7zYmvd8uL5Qzyg0CHAXiXKROflh801quA6+/DsT4ODDthOC/OA==
+ dependencies:
+ "@jest/types" "^28.1.3"
+ camelcase "^6.2.0"
+ chalk "^4.0.0"
+ jest-get-type "^28.0.2"
+ leven "^3.1.0"
+ pretty-format "^28.1.3"
+
+jest-watcher@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-28.1.3.tgz#c6023a59ba2255e3b4c57179fc94164b3e73abd4"
+ integrity sha512-t4qcqj9hze+jviFPUN3YAtAEeFnr/azITXQEMARf5cMwKY2SMBRnCQTXLixTl20OR6mLh9KLMrgVJgJISym+1g==
+ dependencies:
+ "@jest/test-result" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ "@types/node" "*"
+ ansi-escapes "^4.2.1"
+ chalk "^4.0.0"
+ emittery "^0.10.2"
+ jest-util "^28.1.3"
+ string-length "^4.0.1"
+
+jest-worker@^26.6.2:
+ version "26.6.2"
+ resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-26.6.2.tgz#7f72cbc4d643c365e27b9fd775f9d0eaa9c7a8ed"
+ integrity sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==
+ dependencies:
+ "@types/node" "*"
+ merge-stream "^2.0.0"
+ supports-color "^7.0.0"
+
+jest-worker@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-28.1.3.tgz#7e3c4ce3fa23d1bb6accb169e7f396f98ed4bb98"
+ integrity sha512-CqRA220YV/6jCo8VWvAt1KKx6eek1VIHMPeLEbpcfSfkEeWyBNppynM/o6q+Wmw+sOhos2ml34wZbSX3G13//g==
+ dependencies:
+ "@types/node" "*"
+ merge-stream "^2.0.0"
+ supports-color "^8.0.0"
+
+jest@^28:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/jest/-/jest-28.1.3.tgz#e9c6a7eecdebe3548ca2b18894a50f45b36dfc6b"
+ integrity sha512-N4GT5on8UkZgH0O5LUavMRV1EDEhNTL0KEfRmDIeZHSV7p2XgLoY9t9VDUgL6o+yfdgYHVxuz81G8oB9VG5uyA==
+ dependencies:
+ "@jest/core" "^28.1.3"
+ "@jest/types" "^28.1.3"
+ import-local "^3.0.2"
+ jest-cli "^28.1.3"
+
"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==
+js-yaml@^3.13.1:
+ version "3.14.1"
+ resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537"
+ integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==
+ dependencies:
+ argparse "^1.0.7"
+ esprima "^4.0.0"
+
js-yaml@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602"
@@ -1657,6 +3496,11 @@ jsesc@^2.5.1:
resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4"
integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==
+json-parse-even-better-errors@^2.3.0:
+ version "2.3.1"
+ resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d"
+ integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==
+
json-schema-traverse@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660"
@@ -1680,12 +3524,46 @@ json5@^2.2.1:
integrity sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==
"jsx-ast-utils@^2.4.1 || ^3.0.0":
- version "3.3.0"
- resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-3.3.0.tgz#e624f259143b9062c92b6413ff92a164c80d3ccb"
- integrity sha512-XzO9luP6L0xkxwhIJMTJQpZo/eeN60K08jHdexfD569AGxeNug6UketeHXEhROoM8aR7EcUoOQmIhcJQjcuq8Q==
+ version "3.3.3"
+ resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-3.3.3.tgz#76b3e6e6cece5c69d49a5792c3d01bd1a0cdc7ea"
+ integrity sha512-fYQHZTZ8jSfmWZ0iyzfwiU4WDX4HpHbMCZ3gPlWYiCl3BoeOTsqKBqnTVfH2rYT7eP5c3sVbeSPHnnJOaTrWiw==
dependencies:
- array-includes "^3.1.4"
- object.assign "^4.1.2"
+ array-includes "^3.1.5"
+ object.assign "^4.1.3"
+
+kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0:
+ version "3.2.2"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
+ integrity sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ==
+ dependencies:
+ is-buffer "^1.1.5"
+
+kind-of@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
+ integrity sha512-24XsCxmEbRwEDbz/qz3stgin8TTzZ1ESR56OMCN0ujYg+vRutNSiOj9bHH9u85DKgXguraugV5sFuvbD4FW/hw==
+ dependencies:
+ is-buffer "^1.1.5"
+
+kind-of@^5.0.0:
+ version "5.1.0"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d"
+ integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==
+
+kind-of@^6.0.0, kind-of@^6.0.2:
+ version "6.0.3"
+ resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd"
+ integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==
+
+kleur@^3.0.3:
+ version "3.0.3"
+ resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
+ integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==
+
+leven@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2"
+ integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==
levn@^0.4.1:
version "0.4.1"
@@ -1695,13 +3573,10 @@ levn@^0.4.1:
prelude-ls "^1.2.1"
type-check "~0.4.0"
-locate-path@^2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e"
- integrity sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==
- dependencies:
- p-locate "^2.0.0"
- path-exists "^3.0.0"
+lines-and-columns@^1.1.6:
+ version "1.2.4"
+ resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632"
+ integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==
locate-path@^5.0.0:
version "5.0.0"
@@ -1710,23 +3585,100 @@ locate-path@^5.0.0:
dependencies:
p-locate "^4.1.0"
+locate-path@^6.0.0:
+ version "6.0.0"
+ resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286"
+ integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==
+ dependencies:
+ p-locate "^5.0.0"
+
lodash.merge@^4.6.2:
version "4.6.2"
resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"
integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==
-loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.4.0:
+lodash@^4:
+ version "4.17.21"
+ resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
+ integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
+
+loose-envify@^1.1.0, loose-envify@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"
integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==
dependencies:
js-tokens "^3.0.0 || ^4.0.0"
+lru-cache@^6.0.0:
+ version "6.0.0"
+ resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
+ integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
+ dependencies:
+ yallist "^4.0.0"
+
+make-dir@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f"
+ integrity sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==
+ dependencies:
+ semver "^6.0.0"
+
+makeerror@1.0.12:
+ version "1.0.12"
+ resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.12.tgz#3e5dd2079a82e812e983cc6610c4a2cb0eaa801a"
+ integrity sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==
+ dependencies:
+ tmpl "1.0.5"
+
+map-cache@^0.2.2:
+ version "0.2.2"
+ resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf"
+ integrity sha512-8y/eV9QQZCiyn1SprXSrCmqJN0yNRATe+PO8ztwqrvrbdRLA3eYJF0yaR0YayLWkMbsQSKWS9N2gPcGEc4UsZg==
+
+map-visit@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f"
+ integrity sha512-4y7uGv8bd2WdM9vpQsiQNo41Ln1NvhvDRuVt0k2JZQ+ezN2uaQes7lZeZ+QQUHOLQAtDaBJ+7wCbi+ab/KFs+w==
+ dependencies:
+ object-visit "^1.0.0"
+
merge-stream@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"
integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==
+merge2@^1.3.0, merge2@^1.4.1:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"
+ integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==
+
+micromatch@^3.1.4:
+ version "3.1.10"
+ resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23"
+ integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==
+ dependencies:
+ arr-diff "^4.0.0"
+ array-unique "^0.3.2"
+ braces "^2.3.1"
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ extglob "^2.0.4"
+ fragment-cache "^0.2.1"
+ kind-of "^6.0.2"
+ nanomatch "^1.2.9"
+ object.pick "^1.3.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.2"
+
+micromatch@^4.0.2, micromatch@^4.0.4:
+ version "4.0.5"
+ resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6"
+ integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==
+ dependencies:
+ braces "^3.0.2"
+ picomatch "^2.3.1"
+
mimic-fn@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b"
@@ -1739,11 +3691,19 @@ minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.2:
dependencies:
brace-expansion "^1.1.7"
-minimist@^1.2.0, minimist@^1.2.6:
+minimist@^1.1.1, minimist@^1.2.0, minimist@^1.2.6:
version "1.2.6"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44"
integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==
+mixin-deep@^1.2.0:
+ version "1.3.2"
+ resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566"
+ integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==
+ dependencies:
+ for-in "^1.0.2"
+ is-extendable "^1.0.1"
+
mri@^1.1.5:
version "1.2.0"
resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b"
@@ -1780,17 +3740,63 @@ nanoid@^3.3.4:
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.4.tgz#730b67e3cd09e2deacf03c027c81c9d9dbc5e8ab"
integrity sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==
+nanomatch@^1.2.9:
+ version "1.2.13"
+ resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
+ integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==
+ dependencies:
+ arr-diff "^4.0.0"
+ array-unique "^0.3.2"
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ fragment-cache "^0.2.1"
+ is-windows "^1.0.2"
+ kind-of "^6.0.2"
+ object.pick "^1.3.0"
+ regex-not "^1.0.0"
+ snapdragon "^0.8.1"
+ to-regex "^3.0.1"
+
natural-compare@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==
-node-releases@^2.0.5:
- version "2.0.5"
- resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.5.tgz#280ed5bc3eba0d96ce44897d8aee478bfb3d9666"
- integrity sha512-U9h1NLROZTq9uE1SNffn6WuPDg8icmi3ns4rEl/oTfIle4iLjTliCzgTsbaIFMq/Xn078/lfY/BL0GWZ+psK4Q==
+nice-try@^1.0.4:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"
+ integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==
+
+node-int64@^0.4.0:
+ version "0.4.0"
+ resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"
+ integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==
+
+node-releases@^2.0.6:
+ version "2.0.6"
+ resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503"
+ integrity sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==
+
+normalize-path@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9"
+ integrity sha512-3pKJwH184Xo/lnH6oyP1q2pMd7HcypqqmRs91/6/i2CGtWwIKGCkOOMTm/zXbgTEWHw1uNpNi/igc3ePOYHb6w==
+ dependencies:
+ remove-trailing-separator "^1.0.1"
+
+normalize-path@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65"
+ integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==
+
+npm-run-path@^2.0.0:
+ version "2.0.2"
+ resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f"
+ integrity sha512-lJxZYlT4DW/bRUtFh1MQIWqmLwQfAxnqWG4HhEdjMlkrJYnJn0Jrr2u3mgxqaWsdiBc76TYkTG/mhrnYTuzfHw==
+ dependencies:
+ path-key "^2.0.0"
-npm-run-path@^4.0.0:
+npm-run-path@^4.0.0, npm-run-path@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea"
integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==
@@ -1802,6 +3808,15 @@ object-assign@^4.1.1:
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==
+object-copy@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c"
+ integrity sha512-79LYn6VAb63zgtmAteVOWo9Vdj71ZVBy3Pbse+VqxDpEP83XuujMrGqHIwAXJ5I/aM0zU7dIyIAhifVTPrNItQ==
+ dependencies:
+ copy-descriptor "^0.1.0"
+ define-property "^0.2.5"
+ kind-of "^3.0.3"
+
object-inspect@^1.12.0, object-inspect@^1.9.0:
version "1.12.2"
resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.2.tgz#c0641f26394532f28ab8d796ab954e43c009a8ea"
@@ -1812,14 +3827,21 @@ object-keys@^1.1.1:
resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e"
integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==
-object.assign@^4.1.2:
- version "4.1.2"
- resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.2.tgz#0ed54a342eceb37b38ff76eb831a0e788cb63940"
- integrity sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==
+object-visit@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb"
+ integrity sha512-GBaMwwAVK9qbQN3Scdo0OyvgPW7l3lnaVMj84uTOZlswkX0KpF6fyDBJhtTthf7pymztoN36/KEr1DyhF96zEA==
dependencies:
- call-bind "^1.0.0"
- define-properties "^1.1.3"
- has-symbols "^1.0.1"
+ isobject "^3.0.0"
+
+object.assign@^4.1.0, object.assign@^4.1.2, object.assign@^4.1.3:
+ version "4.1.3"
+ resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.3.tgz#d36b7700ddf0019abb6b1df1bb13f6445f79051f"
+ integrity sha512-ZFJnX3zltyjcYJL0RoCJuzb+11zWGyaDbjgxZbdV7rFEcHQuYxrZqhow67aA7xpes6LhojyFDaBKAFfogQrikA==
+ dependencies:
+ call-bind "^1.0.2"
+ define-properties "^1.1.4"
+ has-symbols "^1.0.3"
object-keys "^1.1.1"
object.entries@^1.1.5:
@@ -1848,6 +3870,13 @@ object.hasown@^1.1.1:
define-properties "^1.1.4"
es-abstract "^1.19.5"
+object.pick@^1.3.0:
+ version "1.3.0"
+ resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747"
+ integrity sha512-tqa/UMy/CCoYmj+H5qc07qvSL9dqcs/WZENZ1JbtWBlATP+iVOe778gE6MSijnyCnORzDuX6hU+LA4SZ09YjFQ==
+ dependencies:
+ isobject "^3.0.1"
+
object.values@^1.1.5:
version "1.1.5"
resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.5.tgz#959f63e3ce9ef108720333082131e4a459b716ac"
@@ -1864,7 +3893,7 @@ once@^1.3.0, once@^1.3.1, once@^1.4.0:
dependencies:
wrappy "1"
-onetime@^5.1.0:
+onetime@^5.1.0, onetime@^5.1.2:
version "5.1.2"
resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e"
integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==
@@ -1883,12 +3912,10 @@ optionator@^0.9.1:
type-check "^0.4.0"
word-wrap "^1.2.3"
-p-limit@^1.1.0:
- version "1.3.0"
- resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8"
- integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==
- dependencies:
- p-try "^1.0.0"
+p-finally@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae"
+ integrity sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==
p-limit@^2.2.0:
version "2.3.0"
@@ -1897,12 +3924,12 @@ p-limit@^2.2.0:
dependencies:
p-try "^2.0.0"
-p-locate@^2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43"
- integrity sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==
+p-limit@^3.0.2, p-limit@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b"
+ integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==
dependencies:
- p-limit "^1.1.0"
+ yocto-queue "^0.1.0"
p-locate@^4.1.0:
version "4.1.0"
@@ -1911,10 +3938,12 @@ p-locate@^4.1.0:
dependencies:
p-limit "^2.2.0"
-p-try@^1.0.0:
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3"
- integrity sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww==
+p-locate@^5.0.0:
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834"
+ integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==
+ dependencies:
+ p-limit "^3.0.2"
p-try@^2.0.0:
version "2.2.0"
@@ -1928,10 +3957,20 @@ parent-module@^1.0.0:
dependencies:
callsites "^3.0.0"
-path-exists@^3.0.0:
- version "3.0.0"
- resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515"
- integrity sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==
+parse-json@^5.0.0, parse-json@^5.2.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd"
+ integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==
+ dependencies:
+ "@babel/code-frame" "^7.0.0"
+ error-ex "^1.3.1"
+ json-parse-even-better-errors "^2.3.0"
+ lines-and-columns "^1.1.6"
+
+pascalcase@^0.1.1:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14"
+ integrity sha512-XHXfu/yOQRy9vYOtUDVMN60OEJjW013GoObG1o+xwQTpB9eYJX/BjXMsdW13ZDPruFhYYn0AG22w0xgQMwl3Nw==
path-exists@^4.0.0:
version "4.0.0"
@@ -1943,6 +3982,11 @@ path-is-absolute@^1.0.0:
resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==
+path-key@^2.0.0, path-key@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40"
+ integrity sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==
+
path-key@^3.0.0, path-key@^3.1.0:
version "3.1.1"
resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375"
@@ -1953,20 +3997,42 @@ path-parse@^1.0.7:
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"
integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==
+path-type@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"
+ integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==
+
picocolors@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c"
integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==
-picomatch@^2.2.2:
+picomatch@^2.0.4, picomatch@^2.2.2, picomatch@^2.2.3, picomatch@^2.3.1:
version "2.3.1"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42"
integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==
+pirates@^4.0.1, pirates@^4.0.4:
+ version "4.0.5"
+ resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.5.tgz#feec352ea5c3268fb23a37c702ab1699f35a5f3b"
+ integrity sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==
+
+pkg-dir@^4.2.0:
+ version "4.2.0"
+ resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3"
+ integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==
+ dependencies:
+ find-up "^4.0.0"
+
+posix-character-classes@^0.1.0:
+ version "0.1.1"
+ resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
+ integrity sha512-xTgYBc3fuo7Yt7JbiuFxSYGToMoz8fLoE6TC9Wx1P/u+LfeThMOAqmuyECnlBaaJb+u1m9hHiXUEtwW4OzfUJg==
+
postcss@^8.4.13:
- version "8.4.14"
- resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.14.tgz#ee9274d5622b4858c1007a74d76e42e56fd21caf"
- integrity sha512-E398TUmfAYFPBSdzgeieK2Y1+1cpdxJx8yXbK/m57nRhKSmk1GB2tO4lbLBtlkfPQTDKfe4Xqv1ASWPpayPEig==
+ version "8.4.16"
+ resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.16.tgz#33a1d675fac39941f5f445db0de4db2b6e01d43c"
+ integrity sha512-ipHE1XBvKzm5xI7hiHCZJCSugxvsdq2mPnsq5+UF+VHCjiBvtDrlxJfMBToWaP9D5XlgNmcFGqoHmUn0EYEaRQ==
dependencies:
nanoid "^3.3.4"
picocolors "^1.0.0"
@@ -1989,6 +4055,16 @@ prettier@2:
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.7.1.tgz#e235806850d057f97bb08368a4f7d899f7760c64"
integrity sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==
+pretty-format@^28.1.3:
+ version "28.1.3"
+ resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-28.1.3.tgz#c9fba8cedf99ce50963a11b27d982a9ae90970d5"
+ integrity sha512-8gFb/To0OmxHR9+ZTb14Df2vNxdGCX8g1xWGUTqUw5TiZvcQf5sHKObd5UcPyLLyowNwDAMTF3XWOG1B6mxl1Q==
+ dependencies:
+ "@jest/schemas" "^28.1.3"
+ ansi-regex "^5.0.1"
+ ansi-styles "^5.0.0"
+ react-is "^18.0.0"
+
pretty-quick@^3:
version "3.1.3"
resolved "https://registry.yarnpkg.com/pretty-quick/-/pretty-quick-3.1.3.tgz#15281108c0ddf446675157ca40240099157b638e"
@@ -2001,7 +4077,15 @@ pretty-quick@^3:
mri "^1.1.5"
multimatch "^4.0.0"
-prop-types@^15.6.1, prop-types@^15.8.1:
+prompts@^2.0.1:
+ version "2.4.2"
+ resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069"
+ integrity sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==
+ dependencies:
+ kleur "^3.0.3"
+ sisteransi "^1.0.5"
+
+prop-types@^15.6.2, prop-types@^15.8.1:
version "15.8.1"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5"
integrity sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==
@@ -2023,6 +4107,11 @@ punycode@^2.1.0:
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
+queue-microtask@^1.2.2:
+ version "1.2.3"
+ resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"
+ integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==
+
react-dom@^18:
version "18.2.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.2.0.tgz#22aaf38708db2674ed9ada224ca4aa708d821e3d"
@@ -2031,35 +4120,37 @@ react-dom@^18:
loose-envify "^1.1.0"
scheduler "^0.23.0"
-react-fast-compare@^3.0.1:
- version "3.2.0"
- resolved "https://registry.yarnpkg.com/react-fast-compare/-/react-fast-compare-3.2.0.tgz#641a9da81b6a6320f270e89724fb45a0b39e43bb"
- integrity sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA==
-
react-is@^16.13.1, react-is@^16.7.0:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==
-react-lifecycles-compat@^3.0.4:
- version "3.0.4"
- resolved "https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz#4f1a273afdfc8f3488a8c516bfda78f872352362"
- integrity sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==
-
-react-popper@^2.2.5:
- version "2.3.0"
- resolved "https://registry.yarnpkg.com/react-popper/-/react-popper-2.3.0.tgz#17891c620e1320dce318bad9fede46a5f71c70ba"
- integrity sha512-e1hj8lL3uM+sgSR4Lxzn5h1GxBlpa4CQz0XLF8kx4MDrDRWY0Ena4c97PUeSX9i5W3UAfDP0z0FXCTQkoXUl3Q==
- dependencies:
- react-fast-compare "^3.0.1"
- warning "^4.0.2"
+react-is@^18.0.0:
+ version "18.2.0"
+ resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.2.0.tgz#199431eeaaa2e09f86427efbb4f1473edb47609b"
+ integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==
react-refresh@^0.13.0:
version "0.13.0"
resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.13.0.tgz#cbd01a4482a177a5da8d44c9755ebb1f26d5a1c1"
integrity sha512-XP8A9BT0CpRBD+NYLLeIhld/RqG9+gktUjW1FkE+Vm7OCinbG1SshcK5tb9ls4kzvjZr9mOQc7HYgBngEyPAXg==
-react-textarea-autosize@^8.3.2:
+react-router-dom@^6:
+ version "6.3.0"
+ resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.3.0.tgz#a0216da813454e521905b5fa55e0e5176123f43d"
+ integrity sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw==
+ dependencies:
+ history "^5.2.0"
+ react-router "6.3.0"
+
+react-router@6.3.0:
+ version "6.3.0"
+ resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.3.0.tgz#3970cc64b4cb4eae0c1ea5203a80334fdd175557"
+ integrity sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==
+ dependencies:
+ history "^5.2.0"
+
+react-textarea-autosize@8.3.4:
version "8.3.4"
resolved "https://registry.yarnpkg.com/react-textarea-autosize/-/react-textarea-autosize-8.3.4.tgz#270a343de7ad350534141b02c9cb78903e553524"
integrity sha512-CdtmP8Dc19xL8/R6sWvtknD/eCXkQr30dtvC4VmGInhRsfF8X/ihXCq6+9l9qbxmKRiq407/7z5fxE7cVWQNgQ==
@@ -2068,6 +4159,16 @@ react-textarea-autosize@^8.3.2:
use-composed-ref "^1.3.0"
use-latest "^1.2.1"
+react-transition-group@4.4.2:
+ version "4.4.2"
+ resolved "https://registry.yarnpkg.com/react-transition-group/-/react-transition-group-4.4.2.tgz#8b59a56f09ced7b55cbd53c36768b922890d5470"
+ integrity sha512-/RNYfRAMlZwDSr6z4zNKV6xu53/e2BuaBbGhbyYIXTrmgu/bGHzmqOs7mJSJBHy9Ud+ApHx3QjrkKSp1pxvlFg==
+ dependencies:
+ "@babel/runtime" "^7.5.5"
+ dom-helpers "^5.0.1"
+ loose-envify "^1.4.0"
+ prop-types "^15.6.2"
+
react@^18:
version "18.2.0"
resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5"
@@ -2080,6 +4181,14 @@ regenerator-runtime@^0.13.4:
resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz#8925742a98ffd90814988d7566ad30ca3b263b52"
integrity sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==
+regex-not@^1.0.0, regex-not@^1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c"
+ integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==
+ dependencies:
+ extend-shallow "^3.0.2"
+ safe-regex "^1.1.0"
+
regexp.prototype.flags@^1.4.1, regexp.prototype.flags@^1.4.3:
version "1.4.3"
resolved "https://registry.yarnpkg.com/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz#87cab30f80f66660181a3bb7bf5981a872b367ac"
@@ -2094,12 +4203,54 @@ regexpp@^3.2.0:
resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2"
integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==
+remove-trailing-separator@^1.0.1:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef"
+ integrity sha512-/hS+Y0u3aOfIETiaiirUFwDBDzmXPvO+jAfKTitUngIPzdKc6Z0LoFjM/CK5PL4C+eKwHohlHAb6H0VFfmmUsw==
+
+repeat-element@^1.1.2:
+ version "1.1.4"
+ resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.4.tgz#be681520847ab58c7568ac75fbfad28ed42d39e9"
+ integrity sha512-LFiNfRcSu7KK3evMyYOuCzv3L10TW7yC1G2/+StMjK8Y6Vqd2MG7r/Qjw4ghtuCOjFvlnms/iMmLqpvW/ES/WQ==
+
+repeat-string@^1.6.1:
+ version "1.6.1"
+ resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
+ integrity sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==
+
+require-directory@^2.1.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
+ integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==
+
+resolve-cwd@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d"
+ integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==
+ dependencies:
+ resolve-from "^5.0.0"
+
resolve-from@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6"
integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==
-resolve@^1.20.0:
+resolve-from@^5.0.0:
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69"
+ integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==
+
+resolve-url@^0.2.1:
+ version "0.2.1"
+ resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a"
+ integrity sha512-ZuF55hVUQaaczgOIwqWzkEcEidmlD/xl44x1UZnhOXcYuFN2S6+rcxpG+C1N3So0wvNI3DmJICUFfu2SxhBmvg==
+
+resolve.exports@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/resolve.exports/-/resolve.exports-1.1.0.tgz#5ce842b94b05146c0e03076985d1d0e7e48c90c9"
+ integrity sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==
+
+resolve@^1.19.0, resolve@^1.20.0, resolve@^1.22.0:
version "1.22.1"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177"
integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==
@@ -2108,15 +4259,6 @@ resolve@^1.20.0:
path-parse "^1.0.7"
supports-preserve-symlinks-flag "^1.0.0"
-resolve@^1.22.0:
- version "1.22.0"
- resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.0.tgz#5e0b8c67c15df57a89bdbabe603a002f21731198"
- integrity sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==
- dependencies:
- is-core-module "^2.8.1"
- path-parse "^1.0.7"
- supports-preserve-symlinks-flag "^1.0.0"
-
resolve@^2.0.0-next.3:
version "2.0.0-next.4"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-2.0.0-next.4.tgz#3d37a113d6429f496ec4752d2a2e58efb1fd4660"
@@ -2126,25 +4268,69 @@ resolve@^2.0.0-next.3:
path-parse "^1.0.7"
supports-preserve-symlinks-flag "^1.0.0"
-rimraf@^3.0.2:
+ret@~0.1.10:
+ version "0.1.15"
+ resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc"
+ integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==
+
+reusify@^1.0.4:
+ version "1.0.4"
+ resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76"
+ integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==
+
+rimraf@^3.0.0, rimraf@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==
dependencies:
glob "^7.1.3"
-rollup@^2.59.0:
- version "2.75.6"
- resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.75.6.tgz#ac4dc8600f95942a0180f61c7c9d6200e374b439"
- integrity sha512-OEf0TgpC9vU6WGROJIk1JA3LR5vk/yvqlzxqdrE2CzzXnqKXNzbAwlWUXis8RS3ZPe7LAq+YUxsRa0l3r27MLA==
+"rollup@>=2.59.0 <2.78.0":
+ version "2.77.3"
+ resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.77.3.tgz#8f00418d3a2740036e15deb653bed1a90ee0cc12"
+ integrity sha512-/qxNTG7FbmefJWoeeYJFbHehJ2HNWnjkAFRKzWN/45eNBBF/r8lo992CwcJXEzyVxs5FmfId+vTSTQDb+bxA+g==
optionalDependencies:
fsevents "~2.3.2"
+rsvp@^4.8.4:
+ version "4.8.5"
+ resolved "https://registry.yarnpkg.com/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734"
+ integrity sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA==
+
+run-parallel@^1.1.9:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee"
+ integrity sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==
+ dependencies:
+ queue-microtask "^1.2.2"
+
safe-buffer@~5.1.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==
+safe-regex@^1.1.0:
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e"
+ integrity sha512-aJXcif4xnaNUzvUuC5gcb46oTS7zvg4jpMTnuqtrEPlR3vFr4pxtdTwaF1Qs3Enjn9HK+ZlwQui+a7z0SywIzg==
+ dependencies:
+ ret "~0.1.10"
+
+sane@^4.0.3:
+ version "4.1.0"
+ resolved "https://registry.yarnpkg.com/sane/-/sane-4.1.0.tgz#ed881fd922733a6c461bc189dc2b6c006f3ffded"
+ integrity sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==
+ dependencies:
+ "@cnakazawa/watch" "^1.0.3"
+ anymatch "^2.0.0"
+ capture-exit "^2.0.0"
+ exec-sh "^0.3.2"
+ execa "^1.0.0"
+ fb-watchman "^2.0.0"
+ micromatch "^3.1.4"
+ minimist "^1.1.1"
+ walker "~1.0.5"
+
scheduler@^0.23.0:
version "0.23.0"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.23.0.tgz#ba8041afc3d30eb206a487b6b384002e4e61fdfe"
@@ -2152,11 +4338,40 @@ scheduler@^0.23.0:
dependencies:
loose-envify "^1.1.0"
-semver@^6.3.0:
+semver@^5.5.0:
+ version "5.7.1"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
+ integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==
+
+semver@^6.0.0, semver@^6.3.0:
version "6.3.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d"
integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==
+semver@^7.3.5:
+ version "7.3.7"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.7.tgz#12c5b649afdbf9049707796e22a4028814ce523f"
+ integrity sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==
+ dependencies:
+ lru-cache "^6.0.0"
+
+set-value@^2.0.0, set-value@^2.0.1:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b"
+ integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==
+ dependencies:
+ extend-shallow "^2.0.1"
+ is-extendable "^0.1.1"
+ is-plain-object "^2.0.3"
+ split-string "^3.0.1"
+
+shebang-command@^1.2.0:
+ version "1.2.0"
+ resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea"
+ integrity sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==
+ dependencies:
+ shebang-regex "^1.0.0"
+
shebang-command@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea"
@@ -2164,6 +4379,11 @@ shebang-command@^2.0.0:
dependencies:
shebang-regex "^3.0.0"
+shebang-regex@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3"
+ integrity sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==
+
shebang-regex@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172"
@@ -2178,16 +4398,134 @@ side-channel@^1.0.4:
get-intrinsic "^1.0.2"
object-inspect "^1.9.0"
-signal-exit@^3.0.2:
+signal-exit@^3.0.0, signal-exit@^3.0.2, signal-exit@^3.0.3, signal-exit@^3.0.7:
version "3.0.7"
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9"
integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==
+sisteransi@^1.0.5:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed"
+ integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==
+
+slash@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634"
+ integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==
+
+snapdragon-node@^2.0.1:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
+ integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==
+ dependencies:
+ define-property "^1.0.0"
+ isobject "^3.0.0"
+ snapdragon-util "^3.0.1"
+
+snapdragon-util@^3.0.1:
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2"
+ integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==
+ dependencies:
+ kind-of "^3.2.0"
+
+snapdragon@^0.8.1:
+ version "0.8.2"
+ resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d"
+ integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==
+ dependencies:
+ base "^0.11.1"
+ debug "^2.2.0"
+ define-property "^0.2.5"
+ extend-shallow "^2.0.1"
+ map-cache "^0.2.2"
+ source-map "^0.5.6"
+ source-map-resolve "^0.5.0"
+ use "^3.1.0"
+
source-map-js@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c"
integrity sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==
+source-map-resolve@^0.5.0:
+ version "0.5.3"
+ resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a"
+ integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==
+ dependencies:
+ atob "^2.1.2"
+ decode-uri-component "^0.2.0"
+ resolve-url "^0.2.1"
+ source-map-url "^0.4.0"
+ urix "^0.1.0"
+
+source-map-support@0.5.13:
+ version "0.5.13"
+ resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932"
+ integrity sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==
+ dependencies:
+ buffer-from "^1.0.0"
+ source-map "^0.6.0"
+
+source-map-url@^0.4.0:
+ version "0.4.1"
+ resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.1.tgz#0af66605a745a5a2f91cf1bbf8a7afbc283dec56"
+ integrity sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw==
+
+source-map@^0.5.6, source-map@^0.5.7:
+ version "0.5.7"
+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
+ integrity sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==
+
+source-map@^0.6.0, source-map@^0.6.1:
+ version "0.6.1"
+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
+ integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
+
+split-string@^3.0.1, split-string@^3.0.2:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2"
+ integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==
+ dependencies:
+ extend-shallow "^3.0.0"
+
+sprintf-js@~1.0.2:
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
+ integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==
+
+stack-utils@^2.0.3:
+ version "2.0.5"
+ resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-2.0.5.tgz#d25265fca995154659dbbfba3b49254778d2fdd5"
+ integrity sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==
+ dependencies:
+ escape-string-regexp "^2.0.0"
+
+static-extend@^0.1.1:
+ version "0.1.2"
+ resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6"
+ integrity sha512-72E9+uLc27Mt718pMHt9VMNiAL4LMsmDbBva8mxWUCkT07fSzEGMYUCk0XWY6lp0j6RBAG4cJ3mWuZv2OE3s0g==
+ dependencies:
+ define-property "^0.2.5"
+ object-copy "^0.1.0"
+
+string-length@^4.0.1:
+ version "4.0.2"
+ resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a"
+ integrity sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==
+ dependencies:
+ char-regex "^1.0.2"
+ strip-ansi "^6.0.0"
+
+string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
+ version "4.2.3"
+ resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
+ integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
+ dependencies:
+ emoji-regex "^8.0.0"
+ is-fullwidth-code-point "^3.0.0"
+ strip-ansi "^6.0.1"
+
string.prototype.matchall@^4.0.7:
version "4.0.7"
resolved "https://registry.yarnpkg.com/string.prototype.matchall/-/string.prototype.matchall-4.0.7.tgz#8e6ecb0d8a1fb1fda470d81acecb2dba057a481d"
@@ -2220,7 +4558,7 @@ string.prototype.trimstart@^1.0.5:
define-properties "^1.1.4"
es-abstract "^1.19.5"
-strip-ansi@^6.0.1:
+strip-ansi@^6.0.0, strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
@@ -2232,6 +4570,16 @@ strip-bom@^3.0.0:
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
integrity sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==
+strip-bom@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878"
+ integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==
+
+strip-eof@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf"
+ integrity sha512-7FCwGGmx8mD5xQd3RPUvnSpUXHM3BWuzjtpD4TXsfcZ9EL4azvVVUscFYwD9nx8Kh+uCBC00XBtAykoMHwTh8Q==
+
strip-final-newline@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad"
@@ -2254,28 +4602,97 @@ supports-color@^5.3.0:
dependencies:
has-flag "^3.0.0"
-supports-color@^7.1.0:
+supports-color@^7.0.0, supports-color@^7.1.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da"
integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==
dependencies:
has-flag "^4.0.0"
+supports-color@^8.0.0:
+ version "8.1.1"
+ resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c"
+ integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==
+ dependencies:
+ has-flag "^4.0.0"
+
+supports-hyperlinks@^2.0.0:
+ version "2.2.0"
+ resolved "https://registry.yarnpkg.com/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz#4f77b42488765891774b70c79babd87f9bd594bb"
+ integrity sha512-6sXEzV5+I5j8Bmq9/vUphGRM/RJNT9SCURJLjwfOg51heRtguGWDzcaBlgAzKhQa0EVNpPEKzQuBwZ8S8WaCeQ==
+ dependencies:
+ has-flag "^4.0.0"
+ supports-color "^7.0.0"
+
supports-preserve-symlinks-flag@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09"
integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==
+terminal-link@^2.0.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/terminal-link/-/terminal-link-2.1.1.tgz#14a64a27ab3c0df933ea546fba55f2d078edc994"
+ integrity sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==
+ dependencies:
+ ansi-escapes "^4.2.1"
+ supports-hyperlinks "^2.0.0"
+
+test-exclude@^6.0.0:
+ version "6.0.0"
+ resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e"
+ integrity sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==
+ dependencies:
+ "@istanbuljs/schema" "^0.1.2"
+ glob "^7.1.4"
+ minimatch "^3.0.4"
+
text-table@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==
+tmpl@1.0.5:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.5.tgz#8683e0b902bb9c20c4f726e3c0b69f36518c07cc"
+ integrity sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==
+
to-fast-properties@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz#dc5e698cbd079265bc73e0377681a4e4e83f616e"
integrity sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==
+to-object-path@^0.3.0:
+ version "0.3.0"
+ resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af"
+ integrity sha512-9mWHdnGRuh3onocaHzukyvCZhzvr6tiflAy/JRFXcJX0TjgfWA9pk9t8CMbzmBE4Jfw58pXbkngtBtqYxzNEyg==
+ dependencies:
+ kind-of "^3.0.2"
+
+to-regex-range@^2.1.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38"
+ integrity sha512-ZZWNfCjUokXXDGXFpZehJIkZqq91BcULFq/Pi7M5i4JnxXdhMKAK682z8bCW3o8Hj1wuuzoKcW3DfVzaP6VuNg==
+ dependencies:
+ is-number "^3.0.0"
+ repeat-string "^1.6.1"
+
+to-regex-range@^5.0.1:
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4"
+ integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==
+ dependencies:
+ is-number "^7.0.0"
+
+to-regex@^3.0.1, to-regex@^3.0.2:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce"
+ integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==
+ dependencies:
+ define-property "^2.0.2"
+ extend-shallow "^3.0.2"
+ regex-not "^1.0.2"
+ safe-regex "^1.1.0"
+
tsconfig-paths@^3.14.1:
version "3.14.1"
resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz#ba0734599e8ea36c862798e920bcf163277b137a"
@@ -2286,6 +4703,11 @@ tsconfig-paths@^3.14.1:
minimist "^1.2.6"
strip-bom "^3.0.0"
+tslib@^1.0.0:
+ version "1.14.1"
+ resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
+ integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
+
type-check@^0.4.0, type-check@~0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1"
@@ -2293,11 +4715,28 @@ type-check@^0.4.0, type-check@~0.4.0:
dependencies:
prelude-ls "^1.2.1"
+type-detect@4.0.8:
+ version "4.0.8"
+ resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
+ integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==
+
type-fest@^0.20.2:
version "0.20.2"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4"
integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==
+type-fest@^0.21.3:
+ version "0.21.3"
+ resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37"
+ integrity sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==
+
+typedarray-to-buffer@^3.1.5:
+ version "3.1.5"
+ resolved "https://registry.yarnpkg.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz#a97ee7a9ff42691b9f783ff1bc5112fe3fca9080"
+ integrity sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==
+ dependencies:
+ is-typedarray "^1.0.0"
+
unbox-primitive@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/unbox-primitive/-/unbox-primitive-1.0.2.tgz#29032021057d5e6cdbd08c5129c226dff8ed6f9e"
@@ -2308,6 +4747,32 @@ unbox-primitive@^1.0.2:
has-symbols "^1.0.3"
which-boxed-primitive "^1.0.2"
+union-value@^1.0.0:
+ version "1.0.1"
+ resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847"
+ integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==
+ dependencies:
+ arr-union "^3.1.0"
+ get-value "^2.0.6"
+ is-extendable "^0.1.1"
+ set-value "^2.0.1"
+
+unset-value@^1.0.0:
+ version "1.0.0"
+ resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559"
+ integrity sha512-PcA2tsuGSF9cnySLHTLSh2qrQiJ70mn+r+Glzxv2TWZblxsxCC52BDlZoPCsz7STd9pN7EZetkWZBAvk4cgZdQ==
+ dependencies:
+ has-value "^0.3.1"
+ isobject "^3.0.0"
+
+update-browserslist-db@^1.0.5:
+ version "1.0.5"
+ resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38"
+ integrity sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q==
+ dependencies:
+ escalade "^3.1.1"
+ picocolors "^1.0.0"
+
uri-js@^4.2.2:
version "4.4.1"
resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e"
@@ -2315,11 +4780,21 @@ uri-js@^4.2.2:
dependencies:
punycode "^2.1.0"
+urix@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72"
+ integrity sha512-Am1ousAhSLBeB9cG/7k7r2R0zj50uDRlZHPGbazid5s9rlF1F/QKYObEKSIunSjIOkJZqwRRLpvewjEkM7pSqg==
+
use-composed-ref@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/use-composed-ref/-/use-composed-ref-1.3.0.tgz#3d8104db34b7b264030a9d916c5e94fbe280dbda"
integrity sha512-GLMG0Jc/jiKov/3Ulid1wbv3r54K9HlMW29IWcDFPEqFkSO2nS0MuefWgMJpeHQ9YJeXDL3ZUF+P3jdXlZX/cQ==
+use-context-selector@^1:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/use-context-selector/-/use-context-selector-1.4.1.tgz#eb96279965846b72915d7f899b8e6ef1d768b0ae"
+ integrity sha512-Io2ArvcRO+6MWIhkdfMFt+WKQX+Vb++W8DS2l03z/Vw/rz3BclKpM0ynr4LYGyU85Eke+Yx5oIhTY++QR0ZDoA==
+
use-isomorphic-layout-effect@^1.1.1:
version "1.1.2"
resolved "https://registry.yarnpkg.com/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz#497cefb13d863d687b08477d9e5a164ad8c1a6fb"
@@ -2332,29 +4807,43 @@ use-latest@^1.2.1:
dependencies:
use-isomorphic-layout-effect "^1.1.1"
+use@^3.1.0:
+ version "3.1.1"
+ resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
+ integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==
+
v8-compile-cache@^2.0.3:
version "2.3.0"
resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee"
integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==
+v8-to-istanbul@^9.0.1:
+ version "9.0.1"
+ resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-9.0.1.tgz#b6f994b0b5d4ef255e17a0d17dc444a9f5132fa4"
+ integrity sha512-74Y4LqY74kLE6IFyIjPtkSTWzUZmj8tdHT9Ii/26dvQ6K9Dl2NbEfj0XgU2sHCtKgt5VupqhlO/5aWuqS+IY1w==
+ dependencies:
+ "@jridgewell/trace-mapping" "^0.3.12"
+ "@types/istanbul-lib-coverage" "^2.0.1"
+ convert-source-map "^1.6.0"
+
vite@^2:
- version "2.9.12"
- resolved "https://registry.yarnpkg.com/vite/-/vite-2.9.12.tgz#b1d636b0a8ac636afe9d83e3792d4895509a941b"
- integrity sha512-suxC36dQo9Rq1qMB2qiRorNJtJAdxguu5TMvBHOc/F370KvqAe9t48vYp+/TbPKRNrMh/J55tOUmkuIqstZaew==
+ version "2.9.15"
+ resolved "https://registry.yarnpkg.com/vite/-/vite-2.9.15.tgz#2858dd5b2be26aa394a283e62324281892546f0b"
+ integrity sha512-fzMt2jK4vQ3yK56te3Kqpkaeq9DkcZfBbzHwYpobasvgYmP2SoAr6Aic05CsB4CzCZbsDv4sujX3pkEGhLabVQ==
dependencies:
esbuild "^0.14.27"
postcss "^8.4.13"
resolve "^1.22.0"
- rollup "^2.59.0"
+ rollup ">=2.59.0 <2.78.0"
optionalDependencies:
fsevents "~2.3.2"
-warning@^4.0.2, warning@^4.0.3:
- version "4.0.3"
- resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.3.tgz#16e9e077eb8a86d6af7d64aa1e05fd85b4678ca3"
- integrity sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==
+walker@^1.0.7, walker@^1.0.8, walker@~1.0.5:
+ version "1.0.8"
+ resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f"
+ integrity sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==
dependencies:
- loose-envify "^1.0.0"
+ makeerror "1.0.12"
which-boxed-primitive@^1.0.2:
version "1.0.2"
@@ -2367,6 +4856,13 @@ which-boxed-primitive@^1.0.2:
is-string "^1.0.5"
is-symbol "^1.0.3"
+which@^1.2.9:
+ version "1.3.1"
+ resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
+ integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==
+ dependencies:
+ isexe "^2.0.0"
+
which@^2.0.1:
version "2.0.2"
resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"
@@ -2379,7 +4875,72 @@ word-wrap@^1.2.3:
resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c"
integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==
+wrap-ansi@^7.0.0:
+ version "7.0.0"
+ resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
+ integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
+ dependencies:
+ ansi-styles "^4.0.0"
+ string-width "^4.1.0"
+ strip-ansi "^6.0.0"
+
wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==
+
+write-file-atomic@^3.0.0:
+ version "3.0.3"
+ resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-3.0.3.tgz#56bd5c5a5c70481cd19c571bd39ab965a5de56e8"
+ integrity sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==
+ dependencies:
+ imurmurhash "^0.1.4"
+ is-typedarray "^1.0.0"
+ signal-exit "^3.0.2"
+ typedarray-to-buffer "^3.1.5"
+
+write-file-atomic@^4.0.1:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-4.0.1.tgz#9faa33a964c1c85ff6f849b80b42a88c2c537c8f"
+ integrity sha512-nSKUxgAbyioruk6hU87QzVbY279oYT6uiwgDoujth2ju4mJ+TZau7SQBhtbTmUyuNYTuXnSyRn66FV0+eCgcrQ==
+ dependencies:
+ imurmurhash "^0.1.4"
+ signal-exit "^3.0.7"
+
+y18n@^5.0.5:
+ version "5.0.8"
+ resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"
+ integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==
+
+yallist@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
+ integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
+
+yaml@^1.10.0:
+ version "1.10.2"
+ resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b"
+ integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==
+
+yargs-parser@^21.0.0:
+ version "21.1.1"
+ resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
+ integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==
+
+yargs@^17.3.1:
+ version "17.5.1"
+ resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.5.1.tgz#e109900cab6fcb7fd44b1d8249166feb0b36e58e"
+ integrity sha512-t6YAJcxDkNX7NFYiVtKvWUz8l+PaKTLiL63mJYWR2GnHq2gjEWISzsLp9wg3aY36dY1j+gfIEL3pIF+XlJJfbA==
+ dependencies:
+ cliui "^7.0.2"
+ escalade "^3.1.1"
+ get-caller-file "^2.0.5"
+ require-directory "^2.1.1"
+ string-width "^4.2.3"
+ y18n "^5.0.5"
+ yargs-parser "^21.0.0"
+
+yocto-queue@^0.1.0:
+ version "0.1.0"
+ resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b"
+ integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==
diff --git a/cloud-tenant-base-dependencies-enforcer/pom.xml b/cloud-tenant-base-dependencies-enforcer/pom.xml
index 4197b350df1..1a83afd1be5 100644
--- a/cloud-tenant-base-dependencies-enforcer/pom.xml
+++ b/cloud-tenant-base-dependencies-enforcer/pom.xml
@@ -27,7 +27,7 @@
<httpclient.version>4.5.13</httpclient.version>
<httpcore.version>4.4.13</httpcore.version>
<junit5.version>5.8.1</junit5.version> <!-- TODO: in parent this is named 'junit.version' -->
- <onnxruntime.version>1.8.0</onnxruntime.version>
+ <onnxruntime.version>1.11.0</onnxruntime.version>
<!-- END parent/pom.xml -->
@@ -42,10 +42,10 @@
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<javax.ws.rs-api.version>2.0.1</javax.ws.rs-api.version>
<jaxb.version>2.3.0</jaxb.version>
- <jetty.version>9.4.46.v20220331</jetty.version>
+ <jetty.version>9.4.48.v20220622</jetty.version>
<jetty-alpn.version>1.1.3.v20160715</jetty-alpn.version>
<org.lz4.version>1.8.0</org.lz4.version>
- <org.json.version>20090211</org.json.version>
+ <org.json.version>20220320</org.json.version>
<slf4j.version>1.7.32</slf4j.version> <!-- WARNING: when updated, also update c.y.v.tenant:base pom -->
<xml-apis.version>1.4.01</xml-apis.version>
</properties>
@@ -142,7 +142,6 @@
<include>com.yahoo.vespa:vespaclient-container-plugin:*:jar:provided</include>
<include>com.yahoo.vespa:vespajlib:*:jar:provided</include>
<include>com.yahoo.vespa:vespalog:*:jar:provided</include>
- <include>com.yahoo.vespa:yolean:*:jar:provided</include>
<!-- Vespa test dependencies -->
<include>com.yahoo.vespa:application:*:jar:test</include>
@@ -220,7 +219,7 @@
<include>org.eclipse.jetty:jetty-util:[${jetty.version}]:jar:test</include>
<include>org.hamcrest:hamcrest-core:1.3:jar:test</include>
<include>org.hdrhistogram:HdrHistogram:2.1.8:jar:test</include>
- <include>org.json:json:20090211:jar:test</include>
+ <include>org.json:json:${org.json.version}:jar:test</include>
<include>org.junit.jupiter:junit-jupiter-api:[${junit5.version}]:jar:test</include>
<include>org.junit.jupiter:junit-jupiter-engine:[${junit5.version}]:jar:test</include>
<include>org.junit.platform:junit-platform-commons:[${junit5.platform.version}]:jar:test</include>
diff --git a/clustercontroller-apps/pom.xml b/clustercontroller-apps/pom.xml
index fa0f5c064ad..8a3fa2da811 100644
--- a/clustercontroller-apps/pom.xml
+++ b/clustercontroller-apps/pom.xml
@@ -13,21 +13,16 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
- <exclusions>
- <exclusion>
- <groupId>org.antlr</groupId>
- <artifactId>antlr4-runtime</artifactId>
- </exclusion>
- </exclusions>
+ <exclusions>
+ <exclusion>
+ <groupId>org.antlr</groupId>
+ <artifactId>antlr4-runtime</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -58,6 +53,16 @@
<artifactId>jettison</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
index dda18fc3396..7c5913774c3 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
@@ -6,19 +6,19 @@ import com.yahoo.cloud.config.ZookeepersConfig;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.config.content.StorDistributionConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class ClusterControllerClusterConfigurerTest {
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
ClusterController controller = new ClusterController();
StorDistributionConfig.Builder distributionConfig = new StorDistributionConfig.Builder();
StorDistributionConfig.Group.Builder group = new StorDistributionConfig.Group.Builder();
@@ -45,13 +45,17 @@ public class ClusterControllerClusterConfigurerTest {
zookeepersConfig.zookeeperserverlist("foo");
Metric metric = new Metric() {
@Override
- public void set(String s, Number number, Context context) {}
+ public void set(String s, Number number, Context context) {
+ }
@Override
- public void add(String s, Number number, Context context) {}
+ public void add(String s, Number number, Context context) {
+ }
@Override
- public Context createContext(Map<String, ?> stringMap) { return null; }
+ public Context createContext(Map<String, ?> stringMap) {
+ return null;
+ }
};
- // Used in standalone mode to get config without a cluster controller instance
+ // Used in standalone mode to get config without a cluster controller instance
ClusterControllerClusterConfigurer configurer = new ClusterControllerClusterConfigurer(
null,
new StorDistributionConfig(distributionConfig),
@@ -68,7 +72,7 @@ public class ClusterControllerClusterConfigurerTest {
assertEquals(0.7, configurer.getOptions().clusterFeedBlockLimit.get("bar"), 0.01);
assertEquals(0.05, configurer.getOptions().clusterFeedBlockNoiseLevel, 0.001);
- try{
+ try {
zookeepersConfig.zookeeperserverlist("");
new ClusterControllerClusterConfigurer(
controller,
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
index 2c33f781737..cfda92b472d 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
@@ -5,17 +5,17 @@ import com.yahoo.jdisc.Metric;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vespa.clustercontroller.core.FleetController;
import com.yahoo.vespa.clustercontroller.core.FleetControllerOptions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Doesn't really test cluster controller, but runs some lines of code.
@@ -34,7 +34,7 @@ public class ClusterControllerTest {
public Context createContext(Map<String, ?> stringMap) { return null; }
};
- @Before
+ @BeforeEach
public void setUp() {
options = new FleetControllerOptions("storage", Set.of(new ConfiguredNode(0, false)));
options.zooKeeperServerAddress = null;
@@ -43,7 +43,7 @@ public class ClusterControllerTest {
}
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
ClusterController cc = new ClusterController();
cc.setOptions(options, metric);
cc.setOptions(options, metric);
@@ -57,7 +57,7 @@ public class ClusterControllerTest {
}
@Test
- public void testShutdownException() throws Exception {
+ void testShutdownException() throws Exception {
ClusterController cc = new ClusterController() {
void shutdownController(FleetController controller) throws Exception {
throw new Exception("Foo");
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
index bf759e3dc76..7146d95e7ba 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
@@ -3,17 +3,17 @@ package com.yahoo.vespa.clustercontroller.apps.clustercontroller;
import com.yahoo.cloud.config.ClusterInfoConfig;
import com.yahoo.vespa.clustercontroller.core.restapiv2.ClusterControllerStateRestAPI;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class StateRestApiV2HandlerTest {
@Test
- public void testNoMatchingSockets() {
+ void testNoMatchingSockets() {
ClusterController controller = new ClusterController();
ClusterInfoConfig config = new ClusterInfoConfig(
new ClusterInfoConfig.Builder().clusterId("cluster-id").nodeCount(1));
@@ -22,7 +22,7 @@ public class StateRestApiV2HandlerTest {
}
@Test
- public void testMappingOfIndexToClusterControllers() {
+ void testMappingOfIndexToClusterControllers() {
ClusterInfoConfig.Builder builder = new ClusterInfoConfig.Builder()
.clusterId("cluster-id")
.nodeCount(1)
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
index 7a204aa791d..d4eb84677dc 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.apps.clustercontroller;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class StatusHandlerTest {
@Test
- public void testSimple() {
+ void testSimple() {
ClusterController controller = new ClusterController();
StatusHandler handler = new StatusHandler(controller, StatusHandler.testContext());
}
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
index 6a27228feab..19a5a2a60f9 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.clustercontroller.apputil.communication.http;
import com.yahoo.vespa.clustercontroller.utils.communication.http.HttpRequest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* The handler is mostly tested through the apache tests, using it as endpoint here..
@@ -20,7 +20,7 @@ public class JDiscHttpRequestHandlerTest {
private ThreadPoolExecutor executor;
- @Before
+ @BeforeEach
public void setUp() {
executor = new ThreadPoolExecutor(10, 100, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
}
@@ -30,8 +30,8 @@ public class JDiscHttpRequestHandlerTest {
}
@Test
- public void testInvalidMethod() throws Exception {
- try{
+ void testInvalidMethod() throws Exception {
+ try {
HttpRequest request = new HttpRequest();
JDiscHttpRequestHandler.setOperation(request, com.yahoo.jdisc.http.HttpRequest.Method.CONNECT);
fail("Control should not reach here");
@@ -41,7 +41,7 @@ public class JDiscHttpRequestHandlerTest {
}
@Test
- public void testNothingButAddCoverage() throws Exception {
+ void testNothingButAddCoverage() throws Exception {
new JDiscHttpRequestHandler.EmptyCompletionHandler().failed(null);
}
}
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
index e7c8301cfca..a62437d1a8f 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.apputil.communication.http;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class JDiscMetricWrapperTest {
@@ -22,10 +22,10 @@ public class JDiscMetricWrapperTest {
++calls;
return new Context() {};
}
- };
+ }
@Test
- public void testSimple() {
+ void testSimple() {
MetricImpl impl1 = new MetricImpl();
MetricImpl impl2 = new MetricImpl();
JDiscMetricWrapper wrapper = new JDiscMetricWrapper(impl1);
diff --git a/clustercontroller-core/pom.xml b/clustercontroller-core/pom.xml
index 243b69bf1e2..dbd7e14a8f6 100644
--- a/clustercontroller-core/pom.xml
+++ b/clustercontroller-core/pom.xml
@@ -27,8 +27,8 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
@@ -38,13 +38,14 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -53,6 +54,16 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
</dependency>
diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ContentCluster.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ContentCluster.java
index f2a4a9736c3..695fecb6314 100644
--- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ContentCluster.java
+++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ContentCluster.java
@@ -1,20 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vdslib.distribution.Distribution;
-import com.yahoo.vdslib.distribution.Group;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
-import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-import com.yahoo.vespa.clustercontroller.core.status.statuspage.HtmlTable;
-import com.yahoo.vespa.clustercontroller.core.status.statuspage.VdsClusterHtmlRenderer;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStateRequest;
-
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -46,61 +40,6 @@ public class ContentCluster {
setNodes(configuredNodes, new NodeListener() {});
}
- // TODO move out, this doesn't belong in a domain model class
- public void writeHtmlState(
- final VdsClusterHtmlRenderer vdsClusterHtmlRenderer,
- final StringBuilder sb,
- final Timer timer,
- final ClusterStateBundle state,
- final ClusterStatsAggregator statsAggregator,
- final Distribution distribution,
- final FleetControllerOptions options,
- final EventLog eventLog) {
-
- final VdsClusterHtmlRenderer.Table table =
- vdsClusterHtmlRenderer.createNewClusterHtmlTable(clusterName, slobrokGenerationCount);
-
- if (state.clusterFeedIsBlocked()) { // Implies FeedBlock != null
- table.appendRaw("<h3 style=\"color: red\">Cluster feeding is blocked!</h3>\n");
- table.appendRaw(String.format("<p>Summary: <strong>%s</strong></p>\n",
- HtmlTable.escape(state.getFeedBlockOrNull().getDescription())));
- }
-
- final List<Group> groups = LeafGroups.enumerateFrom(distribution.getRootGroup());
-
- for (int j=0; j<groups.size(); ++j) {
- final Group group = groups.get(j);
- assert(group != null);
- final String localName = group.getUnixStylePath();
- assert(localName != null);
- final TreeMap<Integer, NodeInfo> storageNodeInfoByIndex = new TreeMap<>();
- final TreeMap<Integer, NodeInfo> distributorNodeInfoByIndex = new TreeMap<>();
- for (ConfiguredNode configuredNode : group.getNodes()) {
- storeNodeInfo(configuredNode.index(), NodeType.STORAGE, storageNodeInfoByIndex);
- storeNodeInfo(configuredNode.index(), NodeType.DISTRIBUTOR, distributorNodeInfoByIndex);
- }
- table.renderNodes(
- storageNodeInfoByIndex,
- distributorNodeInfoByIndex,
- timer,
- state,
- statsAggregator,
- options.minMergeCompletionRatio,
- options.maxPrematureCrashes,
- options.clusterFeedBlockLimit,
- eventLog,
- clusterName,
- localName);
- }
- table.addTable(sb, options.stableStateTimePeriod);
- }
-
- private void storeNodeInfo(int nodeIndex, NodeType nodeType, Map<Integer, NodeInfo> nodeInfoByIndex) {
- NodeInfo nodeInfo = getNodeInfo(new Node(nodeType, nodeIndex));
- if (nodeInfo == null) return;
- nodeInfoByIndex.put(nodeIndex, nodeInfo);
- }
-
public Distribution getDistribution() { return distribution; }
public void setDistribution(Distribution distribution) {
diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetController.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetController.java
index 7f385c6077c..4097810b633 100644
--- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetController.java
+++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetController.java
@@ -12,8 +12,8 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
-import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
+import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.SystemStateListener;
import com.yahoo.vespa.clustercontroller.core.rpc.RPCCommunicator;
import com.yahoo.vespa.clustercontroller.core.rpc.RpcServer;
@@ -27,8 +27,9 @@ import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageRespon
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServer;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServerInterface;
import com.yahoo.vespa.clustercontroller.utils.util.MetricReporter;
-
import java.io.FileNotFoundException;
+import java.time.Duration;
+import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
@@ -45,7 +46,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import java.util.stream.Stream;
public class FleetController implements NodeListener, SlobrokListener, SystemStateListener,
Runnable, RemoteClusterControllerTaskScheduler {
@@ -155,10 +155,8 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
new ClusterStateRequestHandler(stateVersionTracker));
this.statusRequestRouter.addHandler(
"^/$",
- new LegacyIndexPageRequestHandler(
- timer, options.showLocalSystemStatesInEventLog, cluster,
- masterElectionHandler, stateVersionTracker,
- eventLog, timer.getCurrentTimeInMillis(), dataExtractor));
+ new LegacyIndexPageRequestHandler(timer, cluster, masterElectionHandler, stateVersionTracker, eventLog,
+ timer.getCurrentTimeInMillis(), dataExtractor));
propagateOptions();
}
@@ -505,9 +503,7 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
cluster.setSlobrokGenerationCount(0);
}
- configuredBucketSpaces = Collections.unmodifiableSet(
- Stream.of(FixedBucketSpaces.defaultSpace(), FixedBucketSpaces.globalSpace())
- .collect(Collectors.toSet()));
+ configuredBucketSpaces = Set.of(FixedBucketSpaces.defaultSpace(), FixedBucketSpaces.globalSpace());
stateVersionTracker.setMinMergeCompletionRatio(options.minMergeCompletionRatio);
communicator.propagateOptions(options);
@@ -634,7 +630,7 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
didWork |= metricUpdater.forWork("processAnyPendingStatusPageRequest", this::processAnyPendingStatusPageRequest);
if ( ! isRunning()) { return; }
if (rpcServer != null) {
- didWork |= metricUpdater.forWork("handleRpcRequests", () -> rpcServer.handleRpcRequests(cluster, consolidatedClusterState(), this, this));
+ didWork |= metricUpdater.forWork("handleRpcRequests", () -> rpcServer.handleRpcRequests(cluster, consolidatedClusterState(), this));
}
if ( ! isRunning()) { return; }
@@ -1162,16 +1158,18 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
public NodeListener getNodeStateUpdateListener() { return FleetController.this; }
};
- public void waitForCompleteCycle(long timeoutMS) {
- long endTime = System.currentTimeMillis() + timeoutMS;
+ public void waitForCompleteCycle(Duration timeout) {
+ Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
// To wait at least one complete cycle, if a cycle is already running we need to wait for the next one beyond.
long wantedCycle = cycleCount + (processingCycle ? 2 : 1);
waitingForCycle = true;
try{
while (cycleCount < wantedCycle) {
- if (System.currentTimeMillis() > endTime) throw new IllegalStateException("Timed out waiting for cycle to complete. Not completed after " + timeoutMS + " ms.");
- if ( !isRunning() ) throw new IllegalStateException("Fleetcontroller not running. Will never complete cycles");
+ if (Instant.now().isAfter(endTime))
+ throw new IllegalStateException("Timed out waiting for cycle to complete. Not completed after " + timeout);
+ if ( !isRunning() )
+ throw new IllegalStateException("Fleetcontroller not running. Will never complete cycles");
try{ monitor.wait(100); } catch (InterruptedException e) {}
}
} finally {
@@ -1185,8 +1183,8 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
* But it is only used in unit tests that should not trigger any thread issues. Don't want to add locks that reduce
* live performance to remove a non-problem.
*/
- public void waitForNodesHavingSystemStateVersionEqualToOrAbove(int version, int nodeCount, int timeout) throws InterruptedException {
- long maxTime = System.currentTimeMillis() + timeout;
+ public void waitForNodesHavingSystemStateVersionEqualToOrAbove(int version, int nodeCount, Duration timeout) throws InterruptedException {
+ Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
while (true) {
int ackedNodes = 0;
@@ -1199,17 +1197,16 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
context.log(logger, Level.INFO, ackedNodes + " nodes now have acked system state " + version + " or higher.");
return;
}
- long remainingTime = maxTime - System.currentTimeMillis();
- if (remainingTime <= 0) {
- throw new IllegalStateException("Did not get " + nodeCount + " nodes to system state " + version + " within timeout of " + timeout + " milliseconds.");
+ if (Instant.now().isAfter(endTime)) {
+ throw new IllegalStateException("Did not get " + nodeCount + " nodes to system state " + version + " within timeout of " + timeout);
}
monitor.wait(10);
}
}
}
- public void waitForNodesInSlobrok(int distNodeCount, int storNodeCount, int timeoutMillis) throws InterruptedException {
- long maxTime = System.currentTimeMillis() + timeoutMillis;
+ public void waitForNodesInSlobrok(int distNodeCount, int storNodeCount, Duration timeout) throws InterruptedException {
+ Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
while (true) {
int distCount = 0, storCount = 0;
@@ -1221,10 +1218,9 @@ public class FleetController implements NodeListener, SlobrokListener, SystemSta
}
if (distCount == distNodeCount && storCount == storNodeCount) return;
- long remainingTime = maxTime - System.currentTimeMillis();
- if (remainingTime <= 0) {
+ if (Instant.now().isAfter(endTime)) {
throw new IllegalStateException("Did not get all " + distNodeCount + " distributors and " + storNodeCount
- + " storage nodes registered in slobrok within timeout of " + timeoutMillis + " ms. (Got "
+ + " storage nodes registered in slobrok within timeout of " + timeout + ". (Got "
+ distCount + " distributors and " + storCount + " storage nodes)");
}
monitor.wait(10);
diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicator.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicator.java
index a5a29b8d7f1..e223ad12fb9 100644
--- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicator.java
+++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicator.java
@@ -11,10 +11,9 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.Transport;
import com.yahoo.jrt.Values;
-import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.ClusterState;
+import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.State;
-import java.util.logging.Level;
import com.yahoo.vespa.clustercontroller.core.ActivateClusterStateVersionRequest;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
import com.yahoo.vespa.clustercontroller.core.Communicator;
@@ -24,6 +23,8 @@ import com.yahoo.vespa.clustercontroller.core.NodeInfo;
import com.yahoo.vespa.clustercontroller.core.SetClusterStateRequest;
import com.yahoo.vespa.clustercontroller.core.Timer;
+import java.time.Duration;
+import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Preconditions.checkArgument;
@@ -47,10 +48,10 @@ public class RPCCommunicator implements Communicator {
private final Timer timer;
private final Supervisor supervisor;
- private double nodeStateRequestTimeoutIntervalMaxSeconds;
+ private Duration nodeStateRequestTimeoutIntervalMax;
private int nodeStateRequestTimeoutIntervalStartPercentage;
private int nodeStateRequestTimeoutIntervalStopPercentage;
- private int nodeStateRequestRoundTripTimeMaxSeconds;
+ private Duration nodeStateRequestRoundTripTimeMax;
private final int fleetControllerIndex;
public static Supervisor createRealSupervisor() {
@@ -71,12 +72,12 @@ public class RPCCommunicator implements Communicator {
checkArgument(nodeStateRequestTimeoutIntervalStartPercentage >= 0);
checkArgument(nodeStateRequestTimeoutIntervalStartPercentage <= 100);
checkArgument(nodeStateRequestTimeoutIntervalStopPercentage >= nodeStateRequestTimeoutIntervalStartPercentage);
- checkArgument(nodeStateRequestTimeoutIntervalStartPercentage <= 100);
+ checkArgument(nodeStateRequestTimeoutIntervalStopPercentage <= 100);
checkArgument(nodeStateRequestRoundTripTimeMaxSeconds >= 0);
- this.nodeStateRequestTimeoutIntervalMaxSeconds = nodeStateRequestTimeoutIntervalMaxMs / 1000D;
+ this.nodeStateRequestTimeoutIntervalMax = Duration.ofMillis(nodeStateRequestTimeoutIntervalMaxMs);
this.nodeStateRequestTimeoutIntervalStartPercentage = nodeStateRequestTimeoutIntervalStartPercentage;
this.nodeStateRequestTimeoutIntervalStopPercentage = nodeStateRequestTimeoutIntervalStopPercentage;
- this.nodeStateRequestRoundTripTimeMaxSeconds = nodeStateRequestRoundTripTimeMaxSeconds;
+ this.nodeStateRequestRoundTripTimeMax = Duration.ofSeconds(nodeStateRequestRoundTripTimeMaxSeconds);
this.supervisor = supervisor;
}
@@ -101,10 +102,10 @@ public class RPCCommunicator implements Communicator {
>= options.nodeStateRequestTimeoutEarliestPercentage);
checkArgument(options.nodeStateRequestTimeoutLatestPercentage <= 100);
checkArgument(options.nodeStateRequestRoundTripTimeMaxSeconds >= 0);
- this.nodeStateRequestTimeoutIntervalMaxSeconds = options.nodeStateRequestTimeoutMS / 1000.0;
+ this.nodeStateRequestTimeoutIntervalMax = Duration.ofMillis(options.nodeStateRequestTimeoutMS);
this.nodeStateRequestTimeoutIntervalStartPercentage = options.nodeStateRequestTimeoutEarliestPercentage;
this.nodeStateRequestTimeoutIntervalStopPercentage = options.nodeStateRequestTimeoutLatestPercentage;
- this.nodeStateRequestRoundTripTimeMaxSeconds = options.nodeStateRequestRoundTripTimeMaxSeconds;
+ this.nodeStateRequestRoundTripTimeMax = Duration.ofSeconds(options.nodeStateRequestRoundTripTimeMaxSeconds);
}
@Override
@@ -118,16 +119,15 @@ public class RPCCommunicator implements Communicator {
req.parameters().add(new StringValue(
currentState.getState().equals(State.DOWN) || node.getConnectionAttemptCount() > 0
? "unknown" : currentState.serialize()));
- req.parameters().add(new Int32Value(generateNodeStateRequestTimeoutMs()));
+ req.parameters().add(new Int32Value((int)generateNodeStateRequestTimeout().toMillis()));
req.parameters().add(new Int32Value(fleetControllerIndex));
RPCGetNodeStateRequest stateRequest = new RPCGetNodeStateRequest(node, req);
RPCGetNodeStateWaiter waiter = new RPCGetNodeStateWaiter(stateRequest, externalWaiter, timer);
- double requestTimeoutSeconds =
- nodeStateRequestTimeoutIntervalMaxSeconds + nodeStateRequestRoundTripTimeMaxSeconds;
+ Duration requestTimeout = nodeStateRequestTimeoutIntervalMax.plus(nodeStateRequestRoundTripTimeMax);
- connection.invokeAsync(req, requestTimeoutSeconds, waiter);
+ connection.invokeAsync(req, requestTimeout, waiter);
node.setCurrentNodeStateRequest(stateRequest, timer.getCurrentTimeInMillis());
node.lastRequestInfoConnection = connection;
}
@@ -162,7 +162,7 @@ public class RPCCommunicator implements Communicator {
RPCSetClusterStateRequest stateRequest = new RPCSetClusterStateRequest(node, req, baselineState.getVersion());
waiter.setRequest(stateRequest);
- connection.invokeAsync(req, 60, waiter);
+ connection.invokeAsync(req, Duration.ofSeconds(60), waiter);
node.setClusterStateVersionBundleSent(stateBundle);
}
@@ -184,20 +184,20 @@ public class RPCCommunicator implements Communicator {
var activationRequest = new RPCActivateClusterStateVersionRequest(node, req, clusterStateVersion);
waiter.setRequest(activationRequest);
- connection.invokeAsync(req, 60, waiter);
+ connection.invokeAsync(req, Duration.ofSeconds(60), waiter);
node.setClusterStateVersionActivationSent(clusterStateVersion);
}
// protected for testing.
- protected int generateNodeStateRequestTimeoutMs() {
+ protected Duration generateNodeStateRequestTimeout() {
double intervalFraction = Math.random();
- double earliestTimeoutSeconds =
- nodeStateRequestTimeoutIntervalMaxSeconds * nodeStateRequestTimeoutIntervalStartPercentage / 100.0;
- double latestTimeoutSeconds =
- nodeStateRequestTimeoutIntervalMaxSeconds * nodeStateRequestTimeoutIntervalStopPercentage / 100.0;
- double interval = latestTimeoutSeconds - earliestTimeoutSeconds;
- double timeoutSeconds = earliestTimeoutSeconds + intervalFraction * interval;
- return (int) (timeoutSeconds * 1000);
+ long earliestTimeoutNanos =
+ nodeStateRequestTimeoutIntervalMax.toNanos() * nodeStateRequestTimeoutIntervalStartPercentage / 100;
+ long latestTimeoutNanos =
+ nodeStateRequestTimeoutIntervalMax.toNanos() * nodeStateRequestTimeoutIntervalStopPercentage / 100;
+ long interval = latestTimeoutNanos - earliestTimeoutNanos;
+ long timeoutNanos = earliestTimeoutNanos + (long)(intervalFraction * interval);
+ return Duration.ofNanos(timeoutNanos);
}
}
diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RpcServer.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RpcServer.java
index 6e416ce4906..dc21693dcdb 100644
--- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RpcServer.java
+++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/RpcServer.java
@@ -15,8 +15,6 @@ import com.yahoo.jrt.Transport;
import com.yahoo.jrt.slobrok.api.BackOffPolicy;
import com.yahoo.jrt.slobrok.api.Register;
import com.yahoo.jrt.slobrok.api.SlobrokList;
-import java.util.logging.Level;
-
import com.yahoo.net.HostName;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
@@ -27,34 +25,34 @@ import com.yahoo.vespa.clustercontroller.core.ContentCluster;
import com.yahoo.vespa.clustercontroller.core.MasterElectionHandler;
import com.yahoo.vespa.clustercontroller.core.NodeInfo;
import com.yahoo.vespa.clustercontroller.core.Timer;
-import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.logging.Level;
import java.util.logging.Logger;
public class RpcServer {
- private static Logger log = Logger.getLogger(RpcServer.class.getName());
+ private static final Logger log = Logger.getLogger(RpcServer.class.getName());
private final Timer timer;
private final Object monitor;
private final String clusterName;
private final int fleetControllerIndex;
- private String slobrokConnectionSpecs[];
+ private String[] slobrokConnectionSpecs;
private int port = 0;
private Supervisor supervisor;
private Acceptor acceptor;
private Register register;
private final List<Request> rpcRequests = new LinkedList<>();
private MasterElectionHandler masterHandler;
- private BackOffPolicy slobrokBackOffPolicy;
+ private final BackOffPolicy slobrokBackOffPolicy;
private long lastConnectErrorTime = 0;
private String lastConnectError = "";
@@ -81,10 +79,10 @@ public class RpcServer {
return "storage/cluster." + clusterName + "/fleetcontroller/" + fleetControllerIndex;
}
- public void setSlobrokConnectionSpecs(String slobrokConnectionSpecs[], int port) throws ListenFailedException, UnknownHostException {
- if (this.slobrokConnectionSpecs == null || !this.slobrokConnectionSpecs.equals(slobrokConnectionSpecs) // TODO: <-- probably a bug
- || this.port != port)
- {
+ public void setSlobrokConnectionSpecs(String[] slobrokConnectionSpecs, int port) throws ListenFailedException, UnknownHostException {
+ if (this.slobrokConnectionSpecs == null
+ || !Arrays.equals(this.slobrokConnectionSpecs, slobrokConnectionSpecs)
+ || this.port != port) {
this.slobrokConnectionSpecs = slobrokConnectionSpecs;
this.port = port;
disconnect();
@@ -105,7 +103,7 @@ public class RpcServer {
log.log(Level.FINE, () -> "Fleetcontroller " + fleetControllerIndex + ": Attempting to bind to port " + port);
acceptor = supervisor.listen(new Spec(port));
log.log(Level.FINE, () -> "Fleetcontroller " + fleetControllerIndex + ": RPC server listening to port " + acceptor.port());
- StringBuffer slobroks = new StringBuffer("(");
+ StringBuilder slobroks = new StringBuilder("(");
for (String s : slobrokConnectionSpecs) {
slobroks.append(" ").append(s);
}
@@ -185,10 +183,7 @@ public class RpcServer {
}
}
- public boolean handleRpcRequests(ContentCluster cluster, ClusterState systemState,
- NodeListener changeListener,
- SlobrokListener addedListener)
- {
+ public boolean handleRpcRequests(ContentCluster cluster, ClusterState systemState, NodeListener changeListener) {
boolean handledAnyRequests = false;
if (!isConnected()) {
long time = timer.getCurrentTimeInMillis();
@@ -255,8 +250,6 @@ public class RpcServer {
NodeType nodeType = NodeType.get(req.parameters().get(0).asString());
int nodeIndex = req.parameters().get(1).asInt32();
Node node = new Node(nodeType, nodeIndex);
- // First parameter is current state in system state
- NodeState ns = systemState.getNodeState(node);
req.returnValues().add(new StringValue(systemState.getNodeState(node).serialize()));
// Second parameter is state node is reporting
NodeInfo nodeInfo = cluster.getNodeInfo(node);
@@ -276,7 +269,7 @@ public class RpcServer {
throw new IllegalStateException("Invalid slobrok address '" + slobrokAddress + "'.");
}
NodeType nodeType = NodeType.get(slobrokAddress.substring(nextButLastSlash + 1, lastSlash));
- Integer nodeIndex = Integer.valueOf(slobrokAddress.substring(lastSlash + 1));
+ int nodeIndex = Integer.parseInt(slobrokAddress.substring(lastSlash + 1));
NodeInfo node = cluster.getNodeInfo(new Node(nodeType, nodeIndex));
if (node == null)
throw new IllegalStateException("Cannot set wanted state of node " + new Node(nodeType, nodeIndex) + ". Index does not correspond to a configured node.");
diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/LegacyIndexPageRequestHandler.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/LegacyIndexPageRequestHandler.java
index 378f65f7235..96dc114c734 100644
--- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/LegacyIndexPageRequestHandler.java
+++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/LegacyIndexPageRequestHandler.java
@@ -1,14 +1,29 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core.status;
-import com.yahoo.vdslib.state.ClusterState;
-import com.yahoo.vespa.clustercontroller.core.*;
+import com.yahoo.vdslib.distribution.ConfiguredNode;
+import com.yahoo.vdslib.distribution.Group;
+import com.yahoo.vdslib.state.Node;
+import com.yahoo.vdslib.state.NodeType;
+import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
+import com.yahoo.vespa.clustercontroller.core.ClusterStateHistoryEntry;
+import com.yahoo.vespa.clustercontroller.core.ContentCluster;
+import com.yahoo.vespa.clustercontroller.core.EventLog;
+import com.yahoo.vespa.clustercontroller.core.FleetControllerOptions;
+import com.yahoo.vespa.clustercontroller.core.LeafGroups;
+import com.yahoo.vespa.clustercontroller.core.MasterElectionHandler;
+import com.yahoo.vespa.clustercontroller.core.NodeInfo;
+import com.yahoo.vespa.clustercontroller.core.RealTimer;
+import com.yahoo.vespa.clustercontroller.core.StateVersionTracker;
import com.yahoo.vespa.clustercontroller.core.Timer;
+import com.yahoo.vespa.clustercontroller.core.status.statuspage.HtmlTable;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageResponse;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServer;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.VdsClusterHtmlRenderer;
-
-import java.util.*;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.TreeMap;
/**
* @author Haakon Humberset
@@ -22,15 +37,15 @@ public class LegacyIndexPageRequestHandler implements StatusPageServer.RequestHa
private final EventLog eventLog;
private final long startedTime;
private final RunDataExtractor data;
- private final boolean showLocalSystemStatesInLog;
- public LegacyIndexPageRequestHandler(Timer timer, boolean showLocalSystemStatesInLog, ContentCluster cluster,
+ public LegacyIndexPageRequestHandler(Timer timer,
+ ContentCluster cluster,
MasterElectionHandler masterElectionHandler,
StateVersionTracker stateVersionTracker,
- EventLog eventLog, long startedTime, RunDataExtractor data)
- {
+ EventLog eventLog,
+ long startedTime,
+ RunDataExtractor data) {
this.timer = timer;
- this.showLocalSystemStatesInLog = showLocalSystemStatesInLog;
this.cluster = cluster;
this.masterElectionHandler = masterElectionHandler;
this.stateVersionTracker = stateVersionTracker;
@@ -59,18 +74,9 @@ public class LegacyIndexPageRequestHandler implements StatusPageServer.RequestHa
content.append("<tr><td>Cluster controller uptime:</td><td align=\"right\">" + RealTimer.printDuration(currentTime - startedTime) + "</td></tr></table>");
if (masterElectionHandler.isAmongNthFirst(data.getOptions().stateGatherCount)) {
// Table overview of all the nodes
- cluster.writeHtmlState(
- new VdsClusterHtmlRenderer(),
- content,
- timer,
- stateVersionTracker.getVersionedClusterStateBundle(),
- stateVersionTracker.getAggregatedClusterStats(),
- data.getOptions().storageDistribution,
- data.getOptions(),
- eventLog
- );
+ writeHtmlState(cluster, content, timer, stateVersionTracker, data.getOptions(), eventLog);
// Current cluster state and cluster state history
- writeHtmlState(stateVersionTracker, content, request);
+ writeHtmlState(stateVersionTracker, content);
} else {
// Overview of current config
data.getOptions().writeHtmlState(content);
@@ -87,14 +93,7 @@ public class LegacyIndexPageRequestHandler implements StatusPageServer.RequestHa
return response;
}
- public void writeHtmlState(StateVersionTracker stateVersionTracker, StringBuilder sb, StatusPageServer.HttpRequest request) {
- boolean showLocal = showLocalSystemStatesInLog;
- if (request.hasQueryParameter("showlocal")) {
- showLocal = true;
- } else if (request.hasQueryParameter("hidelocal")) {
- showLocal = false;
- }
-
+ public void writeHtmlState(StateVersionTracker stateVersionTracker, StringBuilder sb) {
sb.append("<h2 id=\"clusterstates\">Cluster states</h2>\n");
writeClusterStates(sb, stateVersionTracker.getVersionedClusterStateBundle());
@@ -153,4 +152,53 @@ public class LegacyIndexPageRequestHandler implements StatusPageServer.RequestHa
sb.append("</td></tr>\n");
}
+ private void writeHtmlState(ContentCluster cluster,
+ StringBuilder sb,
+ Timer timer,
+ StateVersionTracker stateVersionTracker,
+ FleetControllerOptions options,
+ EventLog eventLog) {
+ VdsClusterHtmlRenderer renderer = new VdsClusterHtmlRenderer();
+ VdsClusterHtmlRenderer.Table table = renderer.createNewClusterHtmlTable(cluster.getName(), cluster.getSlobrokGenerationCount());
+
+ ClusterStateBundle state = stateVersionTracker.getVersionedClusterStateBundle();
+ if (state.clusterFeedIsBlocked()) { // Implies FeedBlock != null
+ table.appendRaw("<h3 style=\"color: red\">Cluster feeding is blocked!</h3>\n");
+ table.appendRaw(String.format("<p>Summary: <strong>%s</strong></p>\n",
+ HtmlTable.escape(state.getFeedBlockOrNull().getDescription())));
+ }
+
+ List<Group> groups = LeafGroups.enumerateFrom(options.storageDistribution.getRootGroup());
+
+ for (Group group : groups) {
+ assert (group != null);
+ String localName = group.getUnixStylePath();
+ assert (localName != null);
+ TreeMap<Integer, NodeInfo> storageNodeInfoByIndex = new TreeMap<>();
+ TreeMap<Integer, NodeInfo> distributorNodeInfoByIndex = new TreeMap<>();
+ for (ConfiguredNode configuredNode : group.getNodes()) {
+ storeNodeInfo(cluster, configuredNode.index(), NodeType.STORAGE, storageNodeInfoByIndex);
+ storeNodeInfo(cluster, configuredNode.index(), NodeType.DISTRIBUTOR, distributorNodeInfoByIndex);
+ }
+ table.renderNodes(storageNodeInfoByIndex,
+ distributorNodeInfoByIndex,
+ timer,
+ state,
+ stateVersionTracker.getAggregatedClusterStats(),
+ options.minMergeCompletionRatio,
+ options.maxPrematureCrashes,
+ options.clusterFeedBlockLimit,
+ eventLog,
+ cluster.getName(),
+ localName);
+ }
+ table.addTable(sb, options.stableStateTimePeriod);
+ }
+
+ private void storeNodeInfo(ContentCluster cluster, int nodeIndex, NodeType nodeType, Map<Integer, NodeInfo> nodeInfoByIndex) {
+ NodeInfo nodeInfo = cluster.getNodeInfo(new Node(nodeType, nodeIndex));
+ if (nodeInfo == null) return;
+ nodeInfoByIndex.put(nodeIndex, nodeInfo);
+ }
+
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java
index dece8019e2c..b12f37e092d 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -52,43 +52,43 @@ public class AggregatedStatsMergePendingCheckerTest {
}
@Test
- public void unknown_content_node_may_have_merges_pending() {
+ void unknown_content_node_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 2));
}
@Test
- public void unknown_bucket_space_has_no_merges_pending() {
+ void unknown_bucket_space_has_no_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertFalse(f.mayHaveMergesPending("global", 1));
}
@Test
- public void valid_bucket_space_stats_can_have_no_merges_pending() {
+ void valid_bucket_space_stats_can_have_no_merges_pending() {
Fixture f = Fixture.fromBucketsPending(0);
assertFalse(f.mayHaveMergesPending("default", 1));
}
@Test
- public void valid_bucket_space_stats_may_have_merges_pending() {
+ void valid_bucket_space_stats_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void invalid_bucket_space_stats_may_have_merges_pending() {
+ void invalid_bucket_space_stats_may_have_merges_pending() {
Fixture f = Fixture.fromInvalidBucketStats();
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void cluster_without_updates_from_all_distributors_may_have_merges_pending() {
+ void cluster_without_updates_from_all_distributors_may_have_merges_pending() {
Fixture f = Fixture.fromIncompleteStats();
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void min_merge_completion_ratio_is_used_when_calculating_may_have_merges_pending() {
+ void min_merge_completion_ratio_is_used_when_calculating_may_have_merges_pending() {
// Completion ratio is (5-3)/5 = 0.4
assertTrue(Fixture.fromBucketsPending(3, 0.6).mayHaveMergesPending("default", 1));
// Completion ratio is (5-2)/5 = 0.6
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
index f0b91102e8f..ec6255fd13b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
@@ -10,8 +10,8 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
@@ -22,10 +22,10 @@ import java.util.Set;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.mapOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.createResourceUsageJson;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClusterFeedBlockTest extends FleetControllerTest {
@@ -36,7 +36,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
private FleetController ctrl;
private DummyCommunicator communicator;
- @Before
+ @BeforeEach
public void setUp() {
supervisor = new Supervisor(new Transport());
}
@@ -107,7 +107,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_can_be_blocked_and_unblocked_by_single_node() throws Exception {
+ void cluster_feed_can_be_blocked_and_unblocked_by_single_node() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -127,7 +127,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_options_are_updated() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_options_are_updated() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -142,7 +142,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_resource_block_set_differs() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_resource_block_set_differs() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -155,12 +155,12 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.800 > 0.700), " +
- "wine on node 1 [unknown hostname] (0.500 > 0.400)",
- bundle.getFeedBlock().get().getDescription());
+ "wine on node 1 [unknown hostname] (0.500 > 0.400)",
+ bundle.getFeedBlock().get().getDescription());
}
@Test
- public void cluster_feed_block_state_is_not_recomputed_when_only_resource_usage_levels_differ() throws Exception {
+ void cluster_feed_block_state_is_not_recomputed_when_only_resource_usage_levels_differ() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -177,7 +177,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_usage_enters_hysteresis_range() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_usage_enters_hysteresis_range() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4)), 0.1));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -193,22 +193,22 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
// is not discovered here. Still correct in terms of what resources are blocked or not, but
// the description is not up to date here.
assertEquals("cheese on node 1 [unknown hostname] (0.750 > 0.700)",
- bundle.getFeedBlock().get().getDescription());
+ bundle.getFeedBlock().get().getDescription());
// Trigger an explicit recompute by adding a separate resource exhaustion
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.67), usage("wine", 0.5)));
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.670 > 0.600), " +
- "wine on node 1 [unknown hostname] (0.500 > 0.400)", // Not under hysteresis
- bundle.getFeedBlock().get().getDescription());
+ "wine on node 1 [unknown hostname] (0.500 > 0.400)", // Not under hysteresis
+ bundle.getFeedBlock().get().getDescription());
// Wine usage drops beyond hysteresis range, should be unblocked immediately.
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.61), usage("wine", 0.2)));
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.610 > 0.600)",
- bundle.getFeedBlock().get().getDescription());
+ bundle.getFeedBlock().get().getDescription());
// Cheese now drops below hysteresis range, should be unblocked as well.
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.59), usage("wine", 0.2)));
@@ -217,7 +217,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void unavailable_nodes_are_not_considered_when_computing_feed_blocked_state() throws Exception {
+ void unavailable_nodes_are_not_considered_when_computing_feed_blocked_state() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4)), 0.1));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
index d12541687f0..17c461a487b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.function.Function;
@@ -15,9 +15,7 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.exhaustion;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class ClusterStateBundleTest {
@@ -67,7 +65,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void builder_creates_baseline_state_and_derived_state_per_space() {
+ void builder_creates_baseline_state_and_derived_state_per_space() {
ClusterStateBundle bundle = createTestBundle();
assertThat(bundle.getBaselineClusterState(), equalTo(stateOf("distributor:2 storage:2")));
assertThat(bundle.getDerivedBucketSpaceStates().size(), equalTo(3));
@@ -77,7 +75,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void version_clone_sets_version_for_all_spaces() {
+ void version_clone_sets_version_for_all_spaces() {
ClusterStateBundle bundle = createTestBundle().clonedWithVersionSet(123);
assertThat(bundle.getBaselineClusterState(), equalTo(stateOf("version:123 distributor:2 storage:2")));
assertThat(bundle.getDerivedBucketSpaceStates().size(), equalTo(3));
@@ -87,13 +85,13 @@ public class ClusterStateBundleTest {
}
@Test
- public void same_bundle_instance_considered_similar() {
+ void same_bundle_instance_considered_similar() {
ClusterStateBundle bundle = createTestBundle();
assertTrue(bundle.similarTo(bundle));
}
@Test
- public void similarity_test_considers_all_bucket_spaces() {
+ void similarity_test_considers_all_bucket_spaces() {
ClusterStateBundle bundle = createTestBundle(false);
ClusterStateBundle unchangedBundle = createTestBundle(false);
@@ -106,7 +104,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void similarity_test_considers_cluster_feed_block_state() {
+ void similarity_test_considers_cluster_feed_block_state() {
var nonBlockingBundle = createTestBundle(false);
var blockingBundle = createTestBundleWithFeedBlock("foo");
var blockingBundleWithOtherDesc = createTestBundleWithFeedBlock("bar");
@@ -119,7 +117,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void similarity_test_considers_cluster_feed_block_concrete_exhaustion_set() {
+ void similarity_test_considers_cluster_feed_block_concrete_exhaustion_set() {
var blockingBundleNoSet = createTestBundleWithFeedBlock("foo");
var blockingBundleWithSet = createTestBundleWithFeedBlock("bar", setOf(exhaustion(1, "beer"), exhaustion(1, "wine")));
var blockingBundleWithOtherSet = createTestBundleWithFeedBlock("bar", setOf(exhaustion(1, "beer"), exhaustion(1, "soda")));
@@ -132,7 +130,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void feed_block_state_is_available() {
+ void feed_block_state_is_available() {
var nonBlockingBundle = createTestBundle(false);
var blockingBundle = createTestBundleWithFeedBlock("foo");
@@ -147,14 +145,14 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_without_bucket_space_states_prints_only_baseline_state() {
+ void toString_without_bucket_space_states_prints_only_baseline_state() {
ClusterStateBundle bundle = ClusterStateBundle.ofBaselineOnly(
annotatedStateOf("distributor:2 storage:2"));
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2')"));
}
@Test
- public void toString_includes_all_bucket_space_states() {
+ void toString_includes_all_bucket_space_states() {
ClusterStateBundle bundle = createTestBundle();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -163,7 +161,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_with_feed_blocked_includes_description() {
+ void toString_with_feed_blocked_includes_description() {
var blockingBundle = createTestBundleWithFeedBlock("bear sleeping on server rack");
assertThat(blockingBundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2', " +
@@ -173,19 +171,19 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_without_derived_states_specifies_deferred_activation_iff_set() {
+ void toString_without_derived_states_specifies_deferred_activation_iff_set() {
var bundle = ClusterStateBundle.ofBaselineOnly(annotatedStateOf("distributor:2 storage:2"), null, true);
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2' (deferred activation))"));
}
@Test
- public void toString_without_derived_states_does_not_specify_deferred_activation_iff_not_set() {
+ void toString_without_derived_states_does_not_specify_deferred_activation_iff_not_set() {
var bundle = ClusterStateBundle.ofBaselineOnly(annotatedStateOf("distributor:2 storage:2"), null, false);
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2')"));
}
@Test
- public void toString_with_derived_states_specifies_deferred_activation_iff_set() {
+ void toString_with_derived_states_specifies_deferred_activation_iff_set() {
var bundle = createTestBundleBuilder(true).deferredActivation(true).deriveAndBuild();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -194,7 +192,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_with_derived_states_does_not_specify_deferred_activation_iff_not_set() {
+ void toString_with_derived_states_does_not_specify_deferred_activation_iff_not_set() {
var bundle = createTestBundleBuilder(true).deferredActivation(false).deriveAndBuild();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -203,25 +201,25 @@ public class ClusterStateBundleTest {
}
@Test
- public void deferred_activation_is_disabled_by_default() {
+ void deferred_activation_is_disabled_by_default() {
ClusterStateBundle bundle = createTestBundle();
assertFalse(bundle.deferredActivation());
}
@Test
- public void can_build_bundle_with_deferred_activation_enabled() {
+ void can_build_bundle_with_deferred_activation_enabled() {
var bundle = createTestBundleBuilder(false).deferredActivation(true).deriveAndBuild();
assertTrue(bundle.deferredActivation());
}
@Test
- public void can_build_bundle_with_deferred_activation_disabled() {
+ void can_build_bundle_with_deferred_activation_disabled() {
var bundle = createTestBundleBuilder(false).deferredActivation(false).deriveAndBuild();
assertFalse(bundle.deferredActivation());
}
@Test
- public void simple_bundle_without_derived_states_propagates_deferred_activation_flag() {
+ void simple_bundle_without_derived_states_propagates_deferred_activation_flag() {
var bundle = ClusterStateBundle
.builder(annotatedStateOf("distributor:2 storage:2"))
.deferredActivation(true) // defaults to false
@@ -230,22 +228,23 @@ public class ClusterStateBundleTest {
}
@Test
- public void cloning_preserves_false_deferred_activation_flag() {
+ void cloning_preserves_false_deferred_activation_flag() {
var bundle = createTestBundleBuilder(true).deferredActivation(false).deriveAndBuild();
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
@Test
- public void cloning_preserves_true_deferred_activation_flag() {
+ void cloning_preserves_true_deferred_activation_flag() {
var bundle = createTestBundleBuilder(true).deferredActivation(true).deriveAndBuild();
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
@Test
- public void cloning_preserves_feed_block_state() {
- var bundle = createTestBundleWithFeedBlock("foo");;
+ void cloning_preserves_feed_block_state() {
+ var bundle = createTestBundleWithFeedBlock("foo");
+ ;
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
index f857bfcee89..78911c414a2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Set;
@@ -30,7 +30,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_with_all_nodes_reported_down_has_state_down() {
+ void cluster_with_all_nodes_reported_down_has_state_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(6).markEntireClusterDown();
final AnnotatedClusterState state = generateFromFixtureWithDefaultParams(fixture);
@@ -41,7 +41,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_with_all_nodes_up_state_correct_distributor_and_storage_count() {
+ void cluster_with_all_nodes_up_state_correct_distributor_and_storage_count() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(6).bringEntireClusterUp();
final AnnotatedClusterState state = generateFromFixtureWithDefaultParams(fixture);
@@ -49,7 +49,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_reported_states_reflected_in_generated_state() {
+ void distributor_reported_states_reflected_in_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(9)
.bringEntireClusterUp()
.reportDistributorNodeState(2, State.DOWN)
@@ -61,7 +61,7 @@ public class ClusterStateGeneratorTest {
// NOTE: initializing state tested separately since it involves init progress state info
@Test
- public void storage_reported_states_reflected_in_generated_state() {
+ void storage_reported_states_reflected_in_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(9)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -72,7 +72,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void worse_distributor_wanted_state_overrides_reported_state() {
+ void worse_distributor_wanted_state_overrides_reported_state() {
// Maintenance mode is illegal for distributors and therefore not tested
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
@@ -85,7 +85,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void worse_storage_wanted_state_overrides_reported_state() {
+ void worse_storage_wanted_state_overrides_reported_state() {
// Does not test all maintenance mode overrides; see maintenance_mode_overrides_reported_state
// for that.
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
@@ -100,7 +100,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void better_distributor_wanted_state_does_not_override_reported_state() {
+ void better_distributor_wanted_state_does_not_override_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -111,7 +111,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void better_storage_wanted_state_does_not_override_reported_state() {
+ void better_storage_wanted_state_does_not_override_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.DOWN)
@@ -130,7 +130,7 @@ public class ClusterStateGeneratorTest {
* directly from Maintenance -> Up.
*/
@Test
- public void retired_node_in_init_state_is_set_to_maintenance() {
+ void retired_node_in_init_state_is_set_to_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.INITIALIZING)
@@ -152,7 +152,7 @@ public class ClusterStateGeneratorTest {
* value and triggering on a sufficiently low value.
*/
@Test
- public void storage_node_in_init_mode_while_listing_buckets_is_marked_down() {
+ void storage_node_in_init_mode_while_listing_buckets_is_marked_down() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.STORAGE, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -169,7 +169,7 @@ public class ClusterStateGeneratorTest {
* is set to Maintenance.
*/
@Test
- public void implicit_down_while_listing_buckets_does_not_override_wanted_state() {
+ void implicit_down_while_listing_buckets_does_not_override_wanted_state() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.STORAGE, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -183,7 +183,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_nodes_in_init_mode_are_not_mapped_to_down() {
+ void distributor_nodes_in_init_mode_are_not_mapped_to_down() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.DISTRIBUTOR, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -199,7 +199,7 @@ public class ClusterStateGeneratorTest {
* Maintenance mode overrides all reported states, even Down.
*/
@Test
- public void maintenance_mode_wanted_state_overrides_reported_state() {
+ void maintenance_mode_wanted_state_overrides_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(0, State.MAINTENANCE)
@@ -215,7 +215,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void wanted_state_description_carries_over_to_generated_state() {
+ void wanted_state_description_carries_over_to_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(1, State.MAINTENANCE, "foo")
@@ -230,7 +230,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void config_retired_mode_is_reflected_in_generated_state() {
+ void config_retired_mode_is_reflected_in_generated_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.markNodeAsConfigRetired(2)
.bringEntireClusterUp();
@@ -241,7 +241,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void config_retired_mode_is_overridden_by_worse_wanted_state() {
+ void config_retired_mode_is_overridden_by_worse_wanted_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.markNodeAsConfigRetired(2)
.markNodeAsConfigRetired(3)
@@ -279,17 +279,17 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void reported_down_node_within_transition_time_has_maintenance_generated_state() {
+ void reported_down_node_within_transition_time_has_maintenance_generated_state() {
do_test_change_within_node_transition_time_window_generates_maintenance(State.DOWN);
}
@Test
- public void reported_stopping_node_within_transition_time_has_maintenance_generated_state() {
+ void reported_stopping_node_within_transition_time_has_maintenance_generated_state() {
do_test_change_within_node_transition_time_window_generates_maintenance(State.STOPPING);
}
@Test
- public void reported_node_down_after_transition_time_has_down_generated_state() {
+ void reported_node_down_after_transition_time_has_down_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(11_000)
@@ -306,7 +306,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_nodes_are_not_implicitly_transitioned_to_maintenance_mode() {
+ void distributor_nodes_are_not_implicitly_transitioned_to_maintenance_mode() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -323,7 +323,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void transient_maintenance_mode_does_not_override_wanted_down_state() {
+ void transient_maintenance_mode_does_not_override_wanted_down_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -340,7 +340,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void reported_down_retired_node_within_transition_time_transitions_to_maintenance() {
+ void reported_down_retired_node_within_transition_time_transitions_to_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -356,7 +356,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void crash_count_exceeding_limit_marks_node_as_down() {
+ void crash_count_exceeding_limit_marks_node_as_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10);
@@ -368,7 +368,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void crash_count_not_exceeding_limit_does_not_mark_node_as_down() {
+ void crash_count_not_exceeding_limit_does_not_mark_node_as_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10);
@@ -380,7 +380,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void exceeded_crash_count_does_not_override_wanted_maintenance_state() {
+ void exceeded_crash_count_does_not_override_wanted_maintenance_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(1, State.MAINTENANCE);
@@ -395,7 +395,7 @@ public class ClusterStateGeneratorTest {
// Stopping -> Down is expected and does not indicate an unstable node.
@Test
- public void transition_from_controlled_stop_to_down_does_not_add_to_crash_counter() {
+ void transition_from_controlled_stop_to_down_does_not_add_to_crash_counter() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(2)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.STOPPING, "controlled shutdown") // urgh, string matching logic
@@ -405,7 +405,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void non_observed_storage_node_start_timestamp_is_included_in_state() {
+ void non_observed_storage_node_start_timestamp_is_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.STORAGE, State.UP);
// A reported state timestamp that is not yet marked as observed in the NodeInfo
// for the same node is considered not observed by other nodes and must therefore
@@ -421,7 +421,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void non_observed_distributor_start_timestamp_is_included_in_state() {
+ void non_observed_distributor_start_timestamp_is_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.DISTRIBUTOR, State.UP);
nodeState.setStartTimestamp(6000);
@@ -434,7 +434,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void fully_observed_storage_node_timestamp_not_included_in_state() {
+ void fully_observed_storage_node_timestamp_not_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.STORAGE, State.UP);
nodeState.setStartTimestamp(5000);
@@ -450,7 +450,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void fully_observed_distributor_timestamp_not_included_in_state() {
+ void fully_observed_distributor_timestamp_not_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.DISTRIBUTOR, State.UP);
nodeState.setStartTimestamp(6000);
@@ -466,7 +466,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_count_of_storage_nodes_available() {
+ void cluster_down_if_less_than_min_count_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -479,7 +479,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_count_of_storage_nodes_are_available() {
+ void cluster_not_down_if_more_than_min_count_of_storage_nodes_are_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN);
@@ -491,7 +491,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_count_of_distributors_available() {
+ void cluster_down_if_less_than_min_count_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -504,7 +504,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_count_of_distributors_are_available() {
+ void cluster_not_down_if_more_than_min_count_of_distributors_are_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN);
@@ -516,7 +516,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void maintenance_mode_counted_as_down_for_cluster_availability() {
+ void maintenance_mode_counted_as_down_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -528,7 +528,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void init_and_retired_counted_as_up_for_cluster_availability() {
+ void init_and_retired_counted_as_up_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.INITIALIZING)
@@ -541,7 +541,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_ratio_of_storage_nodes_available() {
+ void cluster_down_if_less_than_min_ratio_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -555,7 +555,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_ratio_of_storage_nodes_available() {
+ void cluster_not_down_if_more_than_min_ratio_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN);
@@ -568,7 +568,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_ratio_of_distributors_available() {
+ void cluster_down_if_less_than_min_ratio_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -582,7 +582,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_ratio_of_distributors_available() {
+ void cluster_not_down_if_more_than_min_ratio_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN);
@@ -594,7 +594,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_marked_down_if_group_availability_too_low() {
+ void group_nodes_are_marked_down_if_group_availability_too_low() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -608,7 +608,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
+ void group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -620,7 +620,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void implicitly_downed_group_nodes_receive_a_state_description() {
+ void implicitly_downed_group_nodes_receive_a_state_description() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(2).eachWithNodeCount(2))
.bringEntireClusterUp()
@@ -634,7 +634,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void implicitly_downed_group_nodes_are_annotated_with_group_reason() {
+ void implicitly_downed_group_nodes_are_annotated_with_group_reason() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(2).eachWithNodeCount(2))
.bringEntireClusterUp()
@@ -647,7 +647,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void maintenance_nodes_in_downed_group_are_not_affected() {
+ void maintenance_nodes_in_downed_group_are_not_affected() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -664,7 +664,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_marked_maintenance_if_group_availability_too_low_by_orchestrator() {
+ void group_nodes_are_marked_maintenance_if_group_availability_too_low_by_orchestrator() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -679,7 +679,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_not_marked_maintenance_if_group_availability_high_by_orchestrator() {
+ void group_nodes_are_not_marked_maintenance_if_group_availability_high_by_orchestrator() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -698,7 +698,7 @@ public class ClusterStateGeneratorTest {
* and any buckets caught over this level would not be accessible in the data space.
*/
@Test
- public void distribution_bits_bounded_by_reported_min_bits_from_storage_node() {
+ void distribution_bits_bounded_by_reported_min_bits_from_storage_node() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(1, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(7));
@@ -708,7 +708,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distribution_bits_bounded_by_lowest_reporting_storage_node() {
+ void distribution_bits_bounded_by_lowest_reporting_storage_node() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(6))
@@ -719,7 +719,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distribution_bits_bounded_by_config_parameter() {
+ void distribution_bits_bounded_by_config_parameter() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().idealDistributionBits(12);
@@ -731,7 +731,7 @@ public class ClusterStateGeneratorTest {
// TODO We generally want to avoid distribution bit decreases if at all possible, since "collapsing"
// the top-level bucket space can cause data loss on timestamp collisions across super buckets.
@Test
- public void distribution_bit_not_influenced_by_nodes_down_or_in_maintenance() {
+ void distribution_bit_not_influenced_by_nodes_down_or_in_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(7))
@@ -760,20 +760,20 @@ public class ClusterStateGeneratorTest {
* let e.g. a transition from 10 bits to 20 bits cause 10 interim full re-distributions.
*/
@Test
- public void published_distribution_bit_bound_by_low_watermark_when_nodes_report_less_than_config_bits() {
+ void published_distribution_bit_bound_by_low_watermark_when_nodes_report_less_than_config_bits() {
assertThat(do_test_distribution_bit_watermark(5, 5),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
assertThat(do_test_distribution_bit_watermark(5, 6),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
assertThat(do_test_distribution_bit_watermark(5, 15),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
}
@Test
- public void published_state_jumps_to_configured_ideal_bits_when_all_nodes_report_it() {
+ void published_state_jumps_to_configured_ideal_bits_when_all_nodes_report_it() {
// Note: the rest of the mocked nodes always report 16 bits by default
assertThat(do_test_distribution_bit_watermark(5, 16),
- equalTo("distributor:3 storage:3")); // "bits:16" implied
+ equalTo("distributor:3 storage:3")); // "bits:16" implied
}
private String do_test_storage_node_with_no_init_progress(State wantedState) {
@@ -793,9 +793,9 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void storage_node_with_no_init_progress_within_timeout_is_marked_down() {
+ void storage_node_with_no_init_progress_within_timeout_is_marked_down() {
assertThat(do_test_storage_node_with_no_init_progress(State.UP),
- equalTo("distributor:3 storage:3 .0.s:d"));
+ equalTo("distributor:3 storage:3 .0.s:d"));
}
/**
@@ -803,9 +803,9 @@ public class ClusterStateGeneratorTest {
* as the wanted state.
*/
@Test
- public void maintenance_wanted_state_overrides_storage_node_with_no_init_progress() {
+ void maintenance_wanted_state_overrides_storage_node_with_no_init_progress() {
assertThat(do_test_storage_node_with_no_init_progress(State.MAINTENANCE),
- equalTo("distributor:3 storage:3 .0.s:m"));
+ equalTo("distributor:3 storage:3 .0.s:m"));
}
/**
@@ -816,7 +816,7 @@ public class ClusterStateGeneratorTest {
* their init stage and would otherwise pop in and out of the cluster state.
*/
@Test
- public void unstable_init_storage_node_has_init_state_substituted_by_down() {
+ void unstable_init_storage_node_has_init_state_substituted_by_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.INITIALIZING)
@@ -828,7 +828,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void storage_node_with_crashes_but_not_unstable_init_does_not_have_init_state_substituted_by_down() {
+ void storage_node_with_crashes_but_not_unstable_init_does_not_have_init_state_substituted_by_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.INITIALIZING).setInitProgress(0.5f));
@@ -846,7 +846,7 @@ public class ClusterStateGeneratorTest {
* potentially contributing additional instability to the cluster.
*/
@Test
- public void unstable_retired_node_should_be_marked_down() {
+ void unstable_retired_node_should_be_marked_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(3, State.RETIRED);
@@ -860,7 +860,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void generator_params_can_inherit_values_from_controller_options() {
+ void generator_params_can_inherit_values_from_controller_options() {
FleetControllerOptions options = new FleetControllerOptions("foocluster", Set.of(new ConfiguredNode(0, false)));
options.maxPrematureCrashes = 1;
options.minStorageNodesUp = 2;
@@ -881,7 +881,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void configured_zero_init_progress_time_disables_auto_init_to_down_feature() {
+ void configured_zero_init_progress_time_disables_auto_init_to_down_feature() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.INITIALIZING).setInitProgress(0.5f));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
index 1125c431cae..473007f6a7c 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.*;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.hostinfo.StorageNodeStatsBridge;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
/**
@@ -25,7 +25,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testWrongNodeType() {
+ void testWrongNodeType() {
when(nodeInfo.isDistributor()).thenReturn(false);
clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("101"));
@@ -34,7 +34,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testStateVersionMismatch() {
+ void testStateVersionMismatch() {
when(nodeInfo.isDistributor()).thenReturn(true);
when(clusterState.getVersion()).thenReturn(101);
@@ -44,7 +44,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testFailToGetStats() {
+ void testFailToGetStats() {
when(nodeInfo.isDistributor()).thenReturn(true);
when(clusterState.getVersion()).thenReturn(101);
@@ -54,17 +54,17 @@ public class ClusterStateViewTest {
}
@Test
- public void testSuccessCase() {
+ void testSuccessCase() {
when(nodeInfo.isDistributor()).thenReturn(true);
HostInfo hostInfo = HostInfo.createHostInfo(
"{" +
- " \"cluster-state-version\": 101," +
- " \"distributor\": {\n" +
- " \"storage-nodes\": [\n" +
- " {\n" +
- " \"node-index\": 3\n" +
- " }\n" +
- " ]}}");
+ " \"cluster-state-version\": 101," +
+ " \"distributor\": {\n" +
+ " \"storage-nodes\": [\n" +
+ " {\n" +
+ " \"node-index\": 3\n" +
+ " }\n" +
+ " ]}}");
when(nodeInfo.getNodeIndex()).thenReturn(3);
@@ -76,7 +76,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testIndicesOfUpNodes() {
+ void testIndicesOfUpNodes() {
when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7);
NodeState nodeState = mock(NodeState.class);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
index 11c00414cb8..2b62915439f 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
@@ -2,13 +2,11 @@
package com.yahoo.vespa.clustercontroller.core;
import com.google.common.collect.Sets;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -67,7 +65,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_updates_to_single_distributor_and_content_node() {
+ void aggregator_handles_updates_to_single_distributor_and_content_node() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3));
ContentClusterStatsBuilder stats = new ContentClusterStatsBuilder()
.add(3, "default", 10, 1)
@@ -77,7 +75,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_updates_to_multiple_distributors_and_content_nodes() {
+ void aggregator_handles_updates_to_multiple_distributors_and_content_nodes() {
Fixture f = new FourNodesFixture();
f.verify(new ContentClusterStatsBuilder()
@@ -88,7 +86,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_multiple_updates_from_same_distributor() {
+ void aggregator_handles_multiple_updates_from_same_distributor() {
Fixture f = new Fixture(distributorNodes(1, 2), contentNodes(3));
f.update(1, new ContentClusterStatsBuilder().add(3, "default"));
@@ -111,7 +109,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_more_content_nodes_that_distributors() {
+ void aggregator_handles_more_content_nodes_that_distributors() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3, 4));
ContentClusterStatsBuilder stats = new ContentClusterStatsBuilder()
.add(3, "default", 10, 1)
@@ -121,7 +119,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_ignores_updates_to_unknown_distributor() {
+ void aggregator_ignores_updates_to_unknown_distributor() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3));
final int downDistributorIndex = 2;
f.update(downDistributorIndex, new ContentClusterStatsBuilder()
@@ -130,7 +128,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_tracks_when_it_has_updates_from_all_distributors() {
+ void aggregator_tracks_when_it_has_updates_from_all_distributors() {
Fixture f = new Fixture(distributorNodes(1, 2), contentNodes(3));
assertFalse(f.hasUpdatesFromAllDistributors());
f.update(1, new ContentClusterStatsBuilder().add(3, "default"));
@@ -142,7 +140,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_can_provide_aggregated_stats_per_distributor() {
+ void aggregator_can_provide_aggregated_stats_per_distributor() {
Fixture f = new FourNodesFixture();
f.verify(1, ContentNodeStatsBuilder.forNode(1)
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
index ae237b3330e..b9e7714671c 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.core;
import com.google.common.collect.Sets;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClusterStatsChangeTrackerTest {
@@ -74,39 +74,39 @@ public class ClusterStatsChangeTrackerTest {
}
@Test
- public void stats_have_not_changed_if_not_all_distributors_are_updated() {
+ void stats_have_not_changed_if_not_all_distributors_are_updated() {
Fixture f = Fixture.empty();
assertFalse(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_in_sync_node_not_found_in_previous_stats() {
+ void stats_have_changed_if_in_sync_node_not_found_in_previous_stats() {
Fixture f = Fixture.fromStats(stats().inSync(0));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_buckets_pending_node_not_found_in_previous_stats() {
+ void stats_have_changed_if_buckets_pending_node_not_found_in_previous_stats() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_one_node_has_in_sync_to_buckets_pending_transition() {
+ void stats_have_changed_if_one_node_has_in_sync_to_buckets_pending_transition() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).inSync(1));
f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_one_node_has_buckets_pending_to_in_sync_transition() {
+ void stats_have_changed_if_one_node_has_buckets_pending_to_in_sync_transition() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).bucketsPending(1));
f.newAggregatedStats(stats().bucketsPending(0).inSync(1));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_not_changed_if_no_nodes_have_changed_state() {
+ void stats_have_not_changed_if_no_nodes_have_changed_state() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).bucketsPending(1));
f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1));
assertFalse(f.statsHaveChanged());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
index ff1c5b0bb17..d43a3e13c6a 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
@@ -7,8 +7,8 @@ import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.VdsClusterHtmlRenderer;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONWriter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.StringWriter;
import java.io.Writer;
@@ -27,7 +27,7 @@ public class ContentClusterHtmlRendererTest {
private final TreeMap<Integer, NodeInfo> distributorNodeInfoByIndex = new TreeMap<>();
private String result;
- @Before
+ @BeforeEach
public void before() throws JSONException {
final ClusterStateBundle stateBundle = ClusterStateBundle.ofBaselineOnly(
AnnotatedClusterState.withoutAnnotations(
@@ -71,7 +71,7 @@ public class ContentClusterHtmlRendererTest {
}
@Test
- public void testVtagRendering() {
+ void testVtagRendering() {
// 9 distribution nodes should have green tag on release1.
assertThat(result.split("<td bgcolor=\"#c0ffc0\" align=\"right\"><nobr>release1</nobr></td>").length, is(10));
// 1 distribution node should have warning on release1bad.
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
index 47d1970e4d6..d30de6f7954 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
@@ -1,18 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.clustercontroller.core.ContentNodeStats.BucketSpaceStats;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class ContentNodeStatsTest {
@Test
- public void bucket_space_stats_can_transition_from_valid_to_invalid() {
- BucketSpaceStats stats = BucketSpaceStats.of(5,1);
+ void bucket_space_stats_can_transition_from_valid_to_invalid() {
+ BucketSpaceStats stats = BucketSpaceStats.of(5, 1);
assertTrue(stats.valid());
stats.merge(BucketSpaceStats.invalid(), 1);
@@ -21,7 +19,7 @@ public class ContentNodeStatsTest {
}
@Test
- public void bucket_space_stats_can_transition_from_invalid_to_valid() {
+ void bucket_space_stats_can_transition_from_invalid_to_valid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
assertFalse(stats.valid());
@@ -33,7 +31,7 @@ public class ContentNodeStatsTest {
}
@Test
- public void bucket_space_stats_tracks_multiple_layers_of_invalid() {
+ void bucket_space_stats_tracks_multiple_layers_of_invalid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
stats.merge(BucketSpaceStats.invalid(), 1);
assertFalse(stats.valid());
@@ -52,19 +50,19 @@ public class ContentNodeStatsTest {
}
@Test
- public void invalid_bucket_space_stats_may_have_pending_buckets() {
+ void invalid_bucket_space_stats_may_have_pending_buckets() {
assertTrue(BucketSpaceStats.invalid().mayHaveBucketsPending(1.0));
}
@Test
- public void bucket_space_stats_without_buckets_total_use_buckets_pending_to_calculate_may_have_buckets_pending() {
+ void bucket_space_stats_without_buckets_total_use_buckets_pending_to_calculate_may_have_buckets_pending() {
assertTrue(BucketSpaceStats.of(0, 2).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(0, 1).mayHaveBucketsPending(0.6));
assertFalse(BucketSpaceStats.of(0, 0).mayHaveBucketsPending(0.6));
}
@Test
- public void min_merge_completion_ratio_is_used_to_calculate_bucket_space_stats_may_have_buckets_pending() {
+ void min_merge_completion_ratio_is_used_to_calculate_bucket_space_stats_may_have_buckets_pending() {
assertTrue(BucketSpaceStats.of(5, 6).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(5, 5).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(5, 4).mayHaveBucketsPending(0.6));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
index 1f7b9293960..4d8c7799c58 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
@@ -10,9 +10,9 @@ import com.yahoo.vespa.clustercontroller.core.database.DatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
@@ -20,8 +20,8 @@ import org.mockito.MockitoAnnotations;
import java.util.Map;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
@@ -89,18 +89,18 @@ public class DatabaseHandlerTest {
}
}
- @Before
+ @BeforeEach
public void setUp() {
openMock = MockitoAnnotations.openMocks(this);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
openMock.close();
}
@Test
- public void can_store_latest_cluster_state_bundle() throws Exception {
+ void can_store_latest_cluster_state_bundle() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
handler.doNextZooKeeperTask(f.createMockContext()); // Database setup step
@@ -110,7 +110,7 @@ public class DatabaseHandlerTest {
}
@Test
- public void can_load_latest_cluster_state_bundle() throws Exception {
+ void can_load_latest_cluster_state_bundle() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
handler.doNextZooKeeperTask(f.createMockContext()); // Database setup step
@@ -124,7 +124,7 @@ public class DatabaseHandlerTest {
// FIXME I don't like the semantics of this, but it mirrors the legacy behavior for the
// rest of the DB load operations exposed by the DatabaseHandler.
@Test
- public void empty_bundle_is_returned_if_no_db_connection() throws Exception {
+ void empty_bundle_is_returned_if_no_db_connection() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
// Note: no DB setup step
@@ -134,7 +134,7 @@ public class DatabaseHandlerTest {
}
@Test
- public void save_wanted_state_of_configured_nodes() throws Exception {
+ void save_wanted_state_of_configured_nodes() throws Exception {
var fixture = new Fixture();
DatabaseHandler handler = fixture.createHandler();
DatabaseHandler.DatabaseContext databaseContext = fixture.createMockContext();
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
index 2ff48e00d0f..9a6a9e063ac 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
@@ -12,22 +12,21 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class DatabaseTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(DatabaseTest.class.getName());
@Test
- public void testWantedStatesInZooKeeper() throws Exception {
+ void testWantedStatesInZooKeeper() throws Exception {
startingTest("DatabaseTest::testWantedStatesInZooKeeper");
FleetControllerOptions options = defaultOptions("mycluster");
options.zooKeeperServerAddress = "127.0.0.1";
@@ -61,7 +60,7 @@ public class DatabaseTest extends FleetControllerTest {
log.info("CHECK THAT WANTED STATES PERSIST FLEETCONTROLLER RESTART");
stopFleetController();
- startFleetController();
+ startFleetController(false);
waitForState("version:\\d+ distributor:10 .2.s:d storage:10 .3.s:m .7.s:r");
assertWantedStates(wantedStates);
@@ -81,7 +80,7 @@ public class DatabaseTest extends FleetControllerTest {
}
@Test
- public void testWantedStateOfUnknownNode() throws Exception {
+ void testWantedStateOfUnknownNode() throws Exception {
startingTest("DatabaseTest::testWantedStatesOfUnknownNode");
FleetControllerOptions options = defaultOptions("mycluster");
options.minRatioOfDistributorNodesUp = 0;
@@ -124,22 +123,22 @@ public class DatabaseTest extends FleetControllerTest {
assertWantedStates(wantedStates);
stopFleetController();
- for (int i=6; i<nodes.size(); ++i) nodes.get(i).disconnect();
- startFleetController();
+ for (int i = 6; i < nodes.size(); ++i) nodes.get(i).disconnect();
+ startFleetController(false);
waitForState("version:\\d+ distributor:3 storage:7 .1.s:m .3.s:d .4.s:d .5.s:d .6.s:m");
setWantedState(new Node(NodeType.STORAGE, 6), new NodeState(NodeType.STORAGE, State.UP), wantedStates);
waitForState("version:\\d+ distributor:3 storage:3 .1.s:m");
- for (int i=6; i<nodes.size(); ++i) nodes.get(i).connect();
+ for (int i = 6; i < nodes.size(); ++i) nodes.get(i).connect();
waitForState("version:\\d+ distributor:10 .8.s:d storage:10 .1.s:m .7.s:r .8.s:d");
assertWantedStates(wantedStates);
}
private void assertWantedStates(Map<Node, NodeState> wantedStates) {
for (DummyVdsNode node : nodes) {
- assertEquals(node.getNode().toString(), wantedStates.get(node.getNode()), fleetController.getWantedNodeState(node.getNode()));
+ assertEquals(wantedStates.get(node.getNode()), fleetController.getWantedNodeState(node.getNode()), node.getNode().toString());
}
}
@@ -155,9 +154,9 @@ public class DatabaseTest extends FleetControllerTest {
Request req = new Request("setNodeState");
req.parameters().add(new StringValue("storage/cluster.mycluster/" + n.getType().toString() + "/" + n.getIndex()));
req.parameters().add(new StringValue(ns.serialize(true)));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ connection.invokeSync(req, timeout());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
wantedStates.put(n, ns);
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
index e9d3a9cf83e..d3b0addbb13 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
@@ -6,12 +6,12 @@ import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class DistributionBitCountTest extends FleetControllerTest {
@@ -37,7 +37,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then altering config to increased bit count, that a new system state is not sent out (and not altered) if a storagenode needs it to be no further split.
*/
@Test
- public void testDistributionBitCountConfigIncrease() throws Exception {
+ void testDistributionBitCountConfigIncrease() throws Exception {
setUpSystem("DistributionBitCountTest::testDistributionBitCountConfigIncrease");
options.distributionBits = 20;
fleetController.updateOptions(options);
@@ -53,7 +53,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then altering config to decrease bit count, that a new system state is sent out with that bit count.
*/
@Test
- public void testDistributionBitCountConfigDecrease() throws Exception {
+ void testDistributionBitCountConfigDecrease() throws Exception {
setUpSystem("DistributionBitCountTest::testDistributionBitCountConfigDecrease");
options.distributionBits = 12;
fleetController.updateOptions(options);
@@ -69,7 +69,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* node now being lowest, the fleetcontroller adjusts to use that bit in system state.
*/
@Test
- public void testStorageNodeReportingHigherBitCount() throws Exception {
+ void testStorageNodeReportingHigherBitCount() throws Exception {
setUpSystem("DistributionBitCountTest::testStorageNodeReportingHigherBitCount");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(11));
@@ -78,12 +78,11 @@ public class DistributionBitCountTest extends FleetControllerTest {
ClusterState startState = waitForState("version:\\d+ bits:11 distributor:10 storage:10");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(12));
- assertEquals(startState + "->" + fleetController.getSystemState(),
- startState.getVersion(), fleetController.getSystemState().getVersion());
+ assertEquals(startState.getVersion(), fleetController.getSystemState().getVersion(), startState + "->" + fleetController.getSystemState());
for (int i = 0; i < 10; ++i) {
// nodes is array of [distr.0, stor.0, distr.1, stor.1, ...] and we just want the storage nodes
- nodes.get(i*2 + 1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(17));
+ nodes.get(i * 2 + 1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(17));
}
assertEquals(startState.getVersion() + 1, waitForState("version:\\d+ bits:17 distributor:10 storage:10").getVersion());
}
@@ -93,7 +92,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then storage node report lower bit count, and then becomes the smallest, the fleetcontroller adjusts to use that bit in system state.
*/
@Test
- public void testStorageNodeReportingLowerBitCount() throws Exception {
+ void testStorageNodeReportingLowerBitCount() throws Exception {
setUpSystem("DistributionBitCountTest::testStorageNodeReportingLowerBitCount");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(13));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DummyVdsNode.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DummyVdsNode.java
index c167c82aa90..fd24966e26a 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DummyVdsNode.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DummyVdsNode.java
@@ -21,7 +21,8 @@ import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.rpc.RPCCommunicator;
import com.yahoo.vespa.clustercontroller.core.rpc.RPCUtil;
-
+import java.time.Duration;
+import java.time.Instant;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@@ -39,7 +40,7 @@ import java.util.stream.Collectors;
*/
public class DummyVdsNode {
- public static Logger log = Logger.getLogger(DummyVdsNode.class.getName());
+ private static final Logger log = Logger.getLogger(DummyVdsNode.class.getName());
private final String[] slobrokConnectionSpecs;
private final String clusterName;
@@ -55,7 +56,7 @@ public class DummyVdsNode {
private final Timer timer;
private boolean failSetSystemStateRequests = false;
private boolean resetTimestampOnReconnect = false;
- private final Map<Node, Long> highestStartTimestamps = new TreeMap<Node, Long>();
+ private final Map<Node, Long> highestStartTimestamps = new TreeMap<>();
int timedOutStateReplies = 0;
int outdatedStateReplies = 0;
int immediateStateReplies = 0;
@@ -88,7 +89,7 @@ public class DummyVdsNode {
private final Thread messageResponder = new Thread() {
public void run() {
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": starting message reponder thread");
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": starting message responder thread");
while (true) {
synchronized (timer) {
if (isInterrupted()) break;
@@ -96,7 +97,7 @@ public class DummyVdsNode {
for (Iterator<Req> it = waitingRequests.iterator(); it.hasNext(); ) {
Req r = it.next();
if (r.timeout <= currentTime) {
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": Responding to node state request at time " + currentTime);
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": Responding to node state request at time " + currentTime);
r.request.returnValues().add(new StringValue(nodeState.serialize()));
if (r.request.methodName().equals("getnodestate3")) {
r.request.returnValues().add(new StringValue("No host info in dummy implementation"));
@@ -113,7 +114,7 @@ public class DummyVdsNode {
}
}
}
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": shut down message reponder thread");
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": shut down message responder thread");
}
};
@@ -170,31 +171,16 @@ public class DummyVdsNode {
registeredInSlobrok = false;
}
- void disconnect() { disconnectImmediately(); }
- void disconnectImmediately() { disconnect(false, 0, false); }
- void disconnectBreakConnection() { disconnect(true, FleetControllerTest.timeoutMS, false); }
- void disconnectAsShutdown() { disconnect(true, FleetControllerTest.timeoutMS, true); }
- private void disconnect(boolean waitForPendingNodeStateRequest, long timeoutms, boolean setStoppingStateFirst) {
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": Breaking connection." + (waitForPendingNodeStateRequest ? " Waiting for pending state first." : ""));
- if (waitForPendingNodeStateRequest) {
- this.waitForPendingGetNodeStateRequest(timeoutms);
- }
- if (setStoppingStateFirst) {
- NodeState newState = nodeState.clone();
- newState.setState(State.STOPPING);
- // newState.setDescription("Received signal 15 (SIGTERM - Termination signal)");
- // Altered in storageserver implementation. Updating now to fit
- newState.setDescription("controlled shutdown");
- setNodeState(newState);
- // Sleep a bit in hopes of answer being written before shutting down socket
- try{ Thread.sleep(10); } catch (InterruptedException e) { /* ignore */ }
- }
+ void disconnectImmediately() { disconnect(); }
+
+ void disconnect() {
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": Breaking connection.");
if (supervisor == null) return;
register.shutdown();
acceptor.shutdown().join();
supervisor.transport().shutdown().join();
supervisor = null;
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": Done breaking connection.");
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": Done breaking connection.");
}
public String toString() {
@@ -210,11 +196,11 @@ public class DummyVdsNode {
public int getStateCommunicationVersion() { return stateCommunicationVersion; }
- void waitForSystemStateVersion(int version, long timeout) {
+ void waitForSystemStateVersion(int version, Duration timeout) {
try {
- long startTime = System.currentTimeMillis();
+ Instant endTime = Instant.now().plus(timeout);
while (getLatestSystemStateVersion().orElse(-1) < version) {
- if ( (System.currentTimeMillis() - startTime) > timeout)
+ if (Instant.now().isAfter(endTime))
throw new RuntimeException("Timed out waiting for state version " + version + " in " + this);
Thread.sleep(10);
}
@@ -237,33 +223,6 @@ public class DummyVdsNode {
}
}
- private void waitForPendingGetNodeStateRequest(long timeout) {
- long startTime = System.currentTimeMillis();
- long endTime = startTime + timeout;
- log.log(Level.FINE, () -> "Dummy node " + this + " waiting for pending node state request.");
- while (true) {
- synchronized(timer) {
- if (!waitingRequests.isEmpty()) {
- log.log(Level.FINE, () -> "Dummy node " + this + " has pending request, returning.");
- return;
- }
- try {
- log.log(Level.FINE, "Dummy node " + this + " waiting " + (endTime - startTime) + " ms for pending request.");
- timer.wait(endTime - startTime);
- } catch (InterruptedException e) { /* ignore */ }
- log.log(Level.FINE, () -> "Dummy node " + this + " woke up to recheck.");
- }
- startTime = System.currentTimeMillis();
- if (startTime >= endTime) {
- log.log(Level.FINE, () -> "Dummy node " + this + " timeout passed. Don't have pending request.");
- if (!waitingRequests.isEmpty()) {
- log.log(Level.FINE, () -> "Dummy node " + this + ". Non-empty set of waiting requests");
- }
- throw new IllegalStateException("Timeout. No pending get node state request pending after waiting " + timeout + " milliseconds.");
- }
- }
- }
-
void replyToPendingNodeStateRequests() {
for(Req req : waitingRequests) {
log.log(Level.FINE, () -> "Dummy node " + this + " answering pending node state request.");
@@ -422,7 +381,7 @@ public class DummyVdsNode {
for (Iterator<Req> it = waitingRequests.iterator(); it.hasNext(); ) {
Req r = it.next();
if (r.request.parameters().size() > 2 && r.request.parameters().get(2).asInt32() == index) {
- log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this.toString() + ": Responding to node state reply from controller " + index + " as we received new one");
+ log.log(Level.FINE, () -> "Dummy node " + DummyVdsNode.this + ": Responding to node state reply from controller " + index + " as we received new one");
r.request.returnValues().add(new StringValue(nodeState.serialize()));
r.request.returnValues().add(new StringValue("No host info from dummy implementation"));
r.request.returnRequest();
@@ -448,9 +407,9 @@ public class DummyVdsNode {
NodeState givenState = (oldState.equals("unknown") ? null : NodeState.deserialize(type, oldState));
if (givenState != null && (givenState.equals(nodeState) || sentReply)) {
log.log(Level.FINE, () -> "Dummy node " + this + ": Has same state as reported " + givenState + ". Queing request. Timeout is " + timeout + " ms. "
- + "Will be answered at time " + (timer.getCurrentTimeInMillis() + timeout * 800l / 1000));
+ + "Will be answered at time " + (timer.getCurrentTimeInMillis() + timeout * 800L / 1000));
req.detach();
- waitingRequests.add(new Req(req, timer.getCurrentTimeInMillis() + timeout * 800l / 1000));
+ waitingRequests.add(new Req(req, timer.getCurrentTimeInMillis() + timeout * 800L / 1000));
log.log(Level.FINE, () -> "Dummy node " + this + " has now " + waitingRequests.size() + " entries and is " + (waitingRequests.isEmpty() ? "empty" : "not empty"));
timer.notifyAll();
} else {
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
index 48d6ccbf655..8b07c216774 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
@@ -18,7 +18,7 @@ import static org.hamcrest.CoreMatchers.hasItem;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.storageNode;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.distributorNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
@@ -124,7 +124,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void single_storage_node_state_transition_emits_altered_node_state_event() {
+ void single_storage_node_state_transition_emits_altered_node_state_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3 .0.s:d");
@@ -138,7 +138,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void single_distributor_node_state_transition_emits_altered_node_state_event() {
+ void single_distributor_node_state_transition_emits_altered_node_state_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 .1.s:d storage:3");
@@ -152,7 +152,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void node_state_change_event_is_tagged_with_given_time() {
+ void node_state_change_event_is_tagged_with_given_time() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -164,7 +164,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void multiple_node_state_transitions_emit_multiple_node_state_events() {
+ void multiple_node_state_transitions_emit_multiple_node_state_events() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .1.s:d")
.clusterStateAfter("distributor:3 .2.s:d storage:3 .0.s:r");
@@ -183,7 +183,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void no_emitted_node_state_event_when_node_state_not_changed() {
+ void no_emitted_node_state_event_when_node_state_not_changed() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3");
@@ -193,7 +193,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void node_down_edge_with_group_down_reason_has_separate_event_emitted() {
+ void node_down_edge_with_group_down_reason_has_separate_event_emitted() {
// We sneakily use a flat cluster here but still use a 'group down' reason. Differ doesn't currently care.
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
@@ -213,7 +213,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void group_down_to_group_down_does_not_emit_new_event() {
+ void group_down_to_group_down_does_not_emit_new_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .1.s:d")
.clusterStateAfter("distributor:3 storage:3 .1.s:m")
@@ -229,7 +229,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void group_down_to_clear_reason_emits_group_up_event() {
+ void group_down_to_clear_reason_emits_group_up_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .2.s:d")
.clusterStateAfter("distributor:3 storage:3")
@@ -247,7 +247,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_up_edge_emits_sufficient_node_availability_event() {
+ void cluster_up_edge_emits_sufficient_node_availability_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("cluster:d distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3");
@@ -259,7 +259,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_down_event_without_reason_annotation_emits_generic_down_event() {
+ void cluster_down_event_without_reason_annotation_emits_generic_down_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3");
@@ -271,7 +271,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_event_is_tagged_with_given_time() {
+ void cluster_event_is_tagged_with_given_time() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -283,7 +283,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void no_event_emitted_for_cluster_down_to_down_edge() {
+ void no_event_emitted_for_cluster_down_to_down_edge() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("cluster:d distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3");
@@ -293,7 +293,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_few_storage_nodes_cluster_down_reason_emits_corresponding_event() {
+ void too_few_storage_nodes_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -307,7 +307,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_few_distributor_nodes_cluster_down_reason_emits_corresponding_event() {
+ void too_few_distributor_nodes_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -320,7 +320,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_low_storage_node_ratio_cluster_down_reason_emits_corresponding_event() {
+ void too_low_storage_node_ratio_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -333,7 +333,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_low_distributor_node_ratio_cluster_down_reason_emits_corresponding_event() {
+ void too_low_distributor_node_ratio_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -346,7 +346,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void may_have_merges_pending_up_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
+ void may_have_merges_pending_up_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -367,7 +367,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void may_have_merges_pending_down_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
+ void may_have_merges_pending_down_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3 .1.s:m")
@@ -388,7 +388,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void both_baseline_and_derived_bucket_space_state_events_are_emitted() {
+ void both_baseline_and_derived_bucket_space_state_events_are_emitted() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -408,7 +408,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void derived_bucket_space_state_events_are_not_emitted_if_similar_to_baseline() {
+ void derived_bucket_space_state_events_are_not_emitted_if_similar_to_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -426,7 +426,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void storage_node_passed_maintenance_grace_period_emits_event() {
+ void storage_node_passed_maintenance_grace_period_emits_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .0.s:m")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -443,7 +443,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() {
+ void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .0.s:u")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -457,7 +457,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engage_edge_emits_cluster_event() {
+ void feed_block_engage_edge_emits_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
@@ -471,7 +471,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_disengage_edge_emits_cluster_event() {
+ void feed_block_disengage_edge_emits_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWithDescription("we're closed"))
@@ -484,7 +484,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engaged_to_engaged_edge_does_not_emit_new_cluster_event() {
+ void feed_block_engaged_to_engaged_edge_does_not_emit_new_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWithDescription("we're closed"))
@@ -496,7 +496,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engage_edge_with_node_exhaustion_info_emits_cluster_and_node_events() {
+ void feed_block_engage_edge_with_node_exhaustion_info_emits_cluster_and_node_events() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
@@ -515,7 +515,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void added_exhaustion_in_feed_block_resource_set_emits_node_event() {
+ void added_exhaustion_in_feed_block_resource_set_emits_node_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWith(
@@ -533,7 +533,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void removed_exhaustion_in_feed_block_resource_set_emits_node_event() {
+ void removed_exhaustion_in_feed_block_resource_set_emits_node_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWith(
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
index afbc50124e2..eee0cb41eeb 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
@@ -3,19 +3,22 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeType;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import java.util.logging.Level;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class EventLogTest {
private final MetricUpdater metricUpdater = mock(MetricUpdater.class);
private final NodeEvent nodeEvent = mock(NodeEvent.class);
@@ -33,7 +36,7 @@ public class EventLogTest {
}
@Test
- public void testMetric() {
+ void testMetric() {
initialize(metricUpdater);
eventLog.addNodeOnlyEvent(nodeEvent, Level.INFO);
@@ -43,7 +46,7 @@ public class EventLogTest {
}
@Test
- public void testNullMetricReporter() {
+ void testNullMetricReporter() {
initialize(null);
eventLog.addNodeOnlyEvent(nodeEvent, Level.INFO);
@@ -52,7 +55,7 @@ public class EventLogTest {
}
@Test
- public void testNoEventsDoNotThrowException() {
+ void testNoEventsDoNotThrowException() {
initialize(metricUpdater);
StringBuilder builder = new StringBuilder();
Node nonExistantNode = new Node(NodeType.DISTRIBUTOR, 0);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java
index 450975076bb..96ce050f33b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -9,7 +9,7 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -20,7 +20,7 @@ public class FleetControllerContextImplTest {
private final FleetControllerContextImpl context = new FleetControllerContextImpl(id);
@Test
- public void verify() {
+ void verify() {
context.log(logger, Level.INFO, "A %s message", "log");
assertEquals(1, logger.records.size());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
index a5eeb69e126..371a57e08c0 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
@@ -22,24 +22,21 @@ import com.yahoo.vespa.clustercontroller.core.rpc.RPCCommunicator;
import com.yahoo.vespa.clustercontroller.core.rpc.RpcServer;
import com.yahoo.vespa.clustercontroller.core.rpc.SlobrokClient;
import com.yahoo.vespa.clustercontroller.core.status.StatusHandler;
-import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServerInterface;
import com.yahoo.vespa.clustercontroller.core.testutils.WaitCondition;
import com.yahoo.vespa.clustercontroller.core.testutils.WaitTask;
import com.yahoo.vespa.clustercontroller.core.testutils.Waiter;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-import org.junit.After;
-import org.junit.Rule;
-import org.junit.rules.TestRule;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.TestWatcher;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
@@ -49,19 +46,21 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Håkon Humberset
*/
+@ExtendWith(FleetControllerTest.CleanupZookeeperLogsOnSuccess.class)
public abstract class FleetControllerTest implements Waiter {
private static final Logger log = Logger.getLogger(FleetControllerTest.class.getName());
private static final int DEFAULT_NODE_COUNT = 10;
- Supervisor supervisor;
+ private final Duration timeout = Duration.ofSeconds(30);
protected final FakeTimer timer = new FakeTimer();
- boolean usingFakeTimer = false;
+
+ Supervisor supervisor;
protected Slobrok slobrok;
protected FleetControllerOptions options;
ZooKeeperTestServer zooKeeperServer;
@@ -69,8 +68,6 @@ public abstract class FleetControllerTest implements Waiter {
protected List<DummyVdsNode> nodes = new ArrayList<>();
private String testName;
- final static int timeoutS;
- final static int timeoutMS;
private final Waiter waiter = new Waiter.Impl(new DataRetriever() {
@Override
public Object getMonitor() { return timer; }
@@ -79,13 +76,11 @@ public abstract class FleetControllerTest implements Waiter {
@Override
public List<DummyVdsNode> getDummyNodes() { return nodes; }
@Override
- public int getTimeoutMS() { return timeoutMS; }
+ public Duration getTimeout() { return timeout; }
});
static {
LogSetup.initVespaLogging("fleetcontroller");
- timeoutS = 30;
- timeoutMS = timeoutS * 1000;
}
static class BackOff implements BackOffPolicy {
@@ -96,30 +91,31 @@ public abstract class FleetControllerTest implements Waiter {
public boolean shouldInform(double v) { return false; }
}
- protected class CleanupZookeeperLogsOnSuccess extends TestWatcher {
+ public static class CleanupZookeeperLogsOnSuccess implements TestWatcher {
+
+ public CleanupZookeeperLogsOnSuccess() {}
+
@Override
- protected void failed(Throwable e, Description description) {
+ public void testFailed(ExtensionContext context, Throwable cause) {
System.err.println("TEST FAILED - NOT cleaning up zookeeper directory");
- shutdownZooKeeper(false);
+ shutdownZooKeeper(context, false);
}
@Override
- protected void succeeded(Description description) {
+ public void testSuccessful(ExtensionContext context) {
System.err.println("TEST SUCCEEDED - cleaning up zookeeper directory");
- shutdownZooKeeper(true);
+ shutdownZooKeeper(context, true);
}
- private void shutdownZooKeeper(boolean cleanupZooKeeperDir) {
- if (zooKeeperServer != null) {
- zooKeeperServer.shutdown(cleanupZooKeeperDir);
- zooKeeperServer = null;
+ private void shutdownZooKeeper(ExtensionContext ctx, boolean cleanupZooKeeperDir) {
+ FleetControllerTest test = (FleetControllerTest) ctx.getTestInstance().orElseThrow();
+ if (test.zooKeeperServer != null) {
+ test.zooKeeperServer.shutdown(cleanupZooKeeperDir);
+ test.zooKeeperServer = null;
}
}
}
- @Rule
- public TestRule cleanupZookeeperLogsOnSuccess = new CleanupZookeeperLogsOnSuccess();
-
protected void startingTest(String name) {
System.err.println("STARTING TEST: " + name);
testName = name;
@@ -141,7 +137,7 @@ public abstract class FleetControllerTest implements Waiter {
return opts;
}
- void setUpSystem(boolean useFakeTimer, FleetControllerOptions options) throws Exception {
+ void setUpSystem(FleetControllerOptions options) throws Exception {
log.log(Level.FINE, "Setting up system");
slobrok = new Slobrok();
this.options = options;
@@ -150,21 +146,15 @@ public abstract class FleetControllerTest implements Waiter {
this.options.zooKeeperServerAddress = zooKeeperServer.getAddress();
log.log(Level.FINE, "Set up new zookeeper server at " + this.options.zooKeeperServerAddress);
}
- this.options.slobrokConnectionSpecs = new String[1];
- this.options.slobrokConnectionSpecs[0] = "tcp/localhost:" + slobrok.port();
- this.usingFakeTimer = useFakeTimer;
+ this.options.slobrokConnectionSpecs = getSlobrokConnectionSpecs(slobrok);
}
- FleetController createFleetController(boolean useFakeTimer, FleetControllerOptions options, boolean startThread, StatusPageServerInterface status) throws Exception {
- Objects.requireNonNull(status, "status server cannot be null");
+ FleetController createFleetController(boolean useFakeTimer, FleetControllerOptions options) throws Exception {
var context = new TestFleetControllerContext(options);
Timer timer = useFakeTimer ? this.timer : new RealTimer();
var metricUpdater = new MetricUpdater(new NoMetricReporter(), options.fleetControllerIndex, options.clusterName);
var log = new EventLog(timer, metricUpdater);
- var cluster = new ContentCluster(
- options.clusterName,
- options.nodes,
- options.storageDistribution);
+ var cluster = new ContentCluster(options.clusterName, options.nodes, options.storageDistribution);
var stateGatherer = new NodeStateGatherer(timer, timer, log);
var communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
@@ -187,24 +177,18 @@ public abstract class FleetControllerTest implements Waiter {
var stateGenerator = new StateChangeHandler(context, timer, log);
var stateBroadcaster = new SystemStateBroadcaster(context, timer, timer);
var masterElectionHandler = new MasterElectionHandler(context, options.fleetControllerIndex, options.fleetControllerCount, timer, timer);
- var controller = new FleetController(context, timer, log, cluster, stateGatherer, communicator, status, rpcServer, lookUp, database, stateGenerator, stateBroadcaster, masterElectionHandler, metricUpdater, options);
- if (startThread) {
- controller.start();
- }
+
+ var status = new StatusHandler.ContainerStatusPageServer();
+ var controller = new FleetController(context, timer, log, cluster, stateGatherer, communicator, status, rpcServer, lookUp,
+ database, stateGenerator, stateBroadcaster, masterElectionHandler, metricUpdater, options);
+ controller.start();
return controller;
}
protected void setUpFleetController(boolean useFakeTimer, FleetControllerOptions options) throws Exception {
- setUpFleetController(useFakeTimer, options, true);
- }
-
- protected void setUpFleetController(boolean useFakeTimer, FleetControllerOptions options, boolean startThread) throws Exception {
- setUpFleetController(useFakeTimer, options, startThread, new StatusHandler.ContainerStatusPageServer());
- }
- protected void setUpFleetController(boolean useFakeTimer, FleetControllerOptions options, boolean startThread, StatusPageServerInterface status) throws Exception {
- if (slobrok == null) setUpSystem(useFakeTimer, options);
+ if (slobrok == null) setUpSystem(options);
if (fleetController == null) {
- fleetController = createFleetController(useFakeTimer, options, startThread, status);
+ fleetController = createFleetController(useFakeTimer, options);
} else {
throw new Exception("called setUpFleetcontroller but it was already setup");
}
@@ -217,9 +201,9 @@ public abstract class FleetControllerTest implements Waiter {
}
}
- void startFleetController() throws Exception {
+ void startFleetController(boolean useFakeTimer) throws Exception {
if (fleetController == null) {
- fleetController = createFleetController(usingFakeTimer, options, true, new StatusHandler.ContainerStatusPageServer());
+ fleetController = createFleetController(useFakeTimer, options);
} else {
log.log(Level.WARNING, "already started fleetcontroller, not starting another");
}
@@ -238,8 +222,7 @@ public abstract class FleetControllerTest implements Waiter {
setUpVdsNodes(useFakeTimer, options, startDisconnected, nodeIndexes);
}
protected void setUpVdsNodes(boolean useFakeTimer, DummyVdsNodeOptions options, boolean startDisconnected, Set<Integer> nodeIndexes) throws Exception {
- String[] connectionSpecs = new String[1];
- connectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ String[] connectionSpecs = getSlobrokConnectionSpecs(slobrok);
for (int nodeIndex : nodeIndexes) {
nodes.add(new DummyVdsNode(useFakeTimer ? timer : new RealTimer(), options, connectionSpecs, this.options.clusterName, true, nodeIndex));
if ( ! startDisconnected) nodes.get(nodes.size() - 1).connect();
@@ -255,8 +238,7 @@ public abstract class FleetControllerTest implements Waiter {
* the returned list is twice as large as configuredNodes.
*/
protected List<DummyVdsNode> setUpVdsNodes(boolean useFakeTimer, DummyVdsNodeOptions options, boolean startDisconnected, List<ConfiguredNode> configuredNodes) throws Exception {
- String[] connectionSpecs = new String[1];
- connectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ String[] connectionSpecs = getSlobrokConnectionSpecs(slobrok);
nodes = new ArrayList<>();
final boolean distributor = true;
for (ConfiguredNode configuredNode : configuredNodes) {
@@ -295,7 +277,7 @@ public abstract class FleetControllerTest implements Waiter {
.collect(Collectors.toList());
}
@Override
- public int getTimeoutMS() { return timeoutMS; }
+ public Duration getTimeout() { return timeout; }
});
subsetWaiter.waitForState(expectedState);
}
@@ -330,7 +312,7 @@ public abstract class FleetControllerTest implements Waiter {
}
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
tearDownSystem();
}
@@ -340,16 +322,16 @@ public abstract class FleetControllerTest implements Waiter {
public ClusterState waitForState(String state) throws Exception { return waiter.waitForState(state); }
public ClusterState waitForStateInAllSpaces(String state) throws Exception { return waiter.waitForStateInAllSpaces(state); }
public ClusterState waitForStateInSpace(String space, String state) throws Exception { return waiter.waitForStateInSpace(space, state); }
- public ClusterState waitForState(String state, int timeoutMS) throws Exception { return waiter.waitForState(state, timeoutMS); }
+ public ClusterState waitForState(String state, Duration timeout) throws Exception { return waiter.waitForState(state, timeout); }
public ClusterState waitForInitProgressPassed(Node n, double progress) { return waiter.waitForInitProgressPassed(n, progress); }
public ClusterState waitForClusterStateIncludingNodesWithMinUsedBits(int bitcount, int nodecount) { return waiter.waitForClusterStateIncludingNodesWithMinUsedBits(bitcount, nodecount); }
- public void wait(WaitCondition c, WaitTask wt, int timeoutMS) {
- waiter.wait(c, wt, timeoutMS);
+ public void wait(WaitCondition condition, WaitTask task, Duration timeout) {
+ waiter.wait(condition, task, timeout);
}
void waitForCompleteCycle() {
- fleetController.waitForCompleteCycle(timeoutMS);
+ fleetController.waitForCompleteCycle(timeout);
}
private static class ExpectLine {
@@ -478,7 +460,7 @@ public abstract class FleetControllerTest implements Waiter {
Request req = new Request("setNodeState");
req.parameters().add(new StringValue(node.getSlobrokName()));
req.parameters().add(new StringValue(ns.serialize()));
- connection.invokeSync(req, timeoutS);
+ connection.invokeSync(req, timeout());
if (req.isError()) {
fail("Failed to invoke setNodeState(): " + req.errorCode() + ": " + req.errorMessage());
}
@@ -487,4 +469,12 @@ public abstract class FleetControllerTest implements Waiter {
}
}
+ static String[] getSlobrokConnectionSpecs(Slobrok slobrok) {
+ String[] connectionSpecs = new String[1];
+ connectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ return connectionSpecs;
+ }
+
+ Duration timeout() { return timeout; }
+
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java
index e6c5c31010f..7f6684e595d 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
@@ -53,14 +53,14 @@ public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
}
@Test
- public void bootstrap_min_ratio_option_is_propagated_to_group_availability_logic() throws Exception {
+ void bootstrap_min_ratio_option_is_propagated_to_group_availability_logic() throws Exception {
setUp3x3ClusterWithMinNodeRatio(0.67);
takeDownContentNode(0);
waitForStateExcludingNodeSubset("version:\\d+ distributor:9 storage:9 .0.s:d .1.s:d .2.s:d", asIntSet(0));
}
@Test
- public void min_ratio_live_reconfig_immediately_takes_effect() throws Exception {
+ void min_ratio_live_reconfig_immediately_takes_effect() throws Exception {
// Initially, arbitrarily many nodes may be down in a group.
setUp3x3ClusterWithMinNodeRatio(0.0);
takeDownContentNode(3);
@@ -75,7 +75,7 @@ public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
}
@Test
- public void live_distribution_config_changes_trigger_cluster_state_change() throws Exception {
+ void live_distribution_config_changes_trigger_cluster_state_change() throws Exception {
setUp3x3ClusterWithMinNodeRatio(0.65);
takeDownContentNode(6);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
index 1d4b2a73560..f0c8503fed9 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -19,7 +19,7 @@ import static com.yahoo.vespa.clustercontroller.core.matchers.NodeEventWithDescr
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -71,17 +71,17 @@ public class GroupAutoTakedownTest {
* not apply to a flat structure.
*/
@Test
- public void config_does_not_apply_to_flat_hierarchy_clusters() {
+ void config_does_not_apply_to_flat_hierarchy_clusters() {
ClusterFixture fixture = createFixtureForAllUpFlatCluster(5, 0.99);
assertEquals("distributor:5 storage:5", fixture.generatedClusterState());
assertEquals("distributor:5 storage:5 .1.s:d",
- stateAfterStorageTransition(fixture, 1, State.DOWN));
+ stateAfterStorageTransition(fixture, 1, State.DOWN));
}
@Test
- public void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
+ void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -89,28 +89,28 @@ public class GroupAutoTakedownTest {
// Same group as node 4
assertEquals("distributor:6 storage:4",
- stateAfterStorageTransition(fixture, 5, State.DOWN));
+ stateAfterStorageTransition(fixture, 5, State.DOWN));
// Same group as node 1
assertEquals("distributor:6 storage:4 .0.s:d .1.s:d",
- stateAfterStorageTransition(fixture, 0, State.DOWN));
+ stateAfterStorageTransition(fixture, 0, State.DOWN));
}
@Test
- public void restored_group_node_availability_takes_group_back_up_automatically() {
+ void restored_group_node_availability_takes_group_back_up_automatically() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
// Group #2 -> down
assertEquals("distributor:6 storage:4",
- stateAfterStorageTransition(fixture, 5, State.DOWN));
+ stateAfterStorageTransition(fixture, 5, State.DOWN));
// Group #2 -> back up again
assertEquals("distributor:6 storage:6",
- stateAfterStorageTransition(fixture, 5, State.UP));
+ stateAfterStorageTransition(fixture, 5, State.UP));
}
@Test
- public void no_op_for_downed_nodes_in_already_downed_group() {
+ void no_op_for_downed_nodes_in_already_downed_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -123,7 +123,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void verbose_node_state_description_updated_for_implicitly_downed_nodes() {
+ void verbose_node_state_description_updated_for_implicitly_downed_nodes() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.75);
@@ -131,15 +131,15 @@ public class GroupAutoTakedownTest {
// Node 8 is taken down by the fixture and gets a fixture-assigned message that
// we should _not_ lose/overwrite.
assertEquals("distributor:9 storage:9 .6.s:d " +
- ".6.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
- ".7.s:d " +
- ".7.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
- ".8.s:d .8.m:mockdesc",
- verboseStateAfterStorageTransition(fixture, 8, State.DOWN));
+ ".6.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
+ ".7.s:d " +
+ ".7.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
+ ".8.s:d .8.m:mockdesc",
+ verboseStateAfterStorageTransition(fixture, 8, State.DOWN));
}
@Test
- public void legacy_cluster_wide_availabilty_ratio_is_computed_after_group_takedowns() {
+ void legacy_cluster_wide_availabilty_ratio_is_computed_after_group_takedowns() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
fixture.setMinNodesUp(5, 5, 0.51, 0.51);
@@ -152,7 +152,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void maintenance_wanted_state_not_overwritten() {
+ void maintenance_wanted_state_not_overwritten() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
@@ -166,7 +166,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void transient_maintenance_mode_on_down_edge_does_not_take_down_group() {
+ void transient_maintenance_mode_on_down_edge_does_not_take_down_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
fixture.enableTransientMaintenanceModeOnDown(1000);
@@ -190,7 +190,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void taking_down_node_adds_node_specific_event() {
+ void taking_down_node_adds_node_specific_event() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -205,7 +205,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void bringing_node_back_up_adds_node_specific_event() {
+ void bringing_node_back_up_adds_node_specific_event() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -223,7 +223,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void wanted_state_retired_implicitly_down_node_is_transitioned_to_retired_mode_immediately() {
+ void wanted_state_retired_implicitly_down_node_is_transitioned_to_retired_mode_immediately() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
@@ -237,7 +237,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void downed_config_retired_node_transitions_back_to_retired_on_up_edge() {
+ void downed_config_retired_node_transitions_back_to_retired_on_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.49);
@@ -252,14 +252,15 @@ public class GroupAutoTakedownTest {
nodes.add(new ConfiguredNode(5, true));
// TODO this should ideally also set the retired flag in the distribution
// config, but only the ConfiguredNodes are actually looked at currently.
- fixture.cluster.setNodes(nodes, new NodeListener() {});
+ fixture.cluster.setNodes(nodes, new NodeListener() {
+ });
assertEquals("distributor:6 storage:6 .4.s:d .5.s:r",
stateAfterStorageTransition(fixture, 5, State.UP));
}
@Test
- public void init_progress_is_preserved_across_group_down_up_edge() {
+ void init_progress_is_preserved_across_group_down_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -277,7 +278,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void down_wanted_state_is_preserved_across_group_down_up_edge() {
+ void down_wanted_state_is_preserved_across_group_down_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.60);
@@ -294,7 +295,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void previously_cleared_start_timestamps_are_not_reintroduced_on_up_edge() throws Exception {
+ void previously_cleared_start_timestamps_are_not_reintroduced_on_up_edge() throws Exception {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
index a5357e0a639..d176455f4c0 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.util.Collections;
@@ -49,7 +49,7 @@ public class GroupAvailabilityCalculatorTest {
private static Set<Integer> emptySet() { return indices(); }
@Test
- public void flat_cluster_does_not_implicitly_take_down_nodes() {
+ void flat_cluster_does_not_implicitly_take_down_nodes() {
GroupAvailabilityCalculator calc = calcForFlatCluster(5, 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -58,7 +58,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
+ void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
// 3 groups of 2 nodes, take down node #4 (1st node in last group). Since we require
// at least 51% of group capacity to be available, implicitly take down the last group
// entirely.
@@ -72,7 +72,7 @@ public class GroupAvailabilityCalculatorTest {
// Setting 50% as min ratio in a group with 2 nodes should let group be up if
// one node goes down.
@Test
- public void min_ratio_per_group_is_closed_interval() {
+ void min_ratio_per_group_is_closed_interval() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.50);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -80,7 +80,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void retired_node_is_counted_as_down() {
+ void retired_node_is_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -88,7 +88,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void initializing_node_not_counted_as_down() {
+ void initializing_node_not_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -96,7 +96,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void maintenance_node_not_counted_as_down() {
+ void maintenance_node_not_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -104,7 +104,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void existing_maintenance_node_not_implicitly_downed_when_group_taken_down() {
+ void existing_maintenance_node_not_implicitly_downed_when_group_taken_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -112,7 +112,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void existing_retired_node_not_implicitly_downed_when_group_taken_down() {
+ void existing_retired_node_not_implicitly_downed_when_group_taken_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -120,7 +120,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void down_to_down_edge_keeps_group_down() {
+ void down_to_down_edge_keeps_group_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.76);
@@ -135,7 +135,7 @@ public class GroupAvailabilityCalculatorTest {
// causing "storage:6 .5.s:d" to be reduced to "storage:5". This still implies a
// node is down according to the distribution config and must be handled as such.
@Test
- public void implicitly_downed_node_at_state_end_is_counted_as_explicitly_down() {
+ void implicitly_downed_node_at_state_end_is_counted_as_explicitly_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -143,7 +143,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void non_uniform_group_sizes_are_supported() {
+ void non_uniform_group_sizes_are_supported() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroupNodes(1, 2, 3, 4), 0.67);
@@ -167,7 +167,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void min_ratio_of_zero_never_takes_down_groups_implicitly() {
+ void min_ratio_of_zero_never_takes_down_groups_implicitly() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.0);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -184,7 +184,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void one_safe_maintenance_node_does_not_take_down_group() {
+ void one_safe_maintenance_node_does_not_take_down_group() {
// 2 groups of 5 nodes each. Set node #5 safely in maintenance (1st node in last group).
// Since the minimum number of nodes that can safely be set to maintenance before taking
// the whole group down is 2, the whole group should NOT be taken down.
@@ -204,7 +204,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void two_safe_maintenance_nodes_takes_down_group() {
+ void two_safe_maintenance_nodes_takes_down_group() {
// 2 groups of 5 nodes each. Set nodes #5 and #6 safely in maintenance (1st and 2nd nodes
// in last group, respectively). Since the minimum number of nodes that can safely be set to
// maintenance before taking the whole group down is 2, the whole group should be taken down.
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
index 418400b3fff..b6bd6a3bf75 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.Group;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -12,7 +12,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class LeafGroupsTest {
@Test
- public void rootGroupCountedAsLeafWhenNoChildren() {
+ void rootGroupCountedAsLeafWhenNoChildren() {
Group g = new Group(0, "donkeykong");
List<Group> leaves = LeafGroups.enumerateFrom(g);
@@ -25,7 +25,7 @@ public class LeafGroupsTest {
}
@Test
- public void singleLeafIsEnumerated() throws Exception {
+ void singleLeafIsEnumerated() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario");
g.addSubGroup(child);
@@ -36,7 +36,7 @@ public class LeafGroupsTest {
}
@Test
- public void singleLeafIsEnumeratedInNestedCase() throws Exception {
+ void singleLeafIsEnumeratedInNestedCase() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario", dummyDistribution());
child.addSubGroup(new Group(2, "toad"));
@@ -48,7 +48,7 @@ public class LeafGroupsTest {
}
@Test
- public void multipleLeafGroupsAreEnumerated() throws Exception {
+ void multipleLeafGroupsAreEnumerated() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario", dummyDistribution());
child.addSubGroup(new Group(2, "toad"));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
index 2f79ad3fa95..6a05cc78508 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.document.FixedBucketSpaces;
import com.yahoo.vdslib.state.ClusterState;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
@@ -53,7 +53,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void no_nodes_set_to_maintenance_in_global_bucket_space_state() {
+ void no_nodes_set_to_maintenance_in_global_bucket_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(globalSpace()), anyInt())).thenReturn(true); // False returned by default otherwise
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:2 storage:2"), globalSpace());
@@ -61,7 +61,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void content_nodes_with_global_merge_pending_set_to_maintenance_in_default_space_state() {
+ void content_nodes_with_global_merge_pending_set_to_maintenance_in_default_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 1)).thenReturn(true);
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 3)).thenReturn(true);
@@ -71,14 +71,14 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void no_nodes_set_to_maintenance_when_no_merges_pending() {
+ void no_nodes_set_to_maintenance_when_no_merges_pending() {
Fixture f = new Fixture();
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:5 storage:5"), defaultSpace());
assertThat(derived, equalTo(stateFromString("distributor:5 storage:5")));
}
@Test
- public void default_space_merges_do_not_count_towards_maintenance() {
+ void default_space_merges_do_not_count_towards_maintenance() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(defaultSpace()), anyInt())).thenReturn(true);
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:2 storage:2"), defaultSpace());
@@ -86,7 +86,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void nodes_only_set_to_maintenance_when_marked_up_init_or_retiring() {
+ void nodes_only_set_to_maintenance_when_marked_up_init_or_retiring() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(globalSpace()), anyInt())).thenReturn(true);
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:5 storage:5 .1.s:m .2.s:r .3.s:i .4.s:d"), defaultSpace());
@@ -96,7 +96,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void node_state_reasons_are_used_as_baseline_in_default_bucket_space_state() {
+ void node_state_reasons_are_used_as_baseline_in_default_bucket_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 1)).thenReturn(true);
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 3)).thenReturn(true);
@@ -108,7 +108,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void node_with_pending_merges_only_set_to_maintenance_if_eligible() {
+ void node_with_pending_merges_only_set_to_maintenance_if_eligible() {
Fixture f = new Fixture();
Arrays.asList(1, 2, 3).forEach(idx -> when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), idx)).thenReturn(true));
Arrays.asList(1, 2, 4).forEach(idx -> when(f.mockTransitionConstraint.maintenanceTransitionAllowed(idx)).thenReturn(false));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
index 257bb54047c..16a3e41f149 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
@@ -11,12 +11,11 @@ import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import com.yahoo.vespa.clustercontroller.core.status.StatusHandler;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestRule;
-import org.junit.rules.Timeout;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.ExtendWith;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
@@ -24,10 +23,12 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+@ExtendWith(FleetControllerTest.CleanupZookeeperLogsOnSuccess.class)
+@Timeout(120)
public class MasterElectionTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(MasterElectionTest.class.getName());
@@ -35,12 +36,6 @@ public class MasterElectionTest extends FleetControllerTest {
private Supervisor supervisor;
private final List<FleetController> fleetControllers = new ArrayList<>();
- @Rule
- public TestRule cleanupZookeeperLogsOnSuccess = new CleanupZookeeperLogsOnSuccess();
-
- @Rule
- public Timeout globalTimeout = Timeout.seconds(120);
-
private static int defaultZkSessionTimeoutInMillis() { return 30_000; }
protected void setUpFleetController(int count, boolean useFakeTimer, FleetControllerOptions options) throws Exception {
@@ -48,46 +43,42 @@ public class MasterElectionTest extends FleetControllerTest {
zooKeeperServer = new ZooKeeperTestServer();
}
slobrok = new Slobrok();
- usingFakeTimer = useFakeTimer;
this.options = options;
this.options.zooKeeperSessionTimeout = defaultZkSessionTimeoutInMillis();
this.options.zooKeeperServerAddress = zooKeeperServer.getAddress();
- this.options.slobrokConnectionSpecs = new String[1];
- this.options.slobrokConnectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ this.options.slobrokConnectionSpecs = getSlobrokConnectionSpecs(slobrok);
this.options.fleetControllerCount = count;
for (int i=0; i<count; ++i) {
FleetControllerOptions nodeOptions = options.clone();
nodeOptions.fleetControllerIndex = i;
- fleetControllers.add(createFleetController(usingFakeTimer, nodeOptions, true, new StatusHandler.ContainerStatusPageServer()));
+ fleetControllers.add(createFleetController(useFakeTimer, nodeOptions));
}
}
- private FleetControllerOptions adjustConfig(FleetControllerOptions o,
- int fleetControllerIndex, int fleetControllerCount) {
+ private FleetControllerOptions adjustConfig(FleetControllerOptions o, int fleetControllerIndex, int fleetControllerCount) {
FleetControllerOptions options = o.clone();
options.zooKeeperSessionTimeout = defaultZkSessionTimeoutInMillis();
options.zooKeeperServerAddress = zooKeeperServer.getAddress();
- options.slobrokConnectionSpecs = new String[1];
- options.slobrokConnectionSpecs[0] = "tcp/localhost:" + slobrok.port(); // Spec.fromLocalHostName(slobrok.port()).toString();
+ options.slobrokConnectionSpecs = getSlobrokConnectionSpecs(slobrok);
options.fleetControllerIndex = fleetControllerIndex;
options.fleetControllerCount = fleetControllerCount;
return options;
}
private void waitForZookeeperDisconnected() throws TimeoutException {
- long maxTime = System.currentTimeMillis() + timeoutMS;
+ Instant maxTime = Instant.now().plus(timeout());
for (FleetController f : fleetControllers) {
while (f.hasZookeeperConnection()) {
try { Thread.sleep(1); } catch (InterruptedException e) { /* ignore */ }
- if (System.currentTimeMillis() > maxTime)
- throw new TimeoutException("Failed to notice zookeeper down within timeout of " + timeoutMS + " ms");
+ if (Instant.now().isAfter(maxTime))
+ throw new TimeoutException("Failed to notice zookeeper down within timeout of " + timeout());
}
}
waitForCompleteCycles();
}
private void waitForCompleteCycle(int findex) {
- fleetControllers.get(findex).waitForCompleteCycle(timeoutMS);
+ fleetControllers.get(findex).waitForCompleteCycle(timeout());
}
private void waitForCompleteCycles() {
@@ -116,12 +107,13 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testMasterElection() throws Exception {
+ void testMasterElection() throws Exception {
startingTest("MasterElectionTest::testMasterElection");
log.log(Level.INFO, "STARTING TEST: MasterElectionTest::testMasterElection()");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 100;
- setUpFleetController(5, false, options);
+ boolean usingFakeTimer = false;
+ setUpFleetController(5, usingFakeTimer, options);
waitForMaster(0);
log.log(Level.INFO, "SHUTTING DOWN FLEET CONTROLLER 0");
fleetControllers.get(0).shutdown();
@@ -135,18 +127,17 @@ public class MasterElectionTest extends FleetControllerTest {
// Too few for there to be a master at this point
for (int i = 0; i < fleetControllers.size(); ++i) {
if (fleetControllers.get(i).isRunning()) waitForCompleteCycle(i);
- assertFalse("Fleet controller " + i, fleetControllers.get(i).isMaster());
+ assertFalse(fleetControllers.get(i).isMaster(), "Fleet controller " + i);
}
- StatusHandler.ContainerStatusPageServer statusPageServer = new StatusHandler.ContainerStatusPageServer();
log.log(Level.INFO, "STARTING FLEET CONTROLLER 2");
- fleetControllers.set(2, createFleetController(usingFakeTimer, fleetControllers.get(2).getOptions(), true, statusPageServer));
+ fleetControllers.set(2, createFleetController(usingFakeTimer, fleetControllers.get(2).getOptions()));
waitForMaster(2);
log.log(Level.INFO, "STARTING FLEET CONTROLLER 0");
- fleetControllers.set(0, createFleetController(usingFakeTimer, fleetControllers.get(0).getOptions(), true, statusPageServer));
+ fleetControllers.set(0, createFleetController(usingFakeTimer, fleetControllers.get(0).getOptions()));
waitForMaster(0);
log.log(Level.INFO, "STARTING FLEET CONTROLLER 1");
- fleetControllers.set(1, createFleetController(usingFakeTimer, fleetControllers.get(1).getOptions(), true, statusPageServer));
+ fleetControllers.set(1, createFleetController(usingFakeTimer, fleetControllers.get(1).getOptions()));
waitForMaster(0);
log.log(Level.INFO, "SHUTTING DOWN FLEET CONTROLLER 4");
@@ -168,7 +159,7 @@ public class MasterElectionTest extends FleetControllerTest {
private void waitForMaster(int master) {
log.log(Level.INFO, "Entering waitForMaster");
boolean isOnlyMaster = false;
- for (int i = 0; i < FleetControllerTest.timeoutMS; i += 100) {
+ for (int i = 0; i < timeout().toMillis(); i += 100) {
if (!fleetControllers.get(master).isMaster()) {
log.log(Level.INFO, "Node " + master + " is not master yet, sleeping more");
timer.advanceTime(100);
@@ -187,7 +178,7 @@ public class MasterElectionTest extends FleetControllerTest {
break;
}
}
- // Have to wait to get zookeeper communication chance to happen.
+ // Have to wait to get zookeeper communication chance to happen.
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
@@ -222,7 +213,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testClusterStateVersionIncreasesAcrossMasterElections() throws Exception {
+ void testClusterStateVersionIncreasesAcrossMasterElections() throws Exception {
startingTest("MasterElectionTest::testClusterStateVersionIncreasesAcrossMasterElections");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -243,7 +234,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testVotingCorrectnessInFaceOfZKDisconnect() throws Exception {
+ void testVotingCorrectnessInFaceOfZKDisconnect() throws Exception {
startingTest("MasterElectionTest::testVotingCorrectnessInFaceOfZKDisconnect");
FleetControllerOptions options = defaultOptions("mycluster");
// "Magic" port value is in range allocated to module for testing.
@@ -264,7 +255,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testZooKeeperUnavailable() throws Exception {
+ void testZooKeeperUnavailable() throws Exception {
startingTest("MasterElectionTest::testZooKeeperUnavailable");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 100;
@@ -279,7 +270,7 @@ public class MasterElectionTest extends FleetControllerTest {
// No one can be master if server is unavailable
log.log(Level.INFO, "Checking master status");
for (int i = 0; i < fleetControllers.size(); ++i) {
- assertFalse("Index " + i, fleetControllers.get(i).isMaster());
+ assertFalse(fleetControllers.get(i).isMaster(), "Index " + i);
}
zooKeeperServer = new ZooKeeperTestServer();
@@ -295,7 +286,8 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testMasterZooKeeperCooldown() throws Exception {
+ @Disabled("Unstable, disable test, as functionality is not deemed critical")
+ void testMasterZooKeeperCooldown() throws Exception {
startingTest("MasterElectionTest::testMasterZooKeeperCooldown");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 3600 * 1000; // An hour
@@ -315,13 +307,13 @@ public class MasterElectionTest extends FleetControllerTest {
waitForMaster(1);
}
- private void waitForMasterReason(String reason, Integer master, List<Target> connections, int nodes[]) {
- long endTime = System.currentTimeMillis() + timeoutMS;
- while (System.currentTimeMillis() < endTime) {
+ private void waitForMasterReason(String reason, Integer master, List<Target> connections, int[] nodes) {
+ Instant endTime = Instant.now().plus(timeout());
+ while (Instant.now().isBefore(endTime)) {
boolean allOk = true;
for (int node : nodes) {
Request req = new Request("getMaster");
- connections.get(node).invokeSync(req, FleetControllerTest.timeoutS);
+ connections.get(node).invokeSync(req, timeout());
if (req.isError()) {
allOk = false;
break;
@@ -338,12 +330,11 @@ public class MasterElectionTest extends FleetControllerTest {
if (allOk) return;
try{ Thread.sleep(100); } catch (InterruptedException e) { /* ignore */ }
}
- throw new IllegalStateException("Did not get master reason '" + reason
- + "' within timeout of " + timeoutMS + " ms");
+ throw new IllegalStateException("Did not get master reason '" + reason + "' within timeout of " + timeout());
}
@Test
- public void testGetMaster() throws Exception {
+ void testGetMaster() throws Exception {
startingTest("MasterElectionTest::testGetMaster");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 3600 * 1000; // An hour
@@ -364,33 +355,34 @@ public class MasterElectionTest extends FleetControllerTest {
Request req = new Request("getMaster");
- for (int nodeIndex = 0; nodeIndex<3; ++nodeIndex) {
- for (int retry = 0; retry < FleetControllerTest.timeoutS * 10; ++retry) {
+ long maxRetries = timeout().toMillis() / 100;
+ for (int nodeIndex = 0; nodeIndex < 3; ++nodeIndex) {
+ for (int retry = 0; retry < maxRetries; ++retry) {
req = new Request("getMaster");
- connections.get(nodeIndex).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ connections.get(nodeIndex).invokeSync(req, timeout());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() == 0 &&
- req.returnValues().get(1).asString().equals("All 3 nodes agree that 0 is current master.")) {
+ req.returnValues().get(1).asString().equals("All 3 nodes agree that 0 is current master.")) {
break;
}
}
- assertEquals(req.toString(), 0, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "All 3 nodes agree that 0 is current master.", req.returnValues().get(1).asString());
+ assertEquals(0, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("All 3 nodes agree that 0 is current master.", req.returnValues().get(1).asString(), req.toString());
}
log.log(Level.INFO, "SHUTTING DOWN FLEET CONTROLLER 0");
fleetControllers.get(0).shutdown();
- // Wait until fc 1 & 2 votes for node 1
+ // Wait until fc 1 & 2 votes for node 1
waitForCompleteCycle(1);
waitForCompleteCycle(2);
- // 5 minutes is not long enough period to wait before letting this node be master.
+ // 5 minutes is not long enough period to wait before letting this node be master.
timer.advanceTime(300 * 1000); // 5 minutes
- int[] remainingNodes = { 1, 2 };
+ int[] remainingNodes = {1, 2};
waitForMasterReason(
"2 of 3 nodes agree 1 should be master, but old master cooldown period of 3600000 ms has not passed yet. To ensure it has got time to realize it is no longer master before we elect a new one, currently there is no master.",
-1, connections, remainingNodes);
- // Verify that fc 1 is not master, and the correct reasons for why not
+ // Verify that fc 1 is not master, and the correct reasons for why not
assertFalse(fleetControllers.get(1).isMaster());
// But after an hour it should become one.
@@ -398,32 +390,32 @@ public class MasterElectionTest extends FleetControllerTest {
waitForMaster(1);
req = new Request("getMaster");
- connections.get(0).invokeSync(req, FleetControllerTest.timeoutS);
- assertEquals(req.toString(), 104, req.errorCode());
- assertEquals(req.toString(), "Connection error", req.errorMessage());
+ connections.get(0).invokeSync(req, timeout());
+ assertEquals(104, req.errorCode(), req.toString());
+ assertEquals("Connection error", req.errorMessage(), req.toString());
- for (int i=0; i<FleetControllerTest.timeoutS * 10; ++i) {
+ for (int i = 0; i < maxRetries; ++i) {
req = new Request("getMaster");
- connections.get(1).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ connections.get(1).invokeSync(req, timeout());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() != -1) break;
- // We may have bad timing causing node not to have realized it is master yet
+ // We may have bad timing causing node not to have realized it is master yet
}
- assertEquals(req.toString(), 1, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString());
+ assertEquals(1, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString(), req.toString());
- for (int i=0; i<FleetControllerTest.timeoutS * 10; ++i) {
+ for (int i = 0; i < maxRetries; ++i) {
req = new Request("getMaster");
- connections.get(2).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ connections.get(2).invokeSync(req, timeout());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() != -1) break;
}
- assertEquals(req.toString(), 1, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString());
+ assertEquals(1, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString(), req.toString());
}
@Test
- public void testReconfigure() throws Exception {
+ void testReconfigure() throws Exception {
startingTest("MasterElectionTest::testReconfigure");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -431,7 +423,7 @@ public class MasterElectionTest extends FleetControllerTest {
waitForMaster(0);
FleetControllerOptions newOptions = options.clone();
- for (int i=0; i<fleetControllers.size(); ++i) {
+ for (int i = 0; i < fleetControllers.size(); ++i) {
FleetControllerOptions nodeOptions = adjustConfig(newOptions, i, fleetControllers.size());
fleetControllers.get(i).updateOptions(nodeOptions);
}
@@ -448,7 +440,7 @@ public class MasterElectionTest extends FleetControllerTest {
* risk rolling back the version number in the face of a reelection.
*/
@Test
- public void cluster_state_version_written_to_zookeeper_even_with_empty_send_set() throws Exception {
+ void cluster_state_version_written_to_zookeeper_even_with_empty_send_set() throws Exception {
startingTest("MasterElectionTest::cluster_state_version_written_to_zookeeper_even_with_empty_send_set");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -474,7 +466,7 @@ public class MasterElectionTest extends FleetControllerTest {
n.disconnectImmediately();
waitForCompleteCycle(0);
});
- setWantedState(this.nodes.get(2*10 - 1), State.MAINTENANCE, "bar");
+ setWantedState(this.nodes.get(2 * 10 - 1), State.MAINTENANCE, "bar");
waitForCompleteCycle(0);
// This receives the version number of the highest _working_ cluster state, with
@@ -494,13 +486,14 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps() throws Exception {
+ void previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps() throws Exception {
startingTest("MasterElectionTest::previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps");
FleetControllerOptions options = defaultOptions("mycluster");
options.clusterHasGlobalDocumentTypes = true;
options.masterZooKeeperCooldownPeriod = 1;
options.minTimeBeforeFirstSystemStateBroadcast = 100000;
- setUpFleetController(3, false, options);
+ boolean useFakeTimer = false;
+ setUpFleetController(3, useFakeTimer, options);
setUpVdsNodes(false, new DummyVdsNodeOptions());
fleetController = fleetControllers.get(0); // Required to prevent waitForStableSystem from NPE'ing
waitForMaster(0);
@@ -526,7 +519,7 @@ public class MasterElectionTest extends FleetControllerTest {
waitForMaster(1);
waitForCompleteCycle(1);
- fleetControllers.set(0, createFleetController(usingFakeTimer, fleetControllers.get(0).getOptions(), true, new StatusHandler.ContainerStatusPageServer()));
+ fleetControllers.set(0, createFleetController(useFakeTimer, fleetControllers.get(0).getOptions()));
waitForMaster(0);
waitForCompleteCycle(0);
@@ -537,7 +530,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types() throws Exception {
+ void default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types() throws Exception {
startingTest("MasterElectionTest::default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types");
FleetControllerOptions options = defaultOptions("mycluster");
options.clusterHasGlobalDocumentTypes = false;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
index 4cd2fcdfbd5..a6defaee7fe 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vespa.clustercontroller.core.matchers.HasMetricContext;
import com.yahoo.vespa.clustercontroller.utils.util.MetricReporter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
@@ -57,7 +57,7 @@ public class MetricReporterTest {
}
@Test
- public void metrics_are_emitted_for_different_node_state_counts() {
+ void metrics_are_emitted_for_different_node_state_counts() {
Fixture f = new Fixture();
f.metricUpdater.updateClusterStateMetrics(f.clusterFixture.cluster(),
ClusterState.stateFromString("distributor:10 .1.s:d storage:9 .1.s:d .2.s:m .4.s:d"),
@@ -90,28 +90,28 @@ public class MetricReporterTest {
}
@Test
- public void metrics_are_emitted_for_partial_node_availability_ratio() {
+ void metrics_are_emitted_for_partial_node_availability_ratio() {
// Only Up, Init, Retired and Maintenance are counted as available states
doTestRatiosInState("distributor:10 .1.s:d storage:9 .1.s:d .2.s:m .4.s:r .5.s:i .6.s:s", 0.9, 0.7);
}
@Test
- public void metrics_are_emitted_for_full_node_availability_ratio() {
+ void metrics_are_emitted_for_full_node_availability_ratio() {
doTestRatiosInState("distributor:10 storage:10", 1.0, 1.0);
}
@Test
- public void metrics_are_emitted_for_zero_node_availability_ratio() {
+ void metrics_are_emitted_for_zero_node_availability_ratio() {
doTestRatiosInState("cluster:d", 0.0, 0.0);
}
@Test
- public void maintenance_mode_is_counted_as_available() {
+ void maintenance_mode_is_counted_as_available() {
doTestRatiosInState("distributor:10 storage:10 .0.s:m", 1.0, 1.0);
}
@Test
- public void metrics_are_emitted_for_resource_usage() {
+ void metrics_are_emitted_for_resource_usage() {
Fixture f = new Fixture();
f.metricUpdater.updateClusterStateMetrics(f.clusterFixture.cluster(),
ClusterState.stateFromString("distributor:10 storage:10"),
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
index bd1ffac089c..62a49ecf969 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class NoZooKeeperTest extends FleetControllerTest {
@Test
- public void testWantedStatesInZooKeeper() throws Exception {
+ void testWantedStatesInZooKeeper() throws Exception {
startingTest("NoZooKeeperTest::testWantedStatesInZooKeeper");
FleetControllerOptions options = defaultOptions("mycluster");
options.zooKeeperServerAddress = null;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
index 129c70d1d29..4b068d107bf 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
@@ -4,16 +4,14 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class NodeInfoTest {
@Test
- public void unstable_init_flag_is_initially_clear() {
+ void unstable_init_flag_is_initially_clear() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
assertFalse(nodeInfo.recentlyObservedUnstableDuringInit());
@@ -26,7 +24,7 @@ public class NodeInfoTest {
}
@Test
- public void down_edge_during_init_state_marks_as_unstable_init() {
+ void down_edge_during_init_state_marks_as_unstable_init() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -34,7 +32,7 @@ public class NodeInfoTest {
}
@Test
- public void stopping_edge_during_init_does_not_mark_as_unstable_init() {
+ void stopping_edge_during_init_does_not_mark_as_unstable_init() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3).reportStorageNodeState(0, State.INITIALIZING);
fixture.reportStorageNodeState(0, State.STOPPING);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 0));
@@ -48,7 +46,7 @@ public class NodeInfoTest {
* from haunting a now stable node.
*/
@Test
- public void zeroing_crash_count_resets_unstable_init_flag() {
+ void zeroing_crash_count_resets_unstable_init_flag() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -61,7 +59,7 @@ public class NodeInfoTest {
* further instabilities and should not clear the unstable init flag.
*/
@Test
- public void non_zero_crash_count_update_does_not_reset_unstable_init_flag() {
+ void non_zero_crash_count_update_does_not_reset_unstable_init_flag() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -70,7 +68,7 @@ public class NodeInfoTest {
}
@Test
- public void non_zero_crash_count_does_not_implicitly_set_unstable_init_flag() {
+ void non_zero_crash_count_does_not_implicitly_set_unstable_init_flag() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -79,7 +77,7 @@ public class NodeInfoTest {
}
@Test
- public void down_wanted_state_overrides_config_retired_state() {
+ void down_wanted_state_overrides_config_retired_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.markNodeAsConfigRetired(1)
.proposeStorageNodeWantedState(1, State.DOWN);
@@ -89,7 +87,7 @@ public class NodeInfoTest {
}
@Test
- public void maintenance_wanted_state_overrides_config_retired_state() {
+ void maintenance_wanted_state_overrides_config_retired_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.markNodeAsConfigRetired(1)
.proposeStorageNodeWantedState(1, State.MAINTENANCE);
@@ -99,7 +97,7 @@ public class NodeInfoTest {
}
@Test
- public void retired_state_overrides_default_up_wanted_state() {
+ void retired_state_overrides_default_up_wanted_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).markNodeAsConfigRetired(1);
NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
index ea539cc13e0..69ddf8e2c02 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.ConfiguredNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.TreeSet;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest {
@@ -32,13 +32,13 @@ public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest
}
@Test
- public void testSlobrokNodeOutsideConfiguredIndexSetIsNotIncludedInCluster() throws Exception {
+ void testSlobrokNodeOutsideConfiguredIndexSetIsNotIncludedInCluster() throws Exception {
setUpClusterWithForeignNode(nodeIndices, foreignNode);
waitForStateExcludingNodeSubset("version:\\d+ distributor:4 storage:4", asIntSet(foreignNode));
}
@Test
- public void testNodeSetReconfigurationForcesFreshSlobrokFetch() throws Exception {
+ void testNodeSetReconfigurationForcesFreshSlobrokFetch() throws Exception {
setUpClusterWithForeignNode(nodeIndices, foreignNode);
waitForStateExcludingNodeSubset("version:\\d+ distributor:4 storage:4", asIntSet(foreignNode));
@@ -53,7 +53,7 @@ public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest
}
@Test
- public void test_removed_retired_node_is_not_included_in_state() throws Exception {
+ void test_removed_retired_node_is_not_included_in_state() throws Exception {
final Set<ConfiguredNode> configuredNodes = asConfiguredNodes(nodeIndices);
FleetControllerOptions options = optionsForConfiguredNodes(configuredNodes);
setUpFleetController(true, options);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
index 87e102c67c1..6af852aa3ed 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
@@ -13,17 +13,14 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStateRequest;
import com.yahoo.vespa.config.content.StorDistributionConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -107,7 +104,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeForce() {
+ void testCanUpgradeForce() {
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(createCluster(createNodes(1)));
NodeState newState = new NodeState(NodeType.STORAGE, State.INITIALIZING);
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
@@ -118,7 +115,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDeniedInMoratorium() {
+ void testDeniedInMoratorium() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = new NodeStateChangeChecker(
requiredRedundancy, noopVisiting, cluster.clusterInfo(), true);
@@ -131,7 +128,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testUnknownStorageNode() {
+ void testUnknownStorageNode() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = new NodeStateChangeChecker(
requiredRedundancy, noopVisiting, cluster.clusterInfo(), false);
@@ -144,7 +141,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenOtherStorageNodeInFlatClusterIsSuspended() {
+ void testSafeMaintenanceDisallowedWhenOtherStorageNodeInFlatClusterIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
ContentCluster cluster = createCluster(createNodes(4));
cluster.clusterInfo().getStorageNodeInfo(0).setWantedState(new NodeState(NodeType.STORAGE, State.MAINTENANCE).setDescription("Orchestrator"));
@@ -164,7 +161,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenOtherDistributorInFlatClusterIsSuspended() {
+ void testSafeMaintenanceDisallowedWhenOtherDistributorInFlatClusterIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
ContentCluster cluster = createCluster(createNodes(4));
cluster.clusterInfo().getDistributorNodeInfo(0)
@@ -185,7 +182,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenDistributorInGroupIsDown() {
+ void testSafeMaintenanceDisallowedWhenDistributorInGroupIsDown() {
// Nodes 0-3, distributor 0 being in maintenance with "Orchestrator" description.
// 2 groups: nodes 0-1 is group 0, 2-3 is group 1.
ContentCluster cluster = createCluster(createNodes(4));
@@ -214,13 +211,13 @@ public class NodeStateChangeCheckerTest {
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
new Node(NodeType.STORAGE, 1), clusterStateWith0InMaintenance,
SetUnitStateRequest.Condition.SAFE, UP_NODE_STATE, MAINTENANCE_NODE_STATE);
- assertFalse(result.getReason(), result.settingWantedStateIsAllowed());
+ assertFalse(result.settingWantedStateIsAllowed(), result.getReason());
assertEquals("Another distributor wants state DOWN: 0", result.getReason());
}
}
@Test
- public void testSafeMaintenanceWhenOtherStorageNodeInGroupIsSuspended() {
+ void testSafeMaintenanceWhenOtherStorageNodeInGroupIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
// 2 groups: nodes 0-1 is group 0, 2-3 is group 1.
ContentCluster cluster = createCluster(createNodes(4));
@@ -249,7 +246,7 @@ public class NodeStateChangeCheckerTest {
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
new Node(NodeType.STORAGE, 1), clusterStateWith0InMaintenance,
SetUnitStateRequest.Condition.SAFE, UP_NODE_STATE, MAINTENANCE_NODE_STATE);
- assertTrue(result.getReason(), result.settingWantedStateIsAllowed());
+ assertTrue(result.settingWantedStateIsAllowed(), result.getReason());
assertFalse(result.wantedStateAlreadySet());
}
}
@@ -295,7 +292,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeSetStateDistributors() {
+ void testSafeSetStateDistributors() {
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(createCluster(createNodes(1)));
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
nodeDistributor, defaultAllUpClusterState(), SetUnitStateRequest.Condition.SAFE,
@@ -306,7 +303,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeSafeMissingStorage() {
+ void testCanUpgradeSafeMissingStorage() {
// Create a content cluster with 4 nodes, and storage node with index 3 down.
ContentCluster cluster = createCluster(createNodes(4));
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 5, 6)));
@@ -327,14 +324,14 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeStorageSafeYes() {
+ void testCanUpgradeStorageSafeYes() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testSetUpFailsIfReportedIsDown() {
+ void testSetUpFailsIfReportedIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
// Not setting nodes up -> all are down
@@ -349,7 +346,7 @@ public class NodeStateChangeCheckerTest {
// A node may be reported as Up but have a generated state of Down if it's part of
// nodes taken down implicitly due to a group having too low node availability.
@Test
- public void testSetUpSucceedsIfReportedIsUpButGeneratedIsDown() {
+ void testSetUpSucceedsIfReportedIsUpButGeneratedIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
@@ -367,7 +364,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanSetUpEvenIfOldWantedStateIsDown() {
+ void testCanSetUpEvenIfOldWantedStateIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -380,7 +377,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeStorageSafeNo() {
+ void testCanUpgradeStorageSafeNo() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -395,7 +392,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeIfMissingMinReplicationFactor() {
+ void testCanUpgradeIfMissingMinReplicationFactor() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -408,7 +405,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeIfStorageNodeMissingFromNodeInfo() {
+ void testCanUpgradeIfStorageNodeMissingFromNodeInfo() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
String hostInfo = "{\n" +
@@ -432,7 +429,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testMissingDistributorState() {
+ void testMissingDistributorState() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
cluster.clusterInfo().getStorageNodeInfo(1).setReportedState(new NodeState(NodeType.STORAGE, State.UP), 0);
@@ -460,20 +457,20 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSettingUpWhenUpCausesAlreadySet() {
+ void testSettingUpWhenUpCausesAlreadySet() {
NodeStateChangeChecker.Result result = transitionToSameState(State.UP, "foo", "bar");
assertTrue(result.wantedStateAlreadySet());
}
@Test
- public void testSettingAlreadySetState() {
+ void testSettingAlreadySetState() {
NodeStateChangeChecker.Result result = transitionToSameState("foo", "foo");
assertFalse(result.settingWantedStateIsAllowed());
assertTrue(result.wantedStateAlreadySet());
}
@Test
- public void testDifferentDescriptionImpliesDenied() {
+ void testDifferentDescriptionImpliesDenied() {
NodeStateChangeChecker.Result result = transitionToSameState("foo", "bar");
assertFalse(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
@@ -526,28 +523,28 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeWhenAllUp() {
+ void testCanUpgradeWhenAllUp() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCanUpgradeWhenAllUpOrRetired() {
+ void testCanUpgradeWhenAllUpOrRetired() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCanUpgradeWhenStorageIsDown() {
+ void testCanUpgradeWhenStorageIsDown() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithOneStorageNodeDown(nodeStorage.getIndex());
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCannotUpgradeWhenOtherStorageIsDown() {
+ void testCannotUpgradeWhenOtherStorageIsDown() {
int otherIndex = 2;
// If this fails, just set otherIndex to some other valid index.
assertNotEquals(nodeStorage.getIndex(), otherIndex);
@@ -559,7 +556,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testNodeRatioRequirementConsidersGeneratedNodeStates() {
+ void testNodeRatioRequirementConsidersGeneratedNodeStates() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
@@ -581,7 +578,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByNonRetiredState() {
+ void testDownDisallowedByNonRetiredState() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
defaultAllUpClusterState(),
State.UP,
@@ -593,7 +590,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByBuckets() {
+ void testDownDisallowedByBuckets() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
@@ -605,7 +602,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByReportedState() {
+ void testDownDisallowedByReportedState() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.INITIALIZING,
@@ -617,7 +614,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByVersionMismatch() {
+ void testDownDisallowedByVersionMismatch() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
@@ -630,7 +627,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testAllowedToSetDown() {
+ void testAllowedToSetDown() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
index e136ddfa72d..24945d0d261 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.storageNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.createFixtureWithReportedUsages;
@@ -11,27 +11,24 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.forNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.mapOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class ResourceExhaustionCalculatorTest {
@Test
- public void no_feed_block_returned_when_no_resources_lower_than_limit() {
+ void no_feed_block_returned_when_no_resources_lower_than_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.49), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void feed_block_returned_when_single_resource_beyond_limit() {
+ void feed_block_returned_when_single_resource_beyond_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
@@ -39,10 +36,10 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void feed_block_description_can_contain_optional_name_component() {
+ void feed_block_description_can_contain_optional_name_component() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", "a-fancy-disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
@@ -50,80 +47,80 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void missing_or_malformed_rpc_addresses_are_emitted_as_unknown_hostnames() {
+ void missing_or_malformed_rpc_addresses_are_emitted_as_unknown_hostnames() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.85)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.85)));
cf.cluster().getNodeInfo(storageNode(1)).setRpcAddress(null);
cf.cluster().getNodeInfo(storageNode(2)).setRpcAddress("max mekker");
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [unknown hostname] (0.510 > 0.500), " +
- "memory on node 2 [unknown hostname] (0.850 > 0.800)", feedBlock.getDescription());
+ "memory on node 2 [unknown hostname] (0.850 > 0.800)", feedBlock.getDescription());
}
@Test
- public void feed_block_returned_when_multiple_resources_beyond_limit() {
+ void feed_block_returned_when_multiple_resources_beyond_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.4), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.85)),
- forNode(2, usage("disk", 0.45), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.45), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [storage.1.local] (0.510 > 0.400), " +
- "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
- "disk on node 2 [storage.2.local] (0.450 > 0.400)",
- feedBlock.getDescription());
+ "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
+ "disk on node 2 [storage.2.local] (0.450 > 0.400)",
+ feedBlock.getDescription());
}
@Test
- public void feed_block_description_is_bounded_in_number_of_described_resources() {
+ void feed_block_description_is_bounded_in_number_of_described_resources() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.4), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.85)),
- forNode(2, usage("disk", 0.45), usage("memory", 0.6)),
- forNode(3, usage("disk", 0.6), usage("memory", 0.9)));
+ forNode(2, usage("disk", 0.45), usage("memory", 0.6)),
+ forNode(3, usage("disk", 0.6), usage("memory", 0.9)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [storage.1.local] (0.510 > 0.400), " +
- "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
- "disk on node 2 [storage.2.local] (0.450 > 0.400) (... and 2 more)",
- feedBlock.getDescription());
+ "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
+ "disk on node 2 [storage.2.local] (0.450 > 0.400) (... and 2 more)",
+ feedBlock.getDescription());
}
@Test
- public void no_feed_block_returned_when_feed_block_disabled() {
+ void no_feed_block_returned_when_feed_block_disabled() {
var calc = new ResourceExhaustionCalculator(false, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void retain_node_feed_block_status_when_within_hysteresis_window_limit_crossed_edge_case() {
+ void retain_node_feed_block_status_when_within_hysteresis_window_limit_crossed_edge_case() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.51)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.51 to 0.49, crossing the 0.5 threshold. Should still be blocked.
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.49)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
// TODO should we not change the limits themselves? Explicit mention of hysteresis state?
assertEquals("memory on node 1 [storage.1.local] (0.490 > 0.400)",
- feedBlock.getDescription());
+ feedBlock.getDescription());
}
@Test
- public void retain_node_feed_block_status_when_within_hysteresis_window_under_limit_edge_case() {
+ void retain_node_feed_block_status_when_within_hysteresis_window_under_limit_edge_case() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.49)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.49 to 0.48, NOT crossing the 0.5 threshold. Should still be blocked.
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.48)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertEquals("memory on node 1 [storage.1.local] (0.480 > 0.400)",
@@ -131,22 +128,22 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void retained_node_feed_block_cleared_once_hysteresis_threshold_is_passed() {
+ void retained_node_feed_block_cleared_once_hysteresis_threshold_is_passed() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.48)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.48 to 0.39. Should be unblocked
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.39)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void node_must_be_available_in_reported_state_to_trigger_feed_block() {
+ void node_must_be_available_in_reported_state_to_trigger_feed_block() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
cf.reportStorageNodeState(1, State.DOWN);
cf.reportStorageNodeState(2, State.DOWN);
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
@@ -154,10 +151,10 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void node_must_be_available_in_wanted_state_to_trigger_feed_block() {
+ void node_must_be_available_in_wanted_state_to_trigger_feed_block() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
cf.proposeStorageNodeWantedState(1, State.DOWN);
cf.proposeStorageNodeWantedState(2, State.MAINTENANCE);
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java
index 2eeaf7658ff..fddd5b52aa2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Collections;
@@ -13,15 +13,14 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.exhaustion;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.forNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
-
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ResourceUsageStatsTest {
private final double DELTA = 0.00001;
@Test
- public void disk_and_memory_utilization_is_max_among_all_content_nodes() {
+ void disk_and_memory_utilization_is_max_among_all_content_nodes() {
var stats = ResourceUsageStats.calculateFrom(createNodeInfo(
forNode(1, usage("disk", 0.3), usage("memory", 0.6)),
forNode(2, usage("disk", 0.4), usage("memory", 0.5))),
@@ -34,7 +33,7 @@ public class ResourceUsageStatsTest {
}
@Test
- public void disk_and_memory_utilization_is_zero_if_no_samples_are_available() {
+ void disk_and_memory_utilization_is_zero_if_no_samples_are_available() {
var stats = ResourceUsageStats.calculateFrom(createNodeInfo(
forNode(1), forNode(2)),
createFeedBlockLimits(0.8, 0.9),
@@ -46,20 +45,20 @@ public class ResourceUsageStatsTest {
}
@Test
- public void nodes_above_limit_is_zero_without_feed_block_status() {
+ void nodes_above_limit_is_zero_without_feed_block_status() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), Optional.empty());
assertEquals(0, stats.getNodesAboveLimit());
}
@Test
- public void nodes_above_limit_is_equal_to_node_resource_exhaustions() {
+ void nodes_above_limit_is_equal_to_node_resource_exhaustions() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(2, "memory")));
assertEquals(2, stats.getNodesAboveLimit());
}
@Test
- public void nodes_above_limit_counts_each_node_only_once() {
+ void nodes_above_limit_counts_each_node_only_once() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(1, "memory")));
assertEquals(1, stats.getNodesAboveLimit());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
index fee1d33725c..641f15467a6 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
@@ -20,7 +20,7 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.rpc.RpcServer;
import com.yahoo.vespa.clustercontroller.core.testutils.LogFormatter;
import com.yahoo.vespa.clustercontroller.core.testutils.WaitCondition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -30,10 +30,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author humbe
@@ -52,11 +49,10 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testRebinding() throws Exception {
+ void testRebinding() throws Exception {
startingTest("RpcServerTest::testRebinding");
Slobrok slobrok = new Slobrok();
- String[] slobrokConnectionSpecs = new String[1];
- slobrokConnectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ String[] slobrokConnectionSpecs = getSlobrokConnectionSpecs(slobrok);
RpcServer server = new RpcServer(timer, new Object(), "mycluster", 0, new BackOff());
server.setSlobrokConnectionSpecs(slobrokConnectionSpecs, 18347);
int portUsed = server.getPort();
@@ -81,17 +77,18 @@ public class RpcServerTest extends FleetControllerTest {
* similar things, so strange if it should be from them too though. Maybe last test there.
*/
@Test
- public void testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork() {
- try{
+ void testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork() {
+ try {
startingTest("RpcServerTest::testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
waitForStableSystem();
- } catch (Throwable t) {}
+ } catch (Throwable t) {
+ }
}
@Test
- public void testGetSystemState() throws Exception {
+ void testGetSystemState() throws Exception {
LogFormatter.initializeLogging();
startingTest("RpcServerTest::testGetSystemState");
FleetControllerOptions options = defaultOptions("mycluster");
@@ -103,7 +100,7 @@ public class RpcServerTest extends FleetControllerTest {
log.log(Level.INFO, "Disconnecting distributor 0. Waiting for state to reflect change.");
nodes.get(0).disconnect();
nodes.get(19).disconnect();
- fleetController.waitForNodesInSlobrok(9, 9, timeoutMS);
+ fleetController.waitForNodesInSlobrok(9, 9, timeout());
timer.advanceTime(options.nodeStateRequestTimeoutMS + options.maxSlobrokDisconnectGracePeriod);
wait(new WaitCondition.StateWait(fleetController, fleetController.getMonitor()) {
@@ -122,7 +119,7 @@ public class RpcServerTest extends FleetControllerTest {
}
return null;
}
- }, null, timeoutMS);
+ }, null, timeout());
int rpcPort = fleetController.getRpcPort();
supervisor = new Supervisor(new Transport());
@@ -130,13 +127,13 @@ public class RpcServerTest extends FleetControllerTest {
assertTrue(connection.isValid());
Request req = new Request("getSystemState");
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ss"));
+ connection.invokeSync(req, timeout());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ss"), req.toString());
String systemState = req.returnValues().get(1).asString();
ClusterState retrievedClusterState = new ClusterState(systemState);
- assertEquals(systemState, State.DOWN, retrievedClusterState.getNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getState());
- assertTrue(systemState, retrievedClusterState.getNodeState(new Node(NodeType.STORAGE, 9)).getState().oneOf("md"));
+ assertEquals(State.DOWN, retrievedClusterState.getNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getState(), systemState);
+ assertTrue(retrievedClusterState.getNodeState(new Node(NodeType.STORAGE, 9)).getState().oneOf("md"), systemState);
}
private void setWantedNodeState(State newState, NodeType nodeType, int nodeIndex) {
@@ -150,16 +147,13 @@ public class RpcServerTest extends FleetControllerTest {
Node node = new Node(nodeType, nodeIndex);
NodeState newNodeState = new NodeState(nodeType, newState);
- Request req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/" + node.getType().toString() + "/" + node.getIndex()));
- req.parameters().add(new StringValue(newNodeState.serialize(true)));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ Request req = setNodeState("storage/cluster.mycluster/" + node.getType().toString() + "/" + node.getIndex(), newNodeState, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
}
@Test
- public void testGetNodeState() throws Exception {
+ void testGetNodeState() throws Exception {
startingTest("RpcServerTest::testGetNodeState");
Set<ConfiguredNode> configuredNodes = new TreeSet<>();
for (int i = 0; i < 10; i++)
@@ -195,89 +189,65 @@ public class RpcServerTest extends FleetControllerTest {
Target connection = supervisor.connect(new Spec("localhost", rpcPort));
assertTrue(connection.isValid());
- Request req = new Request("getNodeState");
- req.parameters().add(new StringValue("distributor"));
- req.parameters().add(new Int32Value(0));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ Request req = getNodeState("distributor", 0, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(0).asString()).getState());
NodeState reported = NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(1).asString());
- assertTrue(req.returnValues().get(1).asString(), reported.getState().oneOf("d-"));
+ assertTrue(reported.getState().oneOf("d-"), req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("distributor"));
- req.parameters().add(new Int32Value(2));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ req = getNodeState("distributor",2, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(0).asString()).getState());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(2).asString()).getState());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("distributor"));
- req.parameters().add(new Int32Value(4));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ req = getNodeState("distributor", 4, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("", req.returnValues().get(0).asString());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("distributor"));
- req.parameters().add(new Int32Value(15));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
+ req = getNodeState("distributor", 15, connection);
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
assertEquals("No node distributor.15 exists in cluster mycluster", req.errorMessage());
- assertFalse(req.toString(), req.checkReturnTypes("ssss"));
-
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("storage"));
- req.parameters().add(new Int32Value(1));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertFalse(req.checkReturnTypes("ssss"), req.toString());
+
+ req = getNodeState("storage", 1, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("s:i i:0.2", req.returnValues().get(0).asString());
assertEquals("s:i i:0.2", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("storage"));
- req.parameters().add(new Int32Value(2));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ req = getNodeState("storage", 2, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(0).asString()).getState());
reported = NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(1).asString());
- assertTrue(req.returnValues().get(1).asString(), reported.getState().oneOf("d-"));
+ assertTrue(reported.getState().oneOf("d-"), req.returnValues().get(1).asString());
assertEquals(State.RETIRED, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(2).asString()).getState());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("storage"));
- req.parameters().add(new Int32Value(5));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ req = getNodeState("storage", 5, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("", req.returnValues().get(0).asString());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
- req = new Request("getNodeState");
- req.parameters().add(new StringValue("storage"));
- req.parameters().add(new Int32Value(7));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ req = getNodeState("storage", 7, connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.MAINTENANCE, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(0).asString()).getState());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals(State.MAINTENANCE, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(2).asString()).getState());
}
@Test
- public void testGetNodeStateWithConfiguredRetired() throws Exception {
+ void testGetNodeStateWithConfiguredRetired() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfiguredRetired");
List<ConfiguredNode> configuredNodes = new ArrayList<>();
for (int i = 0; i < 4; i++)
@@ -311,7 +281,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown() throws Exception {
+ void testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown");
{ // Configuration: 5 nodes, all normal
@@ -392,7 +362,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testGetNodeStateWithConfigurationChangeToRetired() throws Exception {
+ void testGetNodeStateWithConfigurationChangeToRetired() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfigurationChangeToRetired");
{ // Configuration: 5 nodes, all normal
@@ -450,27 +420,27 @@ public class RpcServerTest extends FleetControllerTest {
{ // Configuration change: Remove the previously retired nodes
/*
- TODO: Verify current result: version:23 distributor:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d storage:7 .0.s:m .1.s:m .2.s:m .3.s:m .4.s:m
- TODO: Make this work without stopping/disconnecting (see StateChangeHandler.setNodes
- Set<ConfiguredNode> configuredNodes = new TreeSet<>();
- configuredNodes.add(new ConfiguredNode(5, false));
- configuredNodes.add(new ConfiguredNode(6, false));
- FleetControllerOptions options = new FleetControllerOptions("mycluster", configuredNodes);
- options.slobrokConnectionSpecs = this.options.slobrokConnectionSpecs;
- this.options.maxInitProgressTimeMs = 30000;
- this.options.stableStateTimePeriod = 60000;
- fleetController.updateOptions(options, 0);
- for (int i = 0; i < 5*2; i++) {
- nodes.get(i).disconnectSlobrok();
- nodes.get(i).disconnect();
- }
- waitForState("version:\\d+ distributor:7 storage:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d");
- */
+ TODO: Verify current result: version:23 distributor:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d storage:7 .0.s:m .1.s:m .2.s:m .3.s:m .4.s:m
+ TODO: Make this work without stopping/disconnecting (see StateChangeHandler.setNodes
+ Set<ConfiguredNode> configuredNodes = new TreeSet<>();
+ configuredNodes.add(new ConfiguredNode(5, false));
+ configuredNodes.add(new ConfiguredNode(6, false));
+ FleetControllerOptions options = new FleetControllerOptions("mycluster", configuredNodes);
+ options.slobrokConnectionSpecs = this.options.slobrokConnectionSpecs;
+ this.options.maxInitProgressTimeMs = 30000;
+ this.options.stableStateTimePeriod = 60000;
+ fleetController.updateOptions(options, 0);
+ for (int i = 0; i < 5*2; i++) {
+ nodes.get(i).disconnectSlobrok();
+ nodes.get(i).disconnect();
+ }
+ waitForState("version:\\d+ distributor:7 storage:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d");
+ */
}
}
@Test
- public void testSetNodeState() throws Exception {
+ void testSetNodeState() throws Exception {
startingTest("RpcServerTest::testSetNodeState");
Set<Integer> nodeIndexes = new TreeSet<>(List.of(4, 6, 9, 10, 14, 16, 21, 22, 23, 25));
Set<ConfiguredNode> configuredNodes = nodeIndexes.stream().map(i -> new ConfiguredNode(i, false)).collect(Collectors.toSet());
@@ -485,21 +455,15 @@ public class RpcServerTest extends FleetControllerTest {
Target connection = supervisor.connect(new Spec("localhost", rpcPort));
assertTrue(connection.isValid());
- Request req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/storage/14"));
- req.parameters().add(new StringValue("s:r"));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ Request req = setNodeState("storage/cluster.mycluster/storage/14", "s:r", connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
waitForState("version:\\d+ distributor:26 .* storage:26 .* .14.s:r .*");
- req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/storage/16"));
- req.parameters().add(new StringValue("s:m"));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ req = setNodeState("storage/cluster.mycluster/storage/16", "s:m", connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
waitForState("version:\\d+ distributor:26 .* storage:26 .* .14.s:r.* .16.s:m .*");
nodes.get(5 * 2 + 1).disconnect();
@@ -517,7 +481,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testSetNodeStateOutOfRange() throws Exception {
+ void testSetNodeStateOutOfRange() throws Exception {
startingTest("RpcServerTest::testSetNodeStateOutOfRange");
FleetControllerOptions options = defaultOptions("mycluster");
options.setStorageDistribution(new Distribution(Distribution.getDefaultDistributionConfig(2, 10)));
@@ -530,31 +494,22 @@ public class RpcServerTest extends FleetControllerTest {
Target connection = supervisor.connect(new Spec("localhost", rpcPort));
assertTrue(connection.isValid());
- Request req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/storage/10"));
- req.parameters().add(new StringValue("s:m"));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
- assertEquals(req.toString(), "Cannot set wanted state of node storage.10. Index does not correspond to a configured node.", req.errorMessage());
-
- req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/distributor/10"));
- req.parameters().add(new StringValue("s:m"));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
- assertEquals(req.toString(), "Cannot set wanted state of node distributor.10. Index does not correspond to a configured node.", req.errorMessage());
-
- req = new Request("setNodeState");
- req.parameters().add(new StringValue("storage/cluster.mycluster/storage/9"));
- req.parameters().add(new StringValue("s:m"));
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
+ Request req = setNodeState("storage/cluster.mycluster/storage/10", "s:m", connection);
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
+ assertEquals("Cannot set wanted state of node storage.10. Index does not correspond to a configured node.", req.errorMessage(), req.toString());
+
+ req = setNodeState("storage/cluster.mycluster/distributor/10", "s:m", connection);
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
+ assertEquals("Cannot set wanted state of node distributor.10. Index does not correspond to a configured node.", req.errorMessage(), req.toString());
+
+ req = setNodeState("storage/cluster.mycluster/storage/9", "s:m", connection);
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
waitForState("version:\\d+ distributor:10 storage:10 .9.s:m");
}
@Test
- public void testGetMaster() throws Exception {
+ void testGetMaster() throws Exception {
startingTest("RpcServerTest::testGetMaster");
FleetControllerOptions options = defaultOptions("mycluster");
options.setStorageDistribution(new Distribution(Distribution.getDefaultDistributionConfig(2, 10)));
@@ -568,15 +523,15 @@ public class RpcServerTest extends FleetControllerTest {
assertTrue(connection.isValid());
Request req = new Request("getMaster");
- connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), 0, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "All 1 nodes agree that 0 is current master.", req.returnValues().get(1).asString());
+ connection.invokeSync(req, timeout());
+ assertEquals(0, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("All 1 nodes agree that 0 is current master.", req.returnValues().get(1).asString(), req.toString());
// Note that this feature is tested better in MasterElectionTest.testGetMaster as it has multiple fleetcontrollers
}
@Test
- public void testGetNodeList() throws Exception {
+ void testGetNodeList() throws Exception {
startingTest("RpcServerTest::testGetNodeList");
setUpFleetController(true, defaultOptions("mycluster", 5));
final int nodeCount = 5;
@@ -592,36 +547,52 @@ public class RpcServerTest extends FleetControllerTest {
Target connection = supervisor.connect(new Spec("localhost", rpcPort));
assertTrue(connection.isValid());
- // Possibly do request multiple times if we haven't lost slobrok contact first times yet.
- for (int j = 0; j <= nodeCount; ++j) {
- Request req = new Request("getNodeList");
- connection.invokeSync(req, timeoutS);
- assertEquals(req.errorMessage(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("SS"));
- String[] slobrok = req.returnValues().get(0).asStringArray().clone();
- String[] rpc = req.returnValues().get(1).asStringArray().clone();
-
- assertEquals(2 * nodeCount, slobrok.length);
- assertEquals(2 * nodeCount, rpc.length);
-
- // Verify that we can connect to all addresses returned.
- for (int i = 0; i < 2 * nodeCount; ++i) {
- if (slobrok[i].equals("storage/cluster.mycluster/distributor/0")) {
- if (i < nodeCount && !"".equals(rpc[i])) {
- continue;
- }
- assertEquals(slobrok[i], "", rpc[i]);
+ Request req = new Request("getNodeList");
+ connection.invokeSync(req, timeout());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.errorMessage());
+ assertTrue(req.checkReturnTypes("SS"), req.toString());
+ String[] slobrok = req.returnValues().get(0).asStringArray().clone();
+ String[] rpc = req.returnValues().get(1).asStringArray().clone();
+
+ assertEquals(2 * nodeCount, slobrok.length);
+ assertEquals(2 * nodeCount, rpc.length);
+
+ // Verify that we can connect to all addresses returned.
+ for (int i = 0; i < 2 * nodeCount; ++i) {
+ if (slobrok[i].equals("storage/cluster.mycluster/distributor/0")) {
+ if (i < nodeCount && !"".equals(rpc[i])) {
continue;
}
- assertNotEquals("", rpc[i]);
- Request req2 = new Request("getnodestate2");
- req2.parameters().add(new StringValue("unknown"));
- Target connection2 = supervisor.connect(new Spec(rpc[i]));
- connection2.invokeSync(req2, timeoutS);
- assertEquals(req2.toString(), ErrorCode.NONE, req.errorCode());
+ assertEquals("", rpc[i], slobrok[i]);
+ continue;
}
- break;
+ assertNotEquals("", rpc[i]);
+ Request req2 = new Request("getnodestate2");
+ req2.parameters().add(new StringValue("unknown"));
+ Target connection2 = supervisor.connect(new Spec(rpc[i]));
+ connection2.invokeSync(req2, timeout());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req2.toString());
}
}
+ private Request setNodeState(String node, NodeState newNodeState, Target connection) {
+ return setNodeState(node, newNodeState.serialize(true), connection);
+ }
+
+ private Request setNodeState(String node, String newNodeState, Target connection) {
+ Request req = new Request("setNodeState");
+ req.parameters().add(new StringValue(node));
+ req.parameters().add(new StringValue(newNodeState));
+ connection.invokeSync(req, timeout());
+ return req;
+ }
+
+ private Request getNodeState(String nodeType, int nodeIndex, Target connection) {
+ Request req = new Request("getNodeState");
+ req.parameters().add(new StringValue(nodeType));
+ req.parameters().add(new Int32Value(nodeIndex));
+ connection.invokeSync(req, timeout());
+ return req;
+ }
+
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
index d61cd1271b6..df0b873e25b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -28,13 +28,13 @@ public class RpcVersionAutoDowngradeTest extends FleetControllerTest {
}
@Test
- public void cluster_state_rpc_version_is_auto_downgraded_and_retried_for_older_nodes() throws Exception {
+ void cluster_state_rpc_version_is_auto_downgraded_and_retried_for_older_nodes() throws Exception {
setUpFakeCluster(2); // HEAD is at v4
waitForState("version:\\d+ distributor:10 storage:10");
}
@Test
- public void implicit_activation_for_nodes_that_return_not_found_for_version_activation_rpc() throws Exception {
+ void implicit_activation_for_nodes_that_return_not_found_for_version_activation_rpc() throws Exception {
setUpFakeCluster(3); // HEAD is at v4
waitForState("version:\\d+ distributor:10 storage:10");
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
index 47ba7e1cb77..78576f9600c 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
@@ -2,19 +2,19 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.jrt.slobrok.server.Slobrok;
+import org.junit.jupiter.api.Test;
import java.util.logging.Level;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import java.util.logging.Logger;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
public class SlobrokTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(SlobrokTest.class.getName());
@Test
- public void testSingleSlobrokRestart() throws Exception {
+ void testSingleSlobrokRestart() throws Exception {
startingTest("SlobrokTest::testSingleSlobrokRestart");
FleetControllerOptions options = defaultOptions("mycluster");
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
@@ -26,13 +26,13 @@ public class SlobrokTest extends FleetControllerTest {
int version = fleetController.getSystemState().getVersion();
int slobrokPort = slobrok.port();
- // Test that we survive some slobrok instability without changing system state.
- for (int j=0; j<4; ++j) {
+ // Test that we survive some slobrok instability without changing system state.
+ for (int j = 0; j < 4; ++j) {
log.log(Level.INFO, "Mirror updateForDistributor count is " + fleetController.getSlobrokMirrorUpdates());
- log.log(Level.INFO, "STOPPING SLOBROK SERVER (" + (j+1) + "/4)");
+ log.log(Level.INFO, "STOPPING SLOBROK SERVER (" + (j + 1) + "/4)");
slobrok.stop();
- for (int i=0; i<10; ++i) {
- // Force one node to at least notice that the slobrok server is gone
+ for (int i = 0; i < 10; ++i) {
+ // Force one node to at least notice that the slobrok server is gone
if (i == 5) {
log.log(Level.INFO, "Forcing one node to initate a resend: " + nodes.get(3));
nodes.get(3).replyToPendingNodeStateRequests();
@@ -40,35 +40,35 @@ public class SlobrokTest extends FleetControllerTest {
waitForCompleteCycle();
timer.advanceTime(100);
}
- log.log(Level.INFO, "STARTING SLOBROK SERVER AGAIN (" + (j+1) + "/4)");
+ log.log(Level.INFO, "STARTING SLOBROK SERVER AGAIN (" + (j + 1) + "/4)");
slobrok = new Slobrok(slobrokPort);
- // May take up to 30 seconds for slobrok clients to re-register. Trigger retry.
+ // May take up to 30 seconds for slobrok clients to re-register. Trigger retry.
for (DummyVdsNode node : nodes) {
node.disconnectSlobrok();
node.registerSlobrok();
}
//fleetController.setFreshSlobrokMirror();
waitForCompleteCycle();
- fleetController.waitForNodesInSlobrok(10, 10, timeoutMS);
+ fleetController.waitForNodesInSlobrok(10, 10, timeout());
log.log(Level.INFO, "Waiting for cluster to be up and available again");
- for (int i = 0; i < timeoutMS; i += 10) {
+ for (int i = 0; i < timeout().toMillis(); i += 10) {
if (clusterAvailable()) break;
timer.advanceTime(1000);
waitForCompleteCycle();
- try{
+ try {
Thread.sleep(10);
- } catch (InterruptedException e) { /* ignore */ }
+ } catch (InterruptedException e) { /* ignore */
+ }
}
assertClusterAvailable();
}
- assertEquals("Cluster state was affected, although it should not have been.",
- version, fleetController.getSystemState().getVersion());
+ assertEquals(version, fleetController.getSystemState().getVersion(), "Cluster state was affected, although it should not have been.");
}
@Test
- public void testNodeTooLongOutOfSlobrok() throws Exception {
+ void testNodeTooLongOutOfSlobrok() throws Exception {
startingTest("SlobrokTest::testNodeTooLongOutOfSlobrok");
FleetControllerOptions options = defaultOptions("mycluster");
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -80,14 +80,17 @@ public class SlobrokTest extends FleetControllerTest {
int version = fleetController.getSystemState().getVersion();
nodes.get(0).disconnectSlobrok();
log.log(Level.INFO, "DISCONNECTED NODE FROM SLOBROK. SHOULD BE IN COOLDOWN PERIOD");
- fleetController.waitForNodesInSlobrok(9, 10, timeoutMS);
- synchronized (timer) {
+ fleetController.waitForNodesInSlobrok(9, 10, timeout());
+ synchronized(timer) {
nodes.get(0).sendGetNodeStateReply(0);
}
// Give system a little time to possible faultily removing node not in slobrok
timer.advanceTime(1000);
- try{ Thread.sleep(10); } catch (InterruptedException e) { /* ignore */ }
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) { /* ignore */
+ }
assertEquals(version, fleetController.getSystemState().getVersion());
log.log(Level.INFO, "JUMPING TIME. NODE SHOULD BE MARKED DOWN");
// At this point the fleetcontroller might not have noticed that the node is out of slobrok yet.
@@ -108,8 +111,8 @@ public class SlobrokTest extends FleetControllerTest {
private void assertClusterAvailable() {
ContentCluster cluster = fleetController.getCluster();
for (NodeInfo info : cluster.getNodeInfos()) {
- assertEquals("Node " + info + " connection attempts.", 0, info.getConnectionAttemptCount());
- assertTrue("Node " + info + " has no last request time.", info.getLatestNodeStateRequestTime() != 0);
+ assertEquals(0, info.getConnectionAttemptCount(), "Node " + info + " connection attempts.");
+ assertTrue(info.getLatestNodeStateRequestTime() != 0, "Node " + info + " has no last request time.");
}
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
index 699a35a190c..2bea95ab8c5 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
@@ -12,8 +12,8 @@ import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import com.yahoo.vespa.clustercontroller.core.mocks.TestEventLog;
import com.yahoo.vespa.clustercontroller.core.testutils.LogFormatter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
@@ -21,8 +21,8 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class StateChangeHandlerTest {
@@ -76,7 +76,7 @@ public class StateChangeHandlerTest {
private TestNodeListener nodeStateUpdateListener;
private final ClusterStateGenerator.Params params = new ClusterStateGenerator.Params();
- @Before
+ @BeforeEach
public void setUp() {
LogFormatter.initializeLogging();
}
@@ -125,7 +125,7 @@ public class StateChangeHandlerTest {
log.info("Marking " + node + " out of slobrok");
cluster.getNodeInfo(node).markRpcAddressOutdated(clock);
nodeStateChangeHandler.handleMissingNode(stateBefore, cluster.getNodeInfo(node), nodeStateUpdateListener);
- assertTrue(eventLog.toString(), eventLog.toString().contains("Node is no longer in slobrok"));
+ assertTrue(eventLog.toString().contains("Node is no longer in slobrok"), eventLog.toString());
eventLog.clear();
}
@@ -159,16 +159,16 @@ public class StateChangeHandlerTest {
}
@Test
- public void testUnstableNodeInSlobrok() {
+ void testUnstableNodeInSlobrok() {
initialize(new Config());
startWithStableStateClusterWithNodesUp();
Node node = new Node(NodeType.STORAGE, 0);
- for (int j=0; j<3; ++j) {
+ for (int j = 0; j < 3; ++j) {
log.info("Iteration " + j);
assertEquals(0, cluster.getNodeInfo(node).getPrematureCrashCount());
assertEquals(State.UP, cluster.getNodeInfo(node).getWantedState().getState());
assertEquals(State.UP, currentClusterState().getNodeState(node).getState());
- for (int k=0; k<config.maxPrematureCrashes; ++k) {
+ for (int k = 0; k < config.maxPrematureCrashes; ++k) {
log.info("Premature iteration " + k);
markNodeOutOfSlobrok(node);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
index 5a33414c955..6ad0430b5c3 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.testutils.StateWaiter;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
@@ -25,9 +25,7 @@ import java.util.logging.Logger;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class StateChangeTest extends FleetControllerTest {
@@ -37,7 +35,7 @@ public class StateChangeTest extends FleetControllerTest {
private DummyCommunicator communicator;
private EventLog eventLog;
- @Before
+ @BeforeEach
public void setUp() {
supervisor = new Supervisor(new Transport());
}
@@ -101,7 +99,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNormalStartup() throws Exception {
+ void testNormalStartup() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxInitProgressTime = 50000;
@@ -115,7 +113,7 @@ public class StateChangeTest extends FleetControllerTest {
communicator.setNodeState(new Node(NodeType.DISTRIBUTOR, j), new NodeState(NodeType.DISTRIBUTOR, State.INITIALIZING).setInitProgress(0.0f), "");
}
- for (int i=0; i<100; i += 10) {
+ for (int i = 0; i < 100; i += 10) {
timer.advanceTime(options.maxInitProgressTime / 20);
ctrl.tick();
for (int j = 0; j < 10; ++j) {
@@ -129,9 +127,9 @@ public class StateChangeTest extends FleetControllerTest {
// Regular init progress does not update the cluster state until the node is done initializing (or goes down,
// whichever comes first).
assertEquals("version:6 distributor:10 .0.s:i .0.i:0.0 .1.s:i .1.i:0.0 .2.s:i .2.i:0.0 .3.s:i .3.i:0.0 " +
- ".4.s:i .4.i:0.0 .5.s:i .5.i:0.0 .6.s:i .6.i:0.0 .7.s:i .7.i:0.0 .8.s:i .8.i:0.0 " +
- ".9.s:i .9.i:0.0 storage:10 .0.s:i .0.i:0.1 .1.s:i .1.i:0.1 .2.s:i .2.i:0.1 .3.s:i .3.i:0.1 " +
- ".4.s:i .4.i:0.1 .5.s:i .5.i:0.1 .6.s:i .6.i:0.1 .7.s:i .7.i:0.1 .8.s:i .8.i:0.1 .9.s:i .9.i:0.1",
+ ".4.s:i .4.i:0.0 .5.s:i .5.i:0.0 .6.s:i .6.i:0.0 .7.s:i .7.i:0.0 .8.s:i .8.i:0.0 " +
+ ".9.s:i .9.i:0.0 storage:10 .0.s:i .0.i:0.1 .1.s:i .1.i:0.1 .2.s:i .2.i:0.1 .3.s:i .3.i:0.1 " +
+ ".4.s:i .4.i:0.1 .5.s:i .5.i:0.1 .6.s:i .6.i:0.1 .7.s:i .7.i:0.1 .8.s:i .8.i:0.1 .9.s:i .9.i:0.1",
ctrl.consolidatedClusterState().toString());
timer.advanceTime(options.maxInitProgressTime / 20);
@@ -155,25 +153,25 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Now reporting state I, i 0.00\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'I, i 0.00'\n" +
- "Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'I, i 0.00' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Now reporting state I, i 0.00\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'I, i 0.00'\n" +
+ "Event: distributor.0: Now reporting state U\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'I, i 0.00' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'D'\n" +
- "Event: storage.0: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.0: Altered node state in cluster state from 'D' to 'I, i 0.100 (read)'\n" +
- "Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'D'\n" +
+ "Event: storage.0: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.0: Now reporting state U\n" +
+ "Event: storage.0: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
}
@Test
- public void testNodeGoingDownAndUp() throws Exception {
+ void testNodeGoingDownAndUp() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
options.minTimeBetweenNewSystemStates = 0;
@@ -191,7 +189,7 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
String desc = ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
assertEquals("version:4 distributor:10 .0.s:d storage:10", ctrl.getSystemState().toString());
@@ -208,7 +206,7 @@ public class StateChangeTest extends FleetControllerTest {
assert(!ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).hasDescription());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
timer.advanceTime(options.maxTransitionTime.get(NodeType.STORAGE) + 1);
@@ -217,7 +215,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:6 distributor:10 .0.t:12345678 storage:10 .0.s:d", ctrl.getSystemState().toString());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
timer.advanceTime(1000);
@@ -233,24 +231,24 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Failed to get node state: D: Closed at other end\n" +
- "Event: distributor.0: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: Closed at other end'\n" +
- "Event: distributor.0: Now reporting state U, t 12345678\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345678'\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U, t 12345678' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Failed to get node state: D: Closed at other end\n" +
+ "Event: distributor.0: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: Closed at other end'\n" +
+ "Event: distributor.0: Now reporting state U, t 12345678\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345678'\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U, t 12345678' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Failed to get node state: D: Closed at other end\n" +
- "Event: storage.0: Stopped or possibly crashed after 1000 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'M: Closed at other end'\n" +
- "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.0: Altered node state in cluster state from 'M: Closed at other end' to 'D: Closed at other end'\n" +
- "Event: storage.0: Now reporting state U, t 12345679\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345679'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Failed to get node state: D: Closed at other end\n" +
+ "Event: storage.0: Stopped or possibly crashed after 1000 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'M: Closed at other end'\n" +
+ "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'M: Closed at other end' to 'D: Closed at other end'\n" +
+ "Event: storage.0: Now reporting state U, t 12345679\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345679'\n");
assertEquals(1, ctrl.getCluster().getNodeInfo(new Node(NodeType.DISTRIBUTOR, 0)).getPrematureCrashCount());
assertEquals(1, ctrl.getCluster().getNodeInfo(new Node(NodeType.STORAGE, 0)).getPrematureCrashCount());
@@ -262,7 +260,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNodeGoingDownAndUpNotifying() throws Exception {
+ void testNodeGoingDownAndUpNotifying() throws Exception {
// Same test as above, but node manages to notify why it is going down first.
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
@@ -272,15 +270,15 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
- tick((int)options.stableStateTimePeriod + 1);
+ tick((int) options.stableStateTimePeriod + 1);
communicator.setNodeState(new Node(NodeType.DISTRIBUTOR, 0), State.DOWN, "controlled shutdown");
ctrl.tick();
String desc = ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
tick(1000);
@@ -293,15 +291,15 @@ public class StateChangeTest extends FleetControllerTest {
assert(!ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).hasDescription());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
tick(options.maxTransitionTime.get(NodeType.STORAGE) + 1);
assertEquals("version:6 distributor:10 storage:10 .0.s:d", ctrl.getSystemState().toString());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
communicator.setNodeState(new Node(NodeType.STORAGE, 0), State.UP, "");
@@ -315,26 +313,26 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Failed to get node state: D: controlled shutdown\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: controlled shutdown'\n" +
- "Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Failed to get node state: D: controlled shutdown\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: controlled shutdown'\n" +
+ "Event: distributor.0: Now reporting state U\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Failed to get node state: D: controlled shutdown\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'M: controlled shutdown'\n" +
- "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.0: Altered node state in cluster state from 'M: controlled shutdown' to 'D: controlled shutdown'\n" +
- "Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Failed to get node state: D: controlled shutdown\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'M: controlled shutdown'\n" +
+ "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'M: controlled shutdown' to 'D: controlled shutdown'\n" +
+ "Event: storage.0: Now reporting state U\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
}
@Test
- public void testNodeGoingDownAndUpFast() throws Exception {
+ void testNodeGoingDownAndUpFast() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -370,12 +368,12 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Node is no longer in slobrok, but we still have a pending state request.\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Node is no longer in slobrok, but we still have a pending state request.\n");
}
@Test
- public void testMaintenanceWhileNormalStorageNodeRestart() throws Exception {
+ void testMaintenanceWhileNormalStorageNodeRestart() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -388,7 +386,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:4 distributor:10 storage:10 .6.s:m", ctrl.getSystemState().toString());
NodeState ns = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 6));
- assertTrue(ns.toString(), ns.getDescription().contains("Connection error: Closed at other end"));
+ assertTrue(ns.getDescription().contains("Connection error: Closed at other end"), ns.toString());
tick(1000);
@@ -417,19 +415,19 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'I, i 0.600 (read)'\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.600 (read)' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'I, i 0.600 (read)'\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.600 (read)' to 'U'\n");
}
@Test
- public void testMaintenanceWithoutInitIfRetired() throws Exception {
+ void testMaintenanceWithoutInitIfRetired() throws Exception {
List<ConfiguredNode> nodes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
boolean retired = (i == 6);
@@ -448,7 +446,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:4 distributor:10 storage:10 .6.s:m", ctrl.getSystemState().toString());
NodeState ns = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 6));
- assertTrue(ns.toString(), ns.getDescription().contains("Connection error: Closed at other end"));
+ assertTrue(ns.getDescription().contains("Connection error: Closed at other end"), ns.toString());
tick(1000);
@@ -477,18 +475,18 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'R'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'R' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'R'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'R'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'R' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'R'\n");
}
@Test
- public void testMaintenanceToDownIfPastTransitionTimeAndRetired() throws Exception {
+ void testMaintenanceToDownIfPastTransitionTimeAndRetired() throws Exception {
List<ConfiguredNode> nodes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
boolean retired = (i == 6);
@@ -516,7 +514,7 @@ public class StateChangeTest extends FleetControllerTest {
// Test that a node that has been down for a long time (above steady state period), actually alters cluster state to
// tell that it is initializing, rather than being ignored as a just restarted/unstable node should be.
@Test
- public void testDownNodeInitializing() throws Exception {
+ void testDownNodeInitializing() throws Exception {
// Actually report initializing state if node has been down steadily for a while
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -566,20 +564,20 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00100 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00100 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
}
@Test
- public void testNodeInitializationStalled() throws Exception {
+ void testNodeInitializationStalled() throws Exception {
// Node should eventually be marked down, and not become initializing next time, but stay down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -647,31 +645,31 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
- "Event: storage.6: 5001 milliseconds without initialize progress. Marking node down. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'D'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.6: 5001 milliseconds without initialize progress. Marking node down. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'D'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D' to 'U'\n");
}
@Test
- public void testBackwardsInitializationProgress() throws Exception {
+ void testBackwardsInitializationProgress() throws Exception {
// Same as stalled. Mark down, keep down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
options.maxInitProgressTime = 5000;
options.stableStateTimePeriod = 1000000;
- // Set long so we dont time out RPC requests and mark nodes down due to advancing time to get in steady state
+ // Set long so we dont time out RPC requests and mark nodes down due to advancing time to get in steady state
options.nodeStateRequestTimeoutMS = (int) options.stableStateTimePeriod * 2;
initialize(options);
@@ -708,7 +706,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNodeGoingDownWhileInitializing() throws Exception {
+ void testNodeGoingDownWhileInitializing() throws Exception {
// Same as stalled. Mark down, keep down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -766,7 +764,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testContinuousCrashRightAfterInit() throws Exception {
+ void testContinuousCrashRightAfterInit() throws Exception {
startingTest("StateChangeTest::testContinuousCrashRightAfterInit");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -820,7 +818,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testClusterStateMinNodes() throws Exception {
+ void testClusterStateMinNodes() throws Exception {
startingTest("StateChangeTest::testClusterStateMinNodes");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -875,7 +873,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testClusterStateMinFactor() throws Exception {
+ void testClusterStateMinFactor() throws Exception {
startingTest("StateChangeTest::testClusterStateMinFactor");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -942,47 +940,52 @@ public class StateChangeTest extends FleetControllerTest {
for (ClusterState state : states) {
debugString.append(state.toString()).append("\n");
}
- assertEquals(debugString.toString(), expectedMessageCount(node), states.size());
+ assertEquals(expectedMessageCount(node), states.size(), debugString.toString());
}
}
abstract int expectedMessageCount(final DummyVdsNode node);
}
@Test
- public void testNoSystemStateBeforeInitialTimePeriod() throws Exception {
+ void testNoSystemStateBeforeInitialTimePeriod() throws Exception {
startingTest("StateChangeTest::testNoSystemStateBeforeInitialTimePeriod()");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.minTimeBeforeFirstSystemStateBroadcast = 3 * 60 * 1000;
- setUpSystem(true, options);
- setUpVdsNodes(true, new DummyVdsNodeOptions(), true);
+ setUpSystem(options);
+ boolean useFakeTimer = true;
+ setUpVdsNodes(useFakeTimer, new DummyVdsNodeOptions(), true);
// Leave one node down to avoid sending cluster state due to having seen all node states.
- for (int i=0; i<nodes.size(); ++i) {
+ for (int i = 0; i < nodes.size(); ++i) {
if (i != 3) {
nodes.get(i).connect();
}
}
- setUpFleetController(true, options);
+ setUpFleetController(useFakeTimer, options);
StateWaiter waiter = new StateWaiter(timer);
fleetController.addSystemStateListener(waiter);
// Ensure all nodes have been seen by fleetcontroller and that it has had enough time to possibly have sent a cluster state
// Note: this is a candidate state and therefore NOT versioned yet
- waiter.waitForState("^distributor:10 (\\.\\d+\\.t:\\d+ )*storage:10 (\\.\\d+\\.t:\\d+ )*.1.s:d( \\.\\d+\\.t:\\d+)*", timeoutMS);
+ waiter.waitForState("^distributor:10 (\\.\\d+\\.t:\\d+ )*storage:10 (\\.\\d+\\.t:\\d+ )*.1.s:d( \\.\\d+\\.t:\\d+)*", timeout());
waitForCompleteCycle();
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) { return 0; }
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
+ return 0;
+ }
};
// Pass time and see that the nodes get state
timer.advanceTime(3 * 60 * 1000);
- waiter.waitForState("version:\\d+ distributor:10 storage:10 .1.s:d", timeoutMS);
+ waiter.waitForState("version:\\d+ distributor:10 storage:10 .1.s:d", timeout());
int version = waiter.getCurrentSystemState().getVersion();
- fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(version, 19, timeoutMS);
+ fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(version, 19, timeout());
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) {
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
return node.getNode().equals(new Node(NodeType.STORAGE, 1)) ? 0 : 2;
}
};
@@ -990,14 +993,15 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testSystemStateSentWhenNodesReplied() throws Exception {
+ void testSystemStateSentWhenNodesReplied() throws Exception {
startingTest("StateChangeTest::testSystemStateSentWhenNodesReplied()");
final FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.minTimeBeforeFirstSystemStateBroadcast = 300 * 60 * 1000;
- setUpSystem(true, options);
+ boolean useFakeTimer = true;
+ setUpSystem(options);
- setUpVdsNodes(true, new DummyVdsNodeOptions(), true);
+ setUpVdsNodes(useFakeTimer, new DummyVdsNodeOptions(), true);
for (DummyVdsNode node : nodes) {
node.connect();
@@ -1005,26 +1009,29 @@ public class StateChangeTest extends FleetControllerTest {
// Marking one node as 'initializing' improves testing of state later on.
nodes.get(3).setNodeState(State.INITIALIZING);
- setUpFleetController(true, options);
+ setUpFleetController(useFakeTimer, options);
final StateWaiter waiter = new StateWaiter(timer);
fleetController.addSystemStateListener(waiter);
- waiter.waitForState("version:\\d+ distributor:10 storage:10 .1.s:i .1.i:1.0", timeoutMS);
+ waiter.waitForState("version:\\d+ distributor:10 storage:10 .1.s:i .1.i:1.0", timeout());
waitForCompleteCycle();
final int version = waiter.getCurrentSystemState().getVersion();
- fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(version, 20, timeoutMS);
+ fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(version, 20, timeout());
// The last two versions of the cluster state should be seen (all nodes up,
// zero out timestate)
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) { return 2; }
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
+ return 2;
+ }
};
}
@Test
- public void testDontTagFailingSetSystemStateOk() throws Exception {
+ void testDontTagFailingSetSystemStateOk() throws Exception {
startingTest("StateChangeTest::testDontTagFailingSetSystemStateOk()");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
setUpFleetController(true, options);
@@ -1037,10 +1044,10 @@ public class StateChangeTest extends FleetControllerTest {
nodes.get(1).failSetSystemState(true);
int versionBeforeChange = nodes.get(1).getSystemStatesReceived().get(0).getVersion();
nodes.get(2).disconnect(); // cause a new state
- waiter.waitForState("version:\\d+ distributor:10 .1.s:d storage:10", timeoutMS);
+ waiter.waitForState("version:\\d+ distributor:10 .1.s:d storage:10", timeout());
int versionAfterChange = waiter.getCurrentSystemState().getVersion();
assertTrue(versionAfterChange > versionBeforeChange);
- fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(versionAfterChange, 18, timeoutMS);
+ fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(versionAfterChange, 18, timeout());
// Assert that the failed node has not acknowledged the latest version.
// (The version may still be larger than versionBeforeChange if the fleet controller sends a
@@ -1055,7 +1062,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testAlteringDistributionSplitCount() throws Exception {
+ void testAlteringDistributionSplitCount() throws Exception {
startingTest("StateChangeTest::testAlteringDistributionSplitCount");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.distributionBits = 17;
@@ -1102,7 +1109,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testSetAllTimestampsAfterDowntime() throws Exception {
+ void testSetAllTimestampsAfterDowntime() throws Exception {
startingTest("StateChangeTest::testSetAllTimestampsAfterDowntime");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
setUpFleetController(true, options);
@@ -1115,7 +1122,7 @@ public class StateChangeTest extends FleetControllerTest {
// Simulate netsplit. Take node down without node booting
assertTrue(nodes.get(0).isDistributor());
nodes.get(0).disconnectImmediately();
- waiter.waitForState("version:\\d+ distributor:10 .0.s:d storage:10", timeoutMS);
+ waiter.waitForState("version:\\d+ distributor:10 .0.s:d storage:10", timeout());
// Add node back.
nodes.get(0).connect();
@@ -1123,7 +1130,7 @@ public class StateChangeTest extends FleetControllerTest {
// At this time, node taken down should have cluster states with all starting timestamps set. Others node should not.
for (DummyVdsNode node : nodes) {
- node.waitForSystemStateVersion(waiter.getCurrentSystemState().getVersion(), timeoutMS);
+ node.waitForSystemStateVersion(waiter.getCurrentSystemState().getVersion(), timeout());
List<ClusterState> states = node.getSystemStatesReceived();
ClusterState lastState = states.get(0);
StringBuilder stateHistory = new StringBuilder();
@@ -1135,24 +1142,24 @@ public class StateChangeTest extends FleetControllerTest {
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.STORAGE, i.index());
long ts = lastState.getNodeState(nodeId).getStartTimestamp();
- assertTrue(nodeId + "\n" + stateHistory + "\nWas " + ts + " should be " + fleetController.getCluster().getNodeInfo(nodeId).getStartTimestamp(), ts > 0);
+ assertTrue(ts > 0, nodeId + "\n" + stateHistory + "\nWas " + ts + " should be " + fleetController.getCluster().getNodeInfo(nodeId).getStartTimestamp());
}
} else {
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.STORAGE, i.index());
- assertEquals(nodeId.toString(), 0, lastState.getNodeState(nodeId).getStartTimestamp());
+ assertEquals(0, lastState.getNodeState(nodeId).getStartTimestamp(), nodeId.toString());
}
}
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.DISTRIBUTOR, i.index());
- assertEquals(nodeId.toString(), 0, lastState.getNodeState(nodeId).getStartTimestamp());
+ assertEquals(0, lastState.getNodeState(nodeId).getStartTimestamp(), nodeId.toString());
}
}
}
@Test
- public void consolidated_cluster_state_reflects_node_changes_when_cluster_is_down() throws Exception {
+ void consolidated_cluster_state_reflects_node_changes_when_cluster_is_down() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 0);
options.minStorageNodesUp = 10;
@@ -1166,7 +1173,7 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
assertThat(ctrl.consolidatedClusterState().toString(),
- equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d"));
+ equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d"));
// After this point, any further node changes while the cluster is still down won't be published.
// This is because cluster state similarity checks are short-circuited if both are Down, as no other parts
@@ -1179,14 +1186,14 @@ public class StateChangeTest extends FleetControllerTest {
// NOTE: _same_ version, different node state content. Overall cluster down-state is still the same.
assertThat(ctrl.consolidatedClusterState().toString(),
- equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d .5.s:d"));
+ equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d .5.s:d"));
}
// Related to the above test, watchTimer invocations must receive the _current_ state and not the
// published state. Failure to ensure this would cause events to be fired non-stop, as the effect
// of previous timer invocations (with subsequent state generation) would not be visible.
@Test
- public void timer_events_during_cluster_down_observe_most_recent_node_changes() throws Exception {
+ void timer_events_during_cluster_down_observe_most_recent_node_changes() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 1000);
options.minStorageNodesUp = 10;
@@ -1210,10 +1217,10 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 2),
"Event: storage.2: Now reporting state U\n" +
- "Event: storage.2: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.2: Failed to get node state: D: foo\n" +
- "Event: storage.2: Stopped or possibly crashed after 500 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.2: Altered node state in cluster state from 'U' to 'M: foo'\n");
+ "Event: storage.2: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.2: Failed to get node state: D: foo\n" +
+ "Event: storage.2: Stopped or possibly crashed after 500 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.2: Altered node state in cluster state from 'U' to 'M: foo'\n");
// Note: even though max transition time has passed, events are now emitted only on cluster state
// publish edges. These are currently suppressed when the cluster state is down, as all cluster down
// states are considered similar to other cluster down states. This is not necessarily optimal, but
@@ -1221,7 +1228,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void do_not_emit_multiple_events_when_node_state_does_not_match_versioned_state() throws Exception {
+ void do_not_emit_multiple_events_when_node_state_does_not_match_versioned_state() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
initialize(options);
@@ -1418,7 +1425,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_remote_task_is_completed_when_state_is_acked_by_cluster() throws Exception {
+ void synchronous_remote_task_is_completed_when_state_is_acked_by_cluster() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
MockTask task = fixture.scheduleVersionDependentTaskWithSideEffects();
@@ -1437,7 +1444,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void failing_task_is_immediately_completed() throws Exception {
+ void failing_task_is_immediately_completed() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
MockTask task = fixture.scheduleFailingVersionDependentTaskWithSideEffects();
@@ -1446,7 +1453,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void no_op_synchronous_remote_task_can_complete_immediately_if_current_state_already_acked() throws Exception {
+ void no_op_synchronous_remote_task_can_complete_immediately_if_current_state_already_acked() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsWithZeroTransitionTime());
fixture.markStorageNodeDown(0);
MockTask task = fixture.scheduleNoOpVersionDependentTask(); // Tries to set node 0 into Down; already in that state
@@ -1459,7 +1466,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void no_op_synchronous_remote_task_waits_until_current_state_is_acked() throws Exception {
+ void no_op_synchronous_remote_task_waits_until_current_state_is_acked() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsWithZeroTransitionTime());
communicator.setShouldDeferDistributorClusterStateAcks(true);
@@ -1483,7 +1490,7 @@ public class StateChangeTest extends FleetControllerTest {
// tasks running in such a context as if they were no-ops. I.e. we only require
// the cluster down-state to have been published.
@Test
- public void immediately_complete_sync_remote_task_when_cluster_is_down() throws Exception {
+ void immediately_complete_sync_remote_task_when_cluster_is_down() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsAllowingZeroNodesDown());
// Controller options require 10/10 nodes up, so take one down to trigger a cluster Down edge.
fixture.markStorageNodeDown(1);
@@ -1497,7 +1504,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void multiple_tasks_may_be_scheduled_and_answered_at_the_same_time() throws Exception {
+ void multiple_tasks_may_be_scheduled_and_answered_at_the_same_time() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
communicator.setShouldDeferDistributorClusterStateAcks(true);
@@ -1515,7 +1522,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_task_immediately_failed_when_leadership_lost() throws Exception {
+ void synchronous_task_immediately_failed_when_leadership_lost() throws Exception {
FleetControllerOptions options = optionsWithZeroTransitionTime();
options.fleetControllerCount = 3;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1540,7 +1547,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void cluster_state_ack_is_not_dependent_on_state_send_grace_period() throws Exception {
+ void cluster_state_ack_is_not_dependent_on_state_send_grace_period() throws Exception {
FleetControllerOptions options = defaultOptions();
options.minTimeBetweenNewSystemStates = 10_000;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1560,7 +1567,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_task_immediately_answered_when_not_leader() throws Exception {
+ void synchronous_task_immediately_answered_when_not_leader() throws Exception {
FleetControllerOptions options = optionsWithZeroTransitionTime();
options.fleetControllerCount = 3;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1575,7 +1582,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void task_not_completed_within_deadline_is_failed_with_deadline_exceeded_error() throws Exception {
+ void task_not_completed_within_deadline_is_failed_with_deadline_exceeded_error() throws Exception {
FleetControllerOptions options = defaultOptions();
options.setMaxDeferredTaskVersionWaitTime(Duration.ofSeconds(60));
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1624,14 +1631,14 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void task_not_completed_within_deadline_lists_nodes_not_converged_in_error_message() throws Exception {
+ void task_not_completed_within_deadline_lists_nodes_not_converged_in_error_message() throws Exception {
doTestTaskDeadlineExceeded(false, "the following nodes have not converged to " +
"at least version 4: distributor.0, distributor.1, distributor.2, distributor.3, " +
"distributor.4, distributor.5, distributor.6, distributor.7, distributor.8, distributor.9");
}
@Test
- public void task_not_completed_within_deadline_with_deferred_activation_checks_activation_version() throws Exception {
+ void task_not_completed_within_deadline_with_deferred_activation_checks_activation_version() throws Exception {
doTestTaskDeadlineExceeded(true, "the following nodes have not converged to " +
"at least version 4: distributor.0, distributor.1, distributor.2, distributor.3, " +
"distributor.4, distributor.5, distributor.6, distributor.7, distributor.8, distributor.9 " +
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
index 041f4e4052d..656d5a187d1 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import java.util.logging.Level;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
+import java.time.Instant;
import java.util.concurrent.TimeoutException;
+import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class StateGatherTest extends FleetControllerTest {
@@ -24,7 +24,7 @@ public class StateGatherTest extends FleetControllerTest {
}
@Test
- public void testAlwaysHavePendingGetNodeStateRequestTowardsNodes() throws Exception {
+ void testAlwaysHavePendingGetNodeStateRequestTowardsNodes() throws Exception {
Logger.getLogger(NodeStateGatherer.class.getName()).setLevel(Level.FINEST);
startingTest("StateGatherTest::testOverlappingGetNodeStateRequests");
FleetControllerOptions options = defaultOptions("mycluster");
@@ -33,8 +33,7 @@ public class StateGatherTest extends FleetControllerTest {
options.nodeStateRequestTimeoutEarliestPercentage = 80;
options.nodeStateRequestTimeoutLatestPercentage = 80;
setUpFleetController(true, options);
- String[] connectionSpecs = new String[1];
- connectionSpecs[0] = "tcp/localhost:" + slobrok.port();
+ String[] connectionSpecs = getSlobrokConnectionSpecs(slobrok);
DummyVdsNodeOptions dummyOptions = new DummyVdsNodeOptions();
DummyVdsNode dnode = new DummyVdsNode(timer, dummyOptions, connectionSpecs, this.options.clusterName, true, 0);
DummyVdsNode snode = new DummyVdsNode(timer, dummyOptions, connectionSpecs, this.options.clusterName, false, 0);
@@ -58,11 +57,11 @@ public class StateGatherTest extends FleetControllerTest {
}
private void waitUntilTimedOutGetNodeState(DummyVdsNode dnode, DummyVdsNode snode) throws TimeoutException {
- long timeout = System.currentTimeMillis() + timeoutMS;
+ Instant endTime = Instant.now().plus(timeout());
synchronized (timer) {
while (dnode.timedOutStateReplies != 1 || snode.timedOutStateReplies != 1) {
- if (System.currentTimeMillis() > timeout) {
- throw new TimeoutException("Did not get to have one timed out within timeout of " + timeoutMS + " ms"
+ if (Instant.now().isAfter(endTime)) {
+ throw new TimeoutException("Did not get to have one timed out within timeout of " + timeout()
+ ", " + getGetNodeStateReplyCounts(dnode) + ", " + getGetNodeStateReplyCounts(snode));
}
try{ timer.wait(1); } catch (InterruptedException e) { /* ignore */ }
@@ -71,9 +70,9 @@ public class StateGatherTest extends FleetControllerTest {
}
private void waitUntilPendingGetNodeState(DummyVdsNode dnode, DummyVdsNode snode) throws TimeoutException {
- long timeout = System.currentTimeMillis() + timeoutMS;
+ Instant endTime = Instant.now().plus(timeout());
while (dnode.getPendingNodeStateCount() != 1 || snode.getPendingNodeStateCount() != 1) {
- if (System.currentTimeMillis() > timeout) throw new TimeoutException("Did not get to have one pending within timeout of " + timeoutMS + " ms");
+ if (Instant.now().isAfter(endTime)) throw new TimeoutException("Did not get to have one pending within timeout of " + timeout());
try{ Thread.sleep(1); } catch (InterruptedException e) { /* ignore */ }
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
index 2361a5cefd8..0e3c3c6d4b3 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
@@ -7,13 +7,11 @@ import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -40,7 +38,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_is_incremented_when_new_state_is_applied() {
+ void version_is_incremented_when_new_state_is_applied() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 123);
@@ -49,33 +47,33 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_is_1_upon_construction() {
+ void version_is_1_upon_construction() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(1, versionTracker.getCurrentVersion());
}
@Test
- public void set_current_version_caps_lowest_version_to_1() {
+ void set_current_version_caps_lowest_version_to_1() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(0);
assertEquals(1, versionTracker.getCurrentVersion());
}
@Test
- public void new_version_from_zk_predicate_initially_false() {
+ void new_version_from_zk_predicate_initially_false() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertFalse(versionTracker.hasReceivedNewVersionFromZooKeeper());
}
@Test
- public void new_version_from_zk_predicate_true_after_setting_zk_version() {
+ void new_version_from_zk_predicate_true_after_setting_zk_version() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(5);
assertTrue(versionTracker.hasReceivedNewVersionFromZooKeeper());
}
@Test
- public void new_version_from_zk_predicate_false_after_applying_higher_version() {
+ void new_version_from_zk_predicate_false_after_applying_higher_version() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(5);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 123);
@@ -83,14 +81,14 @@ public class StateVersionTrackerTest {
}
@Test
- public void exposed_states_are_empty_upon_construction() {
+ void exposed_states_are_empty_upon_construction() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertTrue(versionTracker.getVersionedClusterState().toString().isEmpty());
assertTrue(versionTracker.getAnnotatedVersionedClusterState().getClusterState().toString().isEmpty());
}
@Test
- public void diff_from_initial_state_implies_changed_state() {
+ void diff_from_initial_state_implies_changed_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.updateLatestCandidateStateBundle(stateBundleWithoutAnnotations("cluster:d"));
assertTrue(versionTracker.candidateChangedEnoughFromCurrentToWarrantPublish());
@@ -104,48 +102,48 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_mismatch_not_counted_as_changed_state() {
+ void version_mismatch_not_counted_as_changed_state() {
assertFalse(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_distributor_node_count_implies_changed_state() {
+ void different_distributor_node_count_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:3 storage:2"));
assertTrue(stateChangedBetween("distributor:3 storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_storage_node_count_implies_changed_state() {
+ void different_storage_node_count_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:3"));
assertTrue(stateChangedBetween("distributor:2 storage:3", "distributor:2 storage:2"));
}
@Test
- public void different_distributor_node_state_implies_changed_state() {
+ void different_distributor_node_state_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 .0.s:d storage:2"));
assertTrue(stateChangedBetween("distributor:2 .0.s:d storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_storage_node_state_implies_changed_state() {
+ void different_storage_node_state_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:2 .0.s:d"));
assertTrue(stateChangedBetween("distributor:2 storage:2 .0.s:d", "distributor:2 storage:2"));
}
@Test
- public void init_progress_change_not_counted_as_changed_state() {
+ void init_progress_change_not_counted_as_changed_state() {
assertFalse(stateChangedBetween("distributor:2 storage:2 .0.s:i .0.i:0.5",
- "distributor:2 storage:2 .0.s:i .0.i:0.6"));
+ "distributor:2 storage:2 .0.s:i .0.i:0.6"));
}
@Test
- public void lowest_observed_distribution_bit_is_initially_16() {
+ void lowest_observed_distribution_bit_is_initially_16() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(16, versionTracker.getLowestObservedDistributionBits());
}
@Test
- public void lowest_observed_distribution_bit_is_tracked_across_states() {
+ void lowest_observed_distribution_bit_is_tracked_across_states() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
updateAndPromote(versionTracker, stateWithoutAnnotations("bits:15 distributor:2 storage:2"), 100);
assertEquals(15, versionTracker.getLowestObservedDistributionBits());
@@ -161,7 +159,7 @@ public class StateVersionTrackerTest {
// min used bits. The former is derived from the latter, but the latter is not visible in the
// published state (but _is_ visible in the internal ClusterState structures).
@Test
- public void per_node_min_bits_changes_are_not_considered_different() {
+ void per_node_min_bits_changes_are_not_considered_different() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
final AnnotatedClusterState stateWithMinBits = stateWithoutAnnotations("distributor:2 storage:2");
stateWithMinBits.getClusterState().setNodeState(
@@ -173,7 +171,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void state_history_is_initially_empty() {
+ void state_history_is_initially_empty() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertTrue(versionTracker.getClusterStateHistory().isEmpty());
}
@@ -188,9 +186,9 @@ public class StateVersionTrackerTest {
}
@Test
- public void applying_state_adds_to_cluster_state_history() {
+ void applying_state_adds_to_cluster_state_history() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
- updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2") ,100);
+ updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:3 storage:3"), 200);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:4 storage:4"), 300);
@@ -204,11 +202,11 @@ public class StateVersionTrackerTest {
}
@Test
- public void old_states_pruned_when_state_history_limit_reached() {
+ void old_states_pruned_when_state_history_limit_reached() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setMaxHistoryEntryCount(2);
- updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2") ,100);
+ updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:3 storage:3"), 200);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:4 storage:4"), 300);
@@ -227,7 +225,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void can_get_latest_non_published_candidate_state() {
+ void can_get_latest_non_published_candidate_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
AnnotatedClusterState candidate = stateWithoutAnnotations("distributor:2 storage:2");
@@ -258,7 +256,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_change_check_takes_derived_states_into_account() {
+ void version_change_check_takes_derived_states_into_account() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.updateLatestCandidateStateBundle(baselineBundle(false));
versionTracker.promoteCandidateToVersionedState(1234);
@@ -273,7 +271,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void buckets_pending_state_is_tracked_between_cluster_states() {
+ void buckets_pending_state_is_tracked_between_cluster_states() {
final StateVersionTracker tracker = createWithMockedMetrics();
final NodeInfo distributorNode = mock(DistributorNodeInfo.class);
when(distributorNode.isDistributor()).thenReturn(true);
@@ -307,7 +305,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void setting_zookeeper_retrieved_bundle_sets_current_versioned_state_and_resets_candidate_state() {
+ void setting_zookeeper_retrieved_bundle_sets_current_versioned_state_and_resets_candidate_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(100);
versionTracker.updateLatestCandidateStateBundle(
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
index 1832f1132ac..0a193766df3 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -85,7 +85,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void always_publish_baseline_cluster_state() {
+ void always_publish_baseline_cluster_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -95,7 +95,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void non_observed_startup_timestamps_are_published_per_node_for_baseline_state() {
+ void non_observed_startup_timestamps_are_published_per_node_for_baseline_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -112,7 +112,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void bucket_space_states_are_published_verbatim_when_no_additional_timestamps_needed() {
+ void bucket_space_states_are_published_verbatim_when_no_additional_timestamps_needed() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2",
StateMapping.of("default", "version:3 distributor:2 storage:2 .0.s:d"),
@@ -125,7 +125,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void non_observed_startup_timestamps_are_published_per_bucket_space_state() {
+ void non_observed_startup_timestamps_are_published_per_bucket_space_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2",
StateMapping.of("default", "version:3 distributor:2 storage:2 .0.s:d"),
@@ -146,7 +146,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void state_not_broadcast_if_version_not_tagged_as_written_to_zookeeper() {
+ void state_not_broadcast_if_version_not_tagged_as_written_to_zookeeper() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:100 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -159,7 +159,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void state_is_broadcast_if_version_is_tagged_as_written_to_zookeeper() {
+ void state_is_broadcast_if_version_is_tagged_as_written_to_zookeeper() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:100 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -262,9 +262,10 @@ public class SystemStateBroadcasterTest {
}
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_not_sent_before_all_distributors_have_acked_state_bundle() {
+ @SuppressWarnings("unchecked")
+ void activation_not_sent_before_all_distributors_have_acked_state_bundle() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
@@ -292,9 +293,10 @@ public class SystemStateBroadcasterTest {
assertNull(f.broadcaster.getLastClusterStateBundleConverged());
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void state_bundle_not_considered_converged_until_activation_acked_by_all_distributors() {
+ @SuppressWarnings("unchecked")
+ void state_bundle_not_considered_converged_until_activation_acked_by_all_distributors() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
@@ -309,22 +311,23 @@ public class SystemStateBroadcasterTest {
});
respondToActivateClusterStateVersion(cf.cluster.getNodeInfo(Node.ofDistributor(0)),
- f.stateBundle, d0ActivateWaiter.getValue());
+ f.stateBundle, d0ActivateWaiter.getValue());
f.simulateBroadcastTick(cf, 123);
assertNull(f.broadcaster.getLastClusterStateBundleConverged()); // Not yet converged
respondToActivateClusterStateVersion(cf.cluster.getNodeInfo(Node.ofDistributor(1)),
- f.stateBundle, d1ActivateWaiter.getValue());
+ f.stateBundle, d1ActivateWaiter.getValue());
f.simulateBroadcastTick(cf, 123);
// Finally, all distributors have ACKed the version! State is marked as converged.
assertEquals(f.stateBundle, f.broadcaster.getLastClusterStateBundleConverged());
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_not_sent_if_deferred_activation_is_disabled_in_state_bundle() {
+ @SuppressWarnings("unchecked")
+ void activation_not_sent_if_deferred_activation_is_disabled_in_state_bundle() {
var f = StateActivationFixture.withTwoPhaseDisabled();
var cf = f.cf;
@@ -339,9 +342,10 @@ public class SystemStateBroadcasterTest {
});
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_convergence_considers_actual_version_returned_from_node() {
+ @SuppressWarnings("unchecked")
+ void activation_convergence_considers_actual_version_returned_from_node() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
index 6257a10064a..5471a6ff4be 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class UpEdgeMaintenanceTransitionConstraintTest {
@@ -19,27 +19,27 @@ public class UpEdgeMaintenanceTransitionConstraintTest {
}
@Test
- public void transition_allowed_when_previous_state_is_down() {
+ void transition_allowed_when_previous_state_is_down() {
assertTrue(nodeMayTransitionToMaintenanceInState(1, "distributor:5 storage:5 .1.s:d"));
}
@Test
- public void transition_allowed_when_previous_state_is_maintenance() {
+ void transition_allowed_when_previous_state_is_maintenance() {
assertTrue(nodeMayTransitionToMaintenanceInState(1, "distributor:5 storage:5 .1.s:m"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_up() {
+ void transition_not_allowed_when_previous_state_is_up() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_initializing() {
+ void transition_not_allowed_when_previous_state_is_initializing() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5 .0.s:i"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_retired() {
+ void transition_not_allowed_when_previous_state_is_retired() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5 .0.s:r"));
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
index a58f75dba02..7bbae78dbab 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
@@ -2,13 +2,14 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class WantedStateTest extends FleetControllerTest {
@Test
- public void testSettingStorageNodeMaintenanceAndBack() throws Exception {
+ void testSettingStorageNodeMaintenanceAndBack() throws Exception {
startingTest("WantedStateTest::testSettingStorageNodeMaintenanceAndBack()");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
@@ -22,7 +23,7 @@ public class WantedStateTest extends FleetControllerTest {
}
@Test
- public void testOverridingWantedStateOtherReason() throws Exception {
+ void testOverridingWantedStateOtherReason() throws Exception {
startingTest("WantedStateTest::testOverridingWantedStateOtherReason()");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
index 1ce7586adea..79c03a67698 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
@@ -4,22 +4,16 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vespa.clustercontroller.core.database.CasWriteFailed;
import com.yahoo.vespa.clustercontroller.core.database.Database;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabase;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
public class ZooKeeperDatabaseTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
private static class Fixture implements AutoCloseable {
final ZooKeeperTestServer zkServer;
ClusterFixture clusterFixture;
@@ -58,7 +52,7 @@ public class ZooKeeperDatabaseTest {
}
@Test
- public void can_store_and_load_cluster_state_bundle_from_database() throws Exception {
+ void can_store_and_load_cluster_state_bundle_from_database() throws Exception {
try (Fixture f = new Fixture()) {
f.createDatabase();
f.db().retrieveLastPublishedStateBundle(); // Must be called once prior to prime last known znode version
@@ -77,27 +71,29 @@ public class ZooKeeperDatabaseTest {
}
@Test
- public void storing_cluster_state_bundle_with_mismatching_expected_znode_version_throws_exception() throws Exception {
- expectedException.expect(CasWriteFailed.class);
- expectedException.expectMessage("version mismatch in cluster state bundle znode (expected -2)");
- try (Fixture f = new Fixture()) {
- f.createDatabase();
- f.db().storeLastPublishedStateBundle(dummyBundle());
- }
+ void storing_cluster_state_bundle_with_mismatching_expected_znode_version_throws_exception() throws Exception {
+ Throwable exception = assertThrows(CasWriteFailed.class, () -> {
+ try (Fixture f = new Fixture()) {
+ f.createDatabase();
+ f.db().storeLastPublishedStateBundle(dummyBundle());
+ }
+ });
+ assertTrue(exception.getMessage().contains("version mismatch in cluster state bundle znode (expected -2)"));
}
@Test
- public void storing_cluster_state_version_with_mismatching_expected_znode_version_throws_exception() throws Exception {
- expectedException.expect(CasWriteFailed.class);
- expectedException.expectMessage("version mismatch in cluster state version znode (expected -2)");
- try (Fixture f = new Fixture()) {
- f.createDatabase();
- f.db().storeLatestSystemStateVersion(12345);
- }
+ void storing_cluster_state_version_with_mismatching_expected_znode_version_throws_exception() throws Exception {
+ Throwable exception = assertThrows(CasWriteFailed.class, () -> {
+ try (Fixture f = new Fixture()) {
+ f.createDatabase();
+ f.db().storeLatestSystemStateVersion(12345);
+ }
+ });
+ assertTrue(exception.getMessage().contains("version mismatch in cluster state version znode (expected -2)"));
}
@Test
- public void empty_state_bundle_is_returned_if_no_bundle_already_stored_in_database() throws Exception {
+ void empty_state_bundle_is_returned_if_no_bundle_already_stored_in_database() throws Exception {
try (Fixture f = new Fixture()) {
f.createDatabase();
ClusterStateBundle bundleReceived = f.db().retrieveLastPublishedStateBundle();
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java
index b5ad82b6b0c..3c9fd069e14 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core.hostinfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -13,10 +13,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class HostInfoTest {
@@ -29,7 +26,7 @@ public class HostInfoTest {
}
@Test
- public void testEmptyJson() {
+ void testEmptyJson() {
HostInfo hostInfo = HostInfo.createHostInfo("{}");
assertNull(hostInfo.getVtag().getVersionOrNull());
assertTrue(hostInfo.getDistributor().getStorageNodes().isEmpty());
@@ -39,13 +36,13 @@ public class HostInfoTest {
}
@Test
- public void testExtendedJson() throws IOException {
+ void testExtendedJson() throws IOException {
HostInfo hostInfo = HostInfo.createHostInfo(readDataFile("host_info.json"));
assertEquals("5.32.76", hostInfo.getVtag().getVersionOrNull());
}
@Test
- public void testFullSet() throws IOException {
+ void testFullSet() throws IOException {
HostInfo hostInfo = HostInfo.createHostInfo(readDataFile("host_info.json"));
List<StorageNode> storageNodeList = hostInfo.getDistributor().getStorageNodes();
assertEquals(2, storageNodeList.size());
@@ -59,8 +56,8 @@ public class HostInfoTest {
assertEquals(123, hostInfo.getClusterStateVersionOrNull().intValue());
assertEquals(Optional.of(129L), hostInfo.getMetrics()
- .getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "default"))
- .map(Metrics.Value::getLast));
+ .getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "default"))
+ .map(Metrics.Value::getLast));
assertEquals(Optional.of(0L),
hostInfo.getMetrics()
.getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "global"))
@@ -75,7 +72,7 @@ public class HostInfoTest {
}
@Test
- public void testSpeed() throws Exception {
+ void testSpeed() throws Exception {
String json = readDataFile("slow_host_info.json");
long start = 0;
@@ -92,7 +89,7 @@ public class HostInfoTest {
}
@Test
- public void testSharedFile() throws Exception {
+ void testSharedFile() throws Exception {
String json = readDataFile("distributor.json");
HostInfo hostInfo = HostInfo.createHostInfo(json);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
index cb99dfe38e3..0eb25ab5cd4 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.clustercontroller.core.hostinfo;
import com.yahoo.vespa.clustercontroller.core.ContentNodeStats;
import com.yahoo.vespa.clustercontroller.core.ContentClusterStats;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -14,7 +14,7 @@ import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author hakonhall
@@ -29,7 +29,7 @@ public class StorageNodeStatsBridgeTest {
}
@Test
- public void testContentNodeStats() throws IOException {
+ void testContentNodeStats() throws IOException {
String data = getJsonString();
HostInfo hostInfo = HostInfo.createHostInfo(data);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
index 84116674afa..8e49703c94b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
@@ -2,67 +2,68 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClusterListTest extends StateRestApiTest {
@Test
- public void testClusterList() throws Exception {
+ void testClusterList() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
- " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
- "}}";
+ " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
+ " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveClusterList() throws Exception {
+ void testRecursiveClusterList() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("", 1));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:4 storage:4\",\n" +
- " \"bucket-spaces\": [\n" +
- " {\n" +
- " \"name\": \"default\",\n" +
- " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
- " },\n" +
- " {\n" +
- " \"name\": \"global\",\n" +
- " \"state\": \"distributor:4 storage:4\"\n" +
- " }\n" +
- " ]\n" +
- " }}\n" +
- " },\n" +
- " \"music\": {\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
- " \"bucket-spaces\": []\n" +
- " }}\n" +
- " }\n" +
- "}}";
+ " \"books\": {\n" +
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:4 storage:4\",\n" +
+ " \"bucket-spaces\": [\n" +
+ " {\n" +
+ " \"name\": \"default\",\n" +
+ " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"name\": \"global\",\n" +
+ " \"state\": \"distributor:4 storage:4\"\n" +
+ " }\n" +
+ " ]\n" +
+ " }}\n" +
+ " },\n" +
+ " \"music\": {\n" +
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
+ " \"bucket-spaces\": []\n" +
+ " }}\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
index 2efb731c88c..ab9c92a6d9e 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
@@ -2,74 +2,74 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClusterTest extends StateRestApiTest {
@Test
- public void testCluster() throws Exception {
+ void testCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("books", 0));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:4 storage:4\",\n" +
- " \"bucket-spaces\": [\n" +
- " {\n" +
- " \"name\": \"default\",\n" +
- " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
- " },\n" +
- " {\n" +
- " \"name\": \"global\",\n" +
- " \"state\": \"distributor:4 storage:4\"\n" +
- " }\n" +
- " ]\n" +
- " }}\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:4 storage:4\",\n" +
+ " \"bucket-spaces\": [\n" +
+ " {\n" +
+ " \"name\": \"default\",\n" +
+ " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"name\": \"global\",\n" +
+ " \"state\": \"distributor:4 storage:4\"\n" +
+ " }\n" +
+ " ]\n" +
+ " }}\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music", 1));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/7\"}\n" +
- " }},\n" +
- " \"distributor\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
- " }}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
- " \"bucket-spaces\": []\n" +
- " }}\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/7\"}\n" +
+ " }},\n" +
+ " \"distributor\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
+ " }}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
+ " \"bucket-spaces\": []\n" +
+ " }}\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
index 38fab2f5c54..52c46215e50 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
@@ -8,99 +8,99 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.ContentCluster;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NodeTest extends StateRestApiTest {
@Test
- public void testDistributor() throws Exception {
+ void testDistributor() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testStorage() throws Exception {
+ void testStorage() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " },\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " },\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveNode() throws Exception {
+ void testRecursiveNode() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 1));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " },\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " },\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testNodeNotSeenInSlobrok() throws Exception {
+ void testNodeNotSeenInSlobrok() throws Exception {
setUp(true);
ContentCluster old = music.context.cluster;
music.context.cluster = new ContentCluster(old.getName(), old.getConfiguredNodes().values(), old.getDistribution());
@@ -110,22 +110,22 @@ public class NodeTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Not seen\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Node not seen in slobrok.\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Not seen\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Node not seen in slobrok.\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
index d85cf95defc..15aeded2d37 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
@@ -5,19 +5,17 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.OtherMasterEx
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.UnknownMasterException;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class NotMasterTest extends StateRestApiTest {
@Test
- public void testUnknownMaster() throws Exception {
+ void testUnknownMaster() throws Exception {
setUp(true);
music.fleetControllerMaster = null;
- // Non-recursive cluster list works, as it doesn't touches into fleetcontrollers
+ // Non-recursive cluster list works, as it doesn't touches into fleetcontrollers
{
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
@@ -27,49 +25,49 @@ public class NotMasterTest extends StateRestApiTest {
"}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
- // Recursive cluster list does not work
- try{
+ // Recursive cluster list does not work
+ try {
restAPI.getState(new StateRequest("", 1));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- // Other requests does not work either
- try{
+ // Other requests does not work either
+ try {
restAPI.getState(new StateRequest("music", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1/0", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetNodeStateTest.SetUnitStateRequestImpl("music/storage/1")
- .setNewState("user", "down", "test"));
+ .setNewState("user", "down", "test"));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
}
@Test
- public void testKnownOtherMaster() throws Exception {
+ void testKnownOtherMaster() throws Exception {
setUp(true);
ccSockets.put(1, new ClusterControllerStateRestAPI.Socket("otherhost", getDefaults().vespaWebServicePort()));
music.fleetControllerMaster = 1;
@@ -78,59 +76,59 @@ public class NotMasterTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
- " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
- "}}";
+ " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
+ " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
// Recursive cluster list does not work
- try{
+ try {
restAPI.getState(new StateRequest("", 1));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
// Other requests does not work either
- try{
+ try {
restAPI.getState(new StateRequest("music", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1/0", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.setUnitState(new SetNodeStateTest.SetUnitStateRequestImpl("music/storage/1")
.setNewState("user", "down", "test"));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
index ec60adf16d3..65acea02d34 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
@@ -3,47 +3,47 @@ package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class PartitionTest extends StateRestApiTest {
@Test
- public void testPartition() throws Exception {
+ void testPartition() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1/0", 0));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1/0", 1));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
index ec8e7855db6..adbf24bc4d1 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
@@ -2,22 +2,21 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.InternalFailure;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
public class RequestTest {
@Test
- public void testGetResultBeforeCompletion() {
+ void testGetResultBeforeCompletion() {
Request<String> r = new Request<>(Request.MasterState.MUST_BE_MASTER) {
@Override
public String calculateResult(Context context) {
return "foo";
}
};
- try{
+ try {
r.getResult();
fail();
} catch (InternalFailure e) {
@@ -25,7 +24,7 @@ public class RequestTest {
fail();
}
r.notifyCompleted();
- try{
+ try {
r.getResult();
fail();
} catch (InternalFailure e) {
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
index f2aa00ea13e..2e5b610a039 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
@@ -2,119 +2,119 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ServiceTest extends StateRestApiTest {
@Test
- public void testService() throws Exception {
+ void testService() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor", 0));
String expected =
"{\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
- "}}";
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor", 1));
String expected =
"{\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"2\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g1\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Node not seen in slobrok.\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"5\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"7\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " }\n" +
- "}}";
+ " \"1\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"2\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g1\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Node not seen in slobrok.\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"5\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"7\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
index 685ad3f0b43..1b52194b270 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
@@ -18,9 +18,7 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStat
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.SetResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitState;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
@@ -32,11 +30,7 @@ import java.util.regex.Pattern;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
@@ -44,10 +38,6 @@ import static org.mockito.Mockito.when;
public class SetNodeStateTest extends StateRestApiTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
public static class SetUnitStateRequestImpl extends StateRequest implements SetUnitStateRequest {
private final Map<String, UnitState> newStates = new LinkedHashMap<>();
private Condition condition = Condition.FORCE;
@@ -176,7 +166,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
setUp(true);
verifyStateSet("down", "testing");
verifyStateSet("up", "foo");
@@ -186,14 +176,14 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSetNodesForCluster() throws Exception {
+ void testSetNodesForCluster() throws Exception {
setUp(true);
verifyClusterSet("maintenance", "prepare for maintenance");
verifyClusterSet("up", "and we're back online");
}
@Test
- public void testShouldNotModifyDistributorSafe() throws Exception {
+ void testShouldNotModifyDistributorSafe() throws Exception {
setUp(false);
SetResponse setResponse = restAPI.setUnitState(new SetUnitStateRequestImpl("music/distributor/1")
.setNewState("user", "up", "whatever reason.")
@@ -204,7 +194,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testShouldModifyStorageSafeOk() throws Exception {
+ void testShouldModifyStorageSafeOk() throws Exception {
setUp(false);
SetResponse setResponse = restAPI.setUnitState(new SetUnitStateRequestImpl("music/storage/2")
.setNewState("user", "maintenance", "whatever reason.")
@@ -214,7 +204,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testShouldModifyStorageSafeBlocked() throws Exception {
+ void testShouldModifyStorageSafeBlocked() throws Exception {
// Sets up 2 groups: [0, 2, 4] and [1, 3, 5]
setUpMusicGroup(6, "");
@@ -254,7 +244,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void settingSafeMaintenanceWhenNodeDown() throws Exception {
+ void settingSafeMaintenanceWhenNodeDown() throws Exception {
// Sets up 2 groups: [0, 2, 4] and [1, 3, 5], with 1 being down
setUpMusicGroup(6, " .1.s:d");
assertUnitState(1, "generated", State.DOWN, "");
@@ -289,7 +279,7 @@ public class SetNodeStateTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest(path, 0));
Response.NodeResponse nodeResponse = (Response.NodeResponse) response;
UnitState unitState = nodeResponse.getStatePerType().get(type);
- assertNotNull("No such type " + type + " at path " + path, unitState);
+ assertNotNull(unitState, "No such type " + type + " at path " + path);
assertEquals(state.toString().toLowerCase(), unitState.getId());
assertEquals(reason, unitState.getReason());
}
@@ -326,19 +316,18 @@ public class SetNodeStateTest extends StateRestApiTest {
Matcher matcher = Pattern.compile(reasonRegex).matcher(setResponse.getReason());
String errorMessage = "Expected reason to match '" + reasonRegex + "', but got: " + setResponse.getReason() + "'";
- assertTrue(errorMessage, matcher.find());
+ assertTrue(matcher.find(), errorMessage);
int alreadyMaintainedIndex = Integer.parseInt(matcher.group(1));
// Example: Say index 1 is in maintenance, and we try to set 2 in maintenance. This should
// NOT be allowed, since 2 is in a different group than 1.
- assertEquals("Tried to set " + index + " in maintenance, but got: " + setResponse.getReason(),
- index % 2, (alreadyMaintainedIndex + 1) % 2);
+ assertEquals(index % 2, (alreadyMaintainedIndex + 1) % 2, "Tried to set " + index + " in maintenance, but got: " + setResponse.getReason());
assertThat(setResponse.getWasModified(), is(false));
}
@Test
- public void testSetWantedStateOnNodeNotInSlobrok() throws Exception {
+ void testSetWantedStateOnNodeNotInSlobrok() throws Exception {
// Node 2 in cluster music does not have a valid NodeInfo due to passing true to setUp
setUp(true);
restAPI.setUnitState(new SetUnitStateRequestImpl("music/distributor/2").setNewState("user", "down", "borked node"));
@@ -348,73 +337,73 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testWrongUnit() throws Exception {
+ void testWrongUnit() throws Exception {
setUp(true);
String wrongUnitMessage = "State can only be set at cluster or node level";
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
// ... setting at cluster-level is allowed
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
// ... setting at node-level is allowed
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/0").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
}
@Test
- public void testInvalidUnit() throws Exception {
+ void testInvalidUnit() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"foo").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/content").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/bah").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/10").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/0/1").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/bar").setNewState("user", "down", "testing"));
fail();
@@ -423,71 +412,71 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSettingInvalidStateType() throws Exception {
+ void testSettingInvalidStateType() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("foo", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
}
@Test
- public void testSafeIsInvalidForSetNodesStatesForCluster() throws Exception {
+ void testSafeIsInvalidForSetNodesStatesForCluster() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl("music")
.setNewState("user", "maintenance", "example reason")
.setCondition(SetUnitStateRequest.Condition.SAFE));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(
- "Setting all nodes in a cluster to a state is only supported with FORCE"));
+ assertTrue(e.getMessage().contains(
+ "Setting all nodes in a cluster to a state is only supported with FORCE"), e.getMessage());
}
}
@Test
- public void testSettingWrongStateType() throws Exception {
+ void testSettingWrongStateType() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("generated", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("unit", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
}
@Test
- public void testInvalidState() throws Exception {
+ void testInvalidState() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "initializing", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "stopping", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "foo", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
}
@Test
- public void testOverwriteReason() throws Exception {
+ void testOverwriteReason() throws Exception {
setUp(true);
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "down", "testing"));
@@ -508,19 +497,19 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void set_node_state_requests_are_by_default_tagged_as_having_version_ack_dependency() {
+ void set_node_state_requests_are_by_default_tagged_as_having_version_ack_dependency() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
assertTrue(request.hasVersionAckDependency());
}
@Test
- public void set_node_state_requests_not_initially_marked_as_failed() {
+ void set_node_state_requests_not_initially_marked_as_failed() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
assertFalse(request.isFailed());
}
@Test
- public void set_node_state_requests_may_override_version_ack_dependency() {
+ void set_node_state_requests_may_override_version_ack_dependency() {
SetNodeStateRequest request = new SetNodeStateRequest(createDummyId(), new SetUnitStateRequestImpl("music/storage/1")
.setNewState("user", "maintenance", "whatever reason.")
.setResponseWait(SetUnitStateRequest.ResponseWait.NO_WAIT));
@@ -531,40 +520,42 @@ public class SetNodeStateTest extends StateRestApiTest {
// important to test (and expected to happen) for requests that have dependencies on cluster
// state version publishing.
@Test
- public void leadership_loss_fails_set_node_state_request() throws Exception {
- expectedException.expectMessage("Leadership lost before request could complete");
- expectedException.expect(UnknownMasterException.class);
+ void leadership_loss_fails_set_node_state_request() throws Exception {
+ Throwable exception = assertThrows(UnknownMasterException.class, () -> {
- SetNodeStateRequest request = createDummySetNodeStateRequest();
- request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
- request.getResult();
+ SetNodeStateRequest request = createDummySetNodeStateRequest();
+ request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
+ request.getResult();
+ });
+ assertTrue(exception.getMessage().contains("Leadership lost before request could complete"));
}
@Test
- public void leadership_loss_marks_request_as_failed_for_early_out_response() {
+ void leadership_loss_marks_request_as_failed_for_early_out_response() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
assertTrue(request.isFailed());
}
@Test
- public void deadline_exceeded_fails_set_node_state_request() throws Exception {
- expectedException.expectMessage("Task exceeded its version wait deadline: gremlins in the computer");
- expectedException.expect(DeadlineExceededException.class);
+ void deadline_exceeded_fails_set_node_state_request() throws Exception {
+ Throwable exception = assertThrows(DeadlineExceededException.class, () -> {
- SetNodeStateRequest request = createDummySetNodeStateRequest();
- request.handleFailure(RemoteClusterControllerTask.Failure.of(
- RemoteClusterControllerTask.FailureCondition.DEADLINE_EXCEEDED, "gremlins in the computer"));
- request.getResult();
+ SetNodeStateRequest request = createDummySetNodeStateRequest();
+ request.handleFailure(RemoteClusterControllerTask.Failure.of(
+ RemoteClusterControllerTask.FailureCondition.DEADLINE_EXCEEDED, "gremlins in the computer"));
+ request.getResult();
+ });
+ assertTrue(exception.getMessage().contains("Task exceeded its version wait deadline: gremlins in the computer"));
}
@Test
- public void no_fail_if_modified() throws StateRestApiException {
+ void no_fail_if_modified() throws StateRestApiException {
assertFalse(isFailed(true));
}
@Test
- public void fail_if_not_modified() throws StateRestApiException {
+ void fail_if_not_modified() throws StateRestApiException {
assertTrue(isFailed(false));
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
index 9f14b2e71d2..1bd17b11755 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
@@ -15,8 +15,8 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.StateRestApiE
import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStateRequest;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.SetResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitState;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
@@ -43,13 +43,13 @@ public class SetNodeStateRequestTest {
private boolean inMasterMoratorium = false;
private boolean probe = false;
- @Before
+ @BeforeEach
public void setUp() {
newStates.put("user", unitState);
}
@Test
- public void testUpToMaintenance() throws StateRestApiException {
+ void testUpToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.UP, State.UP,
@@ -58,7 +58,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testProbingDoesntChangeState() throws StateRestApiException {
+ void testProbingDoesntChangeState() throws StateRestApiException {
probe = true;
testSetStateRequest(
"maintenance",
@@ -68,7 +68,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testUpToDown() throws StateRestApiException {
+ void testUpToDown() throws StateRestApiException {
testSetStateRequest(
"down",
State.UP, State.UP,
@@ -77,7 +77,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testMaintenanceToUp() throws StateRestApiException {
+ void testMaintenanceToUp() throws StateRestApiException {
testSetStateRequest(
"up",
State.MAINTENANCE, State.DOWN,
@@ -86,7 +86,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testDownToUp() throws StateRestApiException {
+ void testDownToUp() throws StateRestApiException {
testSetStateRequest(
"up",
State.DOWN, State.DOWN,
@@ -95,7 +95,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testOnlyStorageInMaintenaceToMaintenance() throws StateRestApiException {
+ void testOnlyStorageInMaintenaceToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.MAINTENANCE, State.UP,
@@ -104,7 +104,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testNoOpMaintenaceToMaintenance() throws StateRestApiException {
+ void testNoOpMaintenaceToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.MAINTENANCE, State.DOWN,
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
index ca9e81b6bc4..b9a9d7fbf8f 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
@@ -21,19 +21,18 @@ import com.yahoo.vespa.clustercontroller.core.FleetControllerOptions;
import com.yahoo.vespa.clustercontroller.core.NodeInfo;
import com.yahoo.vespa.clustercontroller.core.SetClusterStateRequest;
import com.yahoo.vespa.clustercontroller.core.Timer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
+import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.eq;
@@ -51,7 +50,7 @@ public class RPCCommunicatorTest {
private static final int ROUNDTRIP_LATENCY_SECONDS = 2000;
@Test
- public void testGenerateNodeStateRequestTimeoutMs() {
+ void testGenerateNodeStateRequestTimeoutMs() {
final RPCCommunicator communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
null /* Timer */,
@@ -60,37 +59,37 @@ public class RPCCommunicatorTest {
NODE_STATE_REQUEST_TIMEOUT_INTERVAL_START_PERCENTAGE,
NODE_STATE_REQUEST_TIMEOUT_INTERVAL_STOP_PERCENTAGE,
0);
- int max = -1;
- int min = 100000;
- final Set<Integer> uniqueTimeoutValues = new HashSet<>();
+ long max = -1;
+ long min = 100000;
+ final Set<Long> uniqueTimeoutValues = new HashSet<>();
for (int x = 0; x < TEST_ITERATIONS; x++) {
- int timeOutMs = communicator.generateNodeStateRequestTimeoutMs();
+ long timeOutMs = communicator.generateNodeStateRequestTimeout().toMillis();
min = Math.min(min, timeOutMs);
max = Math.max(max, timeOutMs);
uniqueTimeoutValues.add(timeOutMs);
}
assertTrue(max <= NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS *
NODE_STATE_REQUEST_TIMEOUT_INTERVAL_STOP_PERCENTAGE / 100.);
- assertThat(min, is(not(max)));
+ assertNotEquals(min, max);
assertTrue(min >= NODE_STATE_REQUEST_TIMEOUT_INTERVAL_START_PERCENTAGE *
NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS / 100);
- assertTrue(uniqueTimeoutValues.size()> TEST_ITERATIONS/2);
+ assertTrue(uniqueTimeoutValues.size() > TEST_ITERATIONS / 2);
}
@Test
- public void testGenerateNodeStateRequestTimeoutMsWithUpdates() {
+ void testGenerateNodeStateRequestTimeoutMsWithUpdates() {
final RPCCommunicator communicator = new RPCCommunicator(RPCCommunicator.createRealSupervisor(), null /* Timer */, INDEX, 1, 1, 100, 0);
FleetControllerOptions fleetControllerOptions = new FleetControllerOptions(null /*clustername*/, Set.of(new ConfiguredNode(0, false)));
fleetControllerOptions.nodeStateRequestTimeoutEarliestPercentage = 100;
fleetControllerOptions.nodeStateRequestTimeoutLatestPercentage = 100;
fleetControllerOptions.nodeStateRequestTimeoutMS = NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS;
communicator.propagateOptions(fleetControllerOptions);
- int timeOutMs = communicator.generateNodeStateRequestTimeoutMs();
- assertThat(timeOutMs, is(NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS));
+ long timeOutMs = communicator.generateNodeStateRequestTimeout().toMillis();
+ assertEquals(timeOutMs, NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS);
}
@Test
- public void testRoundtripLatency() {
+ void testRoundtripLatency() {
final Timer timer = new FakeTimer();
final RPCCommunicator communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
@@ -111,7 +110,7 @@ public class RPCCommunicatorTest {
communicator.getNodeState(nodeInfo, null);
Mockito.verify(target).invokeAsync(
any(),
- eq(ROUNDTRIP_LATENCY_SECONDS + NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS/1000.0),
+ eq(Duration.ofSeconds(ROUNDTRIP_LATENCY_SECONDS).plusMillis(NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS)),
any());
}
@@ -141,37 +140,37 @@ public class RPCCommunicatorTest {
receivedRequest.set((Request) invocation.getArguments()[0]);
receivedWaiter.set((RequestWaiter) invocation.getArguments()[2]);
return null;
- }).when(mockTarget).invokeAsync(any(), anyDouble(), any());
+ }).when(mockTarget).invokeAsync(any(), any(Duration.class), any());
}
}
@Test
- public void setSystemState_v3_sends_distribution_states_rpc() {
+ void setSystemState_v3_sends_distribution_states_rpc() {
var f = new Fixture<SetClusterStateRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
var sentBundle = ClusterStateBundleUtil.makeBundle("distributor:3 storage:3");
f.communicator.setSystemState(sentBundle, cf.cluster().getNodeInfo(Node.ofStorage(1)), f.mockWaiter);
Request req = f.receivedRequest.get();
- assertThat(req, notNullValue());
- assertThat(req.methodName(), equalTo(RPCCommunicator.SET_DISTRIBUTION_STATES_RPC_METHOD_NAME));
+ assertNotNull(req);
+ assertEquals(req.methodName(), RPCCommunicator.SET_DISTRIBUTION_STATES_RPC_METHOD_NAME);
assertTrue(req.parameters().satisfies("bix")); // <compression type>, <uncompressed size>, <payload>
ClusterStateBundle receivedBundle = RPCUtil.decodeStateBundleFromSetDistributionStatesRequest(req);
- assertThat(receivedBundle, equalTo(sentBundle));
+ assertEquals(receivedBundle, sentBundle);
}
@Test
- public void set_distribution_states_v3_rpc_auto_downgrades_to_v2_on_unknown_method_error() {
+ void set_distribution_states_v3_rpc_auto_downgrades_to_v2_on_unknown_method_error() {
var f = new Fixture<SetClusterStateRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
var sentBundle = ClusterStateBundleUtil.makeBundle("version:123 distributor:3 storage:3");
f.communicator.setSystemState(sentBundle, cf.cluster().getNodeInfo(Node.ofStorage(1)), f.mockWaiter);
RequestWaiter waiter = f.receivedWaiter.get();
- assertThat(waiter, notNullValue());
+ assertNotNull(waiter);
Request req = f.receivedRequest.get();
- assertThat(req, notNullValue());
+ assertNotNull(req);
req.setError(ErrorCode.NO_SUCH_METHOD, "que?");
waiter.handleRequestDone(req);
@@ -183,21 +182,21 @@ public class RPCCommunicatorTest {
// Now when we try again, we should have been downgraded to the legacy setsystemstate2 RPC
f.communicator.setSystemState(sentBundle, cf.cluster().getNodeInfo(Node.ofStorage(1)), f.mockWaiter);
req = f.receivedRequest.get();
- assertThat(req, notNullValue());
- assertThat(req.methodName(), equalTo(RPCCommunicator.LEGACY_SET_SYSTEM_STATE2_RPC_METHOD_NAME));
+ assertNotNull(req);
+ assertEquals(req.methodName(), RPCCommunicator.LEGACY_SET_SYSTEM_STATE2_RPC_METHOD_NAME);
}
@Test
- public void activateClusterStateVersion_sends_version_activation_rpc() {
+ void activateClusterStateVersion_sends_version_activation_rpc() {
var f = new Fixture<ActivateClusterStateVersionRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
f.communicator.activateClusterStateVersion(12345, cf.cluster().getNodeInfo(Node.ofDistributor(1)), f.mockWaiter);
Request req = f.receivedRequest.get();
- assertThat(req, notNullValue());
- assertThat(req.methodName(), equalTo(RPCCommunicator.ACTIVATE_CLUSTER_STATE_VERSION_RPC_METHOD_NAME));
+ assertNotNull(req);
+ assertEquals(req.methodName(), RPCCommunicator.ACTIVATE_CLUSTER_STATE_VERSION_RPC_METHOD_NAME);
assertTrue(req.parameters().satisfies("i")); // <cluster state version>
- assertThat(req.parameters().get(0).asInt32(), equalTo(12345));
+ assertEquals(req.parameters().get(0).asInt32(), 12345);
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
index 3d3347acb2d..7564fb40d46 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core.rpc;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundleUtil;
import com.yahoo.vespa.clustercontroller.core.StateMapping;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
@@ -25,13 +25,13 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void baseline_only_bundle_can_be_round_trip_encoded() {
+ void baseline_only_bundle_can_be_round_trip_encoded() {
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:2");
assertThat(roundtripEncode(stateBundle), equalTo(stateBundle));
}
@Test
- public void multi_space_state_bundle_can_be_round_trip_encoded() {
+ void multi_space_state_bundle_can_be_round_trip_encoded() {
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:2",
StateMapping.of("default", "distributor:2 storage:2 .0.s:d"),
StateMapping.of("upsidedown", "distributor:2 .0.s:d storage:2"));
@@ -49,7 +49,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void encoded_cluster_states_can_be_compressed() {
+ void encoded_cluster_states_can_be_compressed() {
ClusterStateBundle stateBundle = makeCompressableBundle();
SlimeClusterStateBundleCodec codec = new SlimeClusterStateBundleCodec();
@@ -60,20 +60,20 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void uncompressed_enveloped_bundle_can_be_roundtrip_encoded() {
+ void uncompressed_enveloped_bundle_can_be_roundtrip_encoded() {
// Insufficient length and too much entropy to be compressed
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:3");
assertThat(roundtripEncodeWithEnvelope(stateBundle), equalTo(stateBundle));
}
@Test
- public void compressable_enveloped_bundle_can_be_roundtrip_encoded() {
+ void compressable_enveloped_bundle_can_be_roundtrip_encoded() {
ClusterStateBundle stateBundle = makeCompressableBundle();
assertThat(roundtripEncodeWithEnvelope(stateBundle), equalTo(stateBundle));
}
@Test
- public void can_roundtrip_encode_bundle_with_deferred_activation_enabled() {
+ void can_roundtrip_encode_bundle_with_deferred_activation_enabled() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.deferredActivation(true)
.deriveAndBuild();
@@ -81,7 +81,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void can_roundtrip_encode_bundle_with_deferred_activation_disabled() {
+ void can_roundtrip_encode_bundle_with_deferred_activation_disabled() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.deferredActivation(false)
.deriveAndBuild();
@@ -89,7 +89,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void can_roundtrip_encode_bundle_with_feed_block_state() {
+ void can_roundtrip_encode_bundle_with_feed_block_state() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.feedBlock(ClusterStateBundle.FeedBlock.blockedWithDescription("more cake needed"))
.deriveAndBuild();
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/StateWaiter.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/StateWaiter.java
index 4cfab796a4e..d131c330381 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/StateWaiter.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/StateWaiter.java
@@ -5,7 +5,7 @@ import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
import com.yahoo.vespa.clustercontroller.core.FakeTimer;
import com.yahoo.vespa.clustercontroller.core.listeners.SystemStateListener;
-
+import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -57,8 +57,8 @@ public class StateWaiter implements SystemStateListener {
}
}
- public void waitForState(String stateRegex, long timeout) {
- waitForState(stateRegex, timeout, 0);
+ public void waitForState(String stateRegex, Duration timeout) {
+ waitForState(stateRegex, timeout.toMillis(), 0);
}
/**
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java
index d6c43f54259..d6d3e2876a5 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java
@@ -156,9 +156,10 @@ public interface WaitCondition {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
- sb.append("RegexStateMatcher(\n wanted: '").append(pattern.pattern())
- .append("'\n last checked: '").append(lastCheckedState).append("'")
- .append("'\n current: '").append(currentState).append(")");
+ sb.append("RegexStateMatcher:")
+ .append("\n wanted: '").append(pattern.pattern()).append("'")
+ .append("\n last checked: '").append(lastCheckedState).append("'")
+ .append("\n current: '").append(currentState).append("'");
return sb.toString();
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java
index 6336de3d1a3..7960cd7c9d2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java
@@ -1,16 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core.testutils;
-import java.util.logging.Level;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vespa.clustercontroller.core.DummyVdsNode;
import com.yahoo.vespa.clustercontroller.core.FleetController;
-
+import java.time.Duration;
+import java.time.Instant;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import java.util.logging.Level;
import java.util.logging.Logger;
public interface Waiter {
@@ -19,18 +20,18 @@ public interface Waiter {
Object getMonitor();
FleetController getFleetController();
List<DummyVdsNode> getDummyNodes();
- int getTimeoutMS();
+ Duration getTimeout();
}
ClusterState waitForState(String state) throws Exception;
ClusterState waitForStateInSpace(String space, String state) throws Exception;
ClusterState waitForStateInAllSpaces(String state) throws Exception;
- ClusterState waitForState(String state, int timeoutMS) throws Exception;
+ ClusterState waitForState(String state, Duration timeoutMS) throws Exception;
ClusterState waitForStableSystem() throws Exception;
ClusterState waitForStableSystem(int nodeCount) throws Exception;
ClusterState waitForInitProgressPassed(Node n, double progress);
ClusterState waitForClusterStateIncludingNodesWithMinUsedBits(int bitcount, int nodecount);
- void wait(WaitCondition c, WaitTask wt, int timeoutMS);
+ void wait(WaitCondition c, WaitTask wt, Duration timeout);
class Impl implements Waiter {
@@ -42,7 +43,7 @@ public interface Waiter {
}
// TODO refactor
- private ClusterState waitForState(String state, int timeoutMS, boolean checkAllSpaces, Set<String> checkSpaces) {
+ private ClusterState waitForState(String state, Duration timeoutMS, boolean checkAllSpaces, Set<String> checkSpaces) {
LinkedList<DummyVdsNode> nodesToCheck = new LinkedList<>();
for(DummyVdsNode node : data.getDummyNodes()) {
if (node.isConnected()) nodesToCheck.add(node);
@@ -57,15 +58,15 @@ public interface Waiter {
}
public ClusterState waitForState(String state) {
- return waitForState(state, data.getTimeoutMS());
+ return waitForState(state, data.getTimeout());
}
public ClusterState waitForStateInAllSpaces(String state) {
- return waitForState(state, data.getTimeoutMS(), true, Collections.emptySet());
+ return waitForState(state, data.getTimeout(), true, Collections.emptySet());
}
public ClusterState waitForStateInSpace(String space, String state) {
- return waitForState(state, data.getTimeoutMS(), false, Collections.singleton(space));
+ return waitForState(state, data.getTimeout(), false, Collections.singleton(space));
}
- public ClusterState waitForState(String state, int timeoutMS) {
+ public ClusterState waitForState(String state, Duration timeoutMS) {
return waitForState(state, timeoutMS, false, Collections.emptySet());
}
public ClusterState waitForStableSystem() {
@@ -73,24 +74,23 @@ public interface Waiter {
}
public ClusterState waitForStableSystem(int nodeCount) {
WaitCondition.StateWait swc = new WaitCondition.RegexStateMatcher("version:\\d+ distributor:"+nodeCount+" storage:"+nodeCount, data.getFleetController(), data.getMonitor()).includeNotifyingNodes(data.getDummyNodes());
- wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeoutMS());
+ wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeout());
return swc.getCurrentState();
}
public ClusterState waitForInitProgressPassed(Node n, double progress) {
WaitCondition.StateWait swc = new WaitCondition.InitProgressPassedMatcher(n, progress, data.getFleetController(), data.getMonitor());
- wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeoutMS());
+ wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeout());
return swc.getCurrentState();
}
public ClusterState waitForClusterStateIncludingNodesWithMinUsedBits(int bitcount, int nodecount) {
WaitCondition.StateWait swc = new WaitCondition.MinUsedBitsMatcher(bitcount, nodecount, data.getFleetController(), data.getMonitor());
- wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeoutMS());
+ wait(swc, new WaitTask.StateResender(data.getFleetController()), data.getTimeout());
return swc.getCurrentState();
}
- public final void wait(WaitCondition c, WaitTask wt, int timeoutMS) {
+ public final void wait(WaitCondition c, WaitTask wt, Duration timeout) {
log.log(Level.INFO, "Waiting for " + c + (wt == null ? "" : " with wait task " + wt));
- final long startTime = System.currentTimeMillis();
- final long endTime = startTime + timeoutMS;
+ Instant endTime = Instant.now().plus(timeout);
String lastReason = null;
while (true) {
synchronized (data.getMonitor()) {
@@ -111,11 +111,11 @@ public interface Waiter {
allowWait = false;
}
}
- final long timeLeft = endTime - System.currentTimeMillis();
- if (timeLeft <= 0) {
- throw new IllegalStateException("Timed out waiting max " + timeoutMS + " ms for " + c + (wt == null ? "" : "\n with wait task " + wt) + ",\n reason: " + reason);
- }
- if (allowWait) data.getMonitor().wait(wt == null ? WaitTask.defaultTaskFrequencyMillis : Math.min(wt.getWaitTaskFrequencyInMillis(), timeLeft));
+ Duration timeLeft = Duration.between(Instant.now(), endTime);
+ if (timeLeft.isNegative())
+ throw new IllegalStateException("Timed out waiting max " + timeout + " ms for " + c + (wt == null ? "" : "\n with wait task " + wt) + ",\n reason: " + reason);
+ if (allowWait)
+ data.getMonitor().wait(wt == null ? WaitTask.defaultTaskFrequencyMillis : Math.min(wt.getWaitTaskFrequencyInMillis(), timeLeft.toMillis()));
} catch (InterruptedException e) {
}
}
diff --git a/clustercontroller-reindexer/pom.xml b/clustercontroller-reindexer/pom.xml
index 42e746c1bae..c94b5b134fe 100644
--- a/clustercontroller-reindexer/pom.xml
+++ b/clustercontroller-reindexer/pom.xml
@@ -51,6 +51,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/clustercontroller-reindexer/src/main/java/ai/vespa/reindexing/ReindexingMetrics.java b/clustercontroller-reindexer/src/main/java/ai/vespa/reindexing/ReindexingMetrics.java
index 8a48e4ce272..a1aa5287d2f 100644
--- a/clustercontroller-reindexer/src/main/java/ai/vespa/reindexing/ReindexingMetrics.java
+++ b/clustercontroller-reindexer/src/main/java/ai/vespa/reindexing/ReindexingMetrics.java
@@ -27,31 +27,11 @@ class ReindexingMetrics {
void dump(Reindexing reindexing) {
reindexing.status().forEach((type, status) -> {
- Reindexing.State state = status.state();
metric.set("reindexing.progress",
status.progress().map(ProgressToken::percentFinished).map(percentage -> percentage * 1e-2)
.orElse(status.state() == SUCCESSFUL ? 1.0 : 0.0),
- metric.createContext(Map.of("clusterid", cluster,
- "documenttype", type.getName(),
- "state", toString(state))));
- // Set metric value to -1 for all states not currently active, so we only have one value >= 0 at any given time.
- for (Reindexing.State unset : EnumSet.complementOf(EnumSet.of(state)))
- metric.set("reindexing.progress",
- -1,
- metric.createContext(Map.of("clusterid", cluster,
- "documenttype", type.getName(),
- "state", toString(unset))));
+ metric.createContext(Map.of("clusterid", cluster, "documenttype", type.getName())));
});
}
- private static String toString(Reindexing.State state) {
- switch (state) {
- case READY: return "pending";
- case RUNNING: return "running";
- case FAILED: return "failed";
- case SUCCESSFUL: return "successful";
- default: throw new IllegalArgumentException("Unknown reindexing state '" + state + "'");
- }
- }
-
}
diff --git a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/ReindexerTest.java b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/ReindexerTest.java
index 1bab8f6ee27..dffe1dd43ef 100644
--- a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/ReindexerTest.java
+++ b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/ReindexerTest.java
@@ -121,21 +121,8 @@ class ReindexerTest {
assertEquals(reindexing, database.readReindexing("cluster"));
assertTrue(shutDown.get(), "Session was shut down");
assertEquals(Map.of("reindexing.progress", Map.of(Map.of("documenttype", "music",
- "clusterid", "cluster",
- "state", "successful"),
- 1.0,
- Map.of("documenttype", "music",
- "clusterid", "cluster",
- "state", "pending"),
- -1.0,
- Map.of("documenttype", "music",
- "clusterid", "cluster",
- "state", "failed"),
- -1.0,
- Map.of("documenttype", "music",
- "clusterid", "cluster",
- "state", "running"),
- -1.0)),
+ "clusterid", "cluster"),
+ 1.0)),
metric.metrics());
// One more reindexing, this time shut down before visit completes, but after progress is reported.
@@ -159,8 +146,7 @@ class ReindexerTest {
assertEquals(1.0, // new ProgressToken() is 100% done.
metric.metrics().get("reindexing.progress")
.get(Map.of("documenttype", "music",
- "clusterid", "cluster",
- "state", "pending")));
+ "clusterid", "cluster")));
// Reindexer is created without any ready document types, which means nothing should run.
new Reindexer(cluster, triggers(), database, ReindexerTest::failIfCalled, metric, clock).reindex();
diff --git a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
index 2e3f4942b7d..b4aad7bc3ca 100644
--- a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
+++ b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
@@ -19,7 +19,7 @@ import java.util.List;
import java.util.concurrent.Executors;
import static com.yahoo.jdisc.http.HttpRequest.Method.POST;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
diff --git a/clustercontroller-utils/pom.xml b/clustercontroller-utils/pom.xml
index 03a368ed667..0d8e30d3693 100644
--- a/clustercontroller-utils/pom.xml
+++ b/clustercontroller-utils/pom.xml
@@ -14,11 +14,6 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
</dependency>
@@ -35,10 +30,14 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
index 7cea1adced6..739b8d4bf15 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
@@ -1,19 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.async;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class AsyncTest {
@Test
- public void testListeners() {
+ void testListeners() {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
class Listener implements AsyncCallback<String> {
boolean called = false;
+
@Override
public void done(AsyncOperation<String> op) {
called = true;
@@ -40,7 +41,7 @@ public class AsyncTest {
}
@Test
- public void testMultipleResultSetters() {
+ void testMultipleResultSetters() {
{
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
op.setResult("foo");
@@ -65,7 +66,7 @@ public class AsyncTest {
}
@Test
- public void testPartialResultOnFailure() {
+ void testPartialResultOnFailure() {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
op.setFailure(new Exception("bar"), "foo");
assertEquals("foo", op.getResult());
@@ -74,14 +75,16 @@ public class AsyncTest {
}
@Test
- public void testListenImpl() {
+ void testListenImpl() {
class ListenImpl extends AsyncOperationListenImpl<String> {
public ListenImpl(AsyncOperation<String> op) {
super(op);
}
- };
+ }
+ ;
class Listener implements AsyncCallback<String> {
int calls = 0;
+
@Override
public void done(AsyncOperation<String> op) {
++calls;
@@ -98,7 +101,7 @@ public class AsyncTest {
}
@Test
- public void testRedirectedOperation() {
+ void testRedirectedOperation() {
{
final AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test", "desc");
AsyncOperation<Integer> deleteRequest = new RedirectedAsyncOperation<String, Integer>(op) {
@@ -147,7 +150,7 @@ public class AsyncTest {
}
@Test
- public void testRedirectOnSuccessOperation() {
+ void testRedirectOnSuccessOperation() {
{
final AsyncOperationImpl<Integer> target = new AsyncOperationImpl<>("foo");
SuccessfulAsyncCallback<String, Integer> callback = new SuccessfulAsyncCallback<String, Integer>(target) {
@@ -243,17 +246,17 @@ public class AsyncTest {
}
@Test
- public void testStressCompletionAndRegisterToDetectRace() throws Exception {
+ void testStressCompletionAndRegisterToDetectRace() throws Exception {
int iterations = 1000;
Object monitor = new Object();
Completer completer = new Completer(monitor);
Listener listener = new Listener(monitor);
Thread t1 = new Thread(completer);
Thread t2 = new Thread(listener);
- try{
+ try {
t1.start();
t2.start();
- for (int i=0; i<iterations; ++i) {
+ for (int i = 0; i < iterations; ++i) {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
synchronized (monitor) {
completer.op = op;
@@ -261,7 +264,10 @@ public class AsyncTest {
monitor.notifyAll();
}
while (completer.op != null || listener.op != null) {
- try{ Thread.sleep(0); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(0);
+ } catch (InterruptedException e) {
+ }
}
}
} finally {
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java
index 2583c3392c4..41328494f52 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class HttpRequestTest {
@@ -21,7 +19,7 @@ public class HttpRequestTest {
}
@Test
- public void testEquality() {
+ void testEquality() {
assertEquals(createRequest(), createRequest());
assertNotSame(createRequest(), createRequest().setHost("localhost"));
assertNotSame(createRequest(), createRequest().setPort(40));
@@ -31,16 +29,16 @@ public class HttpRequestTest {
}
@Test
- public void testVerifyComplete() {
+ void testVerifyComplete() {
// To be a complete request, an HTTP request must include:
// - A path
// - The HTTP operation type
- try{
+ try {
new HttpRequest().setPath("/foo").verifyComplete();
assertTrue(false);
} catch (IllegalStateException e) {
}
- try{
+ try {
new HttpRequest().setHttpOperation(HttpRequest.HttpOp.GET).verifyComplete();
assertTrue(false);
} catch (IllegalStateException e) {
@@ -49,7 +47,7 @@ public class HttpRequestTest {
}
@Test
- public void testMerge() {
+ void testMerge() {
{
HttpRequest base = new HttpRequest()
.setHttpOperation(HttpRequest.HttpOp.POST)
@@ -92,25 +90,25 @@ public class HttpRequestTest {
}
@Test
- public void testNonExistingHeader() {
+ void testNonExistingHeader() {
assertEquals("foo", new HttpRequest().getHeader("asd", "foo"));
assertEquals("foo", new HttpRequest().addHttpHeader("bar", "foo").getHeader("asd", "foo"));
}
@Test
- public void testOption() {
+ void testOption() {
assertEquals("bar", new HttpRequest().addUrlOption("foo", "bar").getOption("foo", "foo"));
assertEquals("foo", new HttpRequest().getOption("asd", "foo"));
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("GET? http://localhost:8080/",
- new HttpRequest()
- .setScheme("http")
- .setHost("localhost")
- .setPort(8080)
- .toString(true));
+ new HttpRequest()
+ .setScheme("http")
+ .setHost("localhost")
+ .setPort(8080)
+ .toString(true));
assertEquals("POST http://localhost/",
new HttpRequest()
.setScheme("http")
@@ -127,7 +125,7 @@ public class HttpRequestTest {
}
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
assertEquals(false, new HttpRequest().equals(new Object()));
new HttpRequest().getHeaders();
new HttpRequest().setUrlOptions(new HttpRequest().getUrlOptions());
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java
index 59fd4521efb..3a08d735a4e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpResultTest {
@Test
- public void testSuccess() {
+ void testSuccess() {
assertEquals(false, new HttpResult().setHttpCode(199, "foo").isSuccess());
assertEquals(true, new HttpResult().setHttpCode(200, "foo").isSuccess());
assertEquals(true, new HttpResult().setHttpCode(299, "foo").isSuccess());
@@ -16,7 +16,7 @@ public class HttpResultTest {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("HTTP 200/OK", new HttpResult().setContent("Foo").toString());
assertEquals("HTTP 200/OK\n\nFoo", new HttpResult().setContent("Foo").toString(true));
assertEquals("HTTP 200/OK", new HttpResult().toString(true));
@@ -24,7 +24,7 @@ public class HttpResultTest {
}
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
new HttpResult().getHeaders();
}
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
index 2e8f9ea9b58..19fc27669af 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
@@ -3,31 +3,31 @@ package com.yahoo.vespa.clustercontroller.utils.communication.http;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class JsonHttpResultTest {
@Test
- public void testCopyConstructor() {
+ void testCopyConstructor() {
assertEquals("{}", new JsonHttpResult(new HttpResult()).getJson().toString());
}
@Test
- public void testOutput() {
+ void testOutput() {
assertEquals("HTTP 200/OK\n"
- + "\n"
- + "JSON: {\"foo\": 3}",
- new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : 3 }")).toString(true));
+ + "\n"
+ + "JSON: {\"foo\": 3}",
+ new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : 3 }")).toString(true));
assertEquals("HTTP 200/OK\n"
- + "\n"
- + "{ \"foo\" : }",
+ + "\n"
+ + "{ \"foo\" : }",
new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : }")).toString(true));
}
@Test
- public void testNonJsonOutput() {
+ void testNonJsonOutput() {
JsonHttpResult result = new JsonHttpResult();
result.setContent("Foo");
StringBuilder sb = new StringBuilder();
@@ -36,7 +36,7 @@ public class JsonHttpResultTest {
}
@Test
- public void testInvalidJsonOutput() {
+ void testInvalidJsonOutput() {
JsonHttpResult result = new JsonHttpResult();
result.setJson(new JSONObject() {
@Override
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java
index 2c9d9296aae..52b632c6eb8 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.http.writer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class HttpWriterTest {
@@ -19,34 +19,34 @@ public class HttpWriterTest {
+ "</html>\n";
@Test
- public void testStructure() {
+ void testStructure() {
HttpWriter writer = new HttpWriter();
String header = defaultHeader.replace(defaultTitle, "Untitled page");
assertEquals(header + defaultFooter, writer.toString());
}
@Test
- public void testTitle() {
+ void testTitle() {
HttpWriter writer = new HttpWriter().addTitle(defaultTitle);
assertEquals(defaultHeader + defaultFooter, writer.toString());
}
@Test
- public void testParagraph() {
+ void testParagraph() {
String paragraph = "This is a paragraph";
String paragraph2 = "More text";
HttpWriter writer = new HttpWriter().addTitle(defaultTitle).write(paragraph).write(paragraph2);
String content = " <p>\n"
- + " " + paragraph + "\n"
- + " </p>\n"
- + " <p>\n"
- + " " + paragraph2 + "\n"
- + " </p>\n";
+ + " " + paragraph + "\n"
+ + " </p>\n"
+ + " <p>\n"
+ + " " + paragraph2 + "\n"
+ + " </p>\n";
assertEquals(defaultHeader + content + defaultFooter, writer.toString());
}
@Test
- public void testLink() {
+ void testLink() {
String name = "My link";
String link = "/foo/bar?hmm";
HttpWriter writer = new HttpWriter().addTitle(defaultTitle).writeLink(name, link);
@@ -55,15 +55,15 @@ public class HttpWriterTest {
}
@Test
- public void testErrors() {
- try{
+ void testErrors() {
+ try {
HttpWriter writer = new HttpWriter().addTitle(defaultTitle);
writer.toString();
writer.write("foo");
assertTrue(false);
} catch (IllegalStateException e) {
}
- try{
+ try {
new HttpWriter().write("foo").addTitle("bar");
assertTrue(false);
} catch (IllegalStateException e) {
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
index 0f6e9e235dc..d0378dd9065 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
@@ -9,12 +9,11 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.*;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.server.RestApiHandler;
import com.yahoo.vespa.clustercontroller.utils.test.TestTransport;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class StateRestAPITest {
@@ -60,96 +59,96 @@ public class StateRestAPITest {
AsyncOperation<HttpResult> op = testTransport.getClient().execute(request);
AsyncUtils.waitFor(op);
if (!op.isSuccess()) { // Don't call getCause() unless it fails
- assertTrue(op.getCause().toString(), op.isSuccess());
+ assertTrue(op.isSuccess(), op.getCause().toString());
}
assertTrue(op.getResult() != null);
return op.getResult();
}
private JSONObject executeOkJsonRequest(HttpRequest request) {
HttpResult result = execute(request);
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
return (JSONObject) result.getContent();
}
@Test
- public void testTopLevelList() throws Exception {
+ void testTopLevelList() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"cluster\": {\n"
- + " \"foo\": {\"link\": \"\\/cluster\\/v2\\/foo\"},\n"
- + " \"bar\": {\"link\": \"\\/cluster\\/v2\\/bar\"}\n"
- + "}}";
+ + " \"foo\": {\"link\": \"\\/cluster\\/v2\\/foo\"},\n"
+ + " \"bar\": {\"link\": \"\\/cluster\\/v2\\/bar\"}\n"
+ + "}}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testClusterState() throws Exception {
+ void testClusterState() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"node\": {\n"
- + " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n"
- + " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n"
- + "}}";
+ + " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n"
+ + " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n"
+ + "}}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testNodeState() throws Exception {
+ void testNodeState() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\n"
- + " \"attributes\": {\"group\": \"mygroup\"},\n"
- + " \"state\": {\"current\": {\n"
- + " \"state\": \"up\",\n"
- + " \"reason\": \"\"\n"
- + " }},\n"
- + " \"metrics\": {\"doc-count\": 8}\n"
- + "}";
+ + " \"attributes\": {\"group\": \"mygroup\"},\n"
+ + " \"state\": {\"current\": {\n"
+ + " \"state\": \"up\",\n"
+ + " \"reason\": \"\"\n"
+ + " }},\n"
+ + " \"metrics\": {\"doc-count\": 8}\n"
+ + "}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testRecursiveMode() throws Exception {
+ void testRecursiveMode() throws Exception {
setupDummyStateApi();
{
JSONObject json = executeOkJsonRequest(
new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "true"));
String expected =
"{\"cluster\": {\n" +
- " \"foo\": {\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"initializing\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 5}\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 8}\n" +
- " }\n" +
- " }},\n" +
- " \"bar\": {\"node\": {\"2\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 0}\n" +
- " }}}\n" +
- "}}";
+ " \"foo\": {\"node\": {\n" +
+ " \"1\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"initializing\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 5}\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 8}\n" +
+ " }\n" +
+ " }},\n" +
+ " \"bar\": {\"node\": {\"2\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 0}\n" +
+ " }}}\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
{
@@ -157,17 +156,17 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "1"));
String expected =
"{\"cluster\": {\n" +
- " \"foo\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
- " }},\n" +
- " \"bar\": {\"node\": {\"2\": {\"link\": \"\\/cluster\\/v2\\/bar\\/2\"}}}\n" +
- "}}";
+ " \"foo\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
+ " }},\n" +
+ " \"bar\": {\"node\": {\"2\": {\"link\": \"\\/cluster\\/v2\\/bar\\/2\"}}}\n" +
+ "}}";
// Verify that the actual link does not contain backslash. It's just an artifact of
// jettison json output.
assertEquals("/cluster/v2/foo/1",
- json.getJSONObject("cluster").getJSONObject("foo").getJSONObject("node")
- .getJSONObject("1").getString("link"));
+ json.getJSONObject("cluster").getJSONObject("foo").getJSONObject("node")
+ .getJSONObject("1").getString("link"));
assertEquals(expected, json.toString(2));
}
{
@@ -175,23 +174,23 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2/foo").addUrlOption("recursive", "1"));
String expected =
"{\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"initializing\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 5}\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 8}\n" +
- " }\n" +
- "}}";
+ " \"1\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"initializing\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 5}\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 8}\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
{
@@ -199,9 +198,9 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2/foo").addUrlOption("recursive", "false"));
String expected =
"{\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
- "}}";
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
}
@@ -217,15 +216,15 @@ public class StateRestAPITest {
json.put("response-wait", responseWait.get());
}
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
StringBuilder print = new StringBuilder();
result.printContent(print);
return print.toString();
}
@Test
- public void testSetNodeState() throws Exception {
+ void testSetNodeState() throws Exception {
setupDummyStateApi();
{
JSONObject json = new JSONObject().put("state", new JSONObject()
@@ -233,8 +232,8 @@ public class StateRestAPITest {
.put("state", "retired")
.put("reason", "No reason")));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
}
{
JSONObject json = executeOkJsonRequest(new HttpRequest().setPath("/cluster/v2/foo/3"));
@@ -246,14 +245,14 @@ public class StateRestAPITest {
+ " }},\n"
+ " \"metrics\": {\"doc-count\": 8}\n"
+ "}";
- assertEquals(json.toString(2), expected, json.toString(2));
+ assertEquals(expected, json.toString(2), json.toString(2));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject()));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
}
{
JSONObject json = executeOkJsonRequest(new HttpRequest().setPath("/cluster/v2/foo/3"));
@@ -265,12 +264,12 @@ public class StateRestAPITest {
+ " }},\n"
+ " \"metrics\": {\"doc-count\": 8}\n"
+ "}";
- assertEquals(json.toString(2), expected, json.toString(2));
+ assertEquals(expected, json.toString(2), json.toString(2));
}
}
@Test
- public void set_node_state_response_wait_type_is_propagated_to_handler() throws Exception {
+ void set_node_state_response_wait_type_is_propagated_to_handler() throws Exception {
setupDummyStateApi();
{
String result = retireAndExpectHttp200Response(Optional.of("wait-until-cluster-acked"));
@@ -291,7 +290,7 @@ public class StateRestAPITest {
}
@Test
- public void set_node_state_response_wait_type_is_cluster_acked_by_default() throws Exception {
+ void set_node_state_response_wait_type_is_cluster_acked_by_default() throws Exception {
setupDummyStateApi();
String result = retireAndExpectHttp200Response(Optional.empty());
assertEquals(result,
@@ -302,92 +301,92 @@ public class StateRestAPITest {
}
@Test
- public void testMissingUnits() throws Exception {
+ void testMissingUnits() throws Exception {
setupDummyStateApi();
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/unknown"));
- assertEquals(result.toString(true), 404, result.getHttpReturnCode());
- assertEquals(result.toString(true), "No such resource 'unknown'.", result.getHttpReturnCodeDescription());
+ assertEquals(404, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("No such resource 'unknown'.", result.getHttpReturnCodeDescription(), result.toString(true));
String expected = "{\"message\":\"No such resource 'unknown'.\"}";
assertEquals(expected, result.getContent().toString());
}
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/1234"));
- assertEquals(result.toString(true), 404, result.getHttpReturnCode());
- assertEquals(result.toString(true), "No such resource 'foo/1234'.", result.getHttpReturnCodeDescription());
+ assertEquals(404, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("No such resource 'foo/1234'.", result.getHttpReturnCodeDescription(), result.toString(true));
String expected = "{\"message\":\"No such resource 'foo\\/1234'.\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testUnknownMaster() throws Exception {
+ void testUnknownMaster() throws Exception {
setupDummyStateApi();
stateApi.induceException(new UnknownMasterException());
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 503, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Service Unavailable", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(503, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Service Unavailable", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"No known master cluster controller currently exists.\"}";
assertEquals(expected, result.getContent().toString());
- assertTrue(result.getHeader("Location") == null);
+ assertNull(result.getHeader("Location"));
}
@Test
- public void testOtherMaster() throws Exception {
+ void testOtherMaster() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new OtherMasterException("example.com", 80));
HttpResult result = execute(new HttpRequest().setScheme("https").setPath("/cluster/v2").addUrlOption(" %=?&", "&?%=").addUrlOption("foo", "bar"));
- assertEquals(result.toString(true), 307, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Temporary Redirect", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "https://example.com:80/cluster/v2?%20%25%3D%3F%26=%26%3F%25%3D&foo=bar", result.getHeader("Location"));
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(307, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Temporary Redirect", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("https://example.com:80/cluster/v2?%20%25%3D%3F%26=%26%3F%25%3D&foo=bar", result.getHeader("Location"), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Cluster controller not master. Use master at example.com:80.\"}";
assertEquals(expected, result.getContent().toString());
}
{
stateApi.induceException(new OtherMasterException("example.com", 80));
HttpResult result = execute(new HttpRequest().setScheme("http").setPath("/cluster/v2/foo"));
- assertEquals(result.toString(true), 307, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Temporary Redirect", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "http://example.com:80/cluster/v2/foo", result.getHeader("Location"));
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(307, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Temporary Redirect", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("http://example.com:80/cluster/v2/foo", result.getHeader("Location"), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Cluster controller not master. Use master at example.com:80.\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testRuntimeException() throws Exception {
+ void testRuntimeException() throws Exception {
setupDummyStateApi();
stateApi.induceException(new RuntimeException("Moahaha"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 500, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Failed to process request", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(500, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Failed to process request", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"java.lang.RuntimeException: Moahaha\"}";
assertEquals(expected, result.getContent().toString());
}
@Test
- public void testClientFailures() throws Exception {
+ void testClientFailures() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new InvalidContentException("Foo bar"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Foo bar\"}";
assertEquals(expected, result.getContent().toString());
}
{
stateApi.induceException(new InvalidOptionValueException("foo", "bar", "Foo can not be bar"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'foo' have invalid value 'bar'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'foo' have invalid value 'bar'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'foo' have invalid value 'bar': Foo can not be bar\"}";
assertEquals(expected, result.getContent().toString());
}
@@ -396,94 +395,94 @@ public class StateRestAPITest {
path[0] = "foo";
stateApi.induceException(new OperationNotSupportedForUnitException(path, "Foo"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 405, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Operation not supported for resource", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(405, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Operation not supported for resource", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"[foo]: Foo\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInternalFailure() throws Exception {
+ void testInternalFailure() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new InternalFailure("Foo"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 500, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Failed to process request", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(500, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Failed to process request", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Internal failure. Should not happen: Foo\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInvalidRecursiveValues() throws Exception {
+ void testInvalidRecursiveValues() throws Exception {
setupDummyStateApi();
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "-5"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'recursive' have invalid value '-5'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'recursive' have invalid value '-5'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'recursive' have invalid value '-5': Recursive option must be true, false, 0 or a positive integer\"}";
assertEquals(expected, result.getContent().toString());
}
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "foo"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'recursive' have invalid value 'foo'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'recursive' have invalid value 'foo'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'recursive' have invalid value 'foo': Recursive option must be true, false, 0 or a positive integer\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInvalidJsonInSetStateRequest() throws Exception {
+ void testInvalidJsonInSetStateRequest() throws Exception {
setupDummyStateApi();
{
JSONObject json = new JSONObject();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("Set state requests must contain a state object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("Set state requests must contain a state object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", 5);
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state is not a json object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state is not a json object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", 5));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current is not a json object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current is not a json object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject().put("state", 5)));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current->state is not a string"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current->state is not a string"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject().put("state", "down").put("reason", 5)));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current->reason is not a string"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current->reason is not a string"), result.toString(true));
}
{
String result = retireAndExpectHttp400Response("Non existing condition", "no-wait");
@@ -506,21 +505,21 @@ public class StateRestAPITest {
.put("condition", condition)
.put("response-wait", responseWait);
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
StringBuilder print = new StringBuilder();
result.printContent(print);
return print.toString();
}
@Test
- public void testInvalidPathPrefix() throws Exception {
+ void testInvalidPathPrefix() throws Exception {
DummyBackend backend = new DummyBackend();
stateApi = new DummyStateApi(backend);
populateDummyBackend(backend);
testTransport = new TestTransport();
RestApiHandler handler = new RestApiHandler(stateApi);
- try{
+ try {
handler.setDefaultPathPrefix("cluster/v2");
assertTrue(false);
} catch (IllegalArgumentException e) {
@@ -528,14 +527,14 @@ public class StateRestAPITest {
}
@Test
- public void deadline_exceeded_exception_returns_http_504_error() throws Exception {
+ void deadline_exceeded_exception_returns_http_504_error() throws Exception {
setupDummyStateApi();
stateApi.induceException(new DeadlineExceededException("argh!"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 504, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Gateway Timeout", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(504, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Gateway Timeout", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"argh!\"}";
assertEquals(expected, result.getContent().toString());
}
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
index 2826c70f40a..6363264ce3e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
@@ -2,16 +2,16 @@
package com.yahoo.vespa.clustercontroller.utils.staterestapi.server;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.InvalidContentException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class RestApiHandlerTest {
@Test
- public void testParsingOfTimeout() throws InvalidContentException {
+ void testParsingOfTimeout() throws InvalidContentException {
assertEquals(Optional.empty(), RestApiHandler.parseTimeout(null));
assertEquals(Optional.of(Duration.ofMillis(12500)), RestApiHandler.parseTimeout("12.5"));
assertEquals(Optional.of(Duration.ofMillis(0)), RestApiHandler.parseTimeout("-1"));
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java
index f81c4ba7a96..e14562d42c0 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class CertainlyCloneableTest {
@@ -15,8 +15,8 @@ public class CertainlyCloneableTest {
}
@Test
- public void testSimple() {
- try{
+ void testSimple() {
+ try {
Foo f = new Foo();
f.clone();
fail("Control should not get here");
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java
index ef338d35eb3..c791723615c 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClockTest {
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
long s = new Clock().getTimeInSecs();
long ms = new Clock().getTimeInMillis();
assertTrue(ms >= 1000 * s);
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
index a5f57510194..f09907e7fcd 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class JSONObjectWrapperTest {
@Test
- public void testExceptionWrapping() {
+ void testExceptionWrapping() {
JSONObjectWrapper wrapper = new JSONObjectWrapper();
- try{
+ try {
wrapper.put(null, "foo");
} catch (NullPointerException e) {
assertEquals("Null key.", e.getMessage());
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
index b29de4c972c..33164aaf53e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class MetricReporterTest {
@@ -31,10 +31,10 @@ public class MetricReporterTest {
sb.append(" )\n");
return new Context() {};
}
- };
+ }
@Test
- public void testNoMetricReporter() {
+ void testNoMetricReporter() {
NoMetricReporter reporter = new NoMetricReporter();
reporter.add("foo", 3, null);
reporter.set("foo", 3, null);
@@ -42,7 +42,7 @@ public class MetricReporterTest {
}
@Test
- public void testPrefix() {
+ void testPrefix() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -50,14 +50,14 @@ public class MetricReporterTest {
c.set("bar", 1);
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "add(prefixfoo, 2)\n" +
- "set(prefixbar, 1)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "add(prefixfoo, 2)\n" +
+ "set(prefixbar, 1)\n", mock.sb.toString());
}
@Test
- public void testWithContext() {
+ void testWithContext() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -67,27 +67,27 @@ public class MetricReporterTest {
c.set("bar", 1, c.createContext(myContext));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "createContext( myvar=3 urk=fy )\n" +
- "add(prefixfoo, 2)\n" +
- "createContext( myvar=3 urk=fy )\n" +
- "set(prefixbar, 1)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "createContext( myvar=3 urk=fy )\n" +
+ "add(prefixfoo, 2)\n" +
+ "createContext( myvar=3 urk=fy )\n" +
+ "set(prefixbar, 1)\n", mock.sb.toString());
}
@Test
- public void testDefaultContext() {
+ void testDefaultContext() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
c.add("foo", 2, c.createContext(null));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "add(prefixfoo, 2)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "add(prefixfoo, 2)\n", mock.sb.toString());
}
@Test
- public void testContextOverlap() {
+ void testContextOverlap() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -96,9 +96,9 @@ public class MetricReporterTest {
c.add("foo", 2, c.createContext(myContext));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "createContext( urk=yes )\n" +
- "add(prefixfoo, 2)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "createContext( urk=yes )\n" +
+ "add(prefixfoo, 2)\n", mock.sb.toString());
}
}
diff --git a/component/pom.xml b/component/pom.xml
index a4330957069..e8cee594066 100755
--- a/component/pom.xml
+++ b/component/pom.xml
@@ -16,11 +16,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-bundle</artifactId>
<version>${project.version}</version>
@@ -39,6 +34,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>provided</scope>
diff --git a/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java b/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java
index c4f0e0f7439..45c94591b11 100644
--- a/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java
+++ b/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Locale;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author jonmv
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class VersionCompatibilityTest {
@Test
- public void testNoIncompatibilities() {
+ void testNoIncompatibilities() {
List<String> versions = List.of();
VersionCompatibility compatibility = VersionCompatibility.fromVersionList(versions);
assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
@@ -26,36 +26,36 @@ public class VersionCompatibilityTest {
}
@Test
- public void testValidIncompatibilities() {
+ void testValidIncompatibilities() {
List<String> versions = List.of("1.2.*", "2", "3.*", "4.0.0", "4.0.1", "4.0.3", "4.1.0", "5");
VersionCompatibility compatibility = VersionCompatibility.fromVersionList(versions);
- assertTrue (compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
- assertTrue (compatibility.accept(new Version(0, 0, 0), new Version(1, 1, 1)));
+ assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
+ assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(1, 1, 1)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(1, 2, 3)));
assertFalse(compatibility.accept(new Version(1, 1, 0), new Version(1, 2, 0)));
assertFalse(compatibility.accept(new Version(1, 2, 1), new Version(1, 2, 0)));
assertFalse(compatibility.accept(new Version(1, 1, 0), new Version(1, 3, 0)));
- assertTrue (compatibility.accept(new Version(1, 2, 3), new Version(1, 2, 3)));
- assertTrue (compatibility.accept(new Version(1, 3, 0), new Version(1, 9, 9)));
+ assertTrue(compatibility.accept(new Version(1, 2, 3), new Version(1, 2, 3)));
+ assertTrue(compatibility.accept(new Version(1, 3, 0), new Version(1, 9, 9)));
assertFalse(compatibility.accept(new Version(1, 3, 0), new Version(2, 0, 0)));
- assertTrue (compatibility.accept(new Version(2, 0, 0), new Version(2, 2, 2)));
+ assertTrue(compatibility.accept(new Version(2, 0, 0), new Version(2, 2, 2)));
assertFalse(compatibility.accept(new Version(2, 0, 0), new Version(3, 0, 0)));
- assertTrue (compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 0)));
+ assertTrue(compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 0)));
assertFalse(compatibility.accept(new Version(3, 0, 0), new Version(3, 1, 0)));
- assertTrue (compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 1)));
+ assertTrue(compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 1)));
assertFalse(compatibility.accept(new Version(3, 0, 0), new Version(4, 0, 0)));
assertFalse(compatibility.accept(new Version(4, 0, 0), new Version(4, 0, 1)));
- assertTrue (compatibility.accept(new Version(4, 0, 1), new Version(4, 0, 2)));
+ assertTrue(compatibility.accept(new Version(4, 0, 1), new Version(4, 0, 2)));
assertFalse(compatibility.accept(new Version(4, 0, 2), new Version(4, 0, 3)));
assertFalse(compatibility.accept(new Version(4, 0, 3), new Version(4, 1, 0)));
assertFalse(compatibility.accept(new Version(4, 1, 0), new Version(5, 0, 0)));
- assertTrue (compatibility.accept(new Version(5, 0, 0), new Version(6, 0, 0)));
+ assertTrue(compatibility.accept(new Version(5, 0, 0), new Version(6, 0, 0)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(2, 0, 0)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(6, 0, 0)));
}
@Test
- public void testIllegalIncompatibilities() {
+ void testIllegalIncompatibilities() {
assertThrows(List.of("1", "*"), IllegalArgumentException.class, "may not have siblings");
assertThrows(List.of("*", "*.*"), IllegalArgumentException.class, "may not have siblings");
assertThrows(List.of("*", "*"), IllegalArgumentException.class, "may not have siblings");
diff --git a/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java b/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
index 7b419f0fc5d..cb4b07f1b33 100644
--- a/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
+++ b/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
@@ -1,11 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -13,74 +15,74 @@ import static org.junit.Assert.assertTrue;
public class VersionSpecificationTestCase {
@Test
- public void testPrimitiveCreation() {
- VersionSpecification version=new VersionSpecification(1,2,3,"qualifier");
- assertEquals(1, (int)version.getSpecifiedMajor());
- assertEquals(2, (int)version.getSpecifiedMinor());
- assertEquals(3, (int)version.getSpecifiedMicro());
- assertEquals("qualifier",version.getSpecifiedQualifier());
+ void testPrimitiveCreation() {
+ VersionSpecification version = new VersionSpecification(1, 2, 3, "qualifier");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertEquals(2, (int) version.getSpecifiedMinor());
+ assertEquals(3, (int) version.getSpecifiedMicro());
+ assertEquals("qualifier", version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(2, version.getMinor());
assertEquals(3, version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedPrimitiveCreation() {
- VersionSpecification version=new VersionSpecification(1);
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(null,version.getSpecifiedMinor());
- assertEquals(null,version.getSpecifiedMicro());
- assertEquals(null,version.getSpecifiedQualifier());
+ void testUnderspecifiedPrimitiveCreation() {
+ VersionSpecification version = new VersionSpecification(1);
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertNull(version.getSpecifiedMinor());
+ assertNull(version.getSpecifiedMicro());
+ assertNull(version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(0, version.getMinor());
assertEquals(0, version.getMicro());
- assertEquals("",version.getQualifier());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testStringCreation() {
- VersionSpecification version=new VersionSpecification("1.2.3.qualifier");
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(2,(int)version.getSpecifiedMinor());
- assertEquals(3,(int)version.getSpecifiedMicro());
- assertEquals("qualifier",version.getSpecifiedQualifier());
+ void testStringCreation() {
+ VersionSpecification version = new VersionSpecification("1.2.3.qualifier");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertEquals(2, (int) version.getSpecifiedMinor());
+ assertEquals(3, (int) version.getSpecifiedMicro());
+ assertEquals("qualifier", version.getSpecifiedQualifier());
}
@Test
- public void testUnderspecifiedStringCreation() {
- VersionSpecification version=new VersionSpecification("1");
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(null,version.getSpecifiedMinor());
- assertEquals(null,version.getSpecifiedMicro());
- assertEquals(null,version.getSpecifiedQualifier());
+ void testUnderspecifiedStringCreation() {
+ VersionSpecification version = new VersionSpecification("1");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertNull(version.getSpecifiedMinor());
+ assertNull(version.getSpecifiedMicro());
+ assertNull(version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(0, version.getMinor());
assertEquals(0, version.getMicro());
- assertEquals("",version.getQualifier());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testEquality() {
- assertEquals(new VersionSpecification(),VersionSpecification.emptyVersionSpecification);
- assertEquals(new VersionSpecification(),new VersionSpecification(""));
- assertEquals(new VersionSpecification(1),new VersionSpecification("1"));
- assertEquals(new VersionSpecification(1,2),new VersionSpecification("1.2"));
- assertEquals(new VersionSpecification(1,2,3),new VersionSpecification("1.2.3"));
- assertEquals(new VersionSpecification(1,2,3,"qualifier"),new VersionSpecification("1.2.3.qualifier"));
+ void testEquality() {
+ assertEquals(new VersionSpecification(), VersionSpecification.emptyVersionSpecification);
+ assertEquals(new VersionSpecification(), new VersionSpecification(""));
+ assertEquals(new VersionSpecification(1), new VersionSpecification("1"));
+ assertEquals(new VersionSpecification(1, 2), new VersionSpecification("1.2"));
+ assertEquals(new VersionSpecification(1, 2, 3), new VersionSpecification("1.2.3"));
+ assertEquals(new VersionSpecification(1, 2, 3, "qualifier"), new VersionSpecification("1.2.3.qualifier"));
}
@Test
- public void testToString() {
- assertEquals("",new VersionSpecification().toString());
- assertEquals("1",new VersionSpecification(1).toString());
- assertEquals("1.2",new VersionSpecification(1,2).toString());
- assertEquals("1.2.3",new VersionSpecification(1,2,3).toString());
- assertEquals("1.2.3.qualifier",new VersionSpecification(1,2,3,"qualifier").toString());
+ void testToString() {
+ assertEquals("", new VersionSpecification().toString());
+ assertEquals("1", new VersionSpecification(1).toString());
+ assertEquals("1.2", new VersionSpecification(1, 2).toString());
+ assertEquals("1.2.3", new VersionSpecification(1, 2, 3).toString());
+ assertEquals("1.2.3.qualifier", new VersionSpecification(1, 2, 3, "qualifier").toString());
}
@Test
- public void testMatches() {
+ void testMatches() {
assertTrue(new VersionSpecification("").matches(new Version("1")));
assertTrue(new VersionSpecification("1").matches(new Version("1")));
assertFalse(new VersionSpecification("1").matches(new Version("2")));
@@ -112,19 +114,19 @@ public class VersionSpecificationTestCase {
}
@Test
- public void testOrder() {
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.3"))==0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.4"))<0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.2"))>0);
+ void testOrder() {
+ assertEquals(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.3")), 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.4")) < 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.2")) > 0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("2"))<0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.3"))<0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("2")) < 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.3")) < 0);
- assertTrue(new VersionSpecification("1.0.0").compareTo(new VersionSpecification("1"))==0);
+ assertEquals(new VersionSpecification("1.0.0").compareTo(new VersionSpecification("1")), 0);
}
@Test
- public void testValidIntersect() {
+ void testValidIntersect() {
VersionSpecification mostSpecific = new VersionSpecification(4, 2, 1);
VersionSpecification leastSpecific = new VersionSpecification(4, 2);
@@ -134,9 +136,11 @@ public class VersionSpecificationTestCase {
leastSpecific.intersect(mostSpecific));
}
- @Test(expected=RuntimeException.class)
- public void testInvalidIntersect() {
- new VersionSpecification(4, 1).intersect(
- new VersionSpecification(4, 2));
+ @Test
+ void testInvalidIntersect() {
+ assertThrows(RuntimeException.class, () -> {
+ new VersionSpecification(4, 1).intersect(
+ new VersionSpecification(4, 2));
+ });
}
}
diff --git a/component/src/test/java/com/yahoo/component/VersionTestCase.java b/component/src/test/java/com/yahoo/component/VersionTestCase.java
index f66bc245f85..96adb6ce38f 100644
--- a/component/src/test/java/com/yahoo/component/VersionTestCase.java
+++ b/component/src/test/java/com/yahoo/component/VersionTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.component;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -15,111 +15,111 @@ import static org.junit.Assert.assertTrue;
public class VersionTestCase {
@Test
- public void testPrimitiveCreation() {
- Version version=new Version(1,2,3,"qualifier");
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testPrimitiveCreation() {
+ Version version = new Version(1, 2, 3, "qualifier");
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedPrimitiveCreation() {
- Version version=new Version(1);
- assertEquals(1,version.getMajor());
- assertEquals(1,version.getMajor());
- assertEquals(0,version.getMinor());
- assertEquals(0,version.getMicro());
- assertEquals("",version.getQualifier());
+ void testUnderspecifiedPrimitiveCreation() {
+ Version version = new Version(1);
+ assertEquals(1, version.getMajor());
+ assertEquals(1, version.getMajor());
+ assertEquals(0, version.getMinor());
+ assertEquals(0, version.getMicro());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testStringCreation() {
- Version version=new Version("1.2.3.qualifier");
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testStringCreation() {
+ Version version = new Version("1.2.3.qualifier");
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUtf8StringCreation() {
- Version version=new Version((Utf8Array)new Utf8String("1.2.3.qualifier"));
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testUtf8StringCreation() {
+ Version version = new Version((Utf8Array) new Utf8String("1.2.3.qualifier"));
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedStringCreation() {
- Version version=new Version("1");
- assertEquals(1,version.getMajor());
- assertEquals(0,version.getMinor());
- assertEquals(0,version.getMicro());
- assertEquals("",version.getQualifier());
+ void testUnderspecifiedStringCreation() {
+ Version version = new Version("1");
+ assertEquals(1, version.getMajor());
+ assertEquals(0, version.getMinor());
+ assertEquals(0, version.getMicro());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testEquality() {
- assertEquals(new Version(),Version.emptyVersion);
- assertEquals(new Version(),new Version(""));
- assertEquals(new Version(0,0,0),Version.emptyVersion);
- assertEquals(new Version(1),new Version("1"));
- assertEquals(new Version(1,2),new Version("1.2"));
- assertEquals(new Version(1,2,3),new Version("1.2.3"));
- assertEquals(new Version(1,2,3,"qualifier"),new Version("1.2.3.qualifier"));
+ void testEquality() {
+ assertEquals(new Version(), Version.emptyVersion);
+ assertEquals(new Version(), new Version(""));
+ assertEquals(new Version(0, 0, 0), Version.emptyVersion);
+ assertEquals(new Version(1), new Version("1"));
+ assertEquals(new Version(1, 2), new Version("1.2"));
+ assertEquals(new Version(1, 2, 3), new Version("1.2.3"));
+ assertEquals(new Version(1, 2, 3, "qualifier"), new Version("1.2.3.qualifier"));
}
@Test
- public void testToString() {
- assertEquals("",new Version().toString());
- assertEquals("1",new Version(1).toString());
- assertEquals("1.2",new Version(1,2).toString());
- assertEquals("1.2.3",new Version(1,2,3).toString());
- assertEquals("1.2.3.qualifier",new Version(1,2,3,"qualifier").toString());
+ void testToString() {
+ assertEquals("", new Version().toString());
+ assertEquals("1", new Version(1).toString());
+ assertEquals("1.2", new Version(1, 2).toString());
+ assertEquals("1.2.3", new Version(1, 2, 3).toString());
+ assertEquals("1.2.3.qualifier", new Version(1, 2, 3, "qualifier").toString());
}
@Test
- public void testToFullString() {
- assertEquals("0.0.0",new Version().toFullString());
- assertEquals("1.0.0",new Version(1).toFullString());
- assertEquals("1.2.0",new Version(1,2).toFullString());
- assertEquals("1.2.3",new Version(1,2,3).toFullString());
- assertEquals("1.2.3.qualifier",new Version(1,2,3,"qualifier").toFullString());
+ void testToFullString() {
+ assertEquals("0.0.0", new Version().toFullString());
+ assertEquals("1.0.0", new Version(1).toFullString());
+ assertEquals("1.2.0", new Version(1, 2).toFullString());
+ assertEquals("1.2.3", new Version(1, 2, 3).toFullString());
+ assertEquals("1.2.3.qualifier", new Version(1, 2, 3, "qualifier").toFullString());
}
@Test
- public void testOrder() {
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3"))==0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.4"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3.foo"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.2"))>0);
- assertTrue(new Version("1.2.3.foo").compareTo(new Version("1.2.3"))>0);
- assertTrue(new Version("1.2.3").compareTo(new Version("2"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.3"))<0);
- assertTrue(new Version("1.0.0").compareTo(new Version("1"))==0);
+ void testOrder() {
+ assertEquals(new Version("1.2.3").compareTo(new Version("1.2.3")), 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.4")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3.foo")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.2")) > 0);
+ assertTrue(new Version("1.2.3.foo").compareTo(new Version("1.2.3")) > 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("2")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.3")) < 0);
+ assertEquals(new Version("1.0.0").compareTo(new Version("1")), 0);
}
-
+
@Test
- public void testIsBefore() {
+ void testIsBefore() {
assertFalse(new Version("1.2.3").isBefore(new Version("0.2.3")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.1.3")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.2.2")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.2.3")));
assertFalse(new Version("1.2.3.foo").isBefore(new Version("1.2.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.2.4")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.3.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("2.2.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.2.3.foo")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.2.4")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.3.3")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("2.2.3")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.2.3.foo")));
}
@Test
- public void testIsAfter() {
- assertTrue( new Version("1.2.3").isAfter(new Version("0.2.3")));
- assertTrue( new Version("1.2.3").isAfter(new Version("1.1.3")));
- assertTrue( new Version("1.2.3").isAfter(new Version("1.2.2")));
- assertTrue( new Version("1.2.3.foo").isAfter(new Version("1.2.3")));
+ void testIsAfter() {
+ assertTrue(new Version("1.2.3").isAfter(new Version("0.2.3")));
+ assertTrue(new Version("1.2.3").isAfter(new Version("1.1.3")));
+ assertTrue(new Version("1.2.3").isAfter(new Version("1.2.2")));
+ assertTrue(new Version("1.2.3.foo").isAfter(new Version("1.2.3")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.2.3")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.2.4")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.3.3")));
diff --git a/config-application-package/src/main/java/com/yahoo/config/application/ValidationProcessor.java b/config-application-package/src/main/java/com/yahoo/config/application/ValidationProcessor.java
new file mode 100644
index 00000000000..5f430f70584
--- /dev/null
+++ b/config-application-package/src/main/java/com/yahoo/config/application/ValidationProcessor.java
@@ -0,0 +1,18 @@
+package com.yahoo.config.application;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+
+public class ValidationProcessor implements PreProcessor {
+
+ @Override
+ public Document process(Document input) throws IOException, TransformerException {
+ NodeList includeitems = input.getElementsByTagNameNS("http://www.w3.org/2001/XInclude", "*");
+ if (includeitems.getLength() > 0)
+ throw new UnsupportedOperationException("XInclude not supported, use preprocess:include instead");
+ return input;
+ }
+} \ No newline at end of file
diff --git a/config-application-package/src/main/java/com/yahoo/config/application/XmlPreProcessor.java b/config-application-package/src/main/java/com/yahoo/config/application/XmlPreProcessor.java
index 640cc7bcfa7..ba68894c9f9 100644
--- a/config-application-package/src/main/java/com/yahoo/config/application/XmlPreProcessor.java
+++ b/config-application-package/src/main/java/com/yahoo/config/application/XmlPreProcessor.java
@@ -5,6 +5,7 @@ import com.yahoo.config.application.FileSystemWrapper.FileWrapper;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.RegionName;
+import com.yahoo.text.XML;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@@ -57,7 +58,7 @@ public class XmlPreProcessor {
}
public Document run() throws ParserConfigurationException, IOException, SAXException, TransformerException {
- DocumentBuilder docBuilder = Xml.getPreprocessDocumentBuilder();
+ DocumentBuilder docBuilder = XML.getDocumentBuilder();
Document document = docBuilder.parse(new InputSource(xmlInput));
return execute(document);
}
@@ -74,6 +75,7 @@ public class XmlPreProcessor {
chain.add(new IncludeProcessor(applicationDir));
chain.add(new OverrideProcessor(instance, environment, region));
chain.add(new PropertiesProcessor());
+ chain.add(new ValidationProcessor()); // must be last in chain
return chain;
}
diff --git a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/DeployData.java b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/DeployData.java
index b21f8677984..279af646a8c 100644
--- a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/DeployData.java
+++ b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/DeployData.java
@@ -10,9 +10,6 @@ import com.yahoo.config.provision.ApplicationId;
*/
public class DeployData {
- /** Which user deployed */
- private final String deployedByUser;
-
private final ApplicationId applicationId;
/** The absolute path to the directory holding the application */
@@ -28,14 +25,23 @@ public class DeployData {
private final long generation;
private final long currentlyActiveGeneration;
- public DeployData(String deployedByUser,
+ // TODO: Remove when oldest version in use is 8.13
+ public DeployData(String ignored,
String deployedFromDir,
ApplicationId applicationId,
Long deployTimestamp,
boolean internalRedeploy,
Long generation,
long currentlyActiveGeneration) {
- this.deployedByUser = deployedByUser;
+ this(deployedFromDir, applicationId, deployTimestamp, internalRedeploy, generation, currentlyActiveGeneration);
+ }
+
+ public DeployData(String deployedFromDir,
+ ApplicationId applicationId,
+ Long deployTimestamp,
+ boolean internalRedeploy,
+ Long generation,
+ long currentlyActiveGeneration) {
this.deployedFromDir = deployedFromDir;
this.applicationId = applicationId;
this.deployTimestamp = deployTimestamp;
@@ -44,8 +50,6 @@ public class DeployData {
this.currentlyActiveGeneration = currentlyActiveGeneration;
}
- public String getDeployedByUser() { return deployedByUser; }
-
public String getDeployedFromDir() { return deployedFromDir; }
public long getDeployTimestamp() { return deployTimestamp; }
diff --git a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java
index 826cf85798a..7b483d0603c 100644
--- a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java
+++ b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java
@@ -134,8 +134,7 @@ public class FilesApplicationPackage extends AbstractApplicationPackage {
}
private static ApplicationMetaData metaDataFromDeployData(File appDir, DeployData deployData) {
- return new ApplicationMetaData(deployData.getDeployedByUser(),
- deployData.getDeployedFromDir(),
+ return new ApplicationMetaData(deployData.getDeployedFromDir(),
deployData.getDeployTimestamp(),
deployData.isInternalRedeploy(),
deployData.getApplicationId(),
@@ -480,7 +479,6 @@ public class FilesApplicationPackage extends AbstractApplicationPackage {
private static ApplicationMetaData readMetaData(File appDir) {
String originalAppDir = preprocessed.equals(appDir.getName()) ? appDir.getParentFile().getName() : appDir.getName();
ApplicationMetaData defaultMetaData = new ApplicationMetaData("n/a",
- "n/a",
0L,
false,
ApplicationId.from(TenantName.defaultName(),
@@ -573,7 +571,7 @@ public class FilesApplicationPackage extends AbstractApplicationPackage {
}
@Override
- public void writeMetaData() throws IOException {
+ public void writeMetaData() {
File metaFile = applicationFile(appDir, META_FILE_NAME);
IOUtils.writeFile(metaFile, metaData.asJsonBytes());
}
diff --git a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/SchemaValidators.java b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/SchemaValidators.java
index 57dca2293e6..8bd92d13511 100644
--- a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/SchemaValidators.java
+++ b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/SchemaValidators.java
@@ -63,8 +63,6 @@ public class SchemaValidators {
routingStandaloneXmlValidator = createValidator(schemaDir, routingStandaloneXmlSchemaName);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
- } catch (Exception e) {
- throw e;
} finally {
if (schemaDir != null)
IOUtils.recursiveDeleteDir(schemaDir);
@@ -96,7 +94,7 @@ public class SchemaValidators {
}
/**
- * Look for the schema files in config-model.jar and saves them on temp dir. Uses schema files
+ * Looks for schema files in config-model.jar and saves them in a temp dir. Uses schema files
* in $VESPA_HOME/share/vespa/schema/[major-version].x/ otherwise
*
* @return the directory the schema files are stored in
@@ -104,30 +102,29 @@ public class SchemaValidators {
*/
private File saveSchemasFromJar(File tmpBase, Version vespaVersion) throws IOException {
Class<? extends SchemaValidators> schemaValidatorClass = this.getClass();
- ClassLoader classLoader = schemaValidatorClass.getClassLoader();
- Enumeration<URL> uris = classLoader.getResources("schema");
+ Enumeration<URL> uris = schemaValidatorClass.getClassLoader().getResources("schema");
if (uris == null) throw new IllegalArgumentException("Could not find XML schemas ");
File tmpDir = createTempDirectory(tmpBase.toPath(), "vespa").toFile();
log.log(Level.FINE, () -> "Will save all XML schemas for " + vespaVersion + " to " + tmpDir);
+ boolean schemasFound = false;
while (uris.hasMoreElements()) {
URL u = uris.nextElement();
- log.log(Level.FINE, () -> "uri for resource 'schema'=" + u.toString());
- // TODO: When is this the case? Remove?
+ // Used when building standalone-container
if ("jar".equals(u.getProtocol())) {
JarURLConnection jarConnection = (JarURLConnection) u.openConnection();
JarFile jarFile = jarConnection.getJarFile();
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry je = entries.nextElement();
if (je.getName().startsWith("schema/") && je.getName().endsWith(".rnc")) {
+ schemasFound = true;
writeContentsToFile(tmpDir, je.getName(), jarFile.getInputStream(je));
}
}
jarFile.close();
} else if ("bundle".equals(u.getProtocol())) {
Bundle bundle = getBundle(schemaValidatorClass);
- log.log(Level.FINE, () -> "bundle=" + bundle);
- // TODO: Hack to handle cases where bundle=null (which seems to always be the case with config-model-fat-amended.jar)
+ // Use schemas on disk when bundle is null (which is the case when using config-model-fat-amended.jar)
if (bundle == null) {
String pathPrefix = getDefaults().underVespaHome("share/vespa/schema/");
File schemaPath = new File(pathPrefix + "version/" + vespaVersion.getMajor() + ".x/schema/");
@@ -137,22 +134,28 @@ public class SchemaValidators {
schemaPath = new File(pathPrefix);
}
log.log(Level.FINE, "Using schemas found in " + schemaPath);
+ schemasFound = true;
copySchemas(schemaPath, tmpDir);
} else {
log.log(Level.FINE, () -> String.format("Saving schemas for model bundle %s:%s", bundle.getSymbolicName(), bundle.getVersion()));
- for (Enumeration<URL> entries = bundle.findEntries("schema", "*.rnc", true);
- entries.hasMoreElements(); ) {
-
+ for (Enumeration<URL> entries = bundle.findEntries("schema", "*.rnc", true); entries.hasMoreElements(); ) {
URL url = entries.nextElement();
writeContentsToFile(tmpDir, url.getFile(), url.openStream());
+ schemasFound = true;
}
}
- // TODO: When is this the case? Remove?
- } else if ("file".equals(u.getProtocol())) {
+ } else if ("file".equals(u.getProtocol())) { // Used when running unit tests
File schemaPath = new File(u.getPath());
copySchemas(schemaPath, tmpDir);
+ schemasFound = true;
}
}
+
+ if ( ! schemasFound) {
+ IOUtils.recursiveDeleteDir(tmpDir);
+ throw new IllegalArgumentException("Could not find schemas for version " + vespaVersion);
+ }
+
return tmpDir;
}
diff --git a/config-application-package/src/test/java/com/yahoo/config/application/MultiOverrideProcessorTest.java b/config-application-package/src/test/java/com/yahoo/config/application/MultiOverrideProcessorTest.java
index 2ef4fea9d7a..44bcb12957a 100644
--- a/config-application-package/src/test/java/com/yahoo/config/application/MultiOverrideProcessorTest.java
+++ b/config-application-package/src/test/java/com/yahoo/config/application/MultiOverrideProcessorTest.java
@@ -25,7 +25,7 @@ public class MultiOverrideProcessorTest {
private static final String input =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
- " <container id='qrserver' version='1.0'>\n" +
+ " <container id='default' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
@@ -50,7 +50,7 @@ public class MultiOverrideProcessorTest {
private static final String inputWithIds =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
- " <container id='qrserver' version='1.0'>\n" +
+ " <container id='default' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
@@ -77,7 +77,7 @@ public class MultiOverrideProcessorTest {
String expected =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
- " <container id='qrserver' version='1.0'>\n" +
+ " <container id='default' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
@@ -98,7 +98,7 @@ public class MultiOverrideProcessorTest {
String expected =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<services version=\"1.0\" xmlns:deploy=\"vespa\">\n" +
- " <container id='qrserver' version='1.0'>\n" +
+ " <container id='default' version='1.0'>\n" +
" <component id=\"comp-B\" class=\"com.yahoo.ls.MyComponent\" bundle=\"lsbe-hv\">\n" +
" <config name=\"ls.config.resource-pool\">\n" +
" <resource>\n" +
diff --git a/config-bundle/pom.xml b/config-bundle/pom.xml
index 50205f9fe71..a1770537a3e 100644
--- a/config-bundle/pom.xml
+++ b/config-bundle/pom.xml
@@ -49,12 +49,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>vespalog</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
diff --git a/config-lib/pom.xml b/config-lib/pom.xml
index ea72afb568d..66603deeb38 100644
--- a/config-lib/pom.xml
+++ b/config-lib/pom.xml
@@ -17,11 +17,6 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>annotations</artifactId>
<version>${project.version}</version>
@@ -33,6 +28,16 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java b/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java
index bfa2f747c1c..50d71ba50e9 100644
--- a/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
*/
public class BooleanNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
BooleanNode n = new BooleanNode();
assertTrue(n.doSetValue("true"));
assertTrue(n.doSetValue("TRUE"));
diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
index 613cfe1cced..f05baeff08c 100644
--- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
@@ -6,7 +6,7 @@ import com.yahoo.foo.StructtypesConfig;
import com.yahoo.test.FunctionTestConfig;
import com.yahoo.test.IntConfig;
import com.yahoo.test.RestartConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.lang.reflect.Field;
@@ -26,11 +26,11 @@ import static com.yahoo.test.FunctionTestConfig.RootStruct;
import static com.yahoo.test.FunctionTestConfig.MyStructMap;
import static com.yahoo.foo.MaptypesConfig.Innermap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -40,7 +40,7 @@ public class ConfigInstanceBuilderTest
{
@Test
- public void struct_values_can_be_set_without_declaring_a_new_struct_builder() {
+ void struct_values_can_be_set_without_declaring_a_new_struct_builder() {
var builder = new StructtypesConfig.Builder();
builder.simple
.name("myname")
@@ -52,7 +52,7 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void leaf_map_setter_merges_maps() {
+ void leaf_map_setter_merges_maps() {
MaptypesConfig.Builder builder = new MaptypesConfig.Builder()
.intmap("one", 1);
@@ -66,10 +66,10 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void inner_map_setter_merges_maps() {
+ void inner_map_setter_merges_maps() {
MaptypesConfig.Builder builder = new MaptypesConfig.Builder()
.innermap("one", new Innermap.Builder()
- .foo(1));
+ .foo(1));
Map<String, Innermap.Builder> newMap = new HashMap<>();
newMap.put("two", new Innermap.Builder().foo(2));
@@ -81,13 +81,13 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void testVariableAccessWithBuilder() {
+ void testVariableAccessWithBuilder() {
FunctionTestConfig config = createVariableAccessConfigWithBuilder();
assertVariableAccessValues(config, ":parent:");
}
@Test
- public void require_that_unset_builder_fields_are_null() throws Exception {
+ void require_that_unset_builder_fields_are_null() throws Exception {
FunctionTestConfig.Builder builder = new FunctionTestConfig.Builder();
assertNull(getMember(builder, "bool_val"));
assertNull(getMember(builder, "bool_with_def"));
@@ -111,7 +111,7 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void require_that_set_builder_fields_are_nonNull() throws Exception {
+ void require_that_set_builder_fields_are_nonNull() throws Exception {
FunctionTestConfig.Builder builder = createVariableAccessBuilder();
assertNotNull(getMember(builder, "bool_val"));
assertNotNull(getMember(builder, "bool_with_def"));
@@ -129,13 +129,13 @@ public class ConfigInstanceBuilderTest
assertNotNull(getMember(builder, "refwithdef"));
assertNotNull(getMember(builder, "fileVal"));
- BasicStruct.Builder basicStructBuilder = (BasicStruct.Builder)getMember(builder, "basicStruct");
+ BasicStruct.Builder basicStructBuilder = (BasicStruct.Builder) getMember(builder, "basicStruct");
assertNotNull(getMember(basicStructBuilder, "foo"));
assertNotNull(getMember(basicStructBuilder, "bar"));
}
@Test
- public void require_that_config_can_be_recreated_from_another_configs_builder() {
+ void require_that_config_can_be_recreated_from_another_configs_builder() {
FunctionTestConfig original = createVariableAccessConfigWithBuilder();
FunctionTestConfig copy = new FunctionTestConfig(new FunctionTestConfig.Builder(original));
assertVariableAccessValues(copy, ":parent:");
@@ -330,13 +330,13 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void require_that_config_class_reports_any_restart_values() throws Exception {
+ void require_that_config_class_reports_any_restart_values() throws Exception {
assertTrue(callContainsFieldsFlaggedWithRestart(RestartConfig.class));
assertFalse(callContainsFieldsFlaggedWithRestart(IntConfig.class));
}
@Test
- public void require_that_config_class_can_make_change_report() throws Exception {
+ void require_that_config_class_can_make_change_report() throws Exception {
IntConfig noRestart1 = new IntConfig(new IntConfig.Builder().intVal(42));
IntConfig noRestart2 = new IntConfig(new IntConfig.Builder().intVal(21));
ChangesRequiringRestart report = callGetChangesRequiringRestart(noRestart1, noRestart2);
@@ -370,33 +370,33 @@ public class ConfigInstanceBuilderTest
assertEquals("function-test", report.getName());
assertTrue(
report.toString().startsWith(
- "# An int value\n" +
- "# Also test that multiline comments\n" +
- "# work.\n" +
- "function-test.int_val has changed from 5 to 100\n" +
- "function-test.stringarr[0] has changed from \"bar\" to \"foo\"\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{one} has changed from 1 to 42\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{two} with value 2 was removed\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{three} was added with value 3\n" +
- "# A basic struct\n" +
- "function-test.basicStruct.foo has changed from \"basicFoo\" to \"basic\"\n" +
- "function-test.basicStruct.bar has changed from 3 to 1234\n" +
- "function-test.basicStruct.intArr[0] with value 310 was removed\n" +
- "function-test.basicStruct.intArr[1] with value 311 was removed\n" +
- "function-test.myarray[0].anotherarray[0].foo has changed from 7 to 32\n" +
- "# This is my array\n" +
- "function-test.myarray[1].intval has changed from 5 to 17\n" +
- "function-test.myarray[2] was added with value \n"
+ "# An int value\n" +
+ "# Also test that multiline comments\n" +
+ "# work.\n" +
+ "function-test.int_val has changed from 5 to 100\n" +
+ "function-test.stringarr[0] has changed from \"bar\" to \"foo\"\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{one} has changed from 1 to 42\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{two} with value 2 was removed\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{three} was added with value 3\n" +
+ "# A basic struct\n" +
+ "function-test.basicStruct.foo has changed from \"basicFoo\" to \"basic\"\n" +
+ "function-test.basicStruct.bar has changed from 3 to 1234\n" +
+ "function-test.basicStruct.intArr[0] with value 310 was removed\n" +
+ "function-test.basicStruct.intArr[1] with value 311 was removed\n" +
+ "function-test.myarray[0].anotherarray[0].foo has changed from 7 to 32\n" +
+ "# This is my array\n" +
+ "function-test.myarray[1].intval has changed from 5 to 17\n" +
+ "function-test.myarray[2] was added with value \n"
)
);
assertTrue(
report.toString().contains(
- "function-test.myStructMap{one}.myInt has changed from 1 to 42\n" +
- "function-test.myStructMap{new} was added with value \n"
+ "function-test.myStructMap{one}.myInt has changed from 1 to 42\n" +
+ "function-test.myStructMap{new} was added with value \n"
)
);
diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
index 536c18786da..1584293a137 100644
--- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
@@ -3,8 +3,8 @@ package com.yahoo.config;
import com.yahoo.test.AppConfig;
import com.yahoo.test.FunctionTestConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Arrays;
@@ -14,15 +14,15 @@ import static com.yahoo.test.FunctionTestConfig.Enum_val;
import static com.yahoo.test.FunctionTestConfig.Enumarr;
import static com.yahoo.test.FunctionTestConfig.Myarray;
import static com.yahoo.test.FunctionTestConfig.RootStruct;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class ConfigInstanceEqualsTest {
FunctionTestConfig config1;
FunctionTestConfig.Builder builder2;
FunctionTestConfig config2;
- @Before
+ @BeforeEach
public void reset() {
config1 = new FunctionTestConfig(newBuilder());
builder2 = newBuilder();
@@ -30,28 +30,28 @@ public class ConfigInstanceEqualsTest {
}
@Test
- public void require_same_hashCode_for_equal_instances() {
+ void require_same_hashCode_for_equal_instances() {
assertEquals(config1.hashCode(), config2.hashCode());
}
@Test
- public void require_true_for_equal_instances() {
+ void require_true_for_equal_instances() {
assertEquals(config1, config2);
}
@Test
- public void require_false_for_null() {
+ void require_false_for_null() {
assertNotEquals(null, config1);
}
@Test
- public void require_false_for_different_subclass() {
+ void require_false_for_different_subclass() {
assertNotEquals(config1, new AppConfig(new AppConfig.Builder()));
}
@Test
- public void require_false_for_different_scalars_at_root_node() {
+ void require_false_for_different_scalars_at_root_node() {
assertNotEquals(config1, new FunctionTestConfig(newBuilder().bool_val(true)));
assertNotEquals(config1, new FunctionTestConfig(newBuilder().int_val(0)));
assertNotEquals(config1, new FunctionTestConfig(newBuilder().long_val(0L)));
@@ -63,50 +63,50 @@ public class ConfigInstanceEqualsTest {
}
@Test
- public void require_false_for_different_leaf_array_at_root_node() {
+ void require_false_for_different_leaf_array_at_root_node() {
builder2.longarr.set(0, 0L);
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_scalar_in_struct() {
+ void require_false_for_different_scalar_in_struct() {
builder2.basicStruct(new BasicStruct.Builder(config1.basicStruct()).bar(0));
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_scalar_in_inner_array() {
+ void require_false_for_different_scalar_in_inner_array() {
builder2.myarray.get(0).intval(0);
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_leaf_array_in_inner_array() {
+ void require_false_for_different_leaf_array_in_inner_array() {
builder2.myarray.get(0).stringval.set(0, "");
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_equal_structs_for_equal_configs() {
+ void require_equal_structs_for_equal_configs() {
assertEquals(config1.basicStruct(), config2.basicStruct());
assertEquals(config1.rootStruct(), config2.rootStruct());
assertEquals(config1.rootStruct().inner0(), config2.rootStruct().inner0());
}
@Test
- public void require_equal_inner_arrays_for_equal_configs() {
+ void require_equal_inner_arrays_for_equal_configs() {
assertEquals(config1.myarray(), config2.myarray());
assertEquals(config1.myarray(0).anotherarray(), config2.myarray(0).anotherarray());
}
@Test
- public void require_equal_inner_array_elements_for_equal_configs() {
+ void require_equal_inner_array_elements_for_equal_configs() {
assertEquals(config1.myarray(0), config2.myarray(0));
assertEquals(config1.myarray(0).anotherarray(0), config2.myarray(0).anotherarray(0));
}
@Test
- public void require_equal_leaf_arrays_for_equal_configs() {
+ void require_equal_leaf_arrays_for_equal_configs() {
assertEquals(config1.intarr(), config2.intarr());
assertEquals(config1.boolarr(), config2.boolarr());
assertEquals(config1.longarr(), config2.longarr());
diff --git a/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java b/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java
index 1192cc6673e..475a33104b0 100644
--- a/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
*/
public class DoubleNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
DoubleNode n = new DoubleNode();
assertFalse(n.doSetValue("invalid"));
assertTrue(n.doSetValue("3.14"));
diff --git a/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java b/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
index fac765f40aa..e7723409736 100644
--- a/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -30,7 +30,7 @@ public class EnumNodeTest {
}
@Test
- public void testEnumNode() {
+ void testEnumNode() {
MyNode n = new MyNode();
assertNull(n.getValue());
assertEquals("(null)", n.toString());
diff --git a/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java b/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java
index 42e4978091d..8bec9378f8f 100644
--- a/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class FileNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
FileNode n = new FileNode();
assertEquals("(null)", n.toString());
assertTrue(n.doSetValue("foo.txt"));
@@ -24,7 +24,7 @@ public class FileNodeTest {
assertEquals("\"foo.txt\"", n.toString());
assertEquals("path may not start with '..', but got: foo/../../boo",
- assertThrows(IllegalArgumentException.class, () -> new FileNode("foo/../../boo")).getMessage());
+ assertThrows(IllegalArgumentException.class, () -> new FileNode("foo/../../boo")).getMessage());
}
}
diff --git a/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java b/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java
index 899e34edce4..a195a5f65fb 100644
--- a/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertTrue;
*/
public class IntegerNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
IntegerNode n = new IntegerNode();
assertFalse(n.setValue("invalid"));
assertTrue(n.setValue("10"));
diff --git a/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java b/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java
index fc603ba65ac..dc6d59bbc46 100644
--- a/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertTrue;
*/
public class LongNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
LongNode n = new LongNode();
assertFalse(n.setValue("invalid"));
assertTrue(n.setValue("10"));
diff --git a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
index 9637ab25278..e6b3b4b6a71 100644
--- a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -15,38 +16,78 @@ import static org.junit.Assert.assertTrue;
*/
public class NodeVectorTest {
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_add_throws_exception() { new TestNodeVector("foo").add(barNode()); }
+ @Test
+ void require_that_add_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").add(barNode());
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addindex_throws_exception() { new TestNodeVector("foo").add(0, barNode()); }
+ @Test
+ void require_that_addindex_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").add(0, barNode());
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addAll_throws_exception() { new TestNodeVector("foo").addAll(Arrays.asList(barNode())); }
+ @Test
+ void require_that_addAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").addAll(Arrays.asList(barNode()));
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addAllindex_throws_exception() { new TestNodeVector("foo").addAll(0, Arrays.asList(barNode())); }
+ @Test
+ void require_that_addAllindex_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").addAll(0, Arrays.asList(barNode()));
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_clear_throws_exception() { new TestNodeVector("foo").clear(); }
+ @Test
+ void require_that_clear_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").clear();
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_remove_index_throws_exception() { new TestNodeVector("foo").remove(0); }
+ @Test
+ void require_that_remove_index_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").remove(0);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_remove_object_throws_exception() { new TestNodeVector("foo").remove(null); }
+ @Test
+ void require_that_remove_object_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").remove(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_removeAll_throws_exception() { new TestNodeVector("foo").removeAll(null); }
+ @Test
+ void require_that_removeAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").removeAll(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_retainAll_throws_exception() { new TestNodeVector("foo").retainAll(null); }
+ @Test
+ void require_that_retainAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").retainAll(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_set_throws_exception() { new TestNodeVector("foo").set(0, null); }
+ @Test
+ void require_that_set_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").set(0, null);
+ });
+ }
@Test
- public void require_that_contains_works() {
+ void require_that_contains_works() {
StringNode val = new StringNode("foo");
TestNodeVector v = new TestNodeVector(val.getValue());
assertTrue(v.contains(val));
@@ -56,7 +97,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_indexOf_works() {
+ void require_that_indexOf_works() {
StringNode val = new StringNode("foo");
TestNodeVector v = new TestNodeVector(val.getValue());
assertFalse(v.isEmpty());
@@ -67,7 +108,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_iterators_work() {
+ void require_that_iterators_work() {
String val = "foo";
TestNodeVector v = new TestNodeVector(val, val, val);
assertTrue(v.listIterator().hasNext());
@@ -78,7 +119,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_sublisting_works() {
+ void require_that_sublisting_works() {
String val = "foo";
TestNodeVector v = new TestNodeVector(val, val, val);
assertEquals(1, v.subList(0, 1).size());
diff --git a/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java b/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
index 016c53b42e3..ad8f5e2e65f 100644
--- a/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author gjoranv
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertThrows;
public class PathNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
PathNode n = new PathNode();
assertEquals("(null)", n.toString());
@@ -23,7 +23,7 @@ public class PathNodeTest {
assertEquals(new File("foo.txt").toPath(), n.value());
assertEquals("path may not start with '..', but got: foo/../../boo",
- assertThrows(IllegalArgumentException.class, () -> new PathNode(new FileReference("foo/../../boo"))).getMessage());
+ assertThrows(IllegalArgumentException.class, () -> new PathNode(new FileReference("foo/../../boo"))).getMessage());
}
}
diff --git a/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java b/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java
index 5d606e12454..d0baf8d1837 100644
--- a/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java
@@ -1,9 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author hmusum
@@ -12,7 +13,7 @@ import static org.junit.Assert.assertEquals;
public class StringNodeTest {
@Test
- public void testUnescapeQuotedString() {
+ void testUnescapeQuotedString() {
String a = "\"Hei\"";
assertEquals("Hei", StringNode.unescapeQuotedString(a));
assertEquals("foo\"bar\"", StringNode.unescapeQuotedString("foo\"bar\""));
@@ -21,13 +22,15 @@ public class StringNodeTest {
assertEquals("U", StringNode.unescapeQuotedString("\\x55"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testUnescapedQuotedStringExceptions() {
- StringNode.unescapeQuotedString("foo\\");
+ @Test
+ void testUnescapedQuotedStringExceptions() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ StringNode.unescapeQuotedString("foo\\");
+ });
}
@Test
- public void testToString() {
+ void testToString() {
StringNode n = new StringNode();
assertEquals("(null)", n.toString());
n.setValue("foo");
@@ -35,7 +38,7 @@ public class StringNodeTest {
}
@Test
- public void testSetValue() {
+ void testSetValue() {
StringNode n = new StringNode();
n.setValue("\"foo\"");
assertEquals("foo", n.getValue());
diff --git a/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java b/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
index abf04c34bb8..1f40cb58a71 100644
--- a/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author lesters
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class UrlNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
UrlNode url = new UrlNode();
assertEquals("(null)", url.toString());
diff --git a/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java b/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
index 54e2271f7dc..39e5f64e5e2 100644
--- a/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
@@ -4,9 +4,9 @@ package com.yahoo.config.codegen;
import com.github.myproject.NamespaceAndPackageConfig;
import com.github.myproject.PackageConfig;
import com.yahoo.my.namespace.NamespaceConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -16,17 +16,17 @@ public class NamespaceAndPackageTest {
private static String PACKAGE = "com.github.myproject";
@Test
- public void namespace_is_set_from_def_file() {
+ void namespace_is_set_from_def_file() {
assertEquals(NAMESPACE, NamespaceConfig.CONFIG_DEF_NAMESPACE);
}
@Test
- public void package_is_used_as_namespace_when_namespace_is_not_set_explicitly() {
+ void package_is_used_as_namespace_when_namespace_is_not_set_explicitly() {
assertEquals(PACKAGE, PackageConfig.CONFIG_DEF_NAMESPACE);
}
@Test
- public void package_does_not_override_namespace() {
+ void package_does_not_override_namespace() {
assertEquals(NAMESPACE, NamespaceAndPackageConfig.CONFIG_DEF_NAMESPACE);
}
diff --git a/config-model-api/abi-spec.json b/config-model-api/abi-spec.json
index 47228cf7768..672ad4071d6 100644
--- a/config-model-api/abi-spec.json
+++ b/config-model-api/abi-spec.json
@@ -71,6 +71,7 @@
"public"
],
"methods": [
+ "public void <init>(java.lang.String, java.lang.Long, boolean, com.yahoo.config.provision.ApplicationId, java.lang.String, java.lang.Long, long)",
"public void <init>(java.lang.String, java.lang.String, java.lang.Long, boolean, com.yahoo.config.provision.ApplicationId, java.lang.String, java.lang.Long, long)",
"public java.lang.String getDeployedByUser()",
"public java.lang.String getDeployPath()",
diff --git a/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationMetaData.java b/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationMetaData.java
index 8eec22ddc5d..a23afd994f2 100644
--- a/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationMetaData.java
+++ b/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationMetaData.java
@@ -17,7 +17,6 @@ import java.io.IOException;
*/
public class ApplicationMetaData {
- private final String deployedByUser;
private final String deployedFromDir;
private final long deployTimestamp;
private final boolean internalRedeploy;
@@ -26,9 +25,15 @@ public class ApplicationMetaData {
private final long generation;
private final long previousActiveGeneration;
- public ApplicationMetaData(String deployedByUser, String deployedFromDir, Long deployTimestamp, boolean internalRedeploy,
+ public ApplicationMetaData(String deployedFromDir, Long deployTimestamp, boolean internalRedeploy,
+ ApplicationId applicationId, String checksum, Long generation, long previousActiveGeneration) {
+ this("unknown", deployedFromDir, deployTimestamp, internalRedeploy, applicationId, checksum, generation, previousActiveGeneration);
+ }
+
+ @Deprecated
+ // TODO: Remove in Vespa 9
+ public ApplicationMetaData(String ignored, String deployedFromDir, Long deployTimestamp, boolean internalRedeploy,
ApplicationId applicationId, String checksum, Long generation, long previousActiveGeneration) {
- this.deployedByUser = deployedByUser;
this.deployedFromDir = deployedFromDir;
this.deployTimestamp = deployTimestamp;
this.internalRedeploy = internalRedeploy;
@@ -40,13 +45,11 @@ public class ApplicationMetaData {
/**
* Gets the user who deployed the application.
- * Will return null if a problem occurred while getting metadata
*
* @return user name for the user who ran "deploy-application"
*/
- public String getDeployedByUser() {
- return deployedByUser;
- }
+ @Deprecated // TODO: Remove in Vespa 9
+ public String getDeployedByUser() { return "unknown"; }
/**
* Gets the directory where the application was deployed from.
@@ -86,8 +89,7 @@ public class ApplicationMetaData {
@Override
public String toString() {
- return deployedByUser + ", " + deployedFromDir + ", " + deployTimestamp + ", " + generation + ", " +
- checksum + ", " + previousActiveGeneration;
+ return deployedFromDir + ", " + deployTimestamp + ", " + generation + ", " + checksum + ", " + previousActiveGeneration;
}
public static ApplicationMetaData fromJsonString(String jsonString) {
@@ -97,8 +99,7 @@ public class ApplicationMetaData {
Inspector deploy = root.field("deploy");
Inspector app = root.field("application");
- return new ApplicationMetaData(deploy.field("user").asString(),
- deploy.field("from").asString(),
+ return new ApplicationMetaData(deploy.field("from").asString(),
deploy.field("timestamp").asLong(),
booleanField("internalRedeploy", false, deploy),
ApplicationId.fromSerializedForm(app.field("id").asString()),
@@ -114,7 +115,6 @@ public class ApplicationMetaData {
Slime slime = new Slime();
Cursor meta = slime.setObject();
Cursor deploy = meta.setObject("deploy");
- deploy.setString("user", deployedByUser);
deploy.setString("from", deployedFromDir);
deploy.setLong("timestamp", deployTimestamp);
deploy.setBool("internalRedeploy", internalRedeploy);
diff --git a/config-model-api/src/main/java/com/yahoo/config/model/api/EndpointCertificateSecrets.java b/config-model-api/src/main/java/com/yahoo/config/model/api/EndpointCertificateSecrets.java
index 952a0562f1d..38c947504ce 100644
--- a/config-model-api/src/main/java/com/yahoo/config/model/api/EndpointCertificateSecrets.java
+++ b/config-model-api/src/main/java/com/yahoo/config/model/api/EndpointCertificateSecrets.java
@@ -3,9 +3,9 @@ package com.yahoo.config.model.api;
public class EndpointCertificateSecrets {
public static final EndpointCertificateSecrets MISSING = new EndpointCertificateSecrets();
-
private final String certificate;
private final String key;
+ private final int version;
private EndpointCertificateSecrets() {
this(null, null);
@@ -14,6 +14,13 @@ public class EndpointCertificateSecrets {
public EndpointCertificateSecrets(String certificate, String key) {
this.certificate = certificate;
this.key = key;
+ this.version = -1;
+ }
+
+ public EndpointCertificateSecrets(String certificate, String key, int version) {
+ this.certificate = certificate;
+ this.key = key;
+ this.version = version;
}
public String certificate() {
@@ -24,7 +31,15 @@ public class EndpointCertificateSecrets {
return key;
}
+ public int version() {
+ return version;
+ }
+
+ public static EndpointCertificateSecrets missing(int version) {
+ return new EndpointCertificateSecrets(null, null, version);
+ }
+
public boolean isMissing() {
- return this == MISSING;
+ return this == MISSING || certificate == null || key == null;
}
}
diff --git a/config-model-api/src/main/java/com/yahoo/config/model/api/ModelContext.java b/config-model-api/src/main/java/com/yahoo/config/model/api/ModelContext.java
index 7611376fffb..4536257f8a3 100644
--- a/config-model-api/src/main/java/com/yahoo/config/model/api/ModelContext.java
+++ b/config-model-api/src/main/java/com/yahoo/config/model/api/ModelContext.java
@@ -77,9 +77,19 @@ public interface ModelContext {
@ModelFeatureFlag(owners = {"baldersheim"}, comment = "Select sequencer type use while feeding") default String feedSequencerType() { return "THROUGHPUT"; }
@ModelFeatureFlag(owners = {"baldersheim"}) default String responseSequencerType() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default int defaultNumResponseThreads() { return 2; }
- @ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipCommunicationManagerThread() { throw new UnsupportedOperationException("TODO specify default value"); }
- @ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipMbusRequestThread() { throw new UnsupportedOperationException("TODO specify default value"); }
- @ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipMbusReplyThread() { throw new UnsupportedOperationException("TODO specify default value"); }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="7.last") default boolean skipCommunicationManagerThread() { return true; }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="7.last") default boolean skipMbusRequestThread() { return true; }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="7.last") default boolean skipMbusReplyThread() { return true; }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="8.15") default boolean mbusDispatchOnDecode() { return true; }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="8.15") default boolean mbusDispatchOnEncode() { return true; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int mbusNetworkThreads() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}, removeAfter="8.15") default int mbusThreads() { return 4; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int mbusJavaRpcNumTargets() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int mbusJavaEventsBeforeWakeup() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int mbusCppRpcNumTargets() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int mbusCppEventsBeforeWakeup() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int rpcNumTargets() { return 1; }
+ @ModelFeatureFlag(owners = {"baldersheim"}) default int rpcEventsBeforeWakeup() { return 1; }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean useAsyncMessageHandlingOnSchedule() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default double feedConcurrency() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default double feedNiceness() { return 0.0; }
@@ -104,7 +114,7 @@ public interface ModelContext {
@ModelFeatureFlag(owners = {"arnej"}) default boolean useV8GeoPositions() { return false; }
@ModelFeatureFlag(owners = {"baldersheim", "geirst", "toregge"}) default int maxCompactBuffers() { return 1; }
@ModelFeatureFlag(owners = {"arnej", "andreer"}) default List<String> ignoredHttpUserAgents() { return List.of(); }
- @ModelFeatureFlag(owners = {"bjorncs"}) default boolean enableServerOcspStapling() { return false; }
+ @ModelFeatureFlag(owners = {"bjorncs"}, removeAfter="7.last") default boolean enableServerOcspStapling() { return true; }
@ModelFeatureFlag(owners = {"vekterli"}) default String mergeThrottlingPolicy() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"vekterli"}) default double persistenceThrottlingWsDecrementFactor() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"vekterli"}) default double persistenceThrottlingWsBackoff() { throw new UnsupportedOperationException("TODO specify default value"); }
diff --git a/config-model/pom.xml b/config-model/pom.xml
index b08ff7f7f2e..d1af9eab915 100644
--- a/config-model/pom.xml
+++ b/config-model/pom.xml
@@ -36,8 +36,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -130,15 +135,15 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java b/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java
index 3da85a83119..400aea86834 100644
--- a/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java
+++ b/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java
@@ -78,6 +78,13 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea
private boolean enableBitVectors = false;
private boolean loadCodeAsHugePages = false;
private boolean sharedStringRepoNoReclaim = false;
+ private int mbus_java_num_targets = 1;
+ private int mbus_java_events_before_wakeup = 1;
+ private int mbus_cpp_num_targets = 1;
+ private int mbus_cpp_events_before_wakeup = 1;
+ private int rpc_num_targets = 1;
+ private int rpc_events_before_wakeup = 1;
+ private int mbus_network_threads = 1;
private Architecture adminClusterNodeResourcesArchitecture = Architecture.getDefault();
@Override public ModelContext.FeatureFlags featureFlags() { return this; }
@@ -101,9 +108,6 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea
@Override public Optional<AthenzDomain> athenzDomain() { return Optional.ofNullable(athenzDomain); }
@Override public String responseSequencerType() { return responseSequencerType; }
@Override public int defaultNumResponseThreads() { return responseNumThreads; }
- @Override public boolean skipCommunicationManagerThread() { return false; }
- @Override public boolean skipMbusRequestThread() { return false; }
- @Override public boolean skipMbusReplyThread() { return false; }
@Override public Quota quota() { return quota; }
@Override public boolean useAsyncMessageHandlingOnSchedule() { return useAsyncMessageHandlingOnSchedule; }
@Override public double feedConcurrency() { return feedConcurrency; }
@@ -136,6 +140,14 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea
@Override public Architecture adminClusterArchitecture() { return adminClusterNodeResourcesArchitecture; }
@Override public boolean sharedStringRepoNoReclaim() { return sharedStringRepoNoReclaim; }
@Override public boolean loadCodeAsHugePages() { return loadCodeAsHugePages; }
+ @Override public int mbusNetworkThreads() { return mbus_network_threads; }
+ @Override public int mbusJavaRpcNumTargets() { return mbus_java_num_targets; }
+ @Override public int mbusJavaEventsBeforeWakeup() { return mbus_java_events_before_wakeup; }
+ @Override public int mbusCppRpcNumTargets() { return mbus_cpp_num_targets; }
+ @Override public int mbusCppEventsBeforeWakeup() { return mbus_cpp_events_before_wakeup; }
+ @Override public int rpcNumTargets() { return rpc_num_targets; }
+ @Override public int rpcEventsBeforeWakeup() { return rpc_events_before_wakeup; }
+
public TestProperties sharedStringRepoNoReclaim(boolean sharedStringRepoNoReclaim) {
this.sharedStringRepoNoReclaim = sharedStringRepoNoReclaim;
@@ -361,6 +373,35 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea
return this;
}
+ public TestProperties setMbusNetworkThreads(int value) {
+ this.mbus_network_threads = value;
+ return this;
+ }
+ public TestProperties setMbusJavaRpcNumTargets(int value) {
+ this.mbus_java_num_targets = value;
+ return this;
+ }
+ public TestProperties setMbusJavaEventsBeforeWakeup(int value) {
+ this.mbus_java_events_before_wakeup = value;
+ return this;
+ }
+ public TestProperties setMbusCppEventsBeforeWakeup(int value) {
+ this.mbus_cpp_events_before_wakeup = value;
+ return this;
+ }
+ public TestProperties setMbusCppRpcNumTargets(int value) {
+ this.mbus_cpp_num_targets = value;
+ return this;
+ }
+ public TestProperties setRpcNumTargets(int value) {
+ this.rpc_num_targets = value;
+ return this;
+ }
+ public TestProperties setRpcEventsBeforeWakeup(int value) {
+ this.rpc_events_before_wakeup = value;
+ return this;
+ }
+
public TestProperties setAdminClusterNodeResourcesArchitecture(Architecture architecture) {
this.adminClusterNodeResourcesArchitecture = architecture;
return this;
@@ -386,12 +427,11 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea
@Override
public boolean equals(Object o) {
- if (o instanceof ConfigServerSpec) {
- ConfigServerSpec other = (ConfigServerSpec)o;
+ if (o instanceof ConfigServerSpec rhsSpec) {
- return hostName.equals(other.getHostName()) &&
- configServerPort == other.getConfigServerPort() &&
- zooKeeperPort == other.getZooKeeperPort();
+ return hostName.equals(rhsSpec.getHostName()) &&
+ configServerPort == rhsSpec.getConfigServerPort() &&
+ zooKeeperPort == rhsSpec.getZooKeeperPort();
} else {
return false;
}
diff --git a/config-model/src/main/java/com/yahoo/config/model/provision/InMemoryProvisioner.java b/config-model/src/main/java/com/yahoo/config/model/provision/InMemoryProvisioner.java
index 102023ba1fd..1c93ce4bd6d 100644
--- a/config-model/src/main/java/com/yahoo/config/model/provision/InMemoryProvisioner.java
+++ b/config-model/src/main/java/com/yahoo/config/model/provision/InMemoryProvisioner.java
@@ -237,7 +237,7 @@ public class InMemoryProvisioner implements HostProvisioner {
.findFirst();
if (hostResources.isEmpty()) {
if (canFail)
- throw new IllegalArgumentException("Insufficient capacity for " + requestedResources);
+ throw new IllegalArgumentException("Insufficient capacity for " + requestedResources + " in cluster " + clusterGroup);
else
break; // ¯\_(ツ)_/¯
}
diff --git a/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java b/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java
index abd7ba3be9f..9ee279c68d3 100644
--- a/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java
+++ b/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java
@@ -1,22 +1,22 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.test;
+import com.yahoo.component.Version;
+import com.yahoo.config.application.api.ApplicationFile;
import com.yahoo.config.application.api.ApplicationMetaData;
+import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.ComponentInfo;
import com.yahoo.config.application.api.UnparsedConfigDefinition;
-import com.yahoo.config.application.api.ApplicationFile;
-import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.io.IOUtils;
-import com.yahoo.path.Path;
import com.yahoo.io.reader.NamedReader;
+import com.yahoo.path.Path;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.vespa.config.ConfigDefinitionKey;
-import com.yahoo.config.application.api.ApplicationPackage;
import java.io.BufferedInputStream;
import java.io.File;
@@ -46,7 +46,6 @@ import java.util.stream.Collectors;
*/
public class MockApplicationPackage implements ApplicationPackage {
- public static final String DEPLOYED_BY_USER = "user";
public static final String APPLICATION_NAME = "application";
public static final long APPLICATION_GENERATION = 1L;
public static final String MUSIC_SCHEMA = createSchema("music", "foo");
@@ -80,8 +79,7 @@ public class MockApplicationPackage implements ApplicationPackage {
this.failOnValidateXml = failOnValidateXml;
queryProfileRegistry = new QueryProfileXMLReader().read(asNamedReaderList(queryProfileType),
asNamedReaderList(queryProfile));
- applicationMetaData = new ApplicationMetaData(DEPLOYED_BY_USER,
- "dir",
+ applicationMetaData = new ApplicationMetaData("dir",
0L,
false,
ApplicationId.from(TenantName.defaultName(),
@@ -165,7 +163,7 @@ public class MockApplicationPackage implements ApplicationPackage {
@Override
public ApplicationFile getFile(Path file) {
if (files.containsKey(file)) return files.get(file);
- return new MockApplicationFile(file, Path.fromString(root.toString()));
+ return new MockApplicationFile(file, root);
}
@Override
@@ -288,7 +286,7 @@ public class MockApplicationPackage implements ApplicationPackage {
Map<Path, MockApplicationFile> mockFiles = new HashMap<>();
for (var file : files.entrySet())
mockFiles.put(file.getKey(), new MockApplicationFile(file.getKey(),
- Path.fromString(root.toString()), file.getValue()));
+ root, file.getValue()));
this.files = mockFiles;
return this;
}
@@ -374,8 +372,8 @@ public class MockApplicationPackage implements ApplicationPackage {
public static class MockApplicationFile extends ApplicationFile {
- /** The path to the application package root */
- private final Path root;
+ /** The application package root */
+ private final File root;
/** The File pointing to the actual file represented by this */
private final File file;
@@ -383,14 +381,14 @@ public class MockApplicationPackage implements ApplicationPackage {
/** The content of this file, or null to read it from the file system. */
private final String content;
- public MockApplicationFile(Path filePath, Path applicationPackagePath) {
- this(filePath, applicationPackagePath, null);
+ public MockApplicationFile(Path relativeFile, File root) {
+ this(relativeFile, root, null);
}
- private MockApplicationFile(Path filePath, Path applicationPackagePath, String content) {
- super(filePath);
- this.root = applicationPackagePath;
- file = applicationPackagePath.append(filePath).toFile();
+ private MockApplicationFile(Path relativeFile, File root, String content) {
+ super(relativeFile);
+ this.root = root;
+ this.file = root.toPath().resolve(relativeFile.toString()).toFile();
this.content = content;
}
@@ -491,7 +489,7 @@ public class MockApplicationPackage implements ApplicationPackage {
Iterator<String> pathIterator = path.iterator();
// Skip the path elements this shares with the root
- for (Iterator<String> rootIterator = root.iterator(); rootIterator.hasNext(); ) {
+ for (Iterator<String> rootIterator = Path.fromString(root.toString()).iterator(); rootIterator.hasNext(); ) {
String rootElement = rootIterator.next();
String pathElement = pathIterator.next();
if ( ! rootElement.equals(pathElement)) throw new RuntimeException("Assumption broken");
diff --git a/config-model/src/main/java/com/yahoo/config/model/test/MockRoot.java b/config-model/src/main/java/com/yahoo/config/model/test/MockRoot.java
index 7e2953e6606..74a5e92d2ba 100644
--- a/config-model/src/main/java/com/yahoo/config/model/test/MockRoot.java
+++ b/config-model/src/main/java/com/yahoo/config/model/test/MockRoot.java
@@ -61,7 +61,7 @@ public class MockRoot extends AbstractConfigProducerRoot {
public MockRoot(String rootConfigId, DeployState deployState) {
super(rootConfigId);
- hostSystem = new HostSystem(this, "hostsystem", deployState.getProvisioner(), deployState.getDeployLogger());
+ hostSystem = new HostSystem(this, "hostsystem", deployState.getProvisioner(), deployState.getDeployLogger(), deployState.isHosted());
this.deployState = deployState;
fileReferencesRepository = new FileReferencesRepository(deployState.getFileRegistry());
}
diff --git a/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java b/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java
index d98709569b1..894415091e4 100644
--- a/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java
+++ b/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java
@@ -107,7 +107,7 @@ public class ApplicationBuilder {
this(MockApplicationPackage.createEmpty(), new MockFileRegistry(), new BaseDeployLogger(), properties, rankProfileRegistry, queryProfileRegistry);
}
- /** normal constructor */
+ /** Regular constructor */
public ApplicationBuilder(ApplicationPackage app,
FileRegistry fileRegistry,
DeployLogger deployLogger,
diff --git a/config-model/src/main/java/com/yahoo/schema/derived/IndexInfo.java b/config-model/src/main/java/com/yahoo/schema/derived/IndexInfo.java
index 4887ad52974..277858bed26 100644
--- a/config-model/src/main/java/com/yahoo/schema/derived/IndexInfo.java
+++ b/config-model/src/main/java/com/yahoo/schema/derived/IndexInfo.java
@@ -178,13 +178,11 @@ public class IndexInfo extends Derived implements IndexInfoConfig.Producer {
PrimitiveDataType primitive = dataType.getPrimitiveType();
if (primitive == PrimitiveDataType.STRING) return true;
if (primitive != null) return false;
- if (dataType instanceof StructuredDataType) {
- StructuredDataType structured = (StructuredDataType) dataType;
+ if (dataType instanceof StructuredDataType structured) {
for (Field field : structured.getFields()) {
if (isAnyChildString(field.getDataType())) return true;
}
- } else if (dataType instanceof MapDataType) {
- MapDataType mapType = (MapDataType) dataType;
+ } else if (dataType instanceof MapDataType mapType) {
return isAnyChildString(mapType.getKeyType()) || isAnyChildString(mapType.getValueType());
}
return false;
@@ -494,9 +492,9 @@ public class IndexInfo extends Derived implements IndexInfoConfig.Producer {
*/
public static class IndexCommand {
- private String index;
+ private final String index;
- private String command;
+ private final String command;
public IndexCommand(String index, String command) {
this.index = index;
@@ -523,14 +521,12 @@ public class IndexInfo extends Derived implements IndexInfoConfig.Producer {
}
public boolean equals(Object object) {
- if (!(object instanceof IndexCommand)) {
+ if (!(object instanceof IndexCommand other)) {
return false;
}
- IndexCommand other = (IndexCommand)object;
- return
- other.index.equals(this.index) &&
- other.command.equals(this.command);
+ return other.index.equals(this.index) &&
+ other.command.equals(this.command);
}
public String toString() {
@@ -544,7 +540,7 @@ public class IndexInfo extends Derived implements IndexInfoConfig.Producer {
*/
private static abstract class IndexOverrider {
- protected IndexInfo owner;
+ protected final IndexInfo owner;
public IndexOverrider(IndexInfo owner) {
this.owner = owner;
@@ -560,7 +556,7 @@ public class IndexInfo extends Derived implements IndexInfoConfig.Producer {
private static class StemmingOverrider extends IndexOverrider {
- private Schema schema;
+ private final Schema schema;
public StemmingOverrider(IndexInfo owner, Schema schema) {
super(owner);
diff --git a/config-model/src/main/java/com/yahoo/schema/derived/SummaryClass.java b/config-model/src/main/java/com/yahoo/schema/derived/SummaryClass.java
index 193c6893203..efc64a5aa40 100644
--- a/config-model/src/main/java/com/yahoo/schema/derived/SummaryClass.java
+++ b/config-model/src/main/java/com/yahoo/schema/derived/SummaryClass.java
@@ -59,7 +59,7 @@ public class SummaryClass extends Derived {
/** MUST be called after all other fields are added */
private void deriveImplicitFields(DocumentSummary summary, Map<String, SummaryClassField> fields) {
if (summary.getName().equals("default")) {
- addField(SummaryClass.DOCUMENT_ID_FIELD, DataType.STRING, fields);
+ addField(SummaryClass.DOCUMENT_ID_FIELD, DataType.STRING, SummaryTransform.DOCUMENT_ID, fields);
}
}
@@ -72,10 +72,6 @@ public class SummaryClass extends Derived {
}
}
- private void addField(String name, DataType type, Map<String, SummaryClassField> fields) {
- addField(name, type, null, fields);
- }
-
private void addField(String name, DataType type,
SummaryTransform transform,
Map<String, SummaryClassField> fields) {
diff --git a/config-model/src/main/java/com/yahoo/schema/derived/SummaryMap.java b/config-model/src/main/java/com/yahoo/schema/derived/SummaryMap.java
index 40d763eb897..9d3d00f1481 100644
--- a/config-model/src/main/java/com/yahoo/schema/derived/SummaryMap.java
+++ b/config-model/src/main/java/com/yahoo/schema/derived/SummaryMap.java
@@ -30,6 +30,7 @@ public class SummaryMap extends Derived implements SummarymapConfig.Producer {
for (DocumentSummary documentSummary : schema.getSummaries().values()) {
derive(documentSummary);
}
+ addSummaryTransformForDocumentId();
super.derive(schema);
}
@@ -37,11 +38,22 @@ public class SummaryMap extends Derived implements SummarymapConfig.Producer {
protected void derive(ImmutableSDField field, Schema schema) {
}
+ private void addSummaryTransformForDocumentId() {
+ // The 'documentid' field is added to the 'default' summary class in SummaryClass.deriveImplicitFields().
+ // This ensures the corresponding transform is added as well.
+ if (!resultTransforms.containsKey(SummaryClass.DOCUMENT_ID_FIELD)) {
+ resultTransforms.put(SummaryClass.DOCUMENT_ID_FIELD,
+ new FieldResultTransform(SummaryClass.DOCUMENT_ID_FIELD, SummaryTransform.DOCUMENT_ID, ""));
+ }
+ }
+
private void derive(DocumentSummary documentSummary) {
for (SummaryField summaryField : documentSummary.getSummaryFields().values()) {
if (summaryField.getTransform()== SummaryTransform.NONE) continue;
if (summaryField.getTransform()==SummaryTransform.ATTRIBUTE ||
+ (summaryField.getTransform()==SummaryTransform.ATTRIBUTECOMBINER && summaryField.hasExplicitSingleSource()) ||
+ summaryField.getTransform()==SummaryTransform.COPY ||
summaryField.getTransform()==SummaryTransform.DISTANCE ||
summaryField.getTransform()==SummaryTransform.GEOPOS ||
summaryField.getTransform()==SummaryTransform.POSITIONS ||
@@ -57,7 +69,7 @@ public class SummaryMap extends Derived implements SummarymapConfig.Producer {
// This works, but is suboptimal. We could consolidate to a minimal set and
// use the right value from the minimal set as the third parameter here,
// and add "override" commands to multiple static values
- boolean useFieldNameAsArgument = summaryField.getTransform().isDynamic() || summaryField.getTransform() == SummaryTransform.TEXTEXTRACTOR;
+ boolean useFieldNameAsArgument = summaryField.getTransform().isDynamic();
resultTransforms.put(summaryField.getName(), new FieldResultTransform(summaryField.getName(),
summaryField.getTransform(),
useFieldNameAsArgument ? summaryField.getName() : ""));
diff --git a/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java b/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java
index 335942de99d..221280dc1e4 100644
--- a/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java
+++ b/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java
@@ -83,6 +83,11 @@ public class ImmutableImportedSDField implements ImmutableSDField {
}
@Override
+ public boolean wasConfiguredToDoIndexing() {
+ return importedField.targetField().wasConfiguredToDoIndexing();
+ }
+
+ @Override
public DataType getDataType() {
return importedField.targetField().getDataType();
}
diff --git a/config-model/src/main/java/com/yahoo/schema/document/ImmutableSDField.java b/config-model/src/main/java/com/yahoo/schema/document/ImmutableSDField.java
index 44e442811ba..37cbb3a8171 100644
--- a/config-model/src/main/java/com/yahoo/schema/document/ImmutableSDField.java
+++ b/config-model/src/main/java/com/yahoo/schema/document/ImmutableSDField.java
@@ -45,6 +45,14 @@ public interface ImmutableSDField {
*/
boolean wasConfiguredToDoAttributing();
+ /**
+ * Whether this field at some time was configured to do indexing.
+ *
+ * This function can typically return a different value than doesIndexing(),
+ * which uses the final state of the underlying indexing script instead.
+ */
+ boolean wasConfiguredToDoIndexing();
+
DataType getDataType();
Index getIndex(String name);
diff --git a/config-model/src/main/java/com/yahoo/schema/document/SDField.java b/config-model/src/main/java/com/yahoo/schema/document/SDField.java
index 943d6c6fc14..2d79d89a2a0 100644
--- a/config-model/src/main/java/com/yahoo/schema/document/SDField.java
+++ b/config-model/src/main/java/com/yahoo/schema/document/SDField.java
@@ -117,6 +117,7 @@ public class SDField extends Field implements TypedKey, ImmutableSDField {
private boolean isExtraField = false;
private boolean wasConfiguredToDoAttributing = false;
+ private boolean wasConfiguredToDoIndexing = false;
/**
* Creates a new field. This method is only used to create reserved fields.
@@ -381,6 +382,11 @@ public class SDField extends Field implements TypedKey, ImmutableSDField {
return wasConfiguredToDoAttributing;
}
+ @Override
+ public boolean wasConfiguredToDoIndexing() {
+ return wasConfiguredToDoIndexing;
+ }
+
/** Parse an indexing expression which will use the simple linguistics implementation suitable for testing */
public void parseIndexingScript(String script) {
parseIndexingScript(script, new SimpleLinguistics(), Embedder.throwsOnUse.asMap());
@@ -408,6 +414,9 @@ public class SDField extends Field implements TypedKey, ImmutableSDField {
if (!wasConfiguredToDoAttributing()) {
wasConfiguredToDoAttributing = doesAttributing();
}
+ if (!wasConfiguredToDoIndexing()) {
+ wasConfiguredToDoIndexing = doesIndexing();
+ }
if (!usesStructOrMap()) {
new ExpressionVisitor() {
diff --git a/config-model/src/main/java/com/yahoo/schema/parser/IntermediateCollection.java b/config-model/src/main/java/com/yahoo/schema/parser/IntermediateCollection.java
index 8bb9bca3249..139d20aac82 100644
--- a/config-model/src/main/java/com/yahoo/schema/parser/IntermediateCollection.java
+++ b/config-model/src/main/java/com/yahoo/schema/parser/IntermediateCollection.java
@@ -26,7 +26,7 @@ public class IntermediateCollection {
private final DeployLogger deployLogger;
private final ModelContext.Properties modelProperties;
- private Map<String, ParsedSchema> parsedSchemas = new LinkedHashMap<>();
+ private final Map<String, ParsedSchema> parsedSchemas = new LinkedHashMap<>();
IntermediateCollection() {
this.deployLogger = new BaseDeployLogger();
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/AddExtraFieldsToDocument.java b/config-model/src/main/java/com/yahoo/schema/processing/AddExtraFieldsToDocument.java
index ca81301da73..3afc25131c0 100644
--- a/config-model/src/main/java/com/yahoo/schema/processing/AddExtraFieldsToDocument.java
+++ b/config-model/src/main/java/com/yahoo/schema/processing/AddExtraFieldsToDocument.java
@@ -38,7 +38,7 @@ public class AddExtraFieldsToDocument extends Processor {
case BOLDED:
case DYNAMICBOLDED:
case DYNAMICTEASER:
- case TEXTEXTRACTOR:
+ case DOCUMENT_ID: // TODO: Adding the 'documentid' field should no longer be needed when the docsum framework in the backend has been simplified and the transform is always used.
addSummaryField(schema, document, summaryField, validate);
break;
default:
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java b/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java
index e39b78d0d9f..648ed085a54 100644
--- a/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java
+++ b/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java
@@ -36,6 +36,7 @@ import java.util.logging.Level;
*/
public class CreatePositionZCurve extends Processor {
+ private boolean useV8GeoPositions = false;
private final SDDocumentType repo;
public CreatePositionZCurve(Schema schema, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles) {
@@ -43,8 +44,6 @@ public class CreatePositionZCurve extends Processor {
this.repo = schema.getDocument();
}
- private boolean useV8GeoPositions = false;
-
@Override
public void process(boolean validate, boolean documentsOnly, ModelContext.Properties properties) {
this.useV8GeoPositions = properties.featureFlags().useV8GeoPositions();
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/Processing.java b/config-model/src/main/java/com/yahoo/schema/processing/Processing.java
index 63eca2121c1..8f7e8daeed0 100644
--- a/config-model/src/main/java/com/yahoo/schema/processing/Processing.java
+++ b/config-model/src/main/java/com/yahoo/schema/processing/Processing.java
@@ -52,6 +52,7 @@ public class Processing {
ImplicitSummaries::new,
ImplicitSummaryFields::new,
AdjustPositionSummaryFields::new,
+ SummaryTransformForDocumentId::new,
SummaryConsistency::new,
SummaryNamesFieldCollisions::new,
SummaryFieldsMustHaveValidSource::new,
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/RankingExpressionTypeResolver.java b/config-model/src/main/java/com/yahoo/schema/processing/RankingExpressionTypeResolver.java
index 07f79f16334..d985089b2cb 100644
--- a/config-model/src/main/java/com/yahoo/schema/processing/RankingExpressionTypeResolver.java
+++ b/config-model/src/main/java/com/yahoo/schema/processing/RankingExpressionTypeResolver.java
@@ -93,9 +93,9 @@ public class RankingExpressionTypeResolver extends Processor {
throw new IllegalArgumentException(profile + " is strict but is missing a query profile type " +
"declaration of features " + context.queryFeaturesNotDeclared());
else
- deployLogger.logApplicationPackage(Level.WARNING, "The following query features used in " + profile +
- " are not declared in query profile " +
- "types and will be interpreted as scalars, not tensors: " +
+ deployLogger.logApplicationPackage(Level.WARNING, "The following query features used in " +
+ profile + " are not declared " +
+ "and will be interpreted as scalars, not tensors: " +
context.queryFeaturesNotDeclared());
warnedAbout.addAll(context.queryFeaturesNotDeclared());
}
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/SummaryConsistency.java b/config-model/src/main/java/com/yahoo/schema/processing/SummaryConsistency.java
index 4fb45c3c68f..4aa8f6f0e37 100644
--- a/config-model/src/main/java/com/yahoo/schema/processing/SummaryConsistency.java
+++ b/config-model/src/main/java/com/yahoo/schema/processing/SummaryConsistency.java
@@ -37,6 +37,7 @@ public class SummaryConsistency extends Processor {
assertConsistency(summaryField, schema, validate);
makeAttributeTransformIfAppropriate(summaryField, schema);
makeAttributeCombinerTransformIfAppropriate(summaryField, schema);
+ makeCopyTransformIfAppropriate(summaryField, schema);
}
}
}
@@ -70,14 +71,27 @@ public class SummaryConsistency extends Processor {
/** If the source is a complex field with only struct field attributes then make this use the attribute combiner transform */
private void makeAttributeCombinerTransformIfAppropriate(SummaryField summaryField, Schema schema) {
if (summaryField.getTransform() == SummaryTransform.NONE) {
- String source_field_name = summaryField.getSingleSource();
- ImmutableSDField source = schema.getField(source_field_name);
+ String sourceFieldName = summaryField.getSingleSource();
+ ImmutableSDField source = schema.getField(sourceFieldName);
if (source != null && isComplexFieldWithOnlyStructFieldAttributes(source)) {
summaryField.setTransform(SummaryTransform.ATTRIBUTECOMBINER);
}
}
}
+ /*
+ * This function must be called after makeAttributeCombinerTransformIfAppropriate().
+ */
+ private void makeCopyTransformIfAppropriate(SummaryField summaryField, Schema schema) {
+ if (summaryField.getTransform() == SummaryTransform.NONE) {
+ String sourceFieldName = summaryField.getSingleSource();
+ ImmutableSDField source = schema.getField(sourceFieldName);
+ if (source != null && source.usesStructOrMap() && summaryField.hasExplicitSingleSource()) {
+ summaryField.setTransform(SummaryTransform.COPY);
+ }
+ }
+ }
+
private void assertConsistentTypes(SummaryField existing, SummaryField seen) {
if (existing.getDataType() instanceof WeightedSetDataType && seen.getDataType() instanceof WeightedSetDataType &&
((WeightedSetDataType)existing.getDataType()).getNestedType().equals(((WeightedSetDataType)seen.getDataType()).getNestedType()))
diff --git a/config-model/src/main/java/com/yahoo/schema/processing/SummaryTransformForDocumentId.java b/config-model/src/main/java/com/yahoo/schema/processing/SummaryTransformForDocumentId.java
new file mode 100644
index 00000000000..99419ecd526
--- /dev/null
+++ b/config-model/src/main/java/com/yahoo/schema/processing/SummaryTransformForDocumentId.java
@@ -0,0 +1,32 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.schema.processing;
+
+import com.yahoo.config.application.api.DeployLogger;
+import com.yahoo.schema.RankProfileRegistry;
+import com.yahoo.schema.Schema;
+import com.yahoo.schema.derived.SummaryClass;
+import com.yahoo.vespa.documentmodel.SummaryTransform;
+import com.yahoo.vespa.model.container.search.QueryProfiles;
+
+/**
+ * Adds the corresponding summary transform for all "documentid" summary fields.
+ *
+ * @author geirst
+ */
+public class SummaryTransformForDocumentId extends Processor {
+
+ public SummaryTransformForDocumentId(Schema schema, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles) {
+ super(schema, deployLogger, rankProfileRegistry, queryProfiles);
+ }
+
+ @Override
+ public void process(boolean validate, boolean documentsOnly) {
+ for (var summary : schema.getSummaries().values()) {
+ for (var summaryField : summary.getSummaryFields().values()) {
+ if (summaryField.getName().equals(SummaryClass.DOCUMENT_ID_FIELD)) {
+ summaryField.setTransform(SummaryTransform.DOCUMENT_ID);
+ }
+ }
+ }
+ }
+}
diff --git a/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentManager.java b/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentManager.java
index e54ed1f1a8b..c6fcd4c115c 100644
--- a/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentManager.java
+++ b/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentManager.java
@@ -36,14 +36,13 @@ public class DocumentManager {
private boolean useV8GeoPositions = false;
- public DocumentManager useV8GeoPositions(boolean value) {
- this.useV8GeoPositions = value;
+ public DocumentManager useV8GeoPositions(boolean useV8GeoPositions) {
+ this.useV8GeoPositions = useV8GeoPositions;
return this;
}
public DocumentmanagerConfig.Builder produce(DocumentModel model,
- DocumentmanagerConfig.Builder documentConfigBuilder)
- {
+ DocumentmanagerConfig.Builder documentConfigBuilder) {
return produceDocTypes(model, documentConfigBuilder);
}
@@ -75,6 +74,7 @@ public class DocumentManager {
}
static private class IdxMap {
+
private final Map<Integer, Boolean> doneMap = new HashMap<>();
private final Map<String, Integer> map = new HashMap<>();
private final DataTypeRecognizer recognizer = new DataTypeRecognizer();
diff --git a/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentTypes.java b/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentTypes.java
index 549b94adc02..d62270034f0 100644
--- a/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentTypes.java
+++ b/config-model/src/main/java/com/yahoo/vespa/configmodel/producers/DocumentTypes.java
@@ -33,6 +33,7 @@ import java.util.Set;
* @author baldersheim
*/
public class DocumentTypes {
+
private boolean useV8GeoPositions = false;
public DocumentTypes useV8GeoPositions(boolean value) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/documentmodel/DocumentModel.java b/config-model/src/main/java/com/yahoo/vespa/documentmodel/DocumentModel.java
index 15599c567ab..76f0bbd854e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/documentmodel/DocumentModel.java
+++ b/config-model/src/main/java/com/yahoo/vespa/documentmodel/DocumentModel.java
@@ -4,20 +4,18 @@ package com.yahoo.vespa.documentmodel;
import com.yahoo.documentmodel.DocumentTypeRepo;
/**
- * DocumentModel represents everything derived from a set of search definitions.
- * It contains a document manager managing all defined document types.
- * It contains a search manager managing all specified search definitions.
- * It contains a storage manager managing all specified storage definitions.
+ * DocumentModel represents everything derived from a set of schemas.
+ * It contains a document manager managing all defined document types, and
+ * a search manager managing all search aspects of the schemas.
*
* @author baldersheim
*/
public class DocumentModel {
- private final DocumentTypeRepo documentMan = new DocumentTypeRepo();
- private final SearchManager searchMan = new SearchManager();
+ private final DocumentTypeRepo documentManager = new DocumentTypeRepo();
+ private final SearchManager searchManager = new SearchManager();
- public DocumentTypeRepo getDocumentManager() { return documentMan; }
-
- public SearchManager getSearchManager() { return searchMan; }
+ public DocumentTypeRepo getDocumentManager() { return documentManager; }
+ public SearchManager getSearchManager() { return searchManager; }
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryField.java b/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryField.java
index ed6668f0d0d..58044163885 100644
--- a/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryField.java
+++ b/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryField.java
@@ -263,6 +263,22 @@ public class SummaryField extends Field implements Cloneable, TypedKey {
}
}
+ /**
+ * Returns true if the summary field uses an explicit source, i.e.
+ * a field with different name that is not a nested field.
+ */
+ public boolean hasExplicitSingleSource() {
+ String fieldName = getName();
+ String sourceName = getSingleSource();
+ if (fieldName.equals(sourceName)) {
+ return false;
+ }
+ if (sourceName.contains(".")) {
+ return false;
+ }
+ return true;
+ }
+
public VsmCommand getVsmCommand() {
return vsmCommand;
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryTransform.java b/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryTransform.java
index c50766a2585..e94518c988d 100644
--- a/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryTransform.java
+++ b/config-model/src/main/java/com/yahoo/vespa/documentmodel/SummaryTransform.java
@@ -18,11 +18,12 @@ public enum SummaryTransform {
POSITIONS("positions"),
RANKFEATURES("rankfeatures"),
SUMMARYFEATURES("summaryfeatures"),
- TEXTEXTRACTOR("textextractor"),
GEOPOS("geopos"),
ATTRIBUTECOMBINER("attributecombiner"),
MATCHED_ELEMENTS_FILTER("matchedelementsfilter"),
- MATCHED_ATTRIBUTE_ELEMENTS_FILTER("matchedattributeelementsfilter");
+ MATCHED_ATTRIBUTE_ELEMENTS_FILTER("matchedattributeelementsfilter"),
+ COPY("copy"),
+ DOCUMENT_ID("documentid");
private final String name;
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/HostSystem.java b/config-model/src/main/java/com/yahoo/vespa/model/HostSystem.java
index 6e63a1d9e68..fcad1e20c16 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/HostSystem.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/HostSystem.java
@@ -18,6 +18,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.function.BiConsumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@@ -39,30 +40,34 @@ public class HostSystem extends AbstractConfigProducer<Host> {
private final Map<String, HostResource> hostname2host = new LinkedHashMap<>();
private final HostProvisioner provisioner;
private final DeployLogger deployLogger;
+ private final boolean isHosted;
static {
String checkIpProperty = System.getProperty("config_model.ip_check", "true");
doCheckIp = ! checkIpProperty.equalsIgnoreCase("false");
}
- public HostSystem(AbstractConfigProducer<?> parent, String name, HostProvisioner provisioner, DeployLogger deployLogger) {
+ public HostSystem(AbstractConfigProducer<?> parent, String name, HostProvisioner provisioner, DeployLogger deployLogger, boolean isHosted) {
super(parent, name);
this.provisioner = provisioner;
this.deployLogger = deployLogger;
+ this.isHosted = isHosted;
}
void checkName(String hostname) {
if (doCheckIp) {
+ // Bad DNS config in a hosted system isn't actionable by the tenant, so we log any warnings internally
+ BiConsumer<Level, String> logFunction = isHosted ? deployLogger::log : deployLogger::logApplicationPackage;
// Give a warning if the host does not exist
try {
var inetAddr = java.net.InetAddress.getByName(hostname);
String canonical = inetAddr.getCanonicalHostName();
if (!hostname.equals(canonical)) {
- deployLogger.logApplicationPackage(Level.WARNING, "Host named '" + hostname + "' may not receive any config " +
- "since it differs from its canonical hostname '" + canonical + "' (check DNS and /etc/hosts).");
+ logFunction.accept(Level.WARNING, "Host named '" + hostname + "' may not receive any config " +
+ "since it differs from its canonical hostname '" + canonical + "' (check DNS and /etc/hosts).");
}
} catch (UnknownHostException e) {
- deployLogger.logApplicationPackage(Level.WARNING, "Unable to lookup IP address of host: " + hostname);
+ logFunction.accept(Level.WARNING, "Unable to lookup IP address of host: " + hostname);
}
}
}
@@ -139,7 +144,7 @@ public class HostSystem extends AbstractConfigProducer<Host> {
private Optional<HostResource> getExistingHost(HostSpec key) {
List<HostResource> hosts = hostname2host.values().stream()
.filter(resource -> resource.getHostname().equals(key.hostname()))
- .collect(Collectors.toList());
+ .toList();
if (hosts.isEmpty()) {
return Optional.empty();
} else {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/Logserver.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/Logserver.java
index d5a0b97a416..6f0e5a775e9 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/Logserver.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/Logserver.java
@@ -7,8 +7,7 @@ import com.yahoo.vespa.model.AbstractService;
import com.yahoo.vespa.model.PortAllocBridge;
/**
- * Represents the Logserver. There is exactly one logserver in a Vespa
- * system.
+ * Represents the Logserver. There is exactly one logserver in a Vespa system.
*
* @author gjoranv
* @author bjorncs
@@ -42,9 +41,7 @@ public class Logserver extends AbstractService {
return "exec $ROOT/bin/vespa-logserver-start " + getMyJVMArgs() + " " + getJvmOptions();
}
- /**
- * @return the jvm args to be used by the logserver.
- */
+ /** Returns the jvm args to be used by the logserver. */
private String getMyJVMArgs() {
StringBuilder sb = new StringBuilder();
sb.append("--add-opens=java.base/java.io=ALL-UNNAMED");
@@ -57,9 +54,7 @@ public class Logserver extends AbstractService {
return sb.toString();
}
- /**
- * Returns the desired base port for this service.
- */
+ /** Returns the desired base port for this service. */
public int getWantedPort() {
return 19080;
}
@@ -73,9 +68,7 @@ public class Logserver extends AbstractService {
return true; // TODO Support dynamic port allocation for logserver
}
- /**
- * @return the number of ports needed by the logserver.
- */
+ /** Returns the number of ports needed by the logserver. */
public int getPortCount() {
return 4;
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java
index 75b13a89e83..c50b9b7f842 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java
@@ -36,7 +36,7 @@ public class LogserverContainerCluster extends ContainerCluster<LogserverContain
protected boolean messageBusEnabled() { return false; }
private void addLogHandler() {
- Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
+ Handler logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings(SystemBindingPattern.fromHttpPath("/logs"));
addComponent(logHandler);
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerCluster.java
index bf3ba084091..88acf6cafb8 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerCluster.java
@@ -49,6 +49,7 @@ public class ClusterControllerCluster extends AbstractConfigProducer<ClusterCont
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.clientPort(ZK_CLIENT_PORT);
builder.juteMaxBuffer(1024 * 1024); // 1 Mb should be more than enough for cluster controller
+ builder.snapshotCount(1000); // Use a low value, few transactions per time unit in cluster controller
for (ClusterControllerContainer container : containerCluster.getContainers()) {
ZookeeperServerConfig.Server.Builder serverBuilder = new ZookeeperServerConfig.Server.Builder();
serverBuilder.hostname(container.getHostName());
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainer.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainer.java
index f303da6c9f0..5d60cec0679 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainer.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainer.java
@@ -49,7 +49,7 @@ public class ClusterControllerContainer extends Container implements
private static final int DEFAULT_NETTY_NUM_DIRECT_ARENAS = 1; // Reduced from nettys default of 2*cores
private static final int DEFAULT_NETTY_NUM_HEAP_ARENAS = 1; // Reduced from nettys default of 2*cores
- private final Set<String> bundles = new TreeSet<>();
+ private final Set<String> bundles = new TreeSet<>(); // Ensure stable ordering
public ClusterControllerContainer(AbstractConfigProducer<?> parent,
int index,
@@ -118,7 +118,7 @@ public class ClusterControllerContainer extends Container implements
ZOOKEEPER_SERVER_BUNDLE);
}
- private void addHandler(Handler<?> h, String path) {
+ private void addHandler(Handler h, String path) {
h.addServerBindings(SystemBindingPattern.fromHttpPath(path));
super.addHandler(h);
}
@@ -138,7 +138,7 @@ public class ClusterControllerContainer extends Container implements
}
private void addHandler(String id, String className, String path, ComponentSpecification bundle) {
- addHandler(new Handler<>(createComponentModel(id, className, bundle)), path);
+ addHandler(new Handler(createComponentModel(id, className, bundle)), path);
}
private ReindexingContext reindexingContext() {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
index a7f3a6224f2..f7007fec181 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
@@ -7,8 +7,12 @@ import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
+import java.nio.file.Path;
+import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
/**
* Container cluster for cluster-controller containers.
@@ -18,6 +22,8 @@ import java.util.Optional;
*/
public class ClusterControllerContainerCluster extends ContainerCluster<ClusterControllerContainer> {
+ private static final Set<Path> UNNECESSARY_BUNDLES = Collections.unmodifiableSet(PlatformBundles.VESPA_SECURITY_BUNDLES);
+
private final ReindexingContext reindexingContext;
public ClusterControllerContainerCluster(
@@ -29,6 +35,9 @@ public class ClusterControllerContainerCluster extends ContainerCluster<ClusterC
}
@Override
+ protected Set<Path> unnecessaryPlatformBundles() { return UNNECESSARY_BUNDLES; }
+
+ @Override
protected void doPrepare(DeployState deployState) { }
@Override protected boolean messageBusEnabled() { return false; }
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
index a29647b062a..17f169033d3 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
@@ -36,16 +36,19 @@ import com.yahoo.vespa.model.admin.monitoring.MetricSet;
import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer;
import com.yahoo.vespa.model.admin.monitoring.Monitoring;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
-import com.yahoo.vespa.model.container.PlatformBundles;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static com.yahoo.vespa.model.admin.metricsproxy.ConsumersConfigGenerator.addMetrics;
import static com.yahoo.vespa.model.admin.metricsproxy.ConsumersConfigGenerator.generateConsumers;
@@ -75,6 +78,12 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC
static final Path METRICS_PROXY_BUNDLE_FILE = PlatformBundles.absoluteBundlePath(METRICS_PROXY_NAME);
static final String METRICS_PROXY_BUNDLE_NAME = "com.yahoo.vespa." + METRICS_PROXY_NAME;
+ private static final Set<Path> UNNECESSARY_BUNDLES = Stream.concat
+ (
+ PlatformBundles.VESPA_SECURITY_BUNDLES.stream(),
+ PlatformBundles.VESPA_ZK_BUNDLES.stream()
+ ).collect(Collectors.toSet());
+
static final class AppDimensionNames {
static final String SYSTEM = "system";
static final String TENANT = "tenantName";
@@ -98,6 +107,9 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC
addClusterComponents();
}
+ @Override
+ protected Set<Path> unnecessaryPlatformBundles() { return UNNECESSARY_BUNDLES; }
+
private void addClusterComponents() {
addMetricsProxyComponent(ApplicationDimensions.class);
addMetricsProxyComponent(ConfigSentinelClient.class);
@@ -119,12 +131,12 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC
}
private void addHttpHandler(Class<? extends ThreadedHttpRequestHandler> clazz, String bindingPath) {
- Handler<AbstractConfigProducer<?>> metricsHandler = createMetricsHandler(clazz, bindingPath);
+ Handler metricsHandler = createMetricsHandler(clazz, bindingPath);
addComponent(metricsHandler);
}
- static Handler<AbstractConfigProducer<?>> createMetricsHandler(Class<? extends ThreadedHttpRequestHandler> clazz, String bindingPath) {
- Handler<AbstractConfigProducer<?>> metricsHandler = new Handler<>(
+ static Handler createMetricsHandler(Class<? extends ThreadedHttpRequestHandler> clazz, String bindingPath) {
+ Handler metricsHandler = new Handler(
new ComponentModel(clazz.getName(), null, METRICS_PROXY_BUNDLE_NAME, null));
metricsHandler.addServerBindings(
SystemBindingPattern.fromHttpPath(bindingPath),
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/DefaultMetrics.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/DefaultMetrics.java
index 5e10001baf6..2348970ed1a 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/DefaultMetrics.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/DefaultMetrics.java
@@ -33,7 +33,7 @@ public class DefaultMetrics {
return ImmutableSet.<Metric>builder()
.addAll(getContentMetrics())
.addAll(getContainerMetrics())
- .addAll(getQrserverMetrics())
+ .addAll(getSearchChainMetrics())
.build();
}
@@ -51,15 +51,24 @@ public class DefaultMetrics {
return metrics;
}
- private static Set<Metric> getQrserverMetrics() {
+ private static Set<Metric> getSearchChainMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("queries.rate"));
- metrics.add(new Metric("query_latency.average"));
+ metrics.add(new Metric("query_latency.sum"));
+ metrics.add(new Metric("query_latency.count"));
+ metrics.add(new Metric("query_latency.max"));
+ metrics.add(new Metric("query_latency.average")); // TODO: Remove with Vespa 9
metrics.add(new Metric("query_latency.95percentile"));
metrics.add(new Metric("query_latency.99percentile"));
- metrics.add(new Metric("hits_per_query.average"));
- metrics.add(new Metric("totalhits_per_query.average"));
+ metrics.add(new Metric("hits_per_query.sum"));
+ metrics.add(new Metric("hits_per_query.count"));
+ metrics.add(new Metric("hits_per_query.max"));
+ metrics.add(new Metric("hits_per_query.average")); // TODO: Remove with Vespa 9
+ metrics.add(new Metric("totalhits_per_query.sum"));
+ metrics.add(new Metric("totalhits_per_query.count"));
+ metrics.add(new Metric("totalhits_per_query.max"));
+ metrics.add(new Metric("totalhits_per_query.average")); // TODO: Remove with Vespa 9
metrics.add(new Metric("degraded_queries.rate"));
metrics.add(new Metric("failed_queries.rate"));
metrics.add(new Metric("serverActiveThreads.average"));
@@ -71,8 +80,14 @@ public class DefaultMetrics {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("content.proton.search_protocol.docsum.requested_documents.rate"));
- metrics.add(new Metric("content.proton.search_protocol.docsum.latency.average"));
- metrics.add(new Metric("content.proton.search_protocol.query.latency.average"));
+ metrics.add(new Metric("content.proton.search_protocol.docsum.latency.sum"));
+ metrics.add(new Metric("content.proton.search_protocol.docsum.latency.count"));
+ metrics.add(new Metric("content.proton.search_protocol.docsum.latency.max"));
+ metrics.add(new Metric("content.proton.search_protocol.docsum.latency.average")); // TODO: Remove with Vespa 9
+ metrics.add(new Metric("content.proton.search_protocol.query.latency.sum"));
+ metrics.add(new Metric("content.proton.search_protocol.query.latency.count"));
+ metrics.add(new Metric("content.proton.search_protocol.query.latency.max"));
+ metrics.add(new Metric("content.proton.search_protocol.query.latency.average")); // TODO: Remove with Vespa 9
metrics.add(new Metric("content.proton.documentdb.documents.total.last"));
metrics.add(new Metric("content.proton.documentdb.documents.ready.last"));
@@ -85,9 +100,18 @@ public class DefaultMetrics {
metrics.add(new Metric("content.proton.documentdb.matching.docs_matched.rate"));
metrics.add(new Metric("content.proton.documentdb.matching.docs_reranked.rate"));
- metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.average"));
- metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.average"));
- metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.average"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.sum"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.count"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.max"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_setup_time.average")); // TODO: Remove with Vespa 9
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.sum"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.count"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.max"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.query_latency.average")); // TODO: Remove with Vespa 9
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.sum"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.count"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.max"));
+ metrics.add(new Metric("content.proton.documentdb.matching.rank_profile.rerank_time.average")); // TODO: Remove with Vespa 9
metrics.add(new Metric("content.proton.transactionlog.disk_usage.last"));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/VespaMetricSet.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/VespaMetricSet.java
index 6ce8c54f98c..b25e8aaf2c0 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/VespaMetricSet.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/VespaMetricSet.java
@@ -28,7 +28,7 @@ public class VespaMetricSet {
metrics.addAll(getDistributorMetrics());
metrics.addAll(getDocprocMetrics());
metrics.addAll(getClusterControllerMetrics());
- metrics.addAll(getQrserverMetrics());
+ metrics.addAll(getSearchChainMetrics());
metrics.addAll(getContainerMetrics());
metrics.addAll(getConfigServerMetrics());
metrics.addAll(getSentinelMetrics());
@@ -297,7 +297,7 @@ public class VespaMetricSet {
return metrics;
}
- private static Set<Metric> getQrserverMetrics() {
+ private static Set<Metric> getSearchChainMetrics() {
Set<Metric> metrics = new LinkedHashSet<>();
metrics.add(new Metric("peak_qps.max"));
@@ -351,7 +351,7 @@ public class VespaMetricSet {
metrics.add(new Metric("relevance.at_10.sum"));
metrics.add(new Metric("relevance.at_10.count"));
- // Errors from qrserver
+ // Errors from search container
metrics.add(new Metric("error.timeout.rate"));
metrics.add(new Metric("error.backends_oos.rate"));
metrics.add(new Metric("error.plugin_failure.rate"));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/AbstractBundleValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/AbstractBundleValidator.java
index 1642a8cb3cc..ea6a081bf6a 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/AbstractBundleValidator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/AbstractBundleValidator.java
@@ -9,6 +9,7 @@ import com.yahoo.config.application.api.ComponentInfo;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.path.Path;
+import com.yahoo.text.XML;
import com.yahoo.vespa.model.VespaModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -16,8 +17,6 @@ import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
@@ -96,20 +95,19 @@ public abstract class AbstractBundleValidator extends Validator {
}
private static final Pattern POM_FILE_LOCATION = Pattern.compile("META-INF/maven/.+?/.+?/pom.xml");
- private Optional<Document> getPomXmlContent(DeployLogger deployLogger, JarFile jar) {
+ public Optional<Document> getPomXmlContent(DeployLogger deployLogger, JarFile jar) {
return jar.stream()
.filter(f -> POM_FILE_LOCATION.matcher(f.getName()).matches())
.findFirst()
.map(f -> {
try {
String text = new String(jar.getInputStream(f).readAllBytes());
- return DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder()
+ return XML.getDocumentBuilder(false)
.parse(new InputSource(new StringReader(text)));
- } catch (ParserConfigurationException e) {
- throw new RuntimeException(e);
} catch (SAXException e) {
- deployLogger.log(Level.INFO, String.format("Unable to parse pom.xml from %s", filename(jar)));
- return null;
+ String message = String.format("Unable to parse pom.xml from %s", filename(jar));
+ deployLogger.log(Level.SEVERE, message);
+ throw new RuntimeException(message, e);
} catch (IOException e) {
deployLogger.log(Level.INFO,
String.format("Unable to read '%s' from '%s'", f.getName(), jar.getName()));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldAttributesValidator.java
index 01bf846d4cb..8515c34a377 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldAttributesValidator.java
@@ -22,7 +22,7 @@ import java.util.stream.Collectors;
*
* @author geirst
*/
-public class ComplexAttributeFieldsValidator extends Validator {
+public class ComplexFieldsWithStructFieldAttributesValidator extends Validator {
@Override
public void validate(VespaModel model, DeployState deployState) {
@@ -39,7 +39,7 @@ public class ComplexAttributeFieldsValidator extends Validator {
private static void validateComplexFields(String clusterName, Schema schema) {
String unsupportedFields = schema.allFields()
.filter(field -> isUnsupportedComplexField(field))
- .map(ComplexAttributeFieldsValidator::toString)
+ .map(ComplexFieldsWithStructFieldAttributesValidator::toString)
.collect(Collectors.joining(", "));
if (!unsupportedFields.isEmpty()) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldIndexesValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldIndexesValidator.java
new file mode 100644
index 00000000000..fdd71ebccc5
--- /dev/null
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/ComplexFieldsWithStructFieldIndexesValidator.java
@@ -0,0 +1,75 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.model.application.validation;
+
+import com.yahoo.config.application.api.DeployLogger;
+import com.yahoo.config.model.deploy.DeployState;
+import com.yahoo.schema.Schema;
+import com.yahoo.schema.document.ImmutableSDField;
+import com.yahoo.vespa.model.VespaModel;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.stream.Collectors;
+
+/**
+ * Validates that complex fields (of type struct or map) do not have any struct fields with 'indexing: index'.
+ * This is not supported and will confuse the user if not validated.
+ *
+ * Only applies for indexed search clusters.
+ *
+ * @author geirst
+ */
+public class ComplexFieldsWithStructFieldIndexesValidator extends Validator {
+
+ @Override
+ public void validate(VespaModel model, DeployState deployState) {
+ for (var cluster : model.getSearchClusters()) {
+ if (cluster.isStreaming()) {
+ continue;
+ }
+ for (var spec : cluster.schemas().values()) {
+ validateComplexFields(cluster.getClusterName(), spec.fullSchema(), deployState.getDeployLogger());
+ }
+ }
+ }
+
+ private static void validateComplexFields(String clusterName, Schema schema, DeployLogger logger) {
+ String unsupportedFields = schema.allFields()
+ .filter(field -> hasStructFieldsWithIndex(field))
+ .map(ComplexFieldsWithStructFieldIndexesValidator::toString)
+ .collect(Collectors.joining(", "));
+
+ if (!unsupportedFields.isEmpty()) {
+ // TODO (Vespa 9 or before): Change back to an exception when no applications are using it wrong.
+ logger.logApplicationPackage(Level.WARNING,
+ String.format("For cluster '%s', schema '%s': The following complex fields have struct fields with 'indexing: index' which is not supported and has no effect: %s. " +
+ "Remove setting or change to 'indexing: attribute' if needed for matching.",
+ clusterName, schema.getName(), unsupportedFields));
+ }
+ }
+
+ private static boolean hasStructFieldsWithIndex(ImmutableSDField field) {
+ return (!field.isImportedField() && field.usesStructOrMap() && hasStructFieldsWithIndex(field.getStructFields()));
+ }
+
+ private static String toString(ImmutableSDField field) {
+ return field.getName() + " (" + String.join(", ", getStructFieldsWithIndex(field.getStructFields())) + ")";
+ }
+
+ private static boolean hasStructFieldsWithIndex(Collection<? extends ImmutableSDField> structFields) {
+ return !getStructFieldsWithIndex(structFields).isEmpty();
+ }
+
+ private static List<String> getStructFieldsWithIndex(Collection<? extends ImmutableSDField> structFields) {
+ var result = new ArrayList<String>();
+ for (var structField : structFields) {
+ if (structField.wasConfiguredToDoIndexing()) {
+ result.add(structField.getName());
+ }
+ result.addAll(getStructFieldsWithIndex(structField.getStructFields()));
+ }
+ return result;
+ }
+}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidator.java
index 338c3a71e44..21025c38c13 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidator.java
@@ -1,7 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.application.validation;
-import com.yahoo.config.model.api.EndpointCertificateSecrets;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.provision.CertificateNotReadyException;
import com.yahoo.vespa.model.VespaModel;
@@ -11,9 +10,9 @@ public class EndpointCertificateSecretsValidator extends Validator {
/** This check is delayed until validation to allow node provisioning to complete while we are waiting for cert */
@Override
public void validate(VespaModel model, DeployState deployState) {
- if (deployState.endpointCertificateSecrets().isPresent() && deployState.endpointCertificateSecrets().get() == EndpointCertificateSecrets.MISSING) {
- throw new CertificateNotReadyException("TLS enabled, but could not yet retrieve certificate for application " + deployState.getProperties().applicationId().serializedForm());
+ if (deployState.endpointCertificateSecrets().isPresent() && deployState.endpointCertificateSecrets().get().isMissing()) {
+ throw new CertificateNotReadyException("TLS enabled, but could not yet retrieve certificate version %s for application %s"
+ .formatted(deployState.endpointCertificateSecrets().get().version(), deployState.getProperties().applicationId().serializedForm()));
}
}
-
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/QuotaValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/QuotaValidator.java
index e4a64e8d476..7ea582b99e6 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/QuotaValidator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/QuotaValidator.java
@@ -84,22 +84,21 @@ public class QuotaValidator extends Validator {
}
}
- private void throwIfBudgetNegative(double spend, BigDecimal budget, SystemName systemName) {
+ private static void throwIfBudgetNegative(double spend, BigDecimal budget, SystemName systemName) {
if (budget.doubleValue() < 0) {
- throwBudgetException("Please free up some capacity! This deployment's quota use is ($%.2f) and reserved quota is below zero! ($%.2f)", spend, budget, systemName);
+ throw new IllegalArgumentException(quotaMessage("Please free up some capacity", systemName, spend, budget));
}
}
- private void throwIfBudgetExceeded(double spend, BigDecimal budget, SystemName systemName) {
+ private static void throwIfBudgetExceeded(double spend, BigDecimal budget, SystemName systemName) {
if (budget.doubleValue() < spend) {
- throw new IllegalArgumentException((systemName.equals(SystemName.Public) ? "" : systemName.value() + ": ") +
- "Deployment would make your tenant exceed its quota and has been blocked! Please contact support to update your plan.");
+ throw new IllegalArgumentException(quotaMessage("Deployment exceeds its quota and has been blocked! Please contact support to update your plan", systemName, spend, budget));
}
}
- private void throwBudgetException(String formatMessage, double spend, BigDecimal budget, SystemName systemName) {
- var message = String.format(Locale.US, formatMessage, spend, budget);
- var messageWithSystem = (systemName.equals(SystemName.Public) ? "" : systemName.value() + ": ") + message;
- throw new IllegalArgumentException(messageWithSystem);
+ private static String quotaMessage(String message, SystemName system, double spend, BigDecimal budget) {
+ String quotaDescription = String.format(Locale.ENGLISH, "Quota is $%.2f, but at least $%.2f is required", budget, spend);
+ return (system == SystemName.Public ? "" : system.value() + ": ") + message + ": " + quotaDescription;
}
+
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/UriBindingsValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/UriBindingsValidator.java
index 4f322578b1c..718f1646126 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/UriBindingsValidator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/UriBindingsValidator.java
@@ -24,7 +24,7 @@ class UriBindingsValidator extends Validator {
@Override
public void validate(VespaModel model, DeployState deployState) {
for (ApplicationContainerCluster cluster : model.getContainerClusters().values()) {
- for (Handler<?> handler : cluster.getHandlers()) {
+ for (Handler handler : cluster.getHandlers()) {
for (BindingPattern binding : handler.getServerBindings()) {
validateUserBinding(binding, model, deployState);
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/Validation.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/Validation.java
index ce61d3edc3b..dab1eeccc96 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/Validation.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/Validation.java
@@ -71,7 +71,8 @@ public class Validation {
new SchemasDirValidator().validate(model, deployState);
new BundleValidator().validate(model, deployState);
new SearchDataTypeValidator().validate(model, deployState);
- new ComplexAttributeFieldsValidator().validate(model, deployState);
+ new ComplexFieldsWithStructFieldAttributesValidator().validate(model, deployState);
+ new ComplexFieldsWithStructFieldIndexesValidator().validate(model, deployState);
new StreamingValidator().validate(model, deployState);
new RankSetupValidator(validationParameters.ignoreValidationErrors()).validate(model, deployState);
new NoPrefixForIndexes().validate(model, deployState);
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomClientProviderBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomClientProviderBuilder.java
index 69613944e74..170e8940787 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomClientProviderBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomClientProviderBuilder.java
@@ -5,7 +5,6 @@ import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.text.XML;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
-import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
import org.w3c.dom.Element;
@@ -22,7 +21,7 @@ public class DomClientProviderBuilder extends DomHandlerBuilder {
@Override
protected Handler doBuild(DeployState deployState, AbstractConfigProducer parent, Element clientElement) {
- Handler<? super Component<?, ?>> client = createHandler(clientElement);
+ Handler client = createHandler(clientElement);
for (Element binding : XML.getChildren(clientElement, "binding"))
client.addClientBindings(UserBindingPattern.fromPattern(XML.getValue(binding)));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomHandlerBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomHandlerBuilder.java
index 025a6377b04..7bfe971981e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomHandlerBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/DomHandlerBuilder.java
@@ -9,15 +9,12 @@ import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.text.XML;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.component.BindingPattern;
-import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
import com.yahoo.vespa.model.container.xml.BundleInstantiationSpecificationBuilder;
import org.w3c.dom.Element;
-import java.util.List;
import java.util.Set;
-import java.util.logging.Level;
import static com.yahoo.vespa.model.container.ApplicationContainerCluster.METRICS_V2_HANDLER_BINDING_1;
import static com.yahoo.vespa.model.container.ApplicationContainerCluster.METRICS_V2_HANDLER_BINDING_2;
@@ -29,7 +26,7 @@ import static java.util.logging.Level.INFO;
/**
* @author gjoranv
*/
-public class DomHandlerBuilder extends VespaDomBuilder.DomConfigProducerBuilder<Handler<?>> {
+public class DomHandlerBuilder extends VespaDomBuilder.DomConfigProducerBuilder<Handler> {
private static final Set<BindingPattern> reservedBindings =
Set.of(METRICS_V2_HANDLER_BINDING_1,
@@ -45,8 +42,8 @@ public class DomHandlerBuilder extends VespaDomBuilder.DomConfigProducerBuilder<
}
@Override
- protected Handler<?> doBuild(DeployState deployState, AbstractConfigProducer<?> parent, Element handlerElement) {
- Handler<? super Component<?, ?>> handler = createHandler(handlerElement);
+ protected Handler doBuild(DeployState deployState, AbstractConfigProducer<?> parent, Element handlerElement) {
+ Handler handler = createHandler(handlerElement);
for (Element binding : XML.getChildren(handlerElement, "binding"))
addServerBinding(handler, UserBindingPattern.fromPattern(XML.getValue(binding)), deployState.getDeployLogger());
@@ -56,18 +53,18 @@ public class DomHandlerBuilder extends VespaDomBuilder.DomConfigProducerBuilder<
return handler;
}
- Handler<? super Component<?, ?>> createHandler(Element handlerElement) {
+ Handler createHandler(Element handlerElement) {
BundleInstantiationSpecification bundleSpec = BundleInstantiationSpecificationBuilder.build(handlerElement);
- return new Handler<>(new ComponentModel(bundleSpec));
+ return new Handler(new ComponentModel(bundleSpec));
}
- private void addServerBinding(Handler<? super Component<?, ?>> handler, BindingPattern binding, DeployLogger log) {
+ private void addServerBinding(Handler handler, BindingPattern binding, DeployLogger log) {
throwIfBindingIsReserved(binding, handler);
handler.addServerBindings(binding);
removeExistingServerBinding(binding, handler, log);
}
- private void throwIfBindingIsReserved(BindingPattern binding, Handler<?> newHandler) {
+ private void throwIfBindingIsReserved(BindingPattern binding, Handler newHandler) {
for (var reserved : reservedBindings) {
if (binding.hasSamePattern(reserved)) {
throw new IllegalArgumentException("Binding '" + binding.patternString() + "' is a reserved Vespa binding and " +
@@ -76,7 +73,7 @@ public class DomHandlerBuilder extends VespaDomBuilder.DomConfigProducerBuilder<
}
}
- private void removeExistingServerBinding(BindingPattern binding, Handler<?> newHandler, DeployLogger log) {
+ private void removeExistingServerBinding(BindingPattern binding, Handler newHandler, DeployLogger log) {
for (var handler : cluster.getHandlers()) {
for (BindingPattern serverBinding : handler.getServerBindings()) {
if (serverBinding.hasSamePattern(binding)) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilder.java
index e2bfcb66f37..c6fa7b8a69d 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilder.java
@@ -193,7 +193,7 @@ public class VespaDomBuilder extends VespaModelBuilder {
}
/**
- * The SimpleConfigProducer is the producer for elements such as qrservers, gateways.
+ * The SimpleConfigProducer is the producer for elements such as container.
* Must support overrides for that too, hence this builder
*
* @author vegardh
@@ -230,7 +230,9 @@ public class VespaDomBuilder extends VespaModelBuilder {
deployState.getDocumentModel(),
deployState.getVespaVersion(),
deployState.getProperties().applicationId());
- root.setHostSystem(new HostSystem(root, "hosts", deployState.getProvisioner(), deployState.getDeployLogger()));
+ root.setHostSystem(new HostSystem(root, "hosts", deployState.getProvisioner(),
+ deployState.getDeployLogger(),
+ deployState.isHosted()));
new Client(root);
return root;
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/clients/ContainerDocumentApi.java b/config-model/src/main/java/com/yahoo/vespa/model/clients/ContainerDocumentApi.java
index 8534e1f65a7..f23f27c0d8e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/clients/ContainerDocumentApi.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/clients/ContainerDocumentApi.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.clients;
-import com.yahoo.config.model.producer.AbstractConfigProducer;
-import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.ContainerThreadpool;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
+import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
@@ -21,43 +21,55 @@ import java.util.Collections;
public class ContainerDocumentApi {
public static final String DOCUMENT_V1_PREFIX = "/document/v1";
+ public static final Path VESPACLIENT_CONTAINER_BUNDLE =
+ PlatformBundles.absoluteBundlePath("vespaclient-container-plugin");
- public ContainerDocumentApi(ContainerCluster<?> cluster, Options options) {
- addRestApiHandler(cluster, options);
- addFeedHandler(cluster, options);
+ private final boolean ignoreUndefinedFields;
+
+ public ContainerDocumentApi(ContainerCluster<?> cluster, HandlerOptions handlerOptions, boolean ignoreUndefinedFields) {
+ this.ignoreUndefinedFields = ignoreUndefinedFields;
+ addRestApiHandler(cluster, handlerOptions);
+ addFeedHandler(cluster, handlerOptions);
+ addVespaClientContainerBundle(cluster);
+ }
+
+ public static void addVespaClientContainerBundle(ContainerCluster<?> c) {
+ c.addPlatformBundle(VESPACLIENT_CONTAINER_BUNDLE);
}
- private static void addFeedHandler(ContainerCluster<?> cluster, Options options) {
+ private static void addFeedHandler(ContainerCluster<?> cluster, HandlerOptions handlerOptions) {
String bindingSuffix = ContainerCluster.RESERVED_URI_PREFIX + "/feedapi";
- var handler = newVespaClientHandler("com.yahoo.vespa.http.server.FeedHandler", bindingSuffix, options);
+ var executor = new Threadpool("feedapi-handler", handlerOptions.feedApiThreadpoolOptions);
+ var handler = newVespaClientHandler("com.yahoo.vespa.http.server.FeedHandler",
+ bindingSuffix, handlerOptions, executor);
cluster.addComponent(handler);
- var executor = new Threadpool("feedapi-handler", cluster, options.feedApiThreadpoolOptions);
- handler.inject(executor);
- handler.addComponent(executor);
}
- private static void addRestApiHandler(ContainerCluster<?> cluster, Options options) {
- var handler = newVespaClientHandler("com.yahoo.document.restapi.resource.DocumentV1ApiHandler", DOCUMENT_V1_PREFIX + "/*", options);
+ private static void addRestApiHandler(ContainerCluster<?> cluster, HandlerOptions handlerOptions) {
+ var handler = newVespaClientHandler("com.yahoo.document.restapi.resource.DocumentV1ApiHandler",
+ DOCUMENT_V1_PREFIX + "/*", handlerOptions, null);
cluster.addComponent(handler);
// We need to include a dummy implementation of the previous restapi handler (using the same class name).
// The internal legacy test framework requires that the name of the old handler is listed in /ApplicationStatus.
- var oldHandlerDummy = handlerComponentSpecification("com.yahoo.document.restapi.resource.RestApi");
+ var oldHandlerDummy = createHandler("com.yahoo.document.restapi.resource.RestApi", null);
cluster.addComponent(oldHandlerDummy);
}
- private static Handler<AbstractConfigProducer<?>> newVespaClientHandler(
- String componentId,
- String bindingSuffix,
- Options options) {
- Handler<AbstractConfigProducer<?>> handler = handlerComponentSpecification(componentId);
- if (options.bindings.isEmpty()) {
+ public boolean ignoreUndefinedFields() { return ignoreUndefinedFields; }
+
+ private static Handler newVespaClientHandler(String componentId,
+ String bindingSuffix,
+ HandlerOptions handlerOptions,
+ Threadpool executor) {
+ Handler handler = createHandler(componentId, executor);
+ if (handlerOptions.bindings.isEmpty()) {
handler.addServerBindings(
SystemBindingPattern.fromHttpPath(bindingSuffix),
SystemBindingPattern.fromHttpPath(bindingSuffix + '/'));
} else {
- for (String rootBinding : options.bindings) {
+ for (String rootBinding : handlerOptions.bindings) {
String pathWithoutLeadingSlash = bindingSuffix.substring(1);
handler.addServerBindings(
UserBindingPattern.fromPattern(rootBinding + pathWithoutLeadingSlash),
@@ -67,16 +79,17 @@ public class ContainerDocumentApi {
return handler;
}
- private static Handler<AbstractConfigProducer<?>> handlerComponentSpecification(String className) {
- return new Handler<>(new ComponentModel(
- BundleInstantiationSpecification.getFromStrings(className, null, "vespaclient-container-plugin"), ""));
+ private static Handler createHandler(String className, Threadpool executor) {
+ return new Handler(new ComponentModel(className, null, "vespaclient-container-plugin"),
+ executor);
}
- public static final class Options {
+ public static final class HandlerOptions {
+
private final Collection<String> bindings;
private final ContainerThreadpool.UserOptions feedApiThreadpoolOptions;
- public Options(Collection<String> bindings, ContainerThreadpool.UserOptions feedApiThreadpoolOptions) {
+ public HandlerOptions(Collection<String> bindings, ContainerThreadpool.UserOptions feedApiThreadpoolOptions) {
this.bindings = Collections.unmodifiableCollection(bindings);
this.feedApiThreadpoolOptions = feedApiThreadpoolOptions;
}
@@ -84,22 +97,15 @@ public class ContainerDocumentApi {
private static class Threadpool extends ContainerThreadpool {
- private final ContainerCluster<?> cluster;
-
- Threadpool(String name,
- ContainerCluster<?> cluster,
- ContainerThreadpool.UserOptions threadpoolOptions) {
+ Threadpool(String name, ContainerThreadpool.UserOptions threadpoolOptions) {
super(name, threadpoolOptions);
- this.cluster = cluster;
}
@Override
- public void getConfig(ContainerThreadpoolConfig.Builder builder) {
- super.getConfig(builder);
-
- // User options overrides below configuration
- if (hasUserOptions()) return;
- builder.maxThreads(-4).minThreads(-4).queueSize(500);
+ protected void setDefaultConfigValues(ContainerThreadpoolConfig.Builder builder) {
+ builder.maxThreads(-4)
+ .minThreads(-4)
+ .queueSize(500);
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainer.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainer.java
index 47dab37cc14..9997b20d205 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainer.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainer.java
@@ -27,7 +27,6 @@ public final class ApplicationContainer extends Container implements
private static final String defaultHostedJVMArgs = "-XX:+SuppressFatalErrorMessage";
private final boolean isHostedVespa;
- private final boolean enableServerOcspStapling;
public ApplicationContainer(AbstractConfigProducer<?> parent, String name, int index, DeployState deployState) {
this(parent, name, false, index, deployState);
@@ -36,7 +35,6 @@ public final class ApplicationContainer extends Container implements
public ApplicationContainer(AbstractConfigProducer<?> parent, String name, boolean retired, int index, DeployState deployState) {
super(parent, name, retired, index, deployState);
this.isHostedVespa = deployState.isHosted();
- this.enableServerOcspStapling = deployState.featureFlags().enableServerOcspStapling();
addComponent(new SimpleComponent("com.yahoo.container.jdisc.messagebus.NetworkMultiplexerHolder"));
addComponent(new SimpleComponent("com.yahoo.container.jdisc.messagebus.NetworkMultiplexerProvider"));
@@ -68,12 +66,10 @@ public final class ApplicationContainer extends Container implements
if (hasDocproc()) {
b.append(ApplicationContainer.defaultHostedJVMArgs).append(' ');
}
- if (enableServerOcspStapling) {
- b.append("-Djdk.tls.server.enableStatusRequestExtension=true ")
- .append("-Djdk.tls.stapling.responseTimeout=2000 ")
- .append("-Djdk.tls.stapling.cacheSize=256 ")
- .append("-Djdk.tls.stapling.cacheLifetime=3600 ");
- }
+ b.append("-Djdk.tls.server.enableStatusRequestExtension=true ")
+ .append("-Djdk.tls.stapling.responseTimeout=2000 ")
+ .append("-Djdk.tls.stapling.cacheSize=256 ")
+ .append("-Djdk.tls.stapling.cacheLifetime=3600 ");
}
String jvmArgs = super.getJvmOptions();
if (!jvmArgs.isBlank()) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainerCluster.java
index 2b6efab3389..e316f826ad6 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ApplicationContainerCluster.java
@@ -36,7 +36,6 @@ import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
import com.yahoo.vespa.model.container.configserver.ConfigserverCluster;
-import com.yahoo.vespa.model.container.docproc.DocprocChains;
import com.yahoo.vespa.model.utils.FileSender;
import java.util.ArrayList;
@@ -79,7 +78,6 @@ public final class ApplicationContainerCluster extends ContainerCluster<Applicat
public static final int heapSizePercentageOfTotalNodeMemory = 70;
public static final int heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster = 18;
-
private final Set<FileReference> applicationBundles = new LinkedHashSet<>();
private final Set<String> previousHosts;
@@ -90,6 +88,8 @@ public final class ApplicationContainerCluster extends ContainerCluster<Applicat
private MbusParams mbusParams;
private boolean messageBusEnabled = true;
+ private final int transport_events_before_wakeup;
+ private final int transport_connections_per_target;
private Integer memoryPercentage = null;
@@ -115,6 +115,8 @@ public final class ApplicationContainerCluster extends ContainerCluster<Applicat
addMetricsHandlers();
addTestrunnerComponentsIfTester(deployState);
+ transport_connections_per_target = deployState.featureFlags().mbusJavaRpcNumTargets();
+ transport_events_before_wakeup = deployState.featureFlags().mbusJavaEventsBeforeWakeup();
}
@Override
@@ -145,7 +147,7 @@ public final class ApplicationContainerCluster extends ContainerCluster<Applicat
}
private void addMetricsHandler(String handlerClass, BindingPattern rootBinding, BindingPattern innerBinding) {
- Handler<AbstractConfigProducer<?>> handler = new Handler<>(
+ Handler handler = new Handler(
new ComponentModel(handlerClass, null, null, null));
handler.addServerBindings(rootBinding, innerBinding);
addComponent(handler);
@@ -262,6 +264,8 @@ public final class ApplicationContainerCluster extends ContainerCluster<Applicat
}
if (getDocproc() != null)
getDocproc().getConfig(builder);
+ builder.transport_events_before_wakeup(transport_events_before_wakeup);
+ builder.numconnectionspertarget(transport_connections_per_target);
}
@Override
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/Container.java b/config-model/src/main/java/com/yahoo/vespa/model/container/Container.java
index 4b1c03a170c..3f01ac6a103 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/Container.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/Container.java
@@ -1,7 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container;
-import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.api.ModelContext;
import com.yahoo.config.model.api.container.ContainerServiceType;
import com.yahoo.config.model.deploy.DeployState;
@@ -77,7 +76,7 @@ public abstract class Container extends AbstractService implements
private final boolean dumpHeapOnShutdownTimeout;
private final double shutdownTimeoutS;
- private final ComponentGroup<Handler<?>> handlers = new ComponentGroup<>(this, "handler");
+ private final ComponentGroup<Handler> handlers = new ComponentGroup<>(this, "handler");
private final ComponentGroup<Component<?, ?>> components = new ComponentGroup<>(this, "components");
private final JettyHttpServer defaultHttpServer;
@@ -114,7 +113,7 @@ public abstract class Container extends AbstractService implements
/** True if this container is retired (slated for removal) */
public boolean isRetired() { return retired; }
- public ComponentGroup<Handler<?>> getHandlers() {
+ public ComponentGroup<Handler> getHandlers() {
return handlers;
}
@@ -130,7 +129,7 @@ public abstract class Container extends AbstractService implements
addComponent(new SimpleComponent(new ComponentModel(idSpec, classSpec, bundleSpec)));
}
- public final void addHandler(Handler<?> h) {
+ public final void addHandler(Handler h) {
handlers.addComponent(h);
}
@@ -148,19 +147,11 @@ public abstract class Container extends AbstractService implements
return (parent instanceof ContainerCluster) ? ((ContainerCluster<?>) parent).getHttp() : null;
}
+ @SuppressWarnings("unused") // used by amenders
public JettyHttpServer getDefaultHttpServer() {
return defaultHttpServer;
}
- public JettyHttpServer getHttpServer() {
- Http http = getHttp();
- if (http == null) {
- return defaultHttpServer;
- } else {
- return http.getHttpServer().orElse(null);
- }
- }
-
/** Returns the index of this node. The index of a given node is stable through changes with best effort. */
public final int index() { return index; }
@@ -216,7 +207,7 @@ public abstract class Container extends AbstractService implements
}
/**
- * First Qrserver or container must run on ports familiar to the user.
+ * First container must run on ports familiar to the user.
*/
@Override
public boolean requiresWantedPort() {
@@ -381,7 +372,7 @@ public abstract class Container extends AbstractService implements
@Override
public void getConfig(ContainerMbusConfig.Builder builder) {
- builder.enabled(messageBusEnabled()).port(getMessagingPort());
+ builder.port(getMessagingPort());
}
@Override
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
index 4755f674f69..7e375951c7f 100755
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
@@ -29,8 +29,8 @@ import com.yahoo.metrics.simple.runtime.MetricProperties;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.prelude.semantics.SemanticRulesConfig;
import com.yahoo.search.config.IndexInfoConfig;
-import com.yahoo.search.config.SchemaInfoConfig;
import com.yahoo.search.config.QrStartConfig;
+import com.yahoo.search.config.SchemaInfoConfig;
import com.yahoo.search.pagetemplates.PageTemplatesConfig;
import com.yahoo.search.query.profile.config.QueryProfilesConfig;
import com.yahoo.vespa.configdefinition.IlscriptsConfig;
@@ -64,12 +64,14 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.TreeSet;
+
+import static com.yahoo.vespa.model.container.component.chain.ProcessingHandler.PROCESSING_HANDLER_CLASS;
/**
* Parent class for all container cluster types.
@@ -105,7 +107,7 @@ public abstract class ContainerCluster<CONTAINER extends Container>
/**
* URI prefix used for internal, usually programmatic, APIs. URIs using this
- * prefix should never considered available for direct use by customers, and
+ * prefix should never be considered available for direct use by customers, and
* normal compatibility concerns only applies to libraries using the URIs in
* question, not contents served from the URIs themselves.
*/
@@ -136,11 +138,12 @@ public abstract class ContainerCluster<CONTAINER extends Container>
private ContainerDocproc containerDocproc;
private ContainerDocumentApi containerDocumentApi;
private SecretStore secretStore;
+ private final ContainerThreadpool defaultHandlerThreadpool = new Handler.DefaultHandlerThreadpool();
private boolean rpcServerEnabled = true;
private boolean httpServerEnabled = true;
- private final Set<Path> platformBundles = new LinkedHashSet<>();
+ private final Set<Path> platformBundles = new TreeSet<>(); // Ensure stable ordering
private final ComponentGroup<Component<?, ?>> componentGroup;
private final boolean isHostedVespa;
@@ -175,6 +178,7 @@ public abstract class ContainerCluster<CONTAINER extends Container>
addCommonVespaBundles();
addSimpleComponent(AccessLog.class);
addComponent(new DefaultThreadpoolProvider(this, defaultPoolNumThreads));
+ addComponent(defaultHandlerThreadpool);
addSimpleComponent(com.yahoo.concurrent.classlock.ClassLocking.class);
addSimpleComponent("com.yahoo.container.jdisc.metric.MetricConsumerProviderProvider");
addSimpleComponent("com.yahoo.container.jdisc.metric.MetricProvider");
@@ -190,6 +194,8 @@ public abstract class ContainerCluster<CONTAINER extends Container>
addSimpleComponent(com.yahoo.jdisc.http.server.jetty.Janitor.class);
}
+ protected abstract boolean messageBusEnabled();
+
public ClusterSpec.Id id() { return ClusterSpec.Id.from(getName()); }
public void setZone(Zone zone) {
@@ -211,36 +217,45 @@ public abstract class ContainerCluster<CONTAINER extends Container>
}
public void addMetricStateHandler() {
- Handler<AbstractConfigProducer<?>> stateHandler = new Handler<>(
+ Handler stateHandler = new Handler(
new ComponentModel(STATE_HANDLER_CLASS, null, null, null));
stateHandler.addServerBindings(STATE_HANDLER_BINDING_1, STATE_HANDLER_BINDING_2);
addComponent(stateHandler);
}
public void addDefaultRootHandler() {
- Handler<AbstractConfigProducer<?>> handler = new Handler<>(
- new ComponentModel(BundleInstantiationSpecification.getFromStrings(
+ Handler handler = new Handler(
+ new ComponentModel(BundleInstantiationSpecification.fromStrings(
BINDINGS_OVERVIEW_HANDLER_CLASS, null, null), null)); // null bundle, as the handler is in container-disc
handler.addServerBindings(ROOT_HANDLER_BINDING);
addComponent(handler);
}
public void addApplicationStatusHandler() {
- Handler<AbstractConfigProducer<?>> statusHandler = new Handler<>(
- new ComponentModel(BundleInstantiationSpecification.getInternalHandlerSpecificationFromStrings(
- APPLICATION_STATUS_HANDLER_CLASS, null), null));
+ Handler statusHandler = new Handler(
+ new ComponentModel(BundleInstantiationSpecification.fromStrings(
+ APPLICATION_STATUS_HANDLER_CLASS, null, null), null)); // null bundle, as the handler is in container-disc
statusHandler.addServerBindings(SystemBindingPattern.fromHttpPath("/ApplicationStatus"));
addComponent(statusHandler);
}
public void addVipHandler() {
- Handler<?> vipHandler = Handler.fromClassName(FileStatusHandlerComponent.CLASS);
+ Handler vipHandler = Handler.fromClassName(FileStatusHandlerComponent.CLASS);
vipHandler.addServerBindings(VIP_HANDLER_BINDING);
addComponent(vipHandler);
}
public final void addComponent(Component<?, ?> component) {
componentGroup.addComponent(component);
+ if (component instanceof Handler handler) {
+ ensureHandlerHasThreadpool(handler);
+ }
+ }
+
+ private void ensureHandlerHasThreadpool(Handler handler) {
+ if (! handler.hasCustomThreadPool) {
+ handler.inject(defaultHandlerThreadpool);
+ }
}
public final void addSimpleComponent(String idSpec, String classSpec, String bundleSpec) {
@@ -253,7 +268,7 @@ public abstract class ContainerCluster<CONTAINER extends Container>
* @return the removed component, or null if it was not present
*/
@SuppressWarnings("unused") // Used from other repositories
- public Component removeComponent(ComponentId componentId) {
+ public Component<?, ?> removeComponent(ComponentId componentId) {
return componentGroup.removeComponent(componentId);
}
@@ -299,10 +314,9 @@ public abstract class ContainerCluster<CONTAINER extends Container>
this.processingChains = processingChains;
- // Cannot use the class object for ProcessingHandler, because its superclass is not accessible
ProcessingHandler<?> processingHandler = new ProcessingHandler<>(
processingChains,
- "com.yahoo.processing.handler.ProcessingHandler");
+ BundleInstantiationSpecification.fromStrings(PROCESSING_HANDLER_CLASS, null, null));
for (BindingPattern binding: serverBindings)
processingHandler.addServerBindings(binding);
@@ -361,9 +375,8 @@ public abstract class ContainerCluster<CONTAINER extends Container>
return containerDocproc.getChains();
}
- @SuppressWarnings("unchecked")
- public Collection<Handler<?>> getHandlers() {
- return (Collection<Handler<?>>)(Collection)componentGroup.getComponents(Handler.class);
+ public Collection<Handler> getHandlers() {
+ return componentGroup.getComponents(Handler.class);
}
public void setSecretStore(SecretStore secretStore) {
@@ -411,8 +424,8 @@ public abstract class ContainerCluster<CONTAINER extends Container>
@Override
public void getConfig(DocumentmanagerConfig.Builder builder) {
- if (containerDocproc != null && containerDocproc.isCompressDocuments())
- builder.enablecompression(true);
+ if (containerDocumentApi != null)
+ builder.ignoreundefinedfields(containerDocumentApi.ignoreUndefinedFields());
}
@Override
@@ -435,23 +448,37 @@ public abstract class ContainerCluster<CONTAINER extends Container>
@Override
public void getConfig(ApplicationMetadataConfig.Builder builder) {
- if (applicationMetaData != null) {
+ if (applicationMetaData != null)
builder.name(applicationMetaData.getApplicationId().application().value()).
- user(applicationMetaData.getDeployedByUser()).
path(applicationMetaData.getDeployPath()).
timestamp(applicationMetaData.getDeployTimestamp()).
checksum(applicationMetaData.getChecksum()).
generation(applicationMetaData.getGeneration());
- }
}
/**
- * Adds the Vespa bundles that are necessary for all container types.
+ * Adds the Vespa bundles that are necessary for most container types.
+ * Note that some of these can be removed later by the individual cluster types.
*/
public void addCommonVespaBundles() {
- PlatformBundles.commonVespaBundles().forEach(this::addPlatformBundle);
+ PlatformBundles.COMMON_VESPA_BUNDLES.forEach(this::addPlatformBundle);
+ PlatformBundles.VESPA_SECURITY_BUNDLES.forEach(this::addPlatformBundle);
+ PlatformBundles.VESPA_ZK_BUNDLES.forEach(this::addPlatformBundle);
+ }
+
+ /**
+ * Add all search/docproc/feed related platform bundles.
+ * These are only required for application configured containers as the platform bundle set is not allowed to change
+ * between config generations. For standalone container platform bundles can be added on features enabled as an
+ * update of application package requires restart.
+ */
+ public void addAllPlatformBundles() {
+ ContainerDocumentApi.addVespaClientContainerBundle(this);
+ addSearchAndDocprocBundles();
}
+ public void addSearchAndDocprocBundles() { PlatformBundles.SEARCH_AND_DOCPROC_BUNDLES.forEach(this::addPlatformBundle); }
+
/**
* Adds a bundle present at a known location at the target container nodes.
* Note that the set of platform bundles cannot change during the jdisc container's lifetime.
@@ -459,9 +486,19 @@ public abstract class ContainerCluster<CONTAINER extends Container>
* @param bundlePath usually an absolute path, e.g. '$VESPA_HOME/lib/jars/foo.jar'
*/
public final void addPlatformBundle(Path bundlePath) {
- platformBundles.add(bundlePath);
+ if (! unnecessaryPlatformBundles().contains(bundlePath)) {
+ platformBundles.add(bundlePath);
+ } else {
+ log.fine(() -> "Not installing bundle " + bundlePath + " for cluster " + getName());
+ }
}
+ /**
+ * Implement in subclasses to avoid installing unnecessary bundles, see {@link PlatformBundles}
+ * Should only return constant values, as there is no guarantee for when this is called.
+ */
+ protected Set<Path> unnecessaryPlatformBundles() { return Set.of(); }
+
@Override
public void getConfig(PlatformBundlesConfig.Builder builder) {
platformBundles.stream()
@@ -536,9 +573,7 @@ public abstract class ContainerCluster<CONTAINER extends Container>
@Override
public void getConfig(IlscriptsConfig.Builder builder) {
- List<SearchCluster> searchClusters = new ArrayList<>();
- searchClusters.addAll(Content.getSearchClusters(getRoot().configModelRepo()));
- for (SearchCluster searchCluster : searchClusters) {
+ for (SearchCluster searchCluster : Content.getSearchClusters(getRoot().configModelRepo())) {
searchCluster.getConfig(builder);
}
}
@@ -610,8 +645,6 @@ public abstract class ContainerCluster<CONTAINER extends Container>
public void setEnvironmentVars(String environmentVars) { this.environmentVars = environmentVars; }
- public String getEnvironmentVars() { return environmentVars; }
-
public Optional<String> getJvmGCOptions() { return Optional.ofNullable(jvmGCOptions); }
public final void setRpcServerEnabled(boolean rpcServerEnabled) { this.rpcServerEnabled = rpcServerEnabled; }
@@ -627,8 +660,6 @@ public abstract class ContainerCluster<CONTAINER extends Container>
return "container cluster '" + getName() + "'";
}
- protected abstract boolean messageBusEnabled();
-
/**
* Mark whether the config emitted by this cluster currently should be applied by clients already running with
* a previous generation of it only by restarting the consuming processes.
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerModelEvaluation.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerModelEvaluation.java
index cb8e6ba85ff..088465f56b1 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerModelEvaluation.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerModelEvaluation.java
@@ -63,8 +63,8 @@ public class ContainerModelEvaluation implements
rankProfileList.getConfig(builder);
}
- public static Handler<?> getHandler() {
- Handler<?> handler = new Handler<>(new ComponentModel(REST_HANDLER_NAME, null, EVALUATION_BUNDLE_NAME));
+ public static Handler getHandler() {
+ Handler handler = new Handler(new ComponentModel(REST_HANDLER_NAME, null, EVALUATION_BUNDLE_NAME));
handler.addServerBindings(
SystemBindingPattern.fromHttpPath(REST_BINDING_PATH),
SystemBindingPattern.fromHttpPath(REST_BINDING_PATH + "/*"));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java
index 489e4cc135a..fb4e62f5cd1 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java
@@ -17,14 +17,14 @@ import java.util.Optional;
*
* @author bjorncs
*/
-public class ContainerThreadpool extends SimpleComponent implements ContainerThreadpoolConfig.Producer {
+public abstract class ContainerThreadpool extends SimpleComponent implements ContainerThreadpoolConfig.Producer {
private final String name;
private final UserOptions userOptions;
public ContainerThreadpool(String name, UserOptions userOptions) {
super(new ComponentModel(
- BundleInstantiationSpecification.getFromStrings(
+ BundleInstantiationSpecification.fromStrings(
"threadpool@" + name,
ContainerThreadpoolImpl.class.getName(),
null)));
@@ -32,8 +32,13 @@ public class ContainerThreadpool extends SimpleComponent implements ContainerThr
this.userOptions = userOptions;
}
+ // Must be implemented by subclasses to set values that may be overridden by user options.
+ protected abstract void setDefaultConfigValues(ContainerThreadpoolConfig.Builder builder);
+
@Override
public void getConfig(ContainerThreadpoolConfig.Builder builder) {
+ setDefaultConfigValues(builder);
+
builder.name(this.name);
if (userOptions != null) {
builder.maxThreads(userOptions.maxThreads);
@@ -42,9 +47,6 @@ public class ContainerThreadpool extends SimpleComponent implements ContainerThr
}
}
- protected Optional<UserOptions> userOptions() { return Optional.ofNullable(userOptions); }
- protected boolean hasUserOptions() { return userOptions().isPresent(); }
-
public static class UserOptions {
private final int maxThreads;
private final int minThreads;
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/DefaultThreadpoolProvider.java b/config-model/src/main/java/com/yahoo/vespa/model/container/DefaultThreadpoolProvider.java
index 0b37abaded9..0fdd36b8811 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/DefaultThreadpoolProvider.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/DefaultThreadpoolProvider.java
@@ -19,7 +19,7 @@ class DefaultThreadpoolProvider extends SimpleComponent implements ThreadpoolCon
DefaultThreadpoolProvider(ContainerCluster<?> cluster, int defaultWorkerThreads) {
super(new ComponentModel(
- BundleInstantiationSpecification.getFromStrings(
+ BundleInstantiationSpecification.fromStrings(
"default-threadpool",
ThreadPoolProvider.class.getName(),
null)));
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/IdentityProvider.java b/config-model/src/main/java/com/yahoo/vespa/model/container/IdentityProvider.java
index 7ce2425179b..5e8bb85c29d 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/IdentityProvider.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/IdentityProvider.java
@@ -33,7 +33,7 @@ public class IdentityProvider extends SimpleComponent implements IdentityConfig.
URI ztsUrl,
String athenzDnsSuffix,
Zone zone) {
- super(new ComponentModel(BundleInstantiationSpecification.getFromStrings(CLASS, CLASS, BUNDLE)));
+ super(new ComponentModel(BundleInstantiationSpecification.fromStrings(CLASS, CLASS, BUNDLE)));
this.domain = domain;
this.service = service;
this.loadBalancerName = loadBalancerName;
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
index e5125fe7e1d..7ce82848d09 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
@@ -1,16 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container;
+import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.vespa.defaults.Defaults;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
+ * NOTE: Stable ordering of bundles in config is handled by {@link ContainerCluster#addPlatformBundle(Path)}
+ *
* @author gjoranv
* @author Ulf Lilleengen
*/
@@ -28,12 +30,37 @@ public class PlatformBundles {
}
public static final Path LIBRARY_PATH = Paths.get(Defaults.getDefaults().underVespaHome("lib/jars"));
- public static final String searchAndDocprocBundle = "container-search-and-docproc";
+ public static final String SEARCH_AND_DOCPROC_BUNDLE = BundleInstantiationSpecification.CONTAINER_SEARCH_AND_DOCPROC;
- public static Set<Path> commonVespaBundles() {
- var bundles = new LinkedHashSet<Path>();
- commonVespaBundles.stream().map(PlatformBundles::absoluteBundlePath).forEach(bundles::add);
- return Collections.unmodifiableSet(bundles);
+ // Bundles that must be loaded for all container types.
+ public static final Set<Path> COMMON_VESPA_BUNDLES = toBundlePaths(
+ "container-spifly.jar", // Aries SPIFly repackaged
+ // Used by vespa-athenz, zkfacade, other vespa bundles and nearly all hosted apps.
+ // TODO Vespa 9: stop installing and providing servlet-api. Seems difficult, though.
+ "javax.servlet-api-3.1.0.jar"
+ );
+
+ public static final Set<Path> VESPA_SECURITY_BUNDLES = toBundlePaths(
+ "jdisc-security-filters",
+ "vespa-athenz"
+ );
+
+ public static final Set<Path> VESPA_ZK_BUNDLES = toBundlePaths(
+ "zkfacade",
+ "zookeeper-server"
+ );
+
+ public static final Set<Path> SEARCH_AND_DOCPROC_BUNDLES = toBundlePaths(
+ SEARCH_AND_DOCPROC_BUNDLE,
+ "container-search-gui",
+ "docprocs",
+ "linguistics-components"
+ );
+
+ private static Set<Path> toBundlePaths(String... bundleNames) {
+ return Stream.of(bundleNames)
+ .map(PlatformBundles::absoluteBundlePath)
+ .collect(Collectors.toSet());
}
public static Path absoluteBundlePath(String fileName) {
@@ -42,19 +69,14 @@ public class PlatformBundles {
public static Path absoluteBundlePath(String fileName, JarSuffix jarSuffix) {
if (fileName == null) return null;
- return LIBRARY_PATH.resolve(Paths.get(fileName + jarSuffix.suffix));
+ String fullFilename = fileName.endsWith(".jar") ? fileName : fileName + jarSuffix.suffix;
+ return LIBRARY_PATH.resolve(Paths.get(fullFilename));
}
public static boolean isSearchAndDocprocClass(String className) {
return searchAndDocprocComponents.contains(className);
}
- // Bundles that must be loaded for all container types.
- private static final List<String> commonVespaBundles = List.of(
- "zkfacade",
- "zookeeper-server" // TODO: not necessary in metrics-proxy.
- );
-
// This is a hack to allow users to declare components from the search-and-docproc bundle without naming the bundle.
private static final Set<String> searchAndDocprocComponents = Set.of(
"com.yahoo.docproc.AbstractConcreteDocumentFactory",
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java
index 76124b14209..e4a5c2cd440 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java
@@ -14,16 +14,16 @@ import static java.util.stream.Collectors.toList;
*/
public class DiscBindingsConfigGenerator {
- public static Map<String, Handlers.Builder> generate(Collection<? extends Handler<?>> handlers) {
+ public static Map<String, Handlers.Builder> generate(Collection<? extends Handler> handlers) {
Map<String, Handlers.Builder> handlerBuilders = new LinkedHashMap<>();
- for (Handler<?> handler : handlers) {
+ for (Handler handler : handlers) {
handlerBuilders.putAll(generate(handler));
}
return handlerBuilders;
}
- public static <T extends Handler<?>> Map<String, Handlers.Builder> generate(T handler) {
+ public static <T extends Handler> Map<String, Handlers.Builder> generate(T handler) {
if (handler.getServerBindings().isEmpty() && handler.getClientBindings().isEmpty())
return Collections.emptyMap();
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java
index 8ffdccae896..9f2bfe9251b 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java
@@ -1,8 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;
-import com.yahoo.config.model.producer.AbstractConfigProducer;
+import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
+import com.yahoo.vespa.model.container.ContainerThreadpool;
import java.util.ArrayList;
import java.util.Arrays;
@@ -15,22 +16,35 @@ import java.util.Set;
* Models a jdisc RequestHandler (including ClientProvider).
* RequestHandlers always have at least one server binding,
* while ClientProviders have at least one client binding.
- * <p>
- * Note that this is also used to model vespa handlers (which do not have any bindings)
*
* @author gjoranv
*/
-public class Handler<CHILD extends AbstractConfigProducer<?>> extends Component<CHILD, ComponentModel> {
+public class Handler extends Component<Component<?, ?>, ComponentModel> {
private final Set<BindingPattern> serverBindings = new LinkedHashSet<>();
private final List<BindingPattern> clientBindings = new ArrayList<>();
+ public final boolean hasCustomThreadPool;
+
public Handler(ComponentModel model) {
+ this(model, null);
+ }
+
+ public Handler(ComponentModel model, ContainerThreadpool threadpool) {
super(model);
+
+ // The default threadpool is always added to the cluster, so cannot be added here.
+ if (threadpool != null) {
+ hasCustomThreadPool = true;
+ addComponent(threadpool);
+ inject(threadpool);
+ } else {
+ hasCustomThreadPool = false;
+ }
}
- public static Handler<AbstractConfigProducer<?>> fromClassName(String className) {
- return new Handler<>(new ComponentModel(className, null, null, null));
+ public static Handler fromClassName(String className) {
+ return new Handler(new ComponentModel(className, null, null, null));
}
public void addServerBindings(BindingPattern... bindings) {
@@ -53,4 +67,24 @@ public class Handler<CHILD extends AbstractConfigProducer<?>> extends Component<
return Collections.unmodifiableList(clientBindings);
}
+
+ /**
+ * The default threadpool for all handlers, except those that declare their own, e.g. SearchHandler.
+ */
+ public static class DefaultHandlerThreadpool extends ContainerThreadpool {
+
+ public DefaultHandlerThreadpool() {
+ super("default-handler-common", null);
+ }
+
+ @Override
+ public void setDefaultConfigValues(ContainerThreadpoolConfig.Builder builder) {
+ builder.maxThreadExecutionTimeSeconds(190)
+ .keepAliveTime(5.0)
+ .maxThreads(-2)
+ .minThreads(-2)
+ .queueSize(-40);
+ }
+ }
+
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/SimpleComponent.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/SimpleComponent.java
index 2c4dd9a8dda..23915afacdd 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/SimpleComponent.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/SimpleComponent.java
@@ -17,7 +17,7 @@ public class SimpleComponent extends Component<AbstractConfigProducer<?>, Compon
}
public SimpleComponent(String className) {
- this(new ComponentModel(BundleInstantiationSpecification.getFromStrings(className, null, null)));
+ this(new ComponentModel(BundleInstantiationSpecification.fromStrings(className, null, null)));
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/chain/ProcessingHandler.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/chain/ProcessingHandler.java
index 71524d7e157..897a1f22f30 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/chain/ProcessingHandler.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/chain/ProcessingHandler.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.model.container.component.chain;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.core.ChainsConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
-import com.yahoo.config.model.producer.AbstractConfigProducer;
+import com.yahoo.vespa.model.container.ContainerThreadpool;
import com.yahoo.vespa.model.container.component.Handler;
@@ -14,15 +14,22 @@ import com.yahoo.vespa.model.container.component.Handler;
* @author gjoranv
*/
public class ProcessingHandler<CHAINS extends Chains<?>>
- extends Handler<AbstractConfigProducer<?>>
+ extends Handler
implements ChainsConfig.Producer {
+ // Cannot use the class object for ProcessingHandler, because its superclass is not accessible
+ public static final String PROCESSING_HANDLER_CLASS = "com.yahoo.processing.handler.ProcessingHandler";
+
protected final CHAINS chains;
- public ProcessingHandler(CHAINS chains, String handlerClass) {
- super(new ComponentModel(BundleInstantiationSpecification.getInternalProcessingSpecificationFromStrings(handlerClass, null), null));
- this.chains = chains;
+ // Create a handler that uses the default threadpool for handlers
+ public ProcessingHandler(CHAINS chains, BundleInstantiationSpecification spec) {
+ this(chains, spec, null);
+ }
+ public ProcessingHandler(CHAINS chains, BundleInstantiationSpecification spec, ContainerThreadpool threadpool) {
+ super(new ComponentModel(spec), threadpool);
+ this.chains = chains;
}
@Override
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/ContainerDocproc.java b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/ContainerDocproc.java
index 8be02f77ab3..242f7cbefdb 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/ContainerDocproc.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/ContainerDocproc.java
@@ -15,41 +15,32 @@ import java.util.HashMap;
import java.util.Map;
/**
- * @author einarmr
+ * @author Einar M R Rosenvinge
* @author gjoranv
*/
-public class ContainerDocproc extends ContainerSubsystem<DocprocChains>
- implements
- ContainerMbusConfig.Producer,
- SchemamappingConfig.Producer,
- DocprocConfig.Producer
-{
- public final Options options;
-
- // Whether or not to prefer sending to a local node.
- private boolean preferLocalNode = false;
+public class ContainerDocproc extends ContainerSubsystem<DocprocChains> implements
+ ContainerMbusConfig.Producer,
+ SchemamappingConfig.Producer,
+ DocprocConfig.Producer {
- // The number of nodes to use per client.
- private int numNodesPerClient = 0;
-
- private Map<Pair<String, String>, String> fieldNameSchemaMap = new HashMap<>();
+ public final Options options;
+ private final Map<Pair<String, String>, String> fieldNameSchemaMap = new HashMap<>();
- public ContainerDocproc(ContainerCluster cluster, DocprocChains chains) {
- this(cluster, chains, new Options(false, null, null, null, null, null, null));
+ public ContainerDocproc(ContainerCluster<?> cluster, DocprocChains chains) {
+ this(cluster, chains, Options.empty());
}
- public ContainerDocproc(ContainerCluster cluster, DocprocChains chains, Options options) {
+ public ContainerDocproc(ContainerCluster<?> cluster, DocprocChains chains, Options options) {
this(cluster, chains, options, true);
}
- private void addSource(
- final ContainerCluster cluster, final String name, final SessionConfig.Type.Enum type) {
+ private void addSource(ContainerCluster<?> cluster, String name, SessionConfig.Type.Enum type) {
final MbusClient mbusClient = new MbusClient(name, type);
mbusClient.addClientBindings(SystemBindingPattern.fromPattern("mbus://*/" + mbusClient.getSessionName()));
cluster.addComponent(mbusClient);
}
- public ContainerDocproc(ContainerCluster cluster, DocprocChains chains, Options options, boolean addSourceClientProvider) {
+ public ContainerDocproc(ContainerCluster<?> cluster, DocprocChains chains, Options options, boolean addSourceClientProvider) {
super(chains);
assert (options != null) : "Null Options for " + this + " under cluster " + cluster.getName();
this.options = options;
@@ -58,25 +49,12 @@ public class ContainerDocproc extends ContainerSubsystem<DocprocChains>
addSource(cluster, "source", SessionConfig.Type.SOURCE);
addSource(cluster, MbusRequestContext.internalNoThrottledSource, SessionConfig.Type.INTERNAL);
}
- }
-
- public boolean isCompressDocuments() {
- return options.compressDocuments;
- }
-
- public boolean isPreferLocalNode() {
- return preferLocalNode;
- }
-
- public int getNumNodesPerClient() {
- return numNodesPerClient;
+ cluster.addSearchAndDocprocBundles();
}
@Override
public void getConfig(ContainerMbusConfig.Builder builder) {
builder.maxpendingcount(getMaxMessagesInQueue());
- if (getMaxQueueMbSize() != null)
- builder.maxpendingsize(getMaxQueueMbSize()); //yes, this shall be set in megabytes.
}
private int getMaxMessagesInQueue() {
@@ -84,13 +62,9 @@ public class ContainerDocproc extends ContainerSubsystem<DocprocChains>
return options.maxMessagesInQueue;
}
- //maxmessagesinqueue has not been set for this node. let's try to give a good value anyway:
+ // maxmessagesinqueue has not been set for this node. let's try to give a good value anyway:
return 2048 * getChains().allChains().allComponents().size();
- //intentionally high, getMaxQueueMbSize() will probably kick in before this one!
- }
-
- private Integer getMaxQueueMbSize() {
- return options.maxQueueMbSize;
+ // intentionally high, getMaxQueueMbSize() will probably kick in before this one!
}
private Integer getMaxQueueTimeMs() {
@@ -137,26 +111,24 @@ public class ContainerDocproc extends ContainerSubsystem<DocprocChains>
}
public static class Options {
- // Whether or not to compress documents after processing them.
- public final boolean compressDocuments;
public final Integer maxMessagesInQueue;
- public final Integer maxQueueMbSize;
public final Integer maxQueueTimeMs;
public final Double maxConcurrentFactor;
public final Double documentExpansionFactor;
public final Integer containerCoreMemory;
- public Options(boolean compressDocuments, Integer maxMessagesInQueue, Integer maxQueueMbSize, Integer maxQueueTimeMs, Double maxConcurrentFactor, Double documentExpansionFactor, Integer containerCoreMemory) {
- this.compressDocuments = compressDocuments;
+ public Options(Integer maxMessagesInQueue, Integer maxQueueTimeMs, Double maxConcurrentFactor, Double documentExpansionFactor, Integer containerCoreMemory) {
this.maxMessagesInQueue = maxMessagesInQueue;
- this.maxQueueMbSize = maxQueueMbSize;
this.maxQueueTimeMs = maxQueueTimeMs;
this.maxConcurrentFactor = maxConcurrentFactor;
this.documentExpansionFactor = documentExpansionFactor;
this.containerCoreMemory = containerCoreMemory;
}
+
+ static Options empty() { return new Options(null, null, null, null, null); }
+
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/DocprocChains.java b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/DocprocChains.java
index 4b9897d0950..109ab3e806e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/DocprocChains.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/DocprocChains.java
@@ -3,9 +3,13 @@ package com.yahoo.vespa.model.container.docproc;
import com.yahoo.component.ComponentId;
import com.yahoo.config.model.producer.AbstractConfigProducer;
+import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.jdisc.config.SessionConfig;
+import com.yahoo.docproc.jdisc.observability.DocprocsStatusExtension;
+import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.SimpleComponent;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
@@ -23,8 +27,12 @@ public class DocprocChains extends Chains<DocprocChain> {
public DocprocChains(AbstractConfigProducer<?> parent, String subId) {
super(parent, subId);
- docprocHandler = new ProcessingHandler<>(this, "com.yahoo.docproc.jdisc.DocumentProcessingHandler");
+ docprocHandler = new ProcessingHandler<>(
+ this,
+ BundleInstantiationSpecification.fromSearchAndDocproc("com.yahoo.docproc.jdisc.DocumentProcessingHandler"));
addComponent(docprocHandler);
+ addComponent(new SimpleComponent(
+ new ComponentModel(DocprocsStatusExtension.class.getName(), null, PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE)));
if (! (getParent() instanceof ApplicationContainerCluster)) {
// All application containers already have a DocumentTypeManager,
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/MbusClient.java b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/MbusClient.java
index 28a0748be26..0efcd8df37f 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/MbusClient.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/docproc/MbusClient.java
@@ -6,13 +6,12 @@ import com.yahoo.component.ComponentSpecification;
import com.yahoo.container.jdisc.config.SessionConfig;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.osgi.provider.model.ComponentModel;
-import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author Einar M R Rosenvinge
*/
-public class MbusClient extends Handler<AbstractConfigProducer<?>> implements SessionConfig.Producer {
+public class MbusClient extends Handler implements SessionConfig.Producer {
private static final ComponentSpecification CLASSNAME =
ComponentSpecification.fromString("com.yahoo.container.jdisc.messagebus.MbusClientProvider");
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java
index d85f00a5bb2..3ee0414bf32 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java
@@ -51,7 +51,7 @@ public class AccessControl {
private final String domain;
private ClientAuthentication clientAuthentication = ClientAuthentication.need;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
- private Collection<Handler<?>> handlers = Collections.emptyList();
+ private Collection<Handler> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
@@ -79,12 +79,12 @@ public class AccessControl {
public final String domain;
public final ClientAuthentication clientAuthentication;
private final Set<BindingPattern> excludedBindings;
- private final Collection<Handler<?>> handlers;
+ private final Collection<Handler> handlers;
private AccessControl(String domain,
ClientAuthentication clientAuthentication,
Set<BindingPattern> excludedBindings,
- Collection<Handler<?>> handlers) {
+ Collection<Handler> handlers) {
this.domain = domain;
this.clientAuthentication = clientAuthentication;
this.excludedBindings = Collections.unmodifiableSet(excludedBindings);
@@ -119,7 +119,7 @@ public class AccessControl {
public Set<BindingPattern> excludedBindings() { return excludedBindings; }
/** all handlers (that are known by the access control components) **/
- public Collection<Handler<?>> handlers() { return handlers; }
+ public Collection<Handler> handlers() { return handlers; }
public static boolean hasHandlerThatNeedsProtection(ApplicationContainerCluster cluster) {
return cluster.getHandlers().stream()
@@ -135,7 +135,7 @@ public class AccessControl {
for (BindingPattern excludedBinding : excludedBindings) {
http.getBindings().add(createAccessControlExcludedBinding(excludedBinding));
}
- for (Handler<?> handler : handlers) {
+ for (Handler handler : handlers) {
if (isExcludedHandler(handler)) {
for (BindingPattern binding : handler.getServerBindings()) {
http.getBindings().add(createAccessControlExcludedBinding(binding));
@@ -188,9 +188,9 @@ public class AccessControl {
private static Chain<Filter> createChain(ComponentId id) { return new Chain<>(FilterChains.emptyChainSpec(id)); }
- private static boolean isExcludedHandler(Handler<?> handler) { return EXCLUDED_HANDLERS.contains(handler.getClassId().getName()); }
+ private static boolean isExcludedHandler(Handler handler) { return EXCLUDED_HANDLERS.contains(handler.getClassId().getName()); }
- private static boolean hasNonMbusBinding(Handler<?> handler) {
+ private static boolean hasNonMbusBinding(Handler handler) {
return handler.getServerBindings().stream().anyMatch(binding -> ! binding.scheme().equals("mbus"));
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
index 167dac4c57e..039daba8ad0 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
@@ -7,7 +7,7 @@ import com.yahoo.component.chain.dependencies.Dependencies;
import com.yahoo.component.chain.model.ChainedComponentModel;
import com.yahoo.config.model.api.ContainerEndpoint;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
import com.yahoo.vespa.model.clients.ContainerDocumentApi;
import com.yahoo.vespa.model.container.ContainerCluster;
@@ -17,11 +17,11 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.DefaultRule.Action.Enum.ALLOW;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Action.Enum.BLOCK;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.DELETE;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.POST;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.PUT;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.DefaultRule.Action.Enum.ALLOW;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Action.Enum.BLOCK;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.DELETE;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.POST;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.PUT;
/**
* @author mortent
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/FilterChains.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/FilterChains.java
index bc9a45da08a..476c6249a1e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/FilterChains.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/FilterChains.java
@@ -11,6 +11,7 @@ import com.yahoo.vespa.model.container.component.chain.Chain;
import com.yahoo.vespa.model.container.component.chain.Chains;
import java.util.Collections;
+import java.util.Set;
/**
* @author Tony Vaagenes
@@ -44,8 +45,8 @@ public class FilterChains extends Chains<Chain<Filter>> {
public static ChainSpecification emptyChainSpec(ComponentId chainId) {
return new ChainSpecification(chainId,
new ChainSpecification.Inheritance(null, null),
- Collections.<Phase>emptySet(),
- Collections.<ComponentSpecification>emptySet());
+ Set.of(),
+ Set.of());
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/ContainerSearch.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/ContainerSearch.java
index 97c3f85dced..7a0b6c8e023 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/ContainerSearch.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/ContainerSearch.java
@@ -5,6 +5,7 @@ import com.yahoo.container.QrSearchersConfig;
import com.yahoo.prelude.semantics.SemanticRulesConfig;
import com.yahoo.search.config.IndexInfoConfig;
import com.yahoo.search.config.SchemaInfoConfig;
+import com.yahoo.search.handler.observability.SearchStatusExtension;
import com.yahoo.search.pagetemplates.PageTemplatesConfig;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfilesConfig;
@@ -24,7 +25,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import static com.yahoo.vespa.model.container.PlatformBundles.searchAndDocprocBundle;
+import static com.yahoo.vespa.model.container.PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE;
/**
* @author gjoranv
@@ -55,8 +56,10 @@ public class ContainerSearch extends ContainerSubsystem<SearchChains>
this.owningCluster = cluster;
this.options = options;
- owningCluster.addComponent(Component.fromClassAndBundle(QUERY_PROFILE_REGISTRY_CLASS, searchAndDocprocBundle));
- owningCluster.addComponent(Component.fromClassAndBundle(com.yahoo.search.schema.SchemaInfo.class.getName(), searchAndDocprocBundle));
+ owningCluster.addComponent(Component.fromClassAndBundle(QUERY_PROFILE_REGISTRY_CLASS, SEARCH_AND_DOCPROC_BUNDLE));
+ owningCluster.addComponent(Component.fromClassAndBundle(com.yahoo.search.schema.SchemaInfo.class.getName(), SEARCH_AND_DOCPROC_BUNDLE));
+ owningCluster.addComponent(Component.fromClassAndBundle(SearchStatusExtension.class.getName(), SEARCH_AND_DOCPROC_BUNDLE));
+ cluster.addSearchAndDocprocBundles();
}
public void connectSearchClusters(Map<String, SearchCluster> searchClusters) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/DispatcherComponent.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/DispatcherComponent.java
index 6edcd8901de..44c60cf0619 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/DispatcherComponent.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/DispatcherComponent.java
@@ -32,7 +32,7 @@ public class DispatcherComponent extends Component<AbstractConfigProducer<?>, Co
String dispatcherComponentId = "dispatcher." + indexedSearchCluster.getClusterName(); // used by ClusterSearcher
return new ComponentModel(dispatcherComponentId,
com.yahoo.search.dispatch.Dispatcher.class.getName(),
- PlatformBundles.searchAndDocprocBundle);
+ PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE);
}
@Override
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/GUIHandler.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/GUIHandler.java
index 7087cabafc1..b00faa80715 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/GUIHandler.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/GUIHandler.java
@@ -1,7 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.search;
-import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.component.Handler;
@@ -10,7 +9,7 @@ import com.yahoo.vespa.model.container.component.Handler;
/**
* @author Henrik Høiness
*/
-public class GUIHandler extends Handler<AbstractConfigProducer<?>> {
+public class GUIHandler extends Handler {
public static final String BUNDLE = "container-search-gui";
public static final String CLASS = "com.yahoo.search.query.gui.GUIHandler";
@@ -21,7 +20,7 @@ public class GUIHandler extends Handler<AbstractConfigProducer<?>> {
}
public static BundleInstantiationSpecification bundleSpec(String className, String bundle) {
- return BundleInstantiationSpecification.getFromStrings(className, className, bundle);
+ return BundleInstantiationSpecification.fromStrings(className, className, bundle);
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/RpcResourcePoolComponent.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/RpcResourcePoolComponent.java
index 956d551f6b3..b4b2af3c808 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/RpcResourcePoolComponent.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/RpcResourcePoolComponent.java
@@ -13,6 +13,6 @@ public class RpcResourcePoolComponent extends Component<RpcResourcePoolComponent
private static ComponentModel toComponentModel(String clusterName) {
String componentId = "rpcresourcepool." + clusterName;
- return new ComponentModel(componentId, com.yahoo.search.dispatch.rpc.RpcResourcePool.class.getName(), PlatformBundles.searchAndDocprocBundle);
+ return new ComponentModel(componentId, com.yahoo.search.dispatch.rpc.RpcResourcePool.class.getName(), PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE);
}
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcher.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcher.java
index 1abb62fedab..799309b8ca1 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcher.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcher.java
@@ -45,7 +45,7 @@ public class FederationSearcher extends Searcher<FederationSearcherModel> implem
this.documentTypes = documentTypes;
}
- public FederationConfig.Target.SearchChain.Builder getSearchChainConfig() {
+ FederationConfig.Target.SearchChain.Builder getSearchChainConfig() {
FederationConfig.Target.SearchChain.Builder sB = new FederationConfig.Target.SearchChain.Builder();
FederationOptions resolvedOptions = targetOptions.inherit(searchChain.federationOptions());
sB.
@@ -70,12 +70,12 @@ public class FederationSearcher extends Searcher<FederationSearcherModel> implem
final ComponentId id;
final FederationOptions targetOptions;
- public Target(ComponentId id, FederationOptions targetOptions) {
+ Target(ComponentId id, FederationOptions targetOptions) {
this.id = id;
this.targetOptions = targetOptions;
}
- public FederationConfig.Target.Builder getTargetConfig() {
+ FederationConfig.Target.Builder getTargetConfig() {
FederationConfig.Target.Builder tb = new FederationConfig.Target.Builder();
tb.
id(id.stringValue()).
@@ -92,7 +92,7 @@ public class FederationSearcher extends Searcher<FederationSearcherModel> implem
private final SearchChainConfig searchChainConfig;
- public SearchChainTarget(SearchChain searchChain, FederationOptions targetOptions) {
+ SearchChainTarget(SearchChain searchChain, FederationOptions targetOptions) {
super(searchChain.getComponentId(), targetOptions);
searchChainConfig = new SearchChainConfig(searchChain, null, targetOptions, searchChain.getDocumentTypes());
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/LocalClustersCreator.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/LocalClustersCreator.java
index 229afd56360..0307d5d5774 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/LocalClustersCreator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/LocalClustersCreator.java
@@ -2,15 +2,12 @@
package com.yahoo.vespa.model.container.search.searchchain.defaultsearchchains;
import com.yahoo.component.ComponentId;
-import com.yahoo.component.ComponentSpecification;
-import com.yahoo.component.chain.Phase;
import com.yahoo.component.chain.model.ChainSpecification;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
import com.yahoo.search.searchchain.model.federation.LocalProviderSpec;
import com.yahoo.vespa.model.container.search.searchchain.LocalProvider;
import com.yahoo.vespa.model.container.search.searchchain.SearchChains;
-import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -21,20 +18,20 @@ import java.util.Set;
*/
public class LocalClustersCreator {
- static ChainSpecification emptySearchChainSpecification(String componentName) {
+ private static ChainSpecification emptySearchChainSpecification(String componentName) {
return new ChainSpecification(new ComponentId(componentName),
VespaSearchChainsCreator.inheritsVespaPhases(), //TODO: refactor
List.of(),
Set.of());
}
- static LocalProvider createDefaultLocalProvider(String clusterName) {
+ private static LocalProvider createDefaultLocalProvider(String clusterName) {
return new LocalProvider(emptySearchChainSpecification(clusterName),
new FederationOptions(),
new LocalProviderSpec(clusterName));
}
- static Set<String> presentClusters(SearchChains searchChains) {
+ private static Set<String> presentClusters(SearchChains searchChains) {
Set<String> presentClusters = new LinkedHashSet<>();
for (LocalProvider provider : searchChains.localProviders()) {
presentClusters.add(provider.getClusterName());
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/VespaSearchChainsCreator.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/VespaSearchChainsCreator.java
index eb396c52fca..d9c3beaaf0e 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/VespaSearchChainsCreator.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/defaultsearchchains/VespaSearchChainsCreator.java
@@ -9,10 +9,18 @@ import com.yahoo.component.chain.model.ChainedComponentModel;
import com.yahoo.search.searchchain.PhaseNames;
import com.yahoo.search.searchchain.model.VespaSearchers;
import com.yahoo.search.searchchain.model.federation.FederationSearcherModel;
-import com.yahoo.vespa.model.container.component.Component;
-import com.yahoo.vespa.model.container.search.searchchain.*;
+import com.yahoo.vespa.model.container.search.searchchain.FederationSearcher;
+import com.yahoo.vespa.model.container.search.searchchain.SearchChain;
+import com.yahoo.vespa.model.container.search.searchchain.SearchChains;
+import com.yahoo.vespa.model.container.search.searchchain.Searcher;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Optional;
-import java.util.*;
/**
* Creates the search chains vespaPhases, vespa and native.
@@ -36,17 +44,15 @@ public class VespaSearchChainsCreator {
return new Phase(phase, set(before), null);
}
- public static Collection<Phase> linearPhases(String... phases) {
+ static Collection<Phase> linearPhases(String... phases) {
List<Phase> result = new ArrayList<>();
for (int i=0; i < phases.length - 1; ++i) {
- result.add(
- createPhase(phases[i], phases[i+1]));
+ result.add(createPhase(phases[i], phases[i+1]));
}
if (phases.length > 0) {
- result.add(
- createPhase(lastElement(phases), null));
+ result.add(createPhase(lastElement(phases), null));
}
return result;
@@ -54,11 +60,11 @@ public class VespaSearchChainsCreator {
}
private static Set<ComponentSpecification> noSearcherReferences() {
- return Collections.emptySet();
+ return Set.of();
}
private static Collection<Phase> noPhases() {
- return Collections.emptySet();
+ return Set.of();
}
private static ChainSpecification.Inheritance inherits(ComponentId chainId) {
@@ -79,7 +85,7 @@ public class VespaSearchChainsCreator {
private static Searcher<? extends ChainedComponentModel> createSearcher(ChainedComponentModel searcherModel) {
if (searcherModel instanceof FederationSearcherModel) {
- return new FederationSearcher((FederationSearcherModel) searcherModel, Optional.<Component>empty());
+ return new FederationSearcher((FederationSearcherModel) searcherModel, Optional.empty());
} else {
return new Searcher<>(searcherModel);
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java
index fbdefd0afb0..cdea63cfb70 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java
@@ -10,6 +10,8 @@ import org.w3c.dom.Element;
import java.util.Arrays;
import java.util.List;
+import static com.yahoo.vespa.model.container.component.chain.ProcessingHandler.PROCESSING_HANDLER_CLASS;
+
/**
* This object builds a bundle instantiation spec from an XML element.
*
@@ -30,7 +32,7 @@ public class BundleInstantiationSpecificationBuilder {
private static BundleInstantiationSpecification setBundleForSearchAndDocprocComponents(BundleInstantiationSpecification spec) {
if (PlatformBundles.isSearchAndDocprocClass(spec.getClassName()))
- return spec.inBundle(PlatformBundles.searchAndDocprocBundle);
+ return spec.inBundle(PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE);
else
return spec;
}
@@ -39,7 +41,7 @@ public class BundleInstantiationSpecificationBuilder {
private static void validate(BundleInstantiationSpecification instSpec) {
List<String> forbiddenClasses = Arrays.asList(
SearchHandler.HANDLER_CLASS,
- "com.yahoo.processing.handler.ProcessingHandler");
+ PROCESSING_HANDLER_CLASS);
for (String forbiddenClass: forbiddenClasses) {
if (forbiddenClass.equals(instSpec.getClassName())) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/CloudSecretStore.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/CloudSecretStore.java
index 18916f1e09b..373eb9714d3 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/CloudSecretStore.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/CloudSecretStore.java
@@ -21,7 +21,7 @@ public class CloudSecretStore extends SimpleComponent implements SecretStoreConf
private final List<StoreConfig> configList;
public CloudSecretStore() {
- super(new ComponentModel(BundleInstantiationSpecification.getFromStrings(CLASS, CLASS, BUNDLE)));
+ super(new ComponentModel(BundleInstantiationSpecification.fromStrings(CLASS, CLASS, BUNDLE)));
configList = new ArrayList<>();
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java
index f971aa97e6a..f6174e1740f 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java
@@ -62,13 +62,13 @@ import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.SecretStore;
import com.yahoo.vespa.model.container.component.AccessLogComponent;
import com.yahoo.vespa.model.container.component.BindingPattern;
+import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.ConnectionLogComponent;
import com.yahoo.vespa.model.container.component.FileStatusHandlerComponent;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SimpleComponent;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
-import com.yahoo.vespa.model.container.component.chain.ProcessingHandler;
import com.yahoo.vespa.model.container.docproc.ContainerDocproc;
import com.yahoo.vespa.model.container.docproc.DocprocChains;
import com.yahoo.vespa.model.container.http.AccessControl;
@@ -88,6 +88,7 @@ import com.yahoo.vespa.model.container.xml.embedder.EmbedderConfig;
import com.yahoo.vespa.model.content.StorageGroup;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -205,6 +206,8 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
addServerProviders(deployState, spec, cluster);
+ if (!standaloneBuilder) cluster.addAllPlatformBundles();
+
// Must be added after nodes:
addDeploymentSpecConfig(cluster, context, deployState.getDeployLogger());
addZooKeeper(cluster, spec);
@@ -220,7 +223,7 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
}
if (deployState.zone().system().isPublic()) {
BindingPattern bindingPattern = SystemBindingPattern.fromHttpPath("/validate-secret-store");
- Handler<AbstractConfigProducer<?>> handler = new Handler<>(
+ Handler handler = new Handler(
new ComponentModel("com.yahoo.jdisc.cloud.aws.AwsParameterStoreValidationHandler", null, "jdisc-cloud-aws", null));
handler.addServerBindings(bindingPattern);
cluster.addComponent(handler);
@@ -548,7 +551,10 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
cluster.setSearch(buildSearch(deployState, cluster, searchElement));
addSearchHandler(cluster, searchElement);
- addGUIHandler(cluster);
+
+ // Set up GUI handler only on self hosted
+ if (!deployState.isHosted())
+ addGUIHandler(cluster);
validateAndAddConfiguredComponents(deployState, cluster, searchElement, "renderer", ContainerModelBuilder::validateRendererElement);
}
@@ -595,6 +601,7 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
Element processingElement = XML.getChild(spec, "processing");
if (processingElement == null) return;
+ cluster.addSearchAndDocprocBundles();
addIncludes(processingElement);
cluster.setProcessingChains(new DomProcessingBuilder(null).build(deployState, cluster, processingElement),
serverBindings(processingElement, ProcessingChains.defaultBindings).toArray(BindingPattern[]::new));
@@ -732,9 +739,14 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
private List<ApplicationContainer> createNodes(ApplicationContainerCluster cluster, Element containerElement, Element nodesElement, ConfigModelContext context) {
if (nodesElement.hasAttribute("type")) // internal use for hosted system infrastructure nodes
return createNodesFromNodeType(cluster, nodesElement, context);
- else if (nodesElement.hasAttribute("of")) // hosted node spec referencing a content cluster
- return createNodesFromContentServiceReference(cluster, nodesElement, context);
- else if (nodesElement.hasAttribute("count")) // regular, hosted node spec
+ else if (nodesElement.hasAttribute("of")) {// hosted node spec referencing a content cluster
+ // TODO: Remove support for combined clusters in Vespa 9
+ List<ApplicationContainer> containers = createNodesFromContentServiceReference(cluster, nodesElement, context);
+ log.logApplicationPackage(WARNING, "Declaring combined cluster with <nodes of=\"...\"> is deprecated without " +
+ "replacement, and the feature will be removed in Vespa 9. Use separate container and " +
+ "content clusters instead");
+ return containers;
+ } else if (nodesElement.hasAttribute("count")) // regular, hosted node spec
return createNodesFromNodeCount(cluster, containerElement, nodesElement, context);
else if (cluster.isHostedVespa() && cluster.getZone().environment().isManuallyDeployed()) // default to 1 in manual zones
return createNodesFromNodeCount(cluster, containerElement, nodesElement, context);
@@ -877,19 +889,17 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
}
private void addSearchHandler(ApplicationContainerCluster cluster, Element searchElement) {
- // Magic spell is needed to receive the chains config :-|
- cluster.addComponent(new ProcessingHandler<>(cluster.getSearch().getChains(),
- "com.yahoo.search.searchchain.ExecutionFactory"));
+ SearchHandler searchHandler = new SearchHandler(cluster,
+ serverBindings(searchElement, SearchHandler.DEFAULT_BINDING),
+ ContainerThreadpool.UserOptions.fromXml(searchElement).orElse(null));
+ cluster.addComponent(searchHandler);
- cluster.addComponent(
- new SearchHandler(
- cluster,
- serverBindings(searchElement, SearchHandler.DEFAULT_BINDING),
- ContainerThreadpool.UserOptions.fromXml(searchElement).orElse(null)));
+ // Add as child to SearchHandler to get the correct chains config.
+ searchHandler.addComponent(Component.fromClassAndBundle(SearchHandler.EXECUTION_FACTORY_CLASS, PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE));
}
private void addGUIHandler(ApplicationContainerCluster cluster) {
- Handler<?> guiHandler = new GUIHandler();
+ Handler guiHandler = new GUIHandler();
guiHandler.addServerBindings(SystemBindingPattern.fromHttpPath(GUIHandler.BINDING_PATH));
cluster.addComponent(guiHandler);
}
@@ -919,8 +929,10 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
Element documentApiElement = XML.getChild(spec, "document-api");
if (documentApiElement == null) return null;
- ContainerDocumentApi.Options documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement);
- return new ContainerDocumentApi(cluster, documentApiOptions);
+ ContainerDocumentApi.HandlerOptions documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement);
+ Element ignoreUndefinedFields = XML.getChild(documentApiElement, "ignore-undefined-fields");
+ return new ContainerDocumentApi(cluster, documentApiOptions,
+ "true".equals(XML.getValue(ignoreUndefinedFields)));
}
private ContainerDocproc buildDocproc(DeployState deployState, ApplicationContainerCluster cluster, Element spec) {
@@ -931,7 +943,7 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> {
addIncludes(docprocElement);
DocprocChains chains = new DomDocprocChainsBuilder(null, false).build(deployState, cluster, docprocElement);
- ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement);
+ ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement, deployState.getDeployLogger());
return new ContainerDocproc(cluster, chains, docprocOptions, !standaloneBuilder);
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocprocOptionsBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocprocOptionsBuilder.java
index 1239cbf9bdc..faf2d01d385 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocprocOptionsBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocprocOptionsBuilder.java
@@ -1,18 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
+import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.vespa.model.container.docproc.ContainerDocproc;
import org.w3c.dom.Element;
+import java.util.Set;
+import java.util.logging.Level;
-/**
- * Extracted from DomDocProcClusterBuilder
- */
public class DocprocOptionsBuilder {
- public static ContainerDocproc.Options build(Element spec) {
+ public static ContainerDocproc.Options build(Element spec, DeployLogger deployLogger) {
+ checkForDeprecatedAttributes(spec, Set.of("maxqueuebytesize", "numnodesperclient", "preferlocalnode"), deployLogger);
+
return new ContainerDocproc.Options(
- getCompression(spec),
getMaxMessagesInQueue(spec),
- getSizeInMegabytes(spec.getAttribute("maxqueuebytesize")),
getTime(spec.getAttribute("maxqueuewait")),
getFactor(spec.getAttribute("maxconcurrentfactor")),
getFactor(spec.getAttribute("documentexpansionfactor")),
@@ -20,22 +20,17 @@ public class DocprocOptionsBuilder {
}
private static Integer getInt(String integer) {
- return integer == null || integer.trim().isEmpty() ?
- null:
- Integer.parseInt(integer);
- }
-
- private static boolean getCompression(Element spec) {
- return (spec.hasAttribute("compressdocuments") && spec.getAttribute("compressdocuments").equals("true"));
+ return integer == null || integer.trim().isEmpty()
+ ? null
+ : Integer.parseInt(integer);
}
private static Double getFactor(String factor) {
- return factor == null || factor.trim().isEmpty() ?
- null :
- Double.parseDouble(factor);
+ return factor == null || factor.trim().isEmpty()
+ ? null
+ : Double.parseDouble(factor);
}
-
private static Integer getMaxMessagesInQueue(Element spec) {
// get max queue size (number of messages), if set
Integer maxMessagesInQueue = null;
@@ -45,28 +40,6 @@ public class DocprocOptionsBuilder {
return maxMessagesInQueue;
}
- private static Integer getSizeInMegabytes(String size) {
- if (size == null) {
- return null;
- }
- size = size.trim();
- if (size.isEmpty()) {
- return null;
- }
-
- Integer megabyteSize;
- if (size.endsWith("m")) {
- size = size.substring(0, size.length() - 1);
- megabyteSize = Integer.parseInt(size);
- } else if (size.endsWith("g")) {
- size = size.substring(0, size.length() - 1);
- megabyteSize = Integer.parseInt(size) * 1024;
- } else {
- throw new IllegalArgumentException("Heap sizes for docproc must be set to Xm or Xg, where X is an integer specifying megabytes or gigabytes, respectively.");
- }
- return megabyteSize;
- }
-
private static Integer getTime(String intStr) {
if (intStr == null) {
return null;
@@ -78,4 +51,13 @@ public class DocprocOptionsBuilder {
return 1000 * (int)Double.parseDouble(intStr);
}
+
+ private static void checkForDeprecatedAttributes(Element spec, Set<String> names, DeployLogger deployLogger) {
+ names.forEach(n -> {
+ if (!spec.getAttribute(n).isEmpty())
+ deployLogger.logApplicationPackage(Level.WARNING, "'" + n + "' is ignored, deprecated and will be removed in Vespa 9.");
+ });
+ }
+
+
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocumentApiOptionsBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocumentApiOptionsBuilder.java
index 2ef31469c45..bb1d0af1db9 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocumentApiOptionsBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/DocumentApiOptionsBuilder.java
@@ -18,9 +18,8 @@ public class DocumentApiOptionsBuilder {
private static final Logger log = Logger.getLogger(DocumentApiOptionsBuilder.class.getName());
-
- public static ContainerDocumentApi.Options build(Element spec) {
- return new ContainerDocumentApi.Options(getBindings(spec), threadpoolOptions(spec, "http-client-api"));
+ public static ContainerDocumentApi.HandlerOptions build(Element spec) {
+ return new ContainerDocumentApi.HandlerOptions(getBindings(spec), threadpoolOptions(spec, "http-client-api"));
}
private static ContainerThreadpool.UserOptions threadpoolOptions(Element spec, String elementName) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/SearchHandler.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/SearchHandler.java
index 54d943f498a..54cd061d2c5 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/SearchHandler.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/SearchHandler.java
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
+import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.ContainerThreadpool;
@@ -11,6 +12,8 @@ import com.yahoo.vespa.model.container.search.searchchain.SearchChains;
import java.util.List;
+import static com.yahoo.container.bundle.BundleInstantiationSpecification.fromSearchAndDocproc;
+
/**
* Component definition for {@link com.yahoo.search.handler.SearchHandler}
*
@@ -19,38 +22,34 @@ import java.util.List;
class SearchHandler extends ProcessingHandler<SearchChains> {
static final String HANDLER_CLASS = com.yahoo.search.handler.SearchHandler.class.getName();
+ static final String EXECUTION_FACTORY_CLASS = com.yahoo.search.searchchain.ExecutionFactory.class.getName();
+
+ static final BundleInstantiationSpecification HANDLER_SPEC = fromSearchAndDocproc(HANDLER_CLASS);
static final BindingPattern DEFAULT_BINDING = SystemBindingPattern.fromHttpPath("/search/*");
SearchHandler(ApplicationContainerCluster cluster,
List<BindingPattern> bindings,
ContainerThreadpool.UserOptions threadpoolOptions) {
- super(cluster.getSearchChains(), HANDLER_CLASS);
+ super(cluster.getSearchChains(), HANDLER_SPEC, new Threadpool(threadpoolOptions));
bindings.forEach(this::addServerBindings);
- Threadpool threadpool = new Threadpool(cluster, threadpoolOptions);
- inject(threadpool);
- addComponent(threadpool);
}
+
private static class Threadpool extends ContainerThreadpool {
- private final ApplicationContainerCluster cluster;
- Threadpool(ApplicationContainerCluster cluster, UserOptions options) {
+ Threadpool(UserOptions options) {
super("search-handler", options);
- this.cluster = cluster;
}
@Override
- public void getConfig(ContainerThreadpoolConfig.Builder builder) {
- super.getConfig(builder);
-
- builder.maxThreadExecutionTimeSeconds(190);
- builder.keepAliveTime(5.0);
-
- // User options overrides below configuration
- if (hasUserOptions()) return;
- builder.maxThreads(-2).minThreads(-2).queueSize(-40);
+ public void setDefaultConfigValues(ContainerThreadpoolConfig.Builder builder) {
+ builder.maxThreadExecutionTimeSeconds(190)
+ .keepAliveTime(5.0)
+ .maxThreads(-2)
+ .minThreads(-2)
+ .queueSize(-40);
}
-
}
+
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/document/DocumentFactoryBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/document/DocumentFactoryBuilder.java
index 5df862647a0..7f3d7981bb6 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/document/DocumentFactoryBuilder.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/document/DocumentFactoryBuilder.java
@@ -31,7 +31,7 @@ public class DocumentFactoryBuilder {
String concDocFactory=pkg+"."+CONCRETE_DOC_FACTORY_CLASS;
String bundle = e.getAttribute("bundle");
Component<AbstractConfigProducer<?>, ComponentModel> component = new Component<>(
- new ComponentModel(BundleInstantiationSpecification.getFromStrings(concDocFactory, concDocFactory, bundle)));
+ new ComponentModel(BundleInstantiationSpecification.fromStrings(concDocFactory, concDocFactory, bundle)));
if (!cluster.getComponentsMap().containsKey(component.getComponentId())) cluster.addComponent(component);
types.put(type, concDocFactory);
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java b/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java
index d4595b3adfd..fc2f68ccd92 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java
@@ -54,7 +54,7 @@ public class Content extends ConfigModel {
// Dependencies to other models
private final AdminModel adminModel;
- // to find or add the docproc container and supplement cluster controllers with clusters having less then 3 nodes
+ // to find or add the docproc container and supplement cluster controllers with clusters having less than 3 nodes
private final Collection<ContainerModel> containers;
@SuppressWarnings("UnusedDeclaration") // Created by reflection in ConfigModelRepo
@@ -298,6 +298,7 @@ public class Content extends ConfigModel {
content.ownedIndexingCluster = Optional.of(indexingCluster);
indexingCluster.addDefaultHandlersWithVip();
+ indexingCluster.addAllPlatformBundles();
addDocproc(indexingCluster);
List<ApplicationContainer> nodes = new ArrayList<>();
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/ContentNode.java b/config-model/src/main/java/com/yahoo/vespa/model/content/ContentNode.java
index d6ed6f4f7dd..c52bb6fa2de 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/content/ContentNode.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/content/ContentNode.java
@@ -21,17 +21,21 @@ public abstract class ContentNode extends AbstractService
private final int distributionKey;
private final String rootDirectory;
- private final boolean skipCommunicationManagerThread;
- private final boolean skipMbusRequestThread;
- private final boolean skipMbusReplyThread;
+ private final int mbus_network_threads;
+ private final int mbus_rpc_targets;
+ private final int mbus_events_before_wakeup;
+ private final int rpc_num_targets;
+ private final int rpc_events_before_wakeup;
public ContentNode(ModelContext.FeatureFlags featureFlags, AbstractConfigProducer<?> parent, String clusterName, String rootDirectory, int distributionKey) {
super(parent, "" + distributionKey);
this.distributionKey = distributionKey;
- this.skipCommunicationManagerThread = featureFlags.skipCommunicationManagerThread();
- this.skipMbusRequestThread = featureFlags.skipMbusRequestThread();
- this.skipMbusReplyThread = featureFlags.skipMbusReplyThread();
this.rootDirectory = rootDirectory;
+ mbus_network_threads = featureFlags.mbusNetworkThreads();
+ mbus_rpc_targets = featureFlags.mbusCppRpcNumTargets();
+ mbus_events_before_wakeup = featureFlags.mbusCppEventsBeforeWakeup();
+ rpc_num_targets = featureFlags.rpcNumTargets();
+ rpc_events_before_wakeup = featureFlags.rpcEventsBeforeWakeup();
initialize();
setProp("clustertype", "content");
@@ -75,9 +79,11 @@ public abstract class ContentNode extends AbstractService
public void getConfig(StorCommunicationmanagerConfig.Builder builder) {
builder.mbusport(getRelativePort(0));
builder.rpcport(getRelativePort(1));
- builder.skip_thread(skipCommunicationManagerThread);
- builder.mbus.skip_request_thread(skipMbusRequestThread);
- builder.mbus.skip_reply_thread(skipMbusReplyThread);
+ builder.mbus.num_network_threads(mbus_network_threads);
+ builder.mbus.num_rpc_targets(mbus_rpc_targets);
+ builder.mbus.events_before_wakeup(mbus_events_before_wakeup);
+ builder.rpc.num_targets_per_node(rpc_num_targets);
+ builder.rpc.events_before_wakeup(rpc_events_before_wakeup);
}
@Override
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/DispatchTuning.java b/config-model/src/main/java/com/yahoo/vespa/model/content/DispatchTuning.java
index 4624ae9631d..6cad778dccf 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/content/DispatchTuning.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/content/DispatchTuning.java
@@ -11,7 +11,7 @@ public class DispatchTuning {
public static final DispatchTuning empty = new DispatchTuning.Builder().build();
- public enum DispatchPolicy { ROUNDROBIN, ADAPTIVE}
+ public enum DispatchPolicy { ROUNDROBIN, ADAPTIVE }
private final Integer maxHitsPerPartition;
private DispatchPolicy dispatchPolicy;
@@ -69,7 +69,7 @@ public class DispatchTuning {
private DispatchPolicy toDispatchPolicy(String policy) {
switch (policy.toLowerCase()) {
- case "adaptive": case "random": return DispatchPolicy.ADAPTIVE; // TODO: Deprecate 'random' on Java 8
+ case "adaptive": case "random": return DispatchPolicy.ADAPTIVE; // TODO: Deprecate 'random' on Vespa 9
case "round-robin": return DispatchPolicy.ROUNDROBIN;
default: throw new IllegalArgumentException("Unknown dispatch policy '" + policy + "'");
}
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java b/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java
index 8a8d2742df1..aef00be5ea9 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java
@@ -442,6 +442,11 @@ public class StorageGroup {
nodeRequirement = Optional.of(NodesSpecification.from(nodesElement.get(), context));
else if (nodesElement.isEmpty() && subGroups.isEmpty() && context.getDeployState().isHosted()) // request one node
nodeRequirement = Optional.of(NodesSpecification.nonDedicated(1, context));
+ else if (nodesElement.isPresent() && nodesElement.get().stringAttribute("count") == null && context.getDeployState().isHosted())
+ throw new IllegalArgumentException("""
+ Clusters in hosted environments must have a <nodes count='N'> tag
+ matching all zones, and having no <node> subtags,
+ see https://cloud.vespa.ai/en/reference/services""");
else // Nodes or groups explicitly listed - resolve in GroupBuilder
nodeRequirement = Optional.empty();
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/routing/DocumentProtocol.java b/config-model/src/main/java/com/yahoo/vespa/model/routing/DocumentProtocol.java
index 754800a42e1..8a8d38e23e3 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/routing/DocumentProtocol.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/routing/DocumentProtocol.java
@@ -182,44 +182,26 @@ public final class DocumentProtocol implements Protocol,
return table;
}
- private static void addContainerClusterDocprocHops(Collection<ContainerCluster<?>> containerClusters,
- RoutingTableSpec table) {
-
+ private static void addContainerClusterDocprocHops(Collection<ContainerCluster<?>> containerClusters, RoutingTableSpec table) {
for (ContainerCluster<?> cluster: containerClusters) {
ContainerDocproc docproc = cluster.getDocproc();
if (docproc != null) {
- String policy = policy(docproc);
-
for (DocprocChain chain : docproc.getChains().allChains().allComponents()) {
- addChainHop(table, cluster.getConfigId(), policy, chain);
+ addChainHop(table, cluster.getConfigId(), chain);
}
}
}
}
- private static void addChainHop(RoutingTableSpec table, String configId, String policy, DocprocChain chain) {
- final StringBuilder selector = new StringBuilder();
- if (policy != null) {
- selector.append(configId).append("/").append(policy).append("/").append(chain.getSessionName());
- } else {
- selector.append("[LoadBalancer:cluster=").append(configId)
- .append(";session=").append(chain.getSessionName())
- .append("]");
- }
+ private static void addChainHop(RoutingTableSpec table, String configId, DocprocChain chain) {
+ StringBuilder selector = new StringBuilder();
+ selector.append("[LoadBalancer:cluster=").append(configId)
+ .append(";session=").append(chain.getSessionName())
+ .append("]");
table.addHop(new HopSpec(chain.getServiceName(), selector.toString()));
}
- private static String policy(ContainerDocproc docproc) {
- if (docproc.getNumNodesPerClient() > 0) {
- return "[SubsetService:" + docproc.getNumNodesPerClient() + "]";
- } else if (docproc.isPreferLocalNode()) {
- return "[LocalService]";
- } else {
- return null;
- }
- }
-
/**
* Create hops to all configured storage nodes for the Document protocol. The "Distributor" policy resolves its
* recipients using slobrok lookups, so it requires no configured recipients.
@@ -228,23 +210,22 @@ public final class DocumentProtocol implements Protocol,
* @param table the routing table to add to
*/
private static void addContentRouting(List<ContentCluster> content, RoutingTableSpec table) {
-
- for (ContentCluster cluster : content) {
- RouteSpec spec = new RouteSpec(cluster.getConfigId());
-
- if (cluster.getSearch().hasIndexedCluster()) {
- table.addRoute(spec.addHop("[MessageType:" + cluster.getConfigId() + "]"));
- table.addRoute(new RouteSpec(getIndexedRouteName(cluster.getConfigId()))
- .addHop(cluster.getSearch().getIndexed().getIndexingServiceName())
- .addHop("[Content:cluster=" + cluster.getName() + "]"));
- table.addRoute(new RouteSpec(getDirectRouteName(cluster.getConfigId()))
- .addHop("[Content:cluster=" + cluster.getName() + "]"));
- } else {
- table.addRoute(spec.addHop("[Content:cluster=" + cluster.getName() + "]"));
- }
- table.addRoute(new RouteSpec("storage/cluster." + cluster.getName())
- .addHop("route:" + cluster.getConfigId()));
+ for (ContentCluster cluster : content) {
+ RouteSpec spec = new RouteSpec(cluster.getConfigId());
+
+ if (cluster.getSearch().hasIndexedCluster()) {
+ table.addRoute(spec.addHop("[MessageType:" + cluster.getConfigId() + "]"));
+ table.addRoute(new RouteSpec(getIndexedRouteName(cluster.getConfigId()))
+ .addHop(cluster.getSearch().getIndexed().getIndexingServiceName())
+ .addHop("[Content:cluster=" + cluster.getName() + "]"));
+ table.addRoute(new RouteSpec(getDirectRouteName(cluster.getConfigId()))
+ .addHop("[Content:cluster=" + cluster.getName() + "]"));
+ } else {
+ table.addRoute(spec.addHop("[Content:cluster=" + cluster.getName() + "]"));
}
+ table.addRoute(new RouteSpec("storage/cluster." + cluster.getName())
+ .addHop("route:" + cluster.getConfigId()));
+ }
}
/**
@@ -255,9 +236,8 @@ public final class DocumentProtocol implements Protocol,
* @param table the routing table to add to
*/
private static void addIndexingHop(List<ContentCluster> content, RoutingTableSpec table) {
- if (content.isEmpty()) {
- return;
- }
+ if (content.isEmpty()) return;
+
HopSpec hop = new HopSpec("indexing", "[DocumentRouteSelector]");
for (ContentCluster cluster : content) {
hop.addRecipient(cluster.getConfigId());
@@ -281,9 +261,8 @@ public final class DocumentProtocol implements Protocol,
private static void addDefaultRoutes(List<ContentCluster> content,
Collection<ContainerCluster<?>> containerClusters,
RoutingTableSpec table) {
- if (content.isEmpty() || !indexingHopExists(table)) {
- return;
- }
+ if (content.isEmpty() || !indexingHopExists(table)) return;
+
RouteSpec route = new RouteSpec("default");
String hop = getContainerClustersDocprocHop(containerClusters);
if (hop != null) {
@@ -326,9 +305,9 @@ public final class DocumentProtocol implements Protocol,
}
private static DocprocChain getDefaultChain(ContainerDocproc docproc) {
- return docproc == null ?
- null:
- docproc.getChains().allChains().getComponent("default");
+ return docproc == null
+ ? null
+ : docproc.getChains().allChains().getComponent("default");
}
/**
diff --git a/config-model/src/main/resources/schema/containercluster.rnc b/config-model/src/main/resources/schema/containercluster.rnc
index 1ab3c9893bf..006db8fe510 100644
--- a/config-model/src/main/resources/schema/containercluster.rnc
+++ b/config-model/src/main/resources/schema/containercluster.rnc
@@ -203,6 +203,7 @@ ProcessingInContainer = element processing {
DocumentApi = element document-api {
ServerBindings &
GenericConfig* &
+ element ignore-undefined-fields { xsd:boolean }? &
element abortondocumenterror { xsd:boolean }? &
element retryenabled { xsd:boolean }? &
element route { text }? &
diff --git a/config-model/src/main/resources/schema/docproc.rnc b/config-model/src/main/resources/schema/docproc.rnc
index 1e7e28b2002..11f8e14fb2d 100644
--- a/config-model/src/main/resources/schema/docproc.rnc
+++ b/config-model/src/main/resources/schema/docproc.rnc
@@ -11,9 +11,6 @@ SchemaMapping = element map {
}+
}
-
-
-
#Version 3 config:
DocProcV3 = attribute version { "3.0" },
@@ -22,16 +19,18 @@ DocProcV3 = attribute version { "3.0" },
GenericConfig*
)
+# TODO Here we need a thorough cleaning
DocprocClusterAttributes = attribute compressdocuments { xsd:boolean }? &
- attribute numnodesperclient { xsd:positiveInteger }? &
- attribute preferlocalnode { xsd:boolean }? &
+ attribute numnodesperclient { xsd:positiveInteger }? & # TODO: Remove in Vespa 9
+ attribute preferlocalnode { xsd:boolean }? & # TODO: Remove in Vespa 9
attribute maxmessagesinqueue { xsd:nonNegativeInteger }? &
- attribute maxqueuebytesize { xsd:string { minLength = "1" } }? &
+ attribute maxqueuebytesize { xsd:string { minLength = "1" } }? & # TODO: Remove in Vespa 9
attribute maxqueuewait { xsd:positiveInteger }? &
attribute maxconcurrentfactor { xsd:double { minExclusive = "0.0" maxExclusive = "1.0" } }? &
attribute documentexpansionfactor { xsd:double { minExclusive = "0.0" } }? &
attribute containercorememory { xsd:nonNegativeInteger }?
+# TODO Here we need a thorough cleaning
ClusterV3 = element cluster {
attribute name { xsd:NCName } &
DocprocClusterAttributes? &
diff --git a/config-model/src/test/cfg/admin/adminconfigbaseport/hosts.xml b/config-model/src/test/cfg/admin/adminconfigbaseport/hosts.xml
deleted file mode 100644
index dfc17c11183..00000000000
--- a/config-model/src/test/cfg/admin/adminconfigbaseport/hosts.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-<hosts>
- <host name="localhost">
- <alias>adminserver</alias>
- </host>
-</hosts>
diff --git a/config-model/src/test/cfg/admin/adminconfigbaseport/services.xml b/config-model/src/test/cfg/admin/adminconfigbaseport/services.xml
deleted file mode 100644
index ba2c2ea42da..00000000000
--- a/config-model/src/test/cfg/admin/adminconfigbaseport/services.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-<services>
-
- <admin version="2.0">
- <adminserver hostalias="adminserver" baseport="9999"/>
- <adminserver hostalias="adminserver"/>
- <logserver hostalias="adminserver"/>
- </admin>
-
- <search version="1.0">
- <qrservers>
- <qrserver hostalias="adminserver" baseport="4080"/>
- </qrservers>
- </search>
-
-</services>
diff --git a/config-model/src/test/cfg/application/app_qrserverandgw/hosts.xml b/config-model/src/test/cfg/application/app_qrserverandgw/hosts.xml
deleted file mode 100644
index 3c78eba2e68..00000000000
--- a/config-model/src/test/cfg/application/app_qrserverandgw/hosts.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-<hosts>
- <host name="localhost">
- <alias>node0</alias>
- </host>
-</hosts>
diff --git a/config-model/src/test/cfg/application/app_qrserverandgw/schemas/message.sd b/config-model/src/test/cfg/application/app_qrserverandgw/schemas/message.sd
deleted file mode 100644
index 40457c9e636..00000000000
--- a/config-model/src/test/cfg/application/app_qrserverandgw/schemas/message.sd
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-search message {
-
- document message {
- field foo type string {
- indexing: summary
- }
- }
-}
diff --git a/config-model/src/test/cfg/application/app_qrserverandgw/services.xml b/config-model/src/test/cfg/application/app_qrserverandgw/services.xml
deleted file mode 100644
index fbcd698035e..00000000000
--- a/config-model/src/test/cfg/application/app_qrserverandgw/services.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-
-<services version="1.0">
-
- <admin version="2.0">
- <adminserver hostalias="node0"/>
- </admin>
-
- <container version="1.0">
- <nodes>
- <node hostalias="node0"/>
- </nodes>
- <document-api/>
- <search/>
- </container>
-
- <content version="1.0" id="message">
- <redundancy>1</redundancy>
- <documents>
- <document type="message" mode="index"/>
- </documents>
- <nodes>
- <node hostalias="node0" distribution-key="0" />
- </nodes>
- </content>
-
-
-</services>
diff --git a/config-model/src/test/configmodel/types/documentmanager.cfg b/config-model/src/test/configmodel/types/documentmanager.cfg
index 00920cc6d76..0269efcc4ca 100644
--- a/config-model/src/test/configmodel/types/documentmanager.cfg
+++ b/config-model/src/test/configmodel/types/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/documenttypes.cfg b/config-model/src/test/configmodel/types/documenttypes.cfg
index 7ea2fa42a2a..b1c3075df2c 100644
--- a/config-model/src/test/configmodel/types/documenttypes.cfg
+++ b/config-model/src/test/configmodel/types/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/documenttypes_with_doc_field.cfg b/config-model/src/test/configmodel/types/documenttypes_with_doc_field.cfg
index 15430101553..be4a18f2ab2 100644
--- a/config-model/src/test/configmodel/types/documenttypes_with_doc_field.cfg
+++ b/config-model/src/test/configmodel/types/documenttypes_with_doc_field.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documentmanager_multiple_imported_fields.cfg b/config-model/src/test/configmodel/types/references/documentmanager_multiple_imported_fields.cfg
index a4b37113ef1..778fe2a44c4 100644
--- a/config-model/src/test/configmodel/types/references/documentmanager_multiple_imported_fields.cfg
+++ b/config-model/src/test/configmodel/types/references/documentmanager_multiple_imported_fields.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documentmanager_refs_to_other_types.cfg b/config-model/src/test/configmodel/types/references/documentmanager_refs_to_other_types.cfg
index f6d4269abcd..4d0a8396d91 100644
--- a/config-model/src/test/configmodel/types/references/documentmanager_refs_to_other_types.cfg
+++ b/config-model/src/test/configmodel/types/references/documentmanager_refs_to_other_types.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documentmanager_refs_to_same_type.cfg b/config-model/src/test/configmodel/types/references/documentmanager_refs_to_same_type.cfg
index 31f514b16cd..17d6264e138 100644
--- a/config-model/src/test/configmodel/types/references/documentmanager_refs_to_same_type.cfg
+++ b/config-model/src/test/configmodel/types/references/documentmanager_refs_to_same_type.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documenttypes_multiple_imported_fields.cfg b/config-model/src/test/configmodel/types/references/documenttypes_multiple_imported_fields.cfg
index 1582c6572da..9e76cb14b20 100644
--- a/config-model/src/test/configmodel/types/references/documenttypes_multiple_imported_fields.cfg
+++ b/config-model/src/test/configmodel/types/references/documenttypes_multiple_imported_fields.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documenttypes_ref_to_self_type.cfg b/config-model/src/test/configmodel/types/references/documenttypes_ref_to_self_type.cfg
index 19bcb81db38..e8398b159dd 100644
--- a/config-model/src/test/configmodel/types/references/documenttypes_ref_to_self_type.cfg
+++ b/config-model/src/test/configmodel/types/references/documenttypes_ref_to_self_type.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
documenttype[].id 2987301
documenttype[].name "ad"
diff --git a/config-model/src/test/configmodel/types/references/documenttypes_refs_to_other_types.cfg b/config-model/src/test/configmodel/types/references/documenttypes_refs_to_other_types.cfg
index 4222229cdd3..0d817fd4e07 100644
--- a/config-model/src/test/configmodel/types/references/documenttypes_refs_to_other_types.cfg
+++ b/config-model/src/test/configmodel/types/references/documenttypes_refs_to_other_types.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/configmodel/types/references/documenttypes_refs_to_same_type.cfg b/config-model/src/test/configmodel/types/references/documenttypes_refs_to_same_type.cfg
index 0d3802bcbe3..f681a8de9ba 100644
--- a/config-model/src/test/configmodel/types/references/documenttypes_refs_to_same_type.cfg
+++ b/config-model/src/test/configmodel/types/references/documenttypes_refs_to_same_type.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/derived/advanced/documentmanager.cfg b/config-model/src/test/derived/advanced/documentmanager.cfg
index 6eea5ae038b..375d42bc63e 100644
--- a/config-model/src/test/derived/advanced/documentmanager.cfg
+++ b/config-model/src/test/derived/advanced/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/advanced/summarymap.cfg b/config-model/src/test/derived/advanced/summarymap.cfg
index 31cc15f07db..f91aebe57f9 100644
--- a/config-model/src/test/derived/advanced/summarymap.cfg
+++ b/config-model/src/test/derived/advanced/summarymap.cfg
@@ -8,3 +8,6 @@ override[].arguments ""
override[].field "location_zcurve"
override[].command "attribute"
override[].arguments "location_zcurve"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/annotationsimplicitstruct/documentmanager.cfg b/config-model/src/test/derived/annotationsimplicitstruct/documentmanager.cfg
index f15b49c6b76..c5acbbf87e3 100644
--- a/config-model/src/test/derived/annotationsimplicitstruct/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsimplicitstruct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationsinheritance/documentmanager.cfg b/config-model/src/test/derived/annotationsinheritance/documentmanager.cfg
index 4098c0fe53c..edf5fd13d1b 100644
--- a/config-model/src/test/derived/annotationsinheritance/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsinheritance/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationsinheritance2/documentmanager.cfg b/config-model/src/test/derived/annotationsinheritance2/documentmanager.cfg
index b67f1df3b4b..d931cae2048 100644
--- a/config-model/src/test/derived/annotationsinheritance2/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsinheritance2/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationspolymorphy/documentmanager.cfg b/config-model/src/test/derived/annotationspolymorphy/documentmanager.cfg
index df8d038fe79..76882afd3c5 100644
--- a/config-model/src/test/derived/annotationspolymorphy/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationspolymorphy/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationsreference/documentmanager.cfg b/config-model/src/test/derived/annotationsreference/documentmanager.cfg
index 94258fdb798..ef0166ba4a7 100644
--- a/config-model/src/test/derived/annotationsreference/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsreference/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationssimple/documentmanager.cfg b/config-model/src/test/derived/annotationssimple/documentmanager.cfg
index e863e305643..a076d5a7479 100644
--- a/config-model/src/test/derived/annotationssimple/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationssimple/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationsstruct/documentmanager.cfg b/config-model/src/test/derived/annotationsstruct/documentmanager.cfg
index 62084994721..d0b527ddaf3 100644
--- a/config-model/src/test/derived/annotationsstruct/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsstruct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/annotationsstructarray/documentmanager.cfg b/config-model/src/test/derived/annotationsstructarray/documentmanager.cfg
index 640655c53b6..80792768c34 100644
--- a/config-model/src/test/derived/annotationsstructarray/documentmanager.cfg
+++ b/config-model/src/test/derived/annotationsstructarray/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/array_of_struct_attribute/summary.cfg b/config-model/src/test/derived/array_of_struct_attribute/summary.cfg
index 3f0994cf2bd..38298feaa0c 100644
--- a/config-model/src/test/derived/array_of_struct_attribute/summary.cfg
+++ b/config-model/src/test/derived/array_of_struct_attribute/summary.cfg
@@ -11,3 +11,12 @@ classes[].fields[].name "summaryfeatures"
classes[].fields[].type "featuredata"
classes[].fields[].name "documentid"
classes[].fields[].type "longstring"
+classes[].id 659145226
+classes[].name "rename"
+classes[].omitsummaryfeatures false
+classes[].fields[].name "new_elem_array"
+classes[].fields[].type "jsonstring"
+classes[].fields[].name "rankfeatures"
+classes[].fields[].type "featuredata"
+classes[].fields[].name "summaryfeatures"
+classes[].fields[].type "featuredata"
diff --git a/config-model/src/test/derived/array_of_struct_attribute/summarymap.cfg b/config-model/src/test/derived/array_of_struct_attribute/summarymap.cfg
index bb99d6ced39..4fb66c0e0b1 100644
--- a/config-model/src/test/derived/array_of_struct_attribute/summarymap.cfg
+++ b/config-model/src/test/derived/array_of_struct_attribute/summarymap.cfg
@@ -1,10 +1,16 @@
defaultoutputclass -1
-override[].field "elem_array"
+override[].field "new_elem_array"
override[].command "attributecombiner"
-override[].arguments ""
+override[].arguments "elem_array"
override[].field "rankfeatures"
override[].command "rankfeatures"
override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "elem_array"
+override[].command "attributecombiner"
+override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/array_of_struct_attribute/test.sd b/config-model/src/test/derived/array_of_struct_attribute/test.sd
index 2f7c7755ca5..969dba96bf8 100644
--- a/config-model/src/test/derived/array_of_struct_attribute/test.sd
+++ b/config-model/src/test/derived/array_of_struct_attribute/test.sd
@@ -16,4 +16,7 @@ schema test {
}
}
}
+ document-summary rename {
+ summary new_elem_array type array<elem> { source: elem_array }
+ }
}
diff --git a/config-model/src/test/derived/arrays/documentmanager.cfg b/config-model/src/test/derived/arrays/documentmanager.cfg
index 9bf53699140..ef3841f180b 100644
--- a/config-model/src/test/derived/arrays/documentmanager.cfg
+++ b/config-model/src/test/derived/arrays/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/attributeprefetch/documentmanager.cfg b/config-model/src/test/derived/attributeprefetch/documentmanager.cfg
index 9d91ad3f5ab..5733c7d1bbd 100644
--- a/config-model/src/test/derived/attributeprefetch/documentmanager.cfg
+++ b/config-model/src/test/derived/attributeprefetch/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/attributeprefetch/summarymap.cfg b/config-model/src/test/derived/attributeprefetch/summarymap.cfg
index 2e4bec651e7..ae5e4b5f7c5 100644
--- a/config-model/src/test/derived/attributeprefetch/summarymap.cfg
+++ b/config-model/src/test/derived/attributeprefetch/summarymap.cfg
@@ -23,3 +23,6 @@ override[].arguments "singledouble"
override[].field "singlestring"
override[].command "attribute"
override[].arguments "singlestring"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/attributes/summarymap.cfg b/config-model/src/test/derived/attributes/summarymap.cfg
index a96f1e3858d..72a5e41e555 100644
--- a/config-model/src/test/derived/attributes/summarymap.cfg
+++ b/config-model/src/test/derived/attributes/summarymap.cfg
@@ -50,3 +50,6 @@ override[].arguments "a11"
override[].field "a12"
override[].command "attribute"
override[].arguments "a12"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/complex/documentmanager.cfg b/config-model/src/test/derived/complex/documentmanager.cfg
index da4f2fc0942..f44ab48c255 100644
--- a/config-model/src/test/derived/complex/documentmanager.cfg
+++ b/config-model/src/test/derived/complex/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/complex/summarymap.cfg b/config-model/src/test/derived/complex/summarymap.cfg
index 6f65e7d3bc3..685b818fc6a 100644
--- a/config-model/src/test/derived/complex/summarymap.cfg
+++ b/config-model/src/test/derived/complex/summarymap.cfg
@@ -29,3 +29,6 @@ override[].arguments "ts"
override[].field "combineda"
override[].command "attribute"
override[].arguments "combineda"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/declstruct/documentmanager.cfg b/config-model/src/test/derived/declstruct/documentmanager.cfg
index 0286af0eade..7b95c78d584 100644
--- a/config-model/src/test/derived/declstruct/documentmanager.cfg
+++ b/config-model/src/test/derived/declstruct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/duplicate_struct/documentmanager.cfg b/config-model/src/test/derived/duplicate_struct/documentmanager.cfg
index bb791943d41..af20f058eed 100644
--- a/config-model/src/test/derived/duplicate_struct/documentmanager.cfg
+++ b/config-model/src/test/derived/duplicate_struct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/duplicate_struct/documenttypes.cfg b/config-model/src/test/derived/duplicate_struct/documenttypes.cfg
index 13567666674..b751b1ebbbf 100644
--- a/config-model/src/test/derived/duplicate_struct/documenttypes.cfg
+++ b/config-model/src/test/derived/duplicate_struct/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/emptydefault/documentmanager.cfg b/config-model/src/test/derived/emptydefault/documentmanager.cfg
index a6530d49507..63732728b05 100644
--- a/config-model/src/test/derived/emptydefault/documentmanager.cfg
+++ b/config-model/src/test/derived/emptydefault/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/emptydefault/summarymap.cfg b/config-model/src/test/derived/emptydefault/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/emptydefault/summarymap.cfg
+++ b/config-model/src/test/derived/emptydefault/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/id/documentmanager.cfg b/config-model/src/test/derived/id/documentmanager.cfg
index fafea7dd4bc..583ca8497b8 100644
--- a/config-model/src/test/derived/id/documentmanager.cfg
+++ b/config-model/src/test/derived/id/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/id/summarymap.cfg b/config-model/src/test/derived/id/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/id/summarymap.cfg
+++ b/config-model/src/test/derived/id/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/imported_fields_inherited_reference/documenttypes.cfg b/config-model/src/test/derived/imported_fields_inherited_reference/documenttypes.cfg
index b15734169a5..aa960e70326 100644
--- a/config-model/src/test/derived/imported_fields_inherited_reference/documenttypes.cfg
+++ b/config-model/src/test/derived/imported_fields_inherited_reference/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/imported_position_field/summarymap.cfg b/config-model/src/test/derived/imported_position_field/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/imported_position_field/summarymap.cfg
+++ b/config-model/src/test/derived/imported_position_field/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/imported_position_field_summary/summarymap.cfg b/config-model/src/test/derived/imported_position_field_summary/summarymap.cfg
index 5ea45a67905..c17dcdce267 100644
--- a/config-model/src/test/derived/imported_position_field_summary/summarymap.cfg
+++ b/config-model/src/test/derived/imported_position_field_summary/summarymap.cfg
@@ -8,3 +8,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/imported_struct_fields/summarymap.cfg b/config-model/src/test/derived/imported_struct_fields/summarymap.cfg
index cd19a75e85f..653b0a26b75 100644
--- a/config-model/src/test/derived/imported_struct_fields/summarymap.cfg
+++ b/config-model/src/test/derived/imported_struct_fields/summarymap.cfg
@@ -1,4 +1,7 @@
defaultoutputclass -1
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
override[].field "my_elem_array"
override[].command "attributecombiner"
override[].arguments ""
diff --git a/config-model/src/test/derived/importedfields/summarymap.cfg b/config-model/src/test/derived/importedfields/summarymap.cfg
index 03ae5e2676e..7a4677301db 100644
--- a/config-model/src/test/derived/importedfields/summarymap.cfg
+++ b/config-model/src/test/derived/importedfields/summarymap.cfg
@@ -23,3 +23,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/indexswitches/documentmanager.cfg b/config-model/src/test/derived/indexswitches/documentmanager.cfg
index 7f6b9150e07..a902a5954a5 100644
--- a/config-model/src/test/derived/indexswitches/documentmanager.cfg
+++ b/config-model/src/test/derived/indexswitches/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/indexswitches/summarymap.cfg b/config-model/src/test/derived/indexswitches/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/indexswitches/summarymap.cfg
+++ b/config-model/src/test/derived/indexswitches/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/inheritance/documentmanager.cfg b/config-model/src/test/derived/inheritance/documentmanager.cfg
index f0917864ebd..fd4994dbefb 100644
--- a/config-model/src/test/derived/inheritance/documentmanager.cfg
+++ b/config-model/src/test/derived/inheritance/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/inheritance/summarymap.cfg b/config-model/src/test/derived/inheritance/summarymap.cfg
index 0f5303a52e7..7fb5eab0200 100644
--- a/config-model/src/test/derived/inheritance/summarymap.cfg
+++ b/config-model/src/test/derived/inheritance/summarymap.cfg
@@ -14,3 +14,6 @@ override[].arguments "overridden"
override[].field "onlymother"
override[].command "attribute"
override[].arguments "onlymother"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/inheritdiamond/documentmanager.cfg b/config-model/src/test/derived/inheritdiamond/documentmanager.cfg
index 10fdcf50026..9f1207b77a3 100644
--- a/config-model/src/test/derived/inheritdiamond/documentmanager.cfg
+++ b/config-model/src/test/derived/inheritdiamond/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/inheritfromgrandparent/documentmanager.cfg b/config-model/src/test/derived/inheritfromgrandparent/documentmanager.cfg
index 8c0ffd50840..68503ebd5aa 100644
--- a/config-model/src/test/derived/inheritfromgrandparent/documentmanager.cfg
+++ b/config-model/src/test/derived/inheritfromgrandparent/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/inheritfromparent/documentmanager.cfg b/config-model/src/test/derived/inheritfromparent/documentmanager.cfg
index 186f3c0e3c1..c8fdeaedf11 100644
--- a/config-model/src/test/derived/inheritfromparent/documentmanager.cfg
+++ b/config-model/src/test/derived/inheritfromparent/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/inheritfromparent/documenttypes.cfg b/config-model/src/test/derived/inheritfromparent/documenttypes.cfg
index e8fd97671ff..fd9623f716a 100644
--- a/config-model/src/test/derived/inheritfromparent/documenttypes.cfg
+++ b/config-model/src/test/derived/inheritfromparent/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/inheritfromparent/summarymap.cfg b/config-model/src/test/derived/inheritfromparent/summarymap.cfg
index cf8b410c850..fb1a18ab864 100644
--- a/config-model/src/test/derived/inheritfromparent/summarymap.cfg
+++ b/config-model/src/test/derived/inheritfromparent/summarymap.cfg
@@ -8,3 +8,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/mail/onlydoc/documentmanager.cfg b/config-model/src/test/derived/mail/onlydoc/documentmanager.cfg
index 27ac015e630..6bf972c1c80 100644
--- a/config-model/src/test/derived/mail/onlydoc/documentmanager.cfg
+++ b/config-model/src/test/derived/mail/onlydoc/documentmanager.cfg
@@ -1,4 +1,3 @@
-enablecompression false
usev8geopositions false
datatype[].id 1381038251
datatype[].structtype[].name "position"
diff --git a/config-model/src/test/derived/map_attribute/summarymap.cfg b/config-model/src/test/derived/map_attribute/summarymap.cfg
index 8936b26ca64..f9267fb39d3 100644
--- a/config-model/src/test/derived/map_attribute/summarymap.cfg
+++ b/config-model/src/test/derived/map_attribute/summarymap.cfg
@@ -8,3 +8,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/map_of_struct_attribute/summary.cfg b/config-model/src/test/derived/map_of_struct_attribute/summary.cfg
index dadf7b5cfe7..997743389c6 100644
--- a/config-model/src/test/derived/map_of_struct_attribute/summary.cfg
+++ b/config-model/src/test/derived/map_of_struct_attribute/summary.cfg
@@ -1,6 +1,6 @@
-defaultsummaryid 1131098132
+defaultsummaryid 1048168773
usev8geopositions true
-classes[].id 1131098132
+classes[].id 1048168773
classes[].name "default"
classes[].omitsummaryfeatures false
classes[].fields[].name "str_elem_map"
@@ -11,5 +11,18 @@ classes[].fields[].name "rankfeatures"
classes[].fields[].type "featuredata"
classes[].fields[].name "summaryfeatures"
classes[].fields[].type "featuredata"
+classes[].fields[].name "new_int_elem_map"
+classes[].fields[].type "jsonstring"
classes[].fields[].name "documentid"
classes[].fields[].type "longstring"
+classes[].id 1424421039
+classes[].name "rename"
+classes[].omitsummaryfeatures false
+classes[].fields[].name "new_str_elem_map"
+classes[].fields[].type "jsonstring"
+classes[].fields[].name "new_int_elem_map"
+classes[].fields[].type "jsonstring"
+classes[].fields[].name "rankfeatures"
+classes[].fields[].type "featuredata"
+classes[].fields[].name "summaryfeatures"
+classes[].fields[].type "featuredata"
diff --git a/config-model/src/test/derived/map_of_struct_attribute/summarymap.cfg b/config-model/src/test/derived/map_of_struct_attribute/summarymap.cfg
index 1540b821ae1..46608a4a885 100644
--- a/config-model/src/test/derived/map_of_struct_attribute/summarymap.cfg
+++ b/config-model/src/test/derived/map_of_struct_attribute/summarymap.cfg
@@ -1,10 +1,19 @@
defaultoutputclass -1
-override[].field "str_elem_map"
+override[].field "new_str_elem_map"
override[].command "attributecombiner"
-override[].arguments ""
+override[].arguments "str_elem_map"
+override[].field "new_int_elem_map"
+override[].command "copy"
+override[].arguments "int_elem_map"
override[].field "rankfeatures"
override[].command "rankfeatures"
override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "str_elem_map"
+override[].command "attributecombiner"
+override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/map_of_struct_attribute/test.sd b/config-model/src/test/derived/map_of_struct_attribute/test.sd
index 7806d49392e..2e71678148b 100644
--- a/config-model/src/test/derived/map_of_struct_attribute/test.sd
+++ b/config-model/src/test/derived/map_of_struct_attribute/test.sd
@@ -29,4 +29,8 @@ schema test {
}
}
}
+ document-summary rename {
+ summary new_str_elem_map type map<string,elem> { source: str_elem_map }
+ summary new_int_elem_map type map<int,elem> { source: int_elem_map }
+ }
}
diff --git a/config-model/src/test/derived/multi_struct/documentmanager.cfg b/config-model/src/test/derived/multi_struct/documentmanager.cfg
index dbf753c6bc3..753196b4d02 100644
--- a/config-model/src/test/derived/multi_struct/documentmanager.cfg
+++ b/config-model/src/test/derived/multi_struct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/multi_struct/documenttypes.cfg b/config-model/src/test/derived/multi_struct/documenttypes.cfg
index 9ce19079177..4926675582b 100644
--- a/config-model/src/test/derived/multi_struct/documenttypes.cfg
+++ b/config-model/src/test/derived/multi_struct/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/multiplesummaries/summarymap.cfg b/config-model/src/test/derived/multiplesummaries/summarymap.cfg
index df6d3bedafd..ee61fac39f4 100644
--- a/config-model/src/test/derived/multiplesummaries/summarymap.cfg
+++ b/config-model/src/test/derived/multiplesummaries/summarymap.cfg
@@ -53,3 +53,6 @@ override[].arguments "abolded"
override[].field "dynamice"
override[].command "dynamicteaser"
override[].arguments "dynamice"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/music/summarymap.cfg b/config-model/src/test/derived/music/summarymap.cfg
index e250c3747cc..2973d4f6750 100644
--- a/config-model/src/test/derived/music/summarymap.cfg
+++ b/config-model/src/test/derived/music/summarymap.cfg
@@ -44,3 +44,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/namecollision/documentmanager.cfg b/config-model/src/test/derived/namecollision/documentmanager.cfg
index 73730595574..79807197b48 100644
--- a/config-model/src/test/derived/namecollision/documentmanager.cfg
+++ b/config-model/src/test/derived/namecollision/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/newrank/summarymap.cfg b/config-model/src/test/derived/newrank/summarymap.cfg
index 3350d892b0c..e769e3a2a5a 100644
--- a/config-model/src/test/derived/newrank/summarymap.cfg
+++ b/config-model/src/test/derived/newrank/summarymap.cfg
@@ -47,3 +47,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/position_nosummary/summarymap.cfg b/config-model/src/test/derived/position_nosummary/summarymap.cfg
index 0a36f98c6ca..2ed737b5205 100644
--- a/config-model/src/test/derived/position_nosummary/summarymap.cfg
+++ b/config-model/src/test/derived/position_nosummary/summarymap.cfg
@@ -8,3 +8,6 @@ override[].arguments ""
override[].field "pos_zcurve"
override[].command "attribute"
override[].arguments "pos_zcurve"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/position_summary/summarymap.cfg b/config-model/src/test/derived/position_summary/summarymap.cfg
index 2223d3380a0..d34c4727810 100644
--- a/config-model/src/test/derived/position_summary/summarymap.cfg
+++ b/config-model/src/test/derived/position_summary/summarymap.cfg
@@ -11,3 +11,6 @@ override[].arguments ""
override[].field "pos_zcurve"
override[].command "attribute"
override[].arguments "pos_zcurve"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/predicate_attribute/summarymap.cfg b/config-model/src/test/derived/predicate_attribute/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/predicate_attribute/summarymap.cfg
+++ b/config-model/src/test/derived/predicate_attribute/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/prefixexactattribute/documentmanager.cfg b/config-model/src/test/derived/prefixexactattribute/documentmanager.cfg
index be048ee2eba..3158348d5be 100644
--- a/config-model/src/test/derived/prefixexactattribute/documentmanager.cfg
+++ b/config-model/src/test/derived/prefixexactattribute/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/rankingexpression/summarymap.cfg b/config-model/src/test/derived/rankingexpression/summarymap.cfg
index e8d9bd08ca7..bc8e67320ad 100644
--- a/config-model/src/test/derived/rankingexpression/summarymap.cfg
+++ b/config-model/src/test/derived/rankingexpression/summarymap.cfg
@@ -32,3 +32,6 @@ override[].arguments "bar3"
override[].field "bar4"
override[].command "attribute"
override[].arguments "bar4"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/ranktypes/documentmanager.cfg b/config-model/src/test/derived/ranktypes/documentmanager.cfg
index 33d41084651..ade7795c3ca 100644
--- a/config-model/src/test/derived/ranktypes/documentmanager.cfg
+++ b/config-model/src/test/derived/ranktypes/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/ranktypes/summarymap.cfg b/config-model/src/test/derived/ranktypes/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/ranktypes/summarymap.cfg
+++ b/config-model/src/test/derived/ranktypes/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/reference_fields/summarymap.cfg b/config-model/src/test/derived/reference_fields/summarymap.cfg
index 8956a146b74..b247ff94bbf 100644
--- a/config-model/src/test/derived/reference_fields/summarymap.cfg
+++ b/config-model/src/test/derived/reference_fields/summarymap.cfg
@@ -5,3 +5,6 @@ override[].arguments ""
override[].field "summaryfeatures"
override[].command "summaryfeatures"
override[].arguments ""
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/reference_from_several/documentmanager.cfg b/config-model/src/test/derived/reference_from_several/documentmanager.cfg
index 6ac1aab0baf..bdcb6a04236 100644
--- a/config-model/src/test/derived/reference_from_several/documentmanager.cfg
+++ b/config-model/src/test/derived/reference_from_several/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/schemainheritance/documentmanager.cfg b/config-model/src/test/derived/schemainheritance/documentmanager.cfg
index 12c29667079..a706c57909e 100644
--- a/config-model/src/test/derived/schemainheritance/documentmanager.cfg
+++ b/config-model/src/test/derived/schemainheritance/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/schemainheritance/summarymap.cfg b/config-model/src/test/derived/schemainheritance/summarymap.cfg
index d09407ca8a5..98885124eab 100644
--- a/config-model/src/test/derived/schemainheritance/summarymap.cfg
+++ b/config-model/src/test/derived/schemainheritance/summarymap.cfg
@@ -11,3 +11,6 @@ override[].arguments "parent_field"
override[].field "child_field"
override[].command "attribute"
override[].arguments "child_field"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/streamingstruct/documentmanager.cfg b/config-model/src/test/derived/streamingstruct/documentmanager.cfg
index 81de2d7ebdb..c29ff0b3489 100644
--- a/config-model/src/test/derived/streamingstruct/documentmanager.cfg
+++ b/config-model/src/test/derived/streamingstruct/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/streamingstruct/summarymap.cfg b/config-model/src/test/derived/streamingstruct/summarymap.cfg
index 865c6f733f1..acb9b3491c3 100644
--- a/config-model/src/test/derived/streamingstruct/summarymap.cfg
+++ b/config-model/src/test/derived/streamingstruct/summarymap.cfg
@@ -11,3 +11,6 @@ override[].arguments ""
override[].field "g"
override[].command "dynamicteaser"
override[].arguments "g"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/derived/structandfieldset/documentmanager.cfg b/config-model/src/test/derived/structandfieldset/documentmanager.cfg
index 85df5249e3a..e9bbc06d77a 100644
--- a/config-model/src/test/derived/structandfieldset/documentmanager.cfg
+++ b/config-model/src/test/derived/structandfieldset/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/structanyorder/documentmanager.cfg b/config-model/src/test/derived/structanyorder/documentmanager.cfg
index b3b6a2587c1..a1e8bb41a97 100644
--- a/config-model/src/test/derived/structanyorder/documentmanager.cfg
+++ b/config-model/src/test/derived/structanyorder/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/structinheritance/documentmanager.cfg b/config-model/src/test/derived/structinheritance/documentmanager.cfg
index ca11481afa4..5897b00c07b 100644
--- a/config-model/src/test/derived/structinheritance/documentmanager.cfg
+++ b/config-model/src/test/derived/structinheritance/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/structinheritance/documenttypes.cfg b/config-model/src/test/derived/structinheritance/documenttypes.cfg
index 8b343665289..3f9fdf85734 100644
--- a/config-model/src/test/derived/structinheritance/documenttypes.cfg
+++ b/config-model/src/test/derived/structinheritance/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/tensor/documentmanager.cfg b/config-model/src/test/derived/tensor/documentmanager.cfg
index d11c67fea01..bae2db34040 100644
--- a/config-model/src/test/derived/tensor/documentmanager.cfg
+++ b/config-model/src/test/derived/tensor/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/tensor/documenttypes.cfg b/config-model/src/test/derived/tensor/documenttypes.cfg
index 9ee6a82245f..d10ecd37c8f 100644
--- a/config-model/src/test/derived/tensor/documenttypes.cfg
+++ b/config-model/src/test/derived/tensor/documenttypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/types/documentmanager.cfg b/config-model/src/test/derived/types/documentmanager.cfg
index 9a73664ac86..ace183e1ab0 100644
--- a/config-model/src/test/derived/types/documentmanager.cfg
+++ b/config-model/src/test/derived/types/documentmanager.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[].name "document"
doctype[].idx 10000
diff --git a/config-model/src/test/derived/types/summarymap.cfg b/config-model/src/test/derived/types/summarymap.cfg
index b87200f6573..21ecb2dd07d 100644
--- a/config-model/src/test/derived/types/summarymap.cfg
+++ b/config-model/src/test/derived/types/summarymap.cfg
@@ -29,3 +29,6 @@ override[].arguments "other"
override[].field "juletre"
override[].command "attribute"
override[].arguments "juletre"
+override[].field "documentid"
+override[].command "documentid"
+override[].arguments ""
diff --git a/config-model/src/test/examples/fieldoftypedocument-doctypes.cfg b/config-model/src/test/examples/fieldoftypedocument-doctypes.cfg
index ea56800ea1c..ebc72c2d73b 100644
--- a/config-model/src/test/examples/fieldoftypedocument-doctypes.cfg
+++ b/config-model/src/test/examples/fieldoftypedocument-doctypes.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/examples/fieldoftypedocument.cfg b/config-model/src/test/examples/fieldoftypedocument.cfg
index b59b3206a2d..5aca758a5f4 100644
--- a/config-model/src/test/examples/fieldoftypedocument.cfg
+++ b/config-model/src/test/examples/fieldoftypedocument.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/examples/structresult.cfg b/config-model/src/test/examples/structresult.cfg
index 34383084625..c2c84eb46b0 100644
--- a/config-model/src/test/examples/structresult.cfg
+++ b/config-model/src/test/examples/structresult.cfg
@@ -1,4 +1,4 @@
-enablecompression false
+ignoreundefinedfields false
usev8geopositions false
doctype[0].name "document"
doctype[0].idx 10000
diff --git a/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java b/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java
index 57a61e40d89..c1dd62316db 100644
--- a/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java
@@ -18,10 +18,9 @@ import com.yahoo.schema.Schema;
import com.yahoo.vespa.config.ConfigDefinition;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.After;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.xml.sax.SAXException;
import java.io.File;
@@ -36,22 +35,18 @@ import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class ApplicationDeployTest {
private static final String TESTDIR = "src/test/cfg/application/";
private static final String TEST_SCHEMAS_DIR = TESTDIR + "app1/schemas/";
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void testVespaModel() throws SAXException, IOException {
+ void testVespaModel() throws SAXException, IOException {
ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "app1");
new VespaModel(tester.app());
List<Schema> schemas = tester.getSchemas();
@@ -72,11 +67,11 @@ public class ApplicationDeployTest {
}
}
assertEquals(Set.of(new File(TEST_SCHEMAS_DIR + "laptop.sd"),
- new File(TEST_SCHEMAS_DIR + "music.sd"),
- new File(TEST_SCHEMAS_DIR + "pc.sd"),
- new File(TEST_SCHEMAS_DIR + "product.sd"),
- new File(TEST_SCHEMAS_DIR + "sock.sd")),
- new HashSet<>(tester.app().getSearchDefinitionFiles()));
+ new File(TEST_SCHEMAS_DIR + "music.sd"),
+ new File(TEST_SCHEMAS_DIR + "pc.sd"),
+ new File(TEST_SCHEMAS_DIR + "product.sd"),
+ new File(TEST_SCHEMAS_DIR + "sock.sd")),
+ new HashSet<>(tester.app().getSearchDefinitionFiles()));
List<FilesApplicationPackage.Component> components = tester.app().getComponents();
assertEquals(1, components.size());
@@ -104,7 +99,7 @@ public class ApplicationDeployTest {
}
@Test
- public void testGetFile() throws IOException {
+ void testGetFile() throws IOException {
ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "app1");
try (Reader foo = tester.app().getFile(Path.fromString("files/foo.json")).createReader()) {
assertEquals(IOUtils.readAll(foo), "foo : foo\n");
@@ -128,7 +123,7 @@ public class ApplicationDeployTest {
}
@Test
- public void include_dirs_are_included() {
+ void include_dirs_are_included() {
ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "include_dirs");
Set<String> includeDirs = new HashSet<>(tester.app().getUserIncludeDirs());
@@ -136,12 +131,12 @@ public class ApplicationDeployTest {
}
@Test
- public void non_existent_include_dir_is_not_allowed() throws Exception {
- File appDir = tmpFolder.newFolder("non-existent-include");
+ void non_existent_include_dir_is_not_allowed() throws Exception {
+ File appDir = newFolder(tmpFolder, "non-existent-include");
String services =
"<services version='1.0'>" +
- " <include dir='non-existent' />" +
- "</services>\n";
+ " <include dir='non-existent' />" +
+ "</services>\n";
IOUtils.writeFile(new File(appDir, "services.xml"), services, false);
try {
@@ -149,13 +144,13 @@ public class ApplicationDeployTest {
fail("Expected exception due to non-existent include dir");
} catch (IllegalArgumentException e) {
assertEquals("Cannot include directory 'non-existent', as it does not exist. Directory must reside in application package, and path must be given relative to application package.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void testThatModelIsRebuiltWhenSearchDefinitionIsAdded() throws IOException {
- File tmpDir = tmpFolder.getRoot();
+ void testThatModelIsRebuiltWhenSearchDefinitionIsAdded() throws IOException {
+ File tmpDir = tmpFolder;
IOUtils.copyDirectory(new File(TESTDIR, "app1"), tmpDir);
ApplicationPackageTester tester = ApplicationPackageTester.create(tmpDir.getAbsolutePath());
assertEquals(5, tester.getSchemas().size());
@@ -166,55 +161,57 @@ public class ApplicationDeployTest {
}
@Test
- public void testThatAppWithDeploymentXmlIsValid() throws IOException {
- File tmpDir = tmpFolder.getRoot();
+ void testThatAppWithDeploymentXmlIsValid() throws IOException {
+ File tmpDir = tmpFolder;
IOUtils.copyDirectory(new File(TESTDIR, "app1"), tmpDir);
ApplicationPackageTester.create(tmpDir.getAbsolutePath());
}
- @Test(expected = IllegalArgumentException.class)
- public void testThatAppWithIllegalDeploymentXmlIsNotValid() throws IOException {
- File tmpDir = tmpFolder.getRoot();
- IOUtils.copyDirectory(new File(TESTDIR, "app_invalid_deployment_xml"), tmpDir);
- ApplicationPackageTester.create(tmpDir.getAbsolutePath());
+ @Test
+ void testThatAppWithIllegalDeploymentXmlIsNotValid() throws IOException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ File tmpDir = tmpFolder;
+ IOUtils.copyDirectory(new File(TESTDIR, "app_invalid_deployment_xml"), tmpDir);
+ ApplicationPackageTester.create(tmpDir.getAbsolutePath());
+ });
}
@Test
- public void testComplicatedDeploymentSpec() throws IOException {
- File tmpDir = tmpFolder.getRoot();
+ void testComplicatedDeploymentSpec() throws IOException {
+ File tmpDir = tmpFolder;
IOUtils.copyDirectory(new File(TESTDIR, "app_complicated_deployment_spec"), tmpDir);
ApplicationPackageTester.create(tmpDir.getAbsolutePath());
}
@Test
- public void testAppWithEmptyProdRegion() throws IOException {
- File tmpDir = tmpFolder.getRoot();
+ void testAppWithEmptyProdRegion() throws IOException {
+ File tmpDir = tmpFolder;
IOUtils.copyDirectory(new File(TESTDIR, "empty_prod_region_in_deployment_xml"), tmpDir);
ApplicationPackageTester.create(tmpDir.getAbsolutePath());
}
@Test
- public void testThatAppWithInvalidParallelDeploymentFails() throws IOException {
+ void testThatAppWithInvalidParallelDeploymentFails() throws IOException {
String expectedMessage = "4: <staging/>\n" +
- "5: <prod global-service-id=\"query\">\n" +
- "6: <parallel>\n" +
- "7: <instance id=\"hello\" />\n" +
- "8: </parallel>\n" +
- "9: </prod>\n" +
- "10:</deployment>\n";
- File tmpDir = tmpFolder.getRoot();
+ "5: <prod global-service-id=\"query\">\n" +
+ "6: <parallel>\n" +
+ "7: <instance id=\"hello\" />\n" +
+ "8: </parallel>\n" +
+ "9: </prod>\n" +
+ "10:</deployment>\n";
+ File tmpDir = tmpFolder;
IOUtils.copyDirectory(new File(TESTDIR, "invalid_parallel_deployment_xml"), tmpDir);
try {
ApplicationPackageTester.create(tmpDir.getAbsolutePath());
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Invalid XML according to XML schema, error in deployment.xml: element \"instance\" not allowed here; expected the element end-tag or element \"delay\", \"region\", \"steps\" or \"test\" [7:30], input:\n" + expectedMessage,
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void testConfigDefinitionsFromJars() {
+ void testConfigDefinitionsFromJars() {
String appName = "src/test/cfg//application/app1";
FilesApplicationPackage app = FilesApplicationPackage.fromFile(new File(appName), false);
Map<ConfigDefinitionKey, UnparsedConfigDefinition> defs = app.getAllExistingConfigDefs();
@@ -222,27 +219,25 @@ public class ApplicationDeployTest {
}
@Test
- public void testMetaData() throws IOException {
+ void testMetaData() throws IOException {
File tmp = Files.createTempDir();
String appPkg = TESTDIR + "app1";
IOUtils.copyDirectory(new File(appPkg), tmp);
ApplicationId applicationId = ApplicationId.from("tenant1", "application1", "instance1");
- DeployData deployData = new DeployData("foo",
- "bar",
- applicationId,
- 13L,
- false,
- 1337L,
- 3L);
+ DeployData deployData = new DeployData("bar",
+ applicationId,
+ 13L,
+ false,
+ 1337L,
+ 3L);
FilesApplicationPackage app = FilesApplicationPackage.fromFileWithDeployData(tmp, deployData);
app.writeMetaData();
FilesApplicationPackage newApp = FilesApplicationPackage.fromFileWithDeployData(tmp, deployData);
ApplicationMetaData meta = newApp.getMetaData();
- assertEquals("foo", meta.getDeployedByUser());
assertEquals("bar", meta.getDeployPath());
assertEquals(applicationId, meta.getApplicationId());
- assertEquals(13L, (long)meta.getDeployTimestamp());
- assertEquals(1337L, (long)meta.getGeneration());
+ assertEquals(13L, (long) meta.getDeployTimestamp());
+ assertEquals(1337L, (long) meta.getGeneration());
assertEquals(3L, meta.getPreviousActiveGeneration());
String checksum = meta.getChecksum();
assertNotNull(checksum);
@@ -259,7 +254,7 @@ public class ApplicationDeployTest {
}
@Test
- public void testGetJarEntryName() {
+ void testGetJarEntryName() {
JarEntry e = new JarEntry("/schemas/foo.sd");
assertEquals(ApplicationPackage.getFileName(e), "foo.sd");
e = new JarEntry("bar");
@@ -269,7 +264,7 @@ public class ApplicationDeployTest {
}
@Test
- public void testGetJarEntryNameForLegacyPath() {
+ void testGetJarEntryNameForLegacyPath() {
JarEntry e = new JarEntry("/searchdefinitions/foo.sd");
assertEquals(ApplicationPackage.getFileName(e), "foo.sd");
e = new JarEntry("bar");
@@ -278,7 +273,7 @@ public class ApplicationDeployTest {
assertEquals(ApplicationPackage.getFileName(e), "");
}
- @After
+ @AfterEach
public void cleanDirs() {
IOUtils.recursiveDeleteDir(new File(TESTDIR + "app1/myDir"));
IOUtils.recursiveDeleteDir(new File(TESTDIR + "app1/searchdefinitions/myDir2"));
@@ -286,7 +281,7 @@ public class ApplicationDeployTest {
}
@SuppressWarnings("ResultOfMethodCallIgnored")
- @After
+ @AfterEach
public void cleanFiles() {
new File(new File(TESTDIR + "app1"),"foo.txt").delete();
new File(new File(TESTDIR + "app1"),"searchdefinitions/bar.text").delete();
@@ -297,13 +292,13 @@ public class ApplicationDeployTest {
* Tests that an invalid jar is identified as not being a jar file
*/
@Test
- public void testInvalidJar() {
+ void testInvalidJar() {
try {
FilesApplicationPackage.getComponents(new File("src/test/cfg/application/validation/invalidjar_app"));
fail();
} catch (IllegalArgumentException e) {
assertEquals("Error opening jar file 'invalid.jar'. Please check that this is a valid jar file",
- e.getMessage());
+ e.getMessage());
}
}
@@ -314,7 +309,7 @@ public class ApplicationDeployTest {
* definition without version in file name
*/
@Test
- public void testConfigDefinitionsAndNamespaces() {
+ void testConfigDefinitionsAndNamespaces() {
final File appDir = new File("src/test/cfg/application/configdeftest");
FilesApplicationPackage app = FilesApplicationPackage.fromFile(appDir);
@@ -332,10 +327,21 @@ public class ApplicationDeployTest {
assertEquals("bar", def.getName());
}
- @Test(expected=IllegalArgumentException.class)
- public void testDifferentNameOfSdFileAndSearchName() {
- ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "sdfilenametest");
- new DeployState.Builder().applicationPackage(tester.app()).build();
+ @Test
+ void testDifferentNameOfSdFileAndSearchName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "sdfilenametest");
+ new DeployState.Builder().applicationPackage(tester.app()).build();
+ });
+ }
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
}
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java
index e5909091534..11de928c14c 100644
--- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java
@@ -3,14 +3,14 @@ package com.yahoo.config.model;
import com.yahoo.config.model.builder.xml.ConfigModelBuilder;
import com.yahoo.config.model.builder.xml.ConfigModelId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author Ulf Lilleengen
@@ -18,33 +18,33 @@ import static org.junit.Assert.assertTrue;
*/
public class ConfigModelBuilderTest {
@Test
- public void testEquals() {
+ void testEquals() {
ConfigModelBuilder<?> ba = new A.Builder();
ConfigModelBuilder<?> ba2 = new A2.Builder();
ConfigModelBuilder<?> bb = new B.Builder();
- ConfigModelBuilder <?>bb2 = new B2.Builder();
+ ConfigModelBuilder<?> bb2 = new B2.Builder();
- assertTrue(ba.equals(ba));
- assertTrue(ba.equals(ba2));
- assertFalse(ba.equals(bb));
- assertFalse(ba.equals(bb2));
+ assertEquals(ba, ba);
+ assertEquals(ba, ba2);
+ assertNotEquals(ba, bb);
+ assertNotEquals(ba, bb2);
- assertTrue(ba2.equals(ba));
- assertTrue(ba2.equals(ba2));
- assertFalse(ba2.equals(bb));
- assertFalse(ba2.equals(bb2));
+ assertEquals(ba2, ba);
+ assertEquals(ba2, ba2);
+ assertNotEquals(ba2, bb);
+ assertNotEquals(ba2, bb2);
- assertFalse(bb.equals(ba));
- assertFalse(bb.equals(ba2));
- assertTrue(bb.equals(bb));
- assertFalse(bb.equals(bb2));
+ assertNotEquals(bb, ba);
+ assertNotEquals(bb, ba2);
+ assertEquals(bb, bb);
+ assertNotEquals(bb, bb2);
- assertFalse(bb2.equals(ba));
- assertFalse(bb2.equals(ba2));
- assertFalse(bb2.equals(bb));
- assertTrue(bb2.equals(bb2));
+ assertNotEquals(bb2, ba);
+ assertNotEquals(bb2, ba2);
+ assertNotEquals(bb2, bb);
+ assertEquals(bb2, bb2);
- assertFalse(ba.equals(new ArrayList<>()));
+ assertNotEquals(ba, new ArrayList<>());
}
private static class A extends ConfigModel {
diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java
index 532c446ec6f..55fe909e70d 100644
--- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.model.test.MockRoot;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author Ulf Lilleengen
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotEquals;
public class ConfigModelContextTest {
@Test
- public void testConfigModelContext() {
+ void testConfigModelContext() {
MockRoot root = new MockRoot();
String id = "foobar";
ApplicationPackage pkg = new MockApplicationPackage.Builder()
diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java
index 325361e0127..3db4948c8c3 100644
--- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java
@@ -2,13 +2,13 @@
package com.yahoo.config.model;
import com.yahoo.config.model.application.provider.Bundle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Ulf Lilleengen
@@ -19,38 +19,38 @@ public class ConfigModelUtilsTest {
public static final String INVALID_TEST_BUNDLE = "src/test/cfg/application/validation/invalidjar_app/components";
@Test
- public void all_def_files_in_correct_directory_are_handled_and_files_outside_are_ignored() {
+ void all_def_files_in_correct_directory_are_handled_and_files_outside_are_ignored() {
List<Bundle> bundles = Bundle.getBundles(new File(VALID_TEST_BUNDLE));
assertEquals(1, bundles.size());
assertEquals(5, bundles.get(0).getDefEntries().size());
}
@Test
- public void def_file_with_namespace_is_handled() {
+ void def_file_with_namespace_is_handled() {
Bundle.DefEntry defEntry = getDefEntry("test-namespace");
assertEquals("config", defEntry.defNamespace);
}
@Test
- public void def_file_with_namespace_and_namespace_in_filename_is_handled() {
+ void def_file_with_namespace_and_namespace_in_filename_is_handled() {
Bundle.DefEntry defEntry = getDefEntry("namespace-in-filename");
assertEquals("a.b", defEntry.defNamespace);
}
@Test
- public void def_file_with_package_is_handled() {
+ void def_file_with_package_is_handled() {
Bundle.DefEntry defEntry = getDefEntry("test-package");
assertEquals("com.mydomain.mypackage", defEntry.defNamespace);
}
@Test
- public void def_file_with_package_and_pacakage_in_filename_is_handled() {
+ void def_file_with_package_and_pacakage_in_filename_is_handled() {
Bundle.DefEntry defEntry = getDefEntry("package-in-filename");
assertEquals("com.mydomain.mypackage", defEntry.defNamespace);
}
@Test
- public void def_file_with_both_package_and_namespace_gets_package_as_namespace() {
+ void def_file_with_both_package_and_namespace_gets_package_as_namespace() {
Bundle.DefEntry defEntry = getDefEntry("namespace-and-package");
assertEquals("com.mydomain.mypackage", defEntry.defNamespace);
}
@@ -66,7 +66,7 @@ public class ConfigModelUtilsTest {
}
@Test
- public void invalid_jar_file_fails_to_load() {
+ void invalid_jar_file_fails_to_load() {
try {
Bundle.getBundles(new File(INVALID_TEST_BUNDLE));
fail();
diff --git a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java
index e5e61459b44..84c1d66a507 100644
--- a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java
@@ -3,14 +3,14 @@ package com.yahoo.config.model;
import com.yahoo.config.model.builder.xml.ConfigModelBuilder;
import com.yahoo.config.model.builder.xml.ConfigModelId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -19,7 +19,7 @@ import static org.junit.Assert.*;
public class MapConfigModelRegistryTest {
@Test
- public void require_that_registry_finds_components() {
+ void require_that_registry_finds_components() {
ModelABuilder ba = new ModelABuilder();
ModelBBuilder bb = new ModelBBuilder();
ConfigModelRegistry registry = MapConfigModelRegistry.createFromList(ba, bb);
@@ -31,7 +31,7 @@ public class MapConfigModelRegistryTest {
}
@Test
- public void require_all_builders_for_a_tag() {
+ void require_all_builders_for_a_tag() {
ModelBBuilder b1 = new ModelBBuilder();
ModelB2Builder b2 = new ModelB2Builder();
ConfigModelRegistry registry = MapConfigModelRegistry.createFromList(b1, b2);
diff --git a/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java b/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java
deleted file mode 100644
index a06da645e17..00000000000
--- a/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.config.model;
-
-import com.yahoo.vespa.model.VespaModel;
-import com.yahoo.vespa.model.container.Container;
-import com.yahoo.vespa.model.container.ApplicationContainer;
-import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
-
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * Tests that qrserver is assigned port Defaults.getDefaults().vespaWebServicePort() even if there is a HTTP gateway configured earlier in
- * vespa-services.xml
- *
- * @author hmusum
- */
-public class QrserverAndGatewayPortAllocationTest {
-
- @Test
- public void testPorts() {
- String appDir = "src/test/cfg/application/app_qrserverandgw/";
- VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg(appDir);
- VespaModel vespaModel = creator.create();
- List<ApplicationContainer> qrservers = vespaModel.getContainerClusters().get("container").getContainers();
- assertEquals(1, qrservers.size());
- assertEquals(Container.BASEPORT, qrservers.get(0).getSearchPort());
- }
-
-}
diff --git a/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java b/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java
index 1bf8c834586..7d3e6e81cd0 100644
--- a/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java
@@ -3,14 +3,15 @@ package com.yahoo.config.model.application.provider;
import com.yahoo.component.Version;
import com.yahoo.vespa.config.VespaVersion;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* @author hmusum
*/
@@ -41,44 +42,43 @@ public class SchemaValidatorTest {
" </admin>\n" +
"</services>\n";
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
- public void testXMLParse() throws IOException {
+ void testXMLParse() throws IOException {
SchemaValidator validator = createValidator();
validator.validate(new StringReader(okServices));
}
@Test
- public void testXMLParseError() throws IOException {
- SchemaValidator validator = createValidator();
- expectedException.expect(RuntimeException.class);
- expectedException.expectMessage(expectedErrorMessage("input"));
- validator.validate(new StringReader(invalidServices));
+ void testXMLParseError() throws IOException {
+ Throwable exception = assertThrows(RuntimeException.class, () -> {
+ SchemaValidator validator = createValidator();
+ validator.validate(new StringReader(invalidServices));
+ });
+ assertTrue(exception.getMessage().contains(expectedErrorMessage("input")));
}
@Test
- public void testXMLParseWithReader() throws IOException {
+ void testXMLParseWithReader() throws IOException {
SchemaValidator validator = createValidator();
validator.validate(new StringReader(okServices));
}
@Test
- public void testXMLParseErrorWithReader() throws IOException {
- SchemaValidator validator = createValidator();
- expectedException.expect(RuntimeException.class);
- expectedException.expectMessage(expectedErrorMessage("input"));
- validator.validate(new StringReader(invalidServices));
+ void testXMLParseErrorWithReader() throws IOException {
+ Throwable exception = assertThrows(RuntimeException.class, () -> {
+ SchemaValidator validator = createValidator();
+ validator.validate(new StringReader(invalidServices));
+ });
+ assertTrue(exception.getMessage().contains(expectedErrorMessage("input")));
}
@Test
- public void testXMLParseErrorFromFile() throws IOException {
- SchemaValidator validator = createValidator();
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(expectedErrorMessage("services.xml"));
- validator.validate(new File("src/test/cfg/application/invalid-services-syntax/services.xml"));
+ void testXMLParseErrorFromFile() throws IOException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SchemaValidator validator = createValidator();
+ validator.validate(new File("src/test/cfg/application/invalid-services-syntax/services.xml"));
+ });
+ assertTrue(exception.getMessage().contains(expectedErrorMessage("services.xml")));
}
private SchemaValidator createValidator() {
diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java
index 931768b6fd9..b1354446d1f 100644
--- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java
@@ -2,12 +2,9 @@
package com.yahoo.config.model.builder.xml;
import com.yahoo.component.Version;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -16,7 +13,7 @@ import static org.junit.Assert.assertTrue;
public class ConfigModelIdTest {
@Test
- public void require_that_element_gets_correct_name() {
+ void require_that_element_gets_correct_name() {
ConfigModelId id = ConfigModelId.fromName("foo");
assertEquals("foo", id.getName());
assertEquals(Version.fromString("1"), id.getVersion());
@@ -26,7 +23,7 @@ public class ConfigModelIdTest {
}
@Test
- public void test_toString() {
+ void test_toString() {
ConfigModelId id = ConfigModelId.fromNameAndVersion("bar", "1.0");
assertEquals("bar.1", id.toString());
id = ConfigModelId.fromNameAndVersion("foo", "1.1.3");
@@ -36,7 +33,7 @@ public class ConfigModelIdTest {
}
@Test
- public void test_equality() {
+ void test_equality() {
ConfigModelId a1 = ConfigModelId.fromName("a");
ConfigModelId a2 = ConfigModelId.fromName("a");
ConfigModelId b = ConfigModelId.fromName("b");
@@ -52,18 +49,18 @@ public class ConfigModelIdTest {
}
@Test
- public void test_compare() {
+ void test_compare() {
ConfigModelId a1 = ConfigModelId.fromName("a");
ConfigModelId a2 = ConfigModelId.fromName("a");
ConfigModelId b = ConfigModelId.fromName("b");
- assertTrue(a1.compareTo(a2) == 0);
- assertTrue(a2.compareTo(a1) == 0);
+ assertEquals(a1.compareTo(a2), 0);
+ assertEquals(a2.compareTo(a1), 0);
assertFalse(a1.compareTo(b) > 0);
assertFalse(a2.compareTo(b) > 0);
assertFalse(b.compareTo(a1) < 0);
assertFalse(b.compareTo(a2) < 0);
- assertTrue(a1.compareTo(a1) == 0);
- assertTrue(a2.compareTo(a2) == 0);
- assertTrue(b.compareTo(b) == 0);
+ assertEquals(a1.compareTo(a1), 0);
+ assertEquals(a2.compareTo(a2), 0);
+ assertEquals(b.compareTo(b), 0);
}
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java
index ee616f59d04..a19bc2347d4 100644
--- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.builder.xml;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.InputSource;
import java.io.FileReader;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -13,24 +13,24 @@ import static org.junit.Assert.assertEquals;
public class XmlErrorHandlingTest {
@Test
- public void requireExceptionWithSourceAndFilenameAndLineNumber() {
+ void requireExceptionWithSourceAndFilenameAndLineNumber() {
try {
XmlHelper.getDocument(new FileReader("src/test/cfg/application/invalid-services-syntax/services.xml"), "services.xml");
} catch (Exception e) {
assertEquals("Invalid XML in services.xml: The element type \"config\" must be terminated by the matching end-tag \"</config>\". [7:5]",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireExceptionWithLineNumber() {
+ void requireExceptionWithLineNumber() {
try {
XmlHelper.getDocumentBuilder().parse(
new InputSource(new FileReader("src/test/cfg/application/invalid-services-syntax/services.xml")));
} catch (Exception e) {
assertEquals("Invalid XML (unknown source): The element type \"config\" must be terminated by the matching end-tag \"</config>\". [7:5]",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java
index 393522b4e33..29a842d8945 100644
--- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java
@@ -2,8 +2,8 @@
package com.yahoo.config.model.builder.xml.test;
import com.yahoo.config.model.test.TestUtil;
+import org.junit.jupiter.api.BeforeEach;
import com.yahoo.config.model.test.MockRoot;
-import org.junit.Before;
import org.w3c.dom.Element;
/**
@@ -22,7 +22,7 @@ abstract public class DomBuilderTest {
protected MockRoot root;
- @Before
+ @BeforeEach
public void setup() {
root = new MockRoot();
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java b/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java
index 64870ff8e49..f0b729a718c 100644
--- a/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java
@@ -14,7 +14,7 @@ import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.config.ConfigDefinition;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.File;
@@ -25,9 +25,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -35,7 +33,7 @@ import static org.junit.Assert.assertTrue;
public class DeployStateTest {
@Test
- public void testProvisionerIsSet() {
+ void testProvisionerIsSet() {
DeployState.Builder builder = new DeployState.Builder();
HostProvisioner provisioner = new InMemoryProvisioner(true, false, "foo.yahoo.com");
builder.modelHostProvisioner(provisioner);
@@ -44,7 +42,7 @@ public class DeployStateTest {
}
@Test
- public void testBuilder() {
+ void testBuilder() {
DeployState.Builder builder = new DeployState.Builder();
ApplicationPackage app = MockApplicationPackage.createEmpty();
builder.permanentApplicationPackage(Optional.of(app));
@@ -53,20 +51,20 @@ public class DeployStateTest {
}
@Test
- public void testPreviousModelIsProvided() throws IOException, SAXException {
+ void testPreviousModelIsProvided() throws IOException, SAXException {
VespaModel prevModel = new VespaModel(MockApplicationPackage.createEmpty());
DeployState.Builder builder = new DeployState.Builder();
assertEquals(prevModel, builder.previousModel(prevModel).build().getPreviousModel().get());
}
@Test
- public void testProperties() {
+ void testProperties() {
DeployState.Builder builder = new DeployState.Builder();
DeployState state = builder.build();
assertEquals(ApplicationId.defaultId(), state.getProperties().applicationId());
ApplicationId customId = new ApplicationId.Builder()
- .tenant("bar")
- .applicationName("foo").instanceName("quux").build();
+ .tenant("bar")
+ .applicationName("foo").instanceName("quux").build();
ModelContext.Properties properties = new TestProperties().setApplicationId(customId);
builder.properties(properties);
state = builder.build();
@@ -74,11 +72,11 @@ public class DeployStateTest {
}
@Test
- public void testDefinitionRepoIsUsed() {
+ void testDefinitionRepoIsUsed() {
Map<ConfigDefinitionKey, com.yahoo.vespa.config.buildergen.ConfigDefinition> defs = new LinkedHashMap<>();
defs.put(new ConfigDefinitionKey("foo", "bar"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("foo", new String[]{"namespace=bar", "foo int default=0"}));
defs.put(new ConfigDefinitionKey("test2", "a.b"),
- new com.yahoo.vespa.config.buildergen.ConfigDefinition("namespace-in-filename", new String[]{"namespace=a.b", "doubleVal double default=1.0"}));
+ new com.yahoo.vespa.config.buildergen.ConfigDefinition("namespace-in-filename", new String[]{"namespace=a.b", "doubleVal double default=1.0"}));
ApplicationPackage app = FilesApplicationPackage.fromFile(new File("src/test/cfg//application/app1"));
DeployState state = createDeployState(app, defs);
@@ -91,7 +89,7 @@ public class DeployStateTest {
}
@Test
- public void testGetConfigDefinition() {
+ void testGetConfigDefinition() {
Map<ConfigDefinitionKey, com.yahoo.vespa.config.buildergen.ConfigDefinition> defs = new LinkedHashMap<>();
defs.put(new ConfigDefinitionKey("test2", "a.b"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("test2", new String[]{"namespace=a.b", "doubleVal double default=1.0"}));
//defs.put(new ConfigDefinitionKey("test2", "c.d"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("test2", new String[]{"namespace=c.d", "doubleVal double default=1.0"}));
@@ -108,7 +106,7 @@ public class DeployStateTest {
}
@Test
- public void testContainerEndpoints() {
+ void testContainerEndpoints() {
assertTrue(new DeployState.Builder().endpoints(Set.of()).build().getEndpoints().isEmpty());
var endpoints = Set.of(new ContainerEndpoint("c1", ApplicationClusterEndpoint.Scope.global, List.of("c1.example.com", "c1-alias.example.com")));
assertEquals(endpoints, new DeployState.Builder().endpoints(endpoints).build().getEndpoints());
diff --git a/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java b/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java
index 70b9fc54882..a9f97d95b74 100644
--- a/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java
+++ b/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java
@@ -16,16 +16,13 @@ import com.yahoo.vespa.model.test.ApiConfigModel;
import com.yahoo.vespa.model.test.SimpleConfigModel;
import com.yahoo.vespa.model.test.SimpleService;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -53,21 +50,21 @@ public class SystemModelTestCase {
}
@Test
- public void testMetrics() {
+ void testMetrics() {
VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "metricsconfig");
- SimpleService service0 = (SimpleService)vespaModel.getConfigProducer("simple/simpleservice.0").get();
+ SimpleService service0 = (SimpleService) vespaModel.getConfigProducer("simple/simpleservice.0").get();
vespaModel.getConfigProducer("simple/simpleservice.1");
assertEquals("testClusterName", service0.getDefaultMetricDimensions().get("clustername"));
}
@Test
- public void testVespaModel() {
+ void testVespaModel() {
VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig/");
assertNotNull(vespaModel);
- assertEquals("There are two instances of the simple model + Routing and AdminModel (set up implicitly)", 4, vespaModel.configModelRepo().asMap().size());
- assertNotNull("One gets the default name as there is no explicit id", vespaModel.configModelRepo().asMap().get("simple"));
- assertNotNull("The other gets the explicit id as name", vespaModel.configModelRepo().asMap().get("second"));
+ assertEquals(4, vespaModel.configModelRepo().asMap().size(), "There are two instances of the simple model + Routing and AdminModel (set up implicitly)");
+ assertNotNull(vespaModel.configModelRepo().asMap().get("simple"), "One gets the default name as there is no explicit id");
+ assertNotNull(vespaModel.configModelRepo().asMap().get("second"), "The other gets the explicit id as name");
ApplicationConfigProducerRoot root = vespaModel.getVespa();
assertNotNull(root);
@@ -108,7 +105,7 @@ public class SystemModelTestCase {
}
@Test
- public void testHostSystem() {
+ void testHostSystem() {
VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig/");
HostSystem hostSystem = vespaModel.hostSystem();
@@ -129,7 +126,7 @@ public class SystemModelTestCase {
}
@Test
- public void testBasePorts() {
+ void testBasePorts() {
VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig");
assertNotNull(vespaModel);
@@ -142,7 +139,7 @@ public class SystemModelTestCase {
* Be sure to update it as well if you change this.
*/
@Test
- public void testPlugins() {
+ void testPlugins() {
VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "plugins");
assertNotNull(vespaModel);
@@ -169,14 +166,14 @@ public class SystemModelTestCase {
assertEquals("routing", plugin.getId());
assertEquals(vespaModel.getConfig(StandardConfig.class, "api/apiservice.0").astring(), "apiservice");
-
+
assertEquals(vespaModel.getConfig(StandardConfig.class, "simple/simpleservice.0").astring(), "simpleservice");
assertEquals(vespaModel.getConfig(StandardConfig.class, "simple/simpleservice.1").astring(), "simpleservice");
assertEquals(vespaModel.getConfig(StandardConfig.class, "simple2/simpleservice.0").astring(), "simpleservice");
}
@Test
- public void testEqualPlugins() {
+ void testEqualPlugins() {
try {
getVespaModelDoNotValidateXml(TESTDIR + "doubleconfig");
fail("No exception upon two plugins with the same name");
diff --git a/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java b/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java
index da8ce7fd425..753f4b11f9f 100644
--- a/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java
@@ -3,16 +3,11 @@ package com.yahoo.config.model.graph;
import com.yahoo.config.model.ConfigModelContext;
import com.yahoo.config.model.test.MockRoot;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -30,7 +25,7 @@ public class ModelGraphTest {
}
@Test
- public void require_that_dependencies_are_correctly_set() {
+ void require_that_dependencies_are_correctly_set() {
ModelGraphBuilder builder = new ModelGraphBuilder();
builder.addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA());
ModelGraph graph = builder.build();
@@ -45,22 +40,24 @@ public class ModelGraphTest {
}
@Test
- public void require_that_dependencies_are_correctly_sorted() {
+ void require_that_dependencies_are_correctly_sorted() {
ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA()).build();
assertOrdering(graph, "ABC");
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_cycles_are_detected() {
- ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BD()).addBuilder(new GraphMock.BE()).build();
- assertEquals(2, graph.getNodes().size());
- assertTrue(graph.getNodes().get(0).dependsOn(graph.getNodes().get(1)));
- assertTrue(graph.getNodes().get(1).dependsOn(graph.getNodes().get(0)));
- graph.topologicalSort();
+ @Test
+ void require_that_cycles_are_detected() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BD()).addBuilder(new GraphMock.BE()).build();
+ assertEquals(2, graph.getNodes().size());
+ assertTrue(graph.getNodes().get(0).dependsOn(graph.getNodes().get(1)));
+ assertTrue(graph.getNodes().get(1).dependsOn(graph.getNodes().get(0)));
+ graph.topologicalSort();
+ });
}
@Test
- public void require_that_instance_can_be_created() {
+ void require_that_instance_can_be_created() {
ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA()).build();
List<ModelNode> nodes = graph.topologicalSort();
MockRoot root = new MockRoot();
@@ -83,30 +80,28 @@ public class ModelGraphTest {
assertTrue(c.b.contains(b2));
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedEx = ExpectedException.none();
-
@Test
- public void require_that_context_must_be_first_ctor_param() {
- expectedEx.expect(IllegalArgumentException.class);
- expectedEx.expectMessage("Constructor for " + GraphMock.Bad.class.getName() + " must have as its first argument a " + ConfigModelContext.class.getName());
- ModelNode node = new ModelNode(new GraphMock.Bad.Builder());
- MockRoot root = new MockRoot();
- node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo"));
+ void require_that_context_must_be_first_ctor_param() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ ModelNode node = new ModelNode(new GraphMock.Bad.Builder());
+ MockRoot root = new MockRoot();
+ node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo"));
+ });
+ assertTrue(exception.getMessage().contains("Constructor for " + GraphMock.Bad.class.getName() + " must have as its first argument a " + ConfigModelContext.class.getName()));
}
@Test
- public void require_that_ctor_arguments_must_be_models_or_collections_of_models() {
- expectedEx.expect(IllegalArgumentException.class);
- expectedEx.expectMessage("Unable to find constructor argument class java.lang.String for com.yahoo.config.model.graph.GraphMock$Bad2");
- ModelNode node = new ModelNode(new GraphMock.Bad2.Builder());
- MockRoot root = new MockRoot();
- node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo"));
+ void require_that_ctor_arguments_must_be_models_or_collections_of_models() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ ModelNode node = new ModelNode(new GraphMock.Bad2.Builder());
+ MockRoot root = new MockRoot();
+ node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo"));
+ });
+ assertTrue(exception.getMessage().contains("Unable to find constructor argument class java.lang.String for com.yahoo.config.model.graph.GraphMock$Bad2"));
}
@Test
- public void require_that_collections_can_be_empty() {
+ void require_that_collections_can_be_empty() {
ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BA()).build();
List<ModelNode> nodes = graph.topologicalSort();
MockRoot root = new MockRoot();
diff --git a/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java b/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java
index 04ae4c76f27..763b9c25072 100644
--- a/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java
@@ -2,10 +2,10 @@
package com.yahoo.config.model.producer;
import com.yahoo.cloud.config.log.LogdConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Verifies some of the logic in the abstract config producer that is not tested in other classes.
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class AbstractConfigProducerTest {
@Test
- public void require_that_interface_is_found_if_directly_implemented() throws ReflectiveOperationException {
+ void require_that_interface_is_found_if_directly_implemented() throws ReflectiveOperationException {
MockLogdProducer producer = new MockLogdProducer("mocky");
ClassLoader loader = producer.getConfigClassLoader(LogdConfig.Producer.class.getName());
assertNotNull(loader);
@@ -29,7 +29,7 @@ public class AbstractConfigProducerTest {
}
@Test
- public void require_that_interface_is_found_if_inherited() throws ReflectiveOperationException {
+ void require_that_interface_is_found_if_inherited() throws ReflectiveOperationException {
MockLogdProducerSubclass producer = new MockLogdProducerSubclass("mocky");
ClassLoader loader = producer.getConfigClassLoader(LogdConfig.Producer.class.getName());
assertNotNull(loader);
diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java
index 810e2c643f3..e678aaa673a 100644
--- a/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java
@@ -2,15 +2,15 @@
package com.yahoo.config.model.provision;
import com.yahoo.config.provision.HostSpec;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author Ulf Lilleengen
@@ -18,31 +18,31 @@ import static org.junit.Assert.assertTrue;
public class HostSpecTest {
@Test
- public void testEquals() {
+ void testEquals() {
HostSpec h1 = new HostSpec("foo", List.of(), Optional.empty());
HostSpec h2 = new HostSpec("foo", List.of(), Optional.empty());
HostSpec h3 = new HostSpec("foo", List.of("my", "alias"), Optional.empty());
HostSpec h4 = new HostSpec("bar", List.of(), Optional.empty());
- assertTrue(h1.equals(h1));
- assertTrue(h1.equals(h2));
- assertTrue(h1.equals(h3));
- assertFalse(h1.equals(h4));
-
- assertTrue(h2.equals(h1));
- assertTrue(h2.equals(h2));
- assertTrue(h2.equals(h3));
- assertFalse(h2.equals(h4));
-
- assertTrue(h3.equals(h1));
- assertTrue(h3.equals(h2));
- assertTrue(h3.equals(h3));
- assertFalse(h3.equals(h4));
-
- assertFalse(h4.equals(h1));
- assertFalse(h4.equals(h2));
- assertFalse(h4.equals(h3));
- assertTrue(h4.equals(h4));
+ assertEquals(h1, h1);
+ assertEquals(h1, h2);
+ assertEquals(h1, h3);
+ assertNotEquals(h1, h4);
+
+ assertEquals(h2, h1);
+ assertEquals(h2, h2);
+ assertEquals(h2, h3);
+ assertNotEquals(h2, h4);
+
+ assertEquals(h3, h1);
+ assertEquals(h3, h2);
+ assertEquals(h3, h3);
+ assertNotEquals(h3, h4);
+
+ assertNotEquals(h4, h1);
+ assertNotEquals(h4, h2);
+ assertNotEquals(h4, h3);
+ assertEquals(h4, h4);
}
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java
index 558e61fc1c2..05b8681b5fa 100644
--- a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.config.model.provision;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.vespa.model.container.Container;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.StringReader;
import java.util.ArrayList;
@@ -15,8 +15,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hmusum
@@ -46,7 +45,7 @@ public class HostsXmlProvisionerTest {
"</hosts>";
@Test
- public void require_basic_works() {
+ void require_basic_works() {
HostsXmlProvisioner hostProvisioner = createProvisioner(threeHosts);
// 4 services, 2 host aliases, mapping to 2 host.
@@ -71,14 +70,16 @@ public class HostsXmlProvisionerTest {
assertEquals(3, map.size());
assertCorrectNumberOfHosts(map, 3);
assertTrue(map.keySet().containsAll(aliases));
-
+
assertEquals("", System.getProperty("zookeeper.vespa.clients"));
}
- @Test(expected = IllegalArgumentException.class)
- public void require_exception_when_unknown_hosts_alias() {
- HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost);
- hostProvisioner.allocateHost("unknown");
+ @Test
+ void require_exception_when_unknown_hosts_alias() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost);
+ hostProvisioner.allocateHost("unknown");
+ });
}
private void assertCorrectNumberOfHosts(Map<String, HostSpec> hostToServiceMap, int expectedHostCount) {
@@ -97,7 +98,7 @@ public class HostsXmlProvisionerTest {
return createAliases(new ArrayList<>());
}
- // Admin services on node1, qrserver on node2 + additional specs
+ // Admin services on node1, container on node2 + additional specs
private List<String> createAliases(Collection<String> additionalAliases) {
ArrayList<String> aliases = new ArrayList<>();
aliases.add("node1");
@@ -117,7 +118,7 @@ public class HostsXmlProvisionerTest {
}
@Test
- public void require_singlenode_HostAlias_is_used_if_hosts_xml() {
+ void require_singlenode_HostAlias_is_used_if_hosts_xml() {
HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost);
HostSpec hostSpec = hostProvisioner.allocateHost(Container.SINGLENODE_CONTAINER_SERVICESPEC);
assertEquals("test1.yahoo.com", hostSpec.hostname());
diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java
index 5e56efc4460..30b848da7f1 100644
--- a/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java
@@ -4,6 +4,7 @@ package com.yahoo.config.model.provision;
import com.yahoo.cloud.config.ZookeeperServerConfig;
import com.yahoo.cloud.config.log.LogdConfig;
import com.yahoo.config.application.api.ApplicationPackage;
+import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.api.container.ContainerServiceType;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
@@ -37,14 +38,16 @@ import com.yahoo.vespa.model.search.SearchNode;
import com.yahoo.vespa.model.test.VespaModelTester;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.StringReader;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
+import java.util.logging.Level;
import java.util.stream.Collectors;
import static com.yahoo.config.model.test.TestUtil.joinLines;
@@ -55,12 +58,13 @@ import static com.yahoo.vespa.defaults.Defaults.getDefaults;
import static com.yahoo.vespa.model.search.NodeResourcesTuning.GB;
import static com.yahoo.vespa.model.search.NodeResourcesTuning.reservedMemoryGb;
import static com.yahoo.vespa.model.test.utils.ApplicationPackageUtils.generateSchemas;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test cases for provisioning nodes to entire Vespa models.
@@ -217,10 +221,10 @@ public class ModelProvisioningTest {
tester.addHosts(8);
VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 1, model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Nodes in cluster without ID", 2, model.getContentClusters().get("content").getRootGroup().getNodes().size());
- assertEquals("Heap size for container", 70, physicalMemoryPercentage(model.getContainerClusters().get("container1")));
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(1, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
+ assertEquals(2, model.getContentClusters().get("content").getRootGroup().getNodes().size(), "Nodes in cluster without ID");
+ assertEquals(70, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size for container");
assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Type.content, model);
assertProvisioned(1, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model);
assertProvisioned(2, ClusterSpec.Id.from("content"), ClusterSpec.Type.content, model);
@@ -268,16 +272,19 @@ public class ModelProvisioningTest {
"</services>";
VespaModelTester tester = new VespaModelTester();
tester.addHosts(5);
- VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Heap size is lowered with combined clusters",
- 18, physicalMemoryPercentage(model.getContainerClusters().get("container1")));
- assertEquals("Memory for proton is lowered to account for the jvm heap",
- (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.18)), protonMemorySize(model.getContentClusters()
- .get("content1")));
+ TestLogger logger = new TestLogger();
+ VespaModel model = tester.createModel(xmlWithNodes, true, new DeployState.Builder().deployLogger(logger));
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
+ assertEquals(18, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is lowered with combined clusters");
+ assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.18)), protonMemorySize(model.getContentClusters()
+ .get("content1")), "Memory for proton is lowered to account for the jvm heap");
assertProvisioned(0, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model);
assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Id.from("container1"), ClusterSpec.Type.combined, model);
+ assertEquals(1, logger.msgs().size());
+ assertEquals("Declaring combined cluster with <nodes of=\"...\"> is deprecated without replacement, " +
+ "and the feature will be removed in Vespa 9. Use separate container and content clusters instead",
+ logger.msgs().get(0).message);
}
@Test
@@ -304,13 +311,11 @@ public class ModelProvisioningTest {
VespaModelTester tester = new VespaModelTester();
tester.addHosts(5);
VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Heap size is lowered with combined clusters",
- 30, physicalMemoryPercentage(model.getContainerClusters().get("container1")));
- assertEquals("Memory for proton is lowered to account for the jvm heap",
- (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.30)), protonMemorySize(model.getContentClusters()
- .get("content1")));
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
+ assertEquals(30, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is lowered with combined clusters");
+ assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.30)), protonMemorySize(model.getContentClusters()
+ .get("content1")), "Memory for proton is lowered to account for the jvm heap");
assertProvisioned(0, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model);
assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Id.from("container1"), ClusterSpec.Type.combined, model);
}
@@ -338,12 +343,10 @@ public class ModelProvisioningTest {
VespaModelTester tester = new VespaModelTester();
tester.addHosts(7);
VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Heap size is normal",
- 70, physicalMemoryPercentage(model.getContainerClusters().get("container1")));
- assertEquals("Memory for proton is normal",
- (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3))), protonMemorySize(model.getContentClusters().get("content1")));
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
+ assertEquals(70, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is normal");
+ assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3))), protonMemorySize(model.getContentClusters().get("content1")), "Memory for proton is normal");
}
@Test
@@ -369,8 +372,8 @@ public class ModelProvisioningTest {
tester.addHosts(5);
VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size());
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
for (Container container : model.getContainerClusters().get("container1").getContainers())
assertTrue(container.getJvmOptions().contains("testoption"));
}
@@ -405,10 +408,10 @@ public class ModelProvisioningTest {
tester.addHosts(8);
VespaModel model = tester.createModel(xmlWithNodes, true);
- assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size());
- assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Nodes in content2", 3, model.getContentClusters().get("content2").getRootGroup().getNodes().size());
- assertEquals("Nodes in container2", 3, model.getContainerClusters().get("container2").getContainers().size());
+ assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1");
+ assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1");
+ assertEquals(3, model.getContentClusters().get("content2").getRootGroup().getNodes().size(), "Nodes in content2");
+ assertEquals(3, model.getContainerClusters().get("container2").getContainers().size(), "Nodes in container2");
}
@Test
@@ -528,10 +531,10 @@ public class ModelProvisioningTest {
.stream().map(cc -> cc.getHostResource()).collect(Collectors.toSet());
Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet());
assertEquals(3, slobrokHosts.size());
- assertTrue("Slobroks are assigned on cluster controller nodes", clusterControllerHosts.containsAll(slobrokHosts));
- assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost()));
- assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size());
- assertEquals("Dedicated admin cluster controllers when hosted", 3, admin.getClusterControllers().getContainers().size());
+ assertTrue(clusterControllerHosts.containsAll(slobrokHosts), "Slobroks are assigned on cluster controller nodes");
+ assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes");
+ assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment");
+ assertEquals(3, admin.getClusterControllers().getContainers().size(), "Dedicated admin cluster controllers when hosted");
// Check content clusters
ContentCluster cluster = model.getContentClusters().get("bar");
@@ -619,10 +622,10 @@ public class ModelProvisioningTest {
Admin admin = model.getAdmin();
Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet());
assertEquals(3, slobrokHosts.size());
- assertTrue("Slobroks are assigned from container nodes",
- containerHosts.containsAll(slobrokHosts));
- assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost()));
- assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size());
+ assertTrue(containerHosts.containsAll(slobrokHosts),
+ "Slobroks are assigned from container nodes");
+ assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes");
+ assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment");
}
@Test
@@ -669,9 +672,9 @@ public class ModelProvisioningTest {
.stream().map(cc -> cc.getHostResource()).collect(Collectors.toSet());
Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet());
assertEquals(3, slobrokHosts.size());
- assertTrue("Slobroks are assigned on cluster controller nodes", clusterControllerHosts.containsAll(slobrokHosts));
- assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost()));
- assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size());
+ assertTrue(clusterControllerHosts.containsAll(slobrokHosts), "Slobroks are assigned on cluster controller nodes");
+ assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes");
+ assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment");
assertEquals(3, admin.getClusterControllers().getContainers().size());
// Check content clusters
@@ -807,11 +810,11 @@ public class ModelProvisioningTest {
assertEquals(numberOfHosts, model.getRoot().hostSystem().getHosts().size());
// Check slobroks clusters
- assertEquals("Includes retired node", 1+3, model.getAdmin().getSlobroks().size());
+ assertEquals(1+3, model.getAdmin().getSlobroks().size(), "Includes retired node");
assertEquals("node-1-3-50-11", model.getAdmin().getSlobroks().get(0).getHostName());
assertEquals("node-1-3-50-10", model.getAdmin().getSlobroks().get(1).getHostName());
assertEquals("node-1-3-50-08", model.getAdmin().getSlobroks().get(2).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-09", model.getAdmin().getSlobroks().get(3).getHostName());
+ assertEquals("node-1-3-50-09", model.getAdmin().getSlobroks().get(3).getHostName(), "Included in addition because it is retired");
}
@Test
@@ -832,12 +835,12 @@ public class ModelProvisioningTest {
assertEquals(10+2, model.getRoot().hostSystem().getHosts().size());
// Check slobroks clusters
- assertEquals("Includes retired node", 3+2, model.getAdmin().getSlobroks().size());
+ assertEquals(3+2, model.getAdmin().getSlobroks().size(), "Includes retired node");
assertEquals("node-1-3-50-12", model.getAdmin().getSlobroks().get(0).getHostName());
assertEquals("node-1-3-50-11", model.getAdmin().getSlobroks().get(1).getHostName());
assertEquals("node-1-3-50-10", model.getAdmin().getSlobroks().get(2).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-04", model.getAdmin().getSlobroks().get(3).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-03", model.getAdmin().getSlobroks().get(4).getHostName());
+ assertEquals("node-1-3-50-04", model.getAdmin().getSlobroks().get(3).getHostName(), "Included in addition because it is retired");
+ assertEquals("node-1-3-50-03", model.getAdmin().getSlobroks().get(4).getHostName(), "Included in addition because it is retired");
}
@Test
@@ -862,14 +865,14 @@ public class ModelProvisioningTest {
// Check slobroks clusters
// ... from cluster default
- assertEquals("Includes retired node", 7, model.getAdmin().getSlobroks().size());
+ assertEquals(7, model.getAdmin().getSlobroks().size(), "Includes retired node");
assertEquals("node-1-3-50-16", model.getAdmin().getSlobroks().get(0).getHostName());
assertEquals("node-1-3-50-14", model.getAdmin().getSlobroks().get(1).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-15", model.getAdmin().getSlobroks().get(2).getHostName());
+ assertEquals("node-1-3-50-15", model.getAdmin().getSlobroks().get(2).getHostName(), "Included in addition because it is retired");
// ... from cluster bar
assertEquals("node-1-3-50-03", model.getAdmin().getSlobroks().get(3).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-05", model.getAdmin().getSlobroks().get(5).getHostName());
- assertEquals("Included in addition because it is retired", "node-1-3-50-04", model.getAdmin().getSlobroks().get(6).getHostName());
+ assertEquals("node-1-3-50-05", model.getAdmin().getSlobroks().get(5).getHostName(), "Included in addition because it is retired");
+ assertEquals("node-1-3-50-04", model.getAdmin().getSlobroks().get(6).getHostName(), "Included in addition because it is retired");
}
@Test
@@ -1248,44 +1251,48 @@ public class ModelProvisioningTest {
assertEquals("bar/storage/0", cluster.getRootGroup().getNodes().get(0).getConfigId());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testRequiringMoreNodesThanAreAvailable() {
- String services =
- "<?xml version='1.0' encoding='utf-8' ?>\n" +
- "<services>" +
- " <content version='1.0' id='bar'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document type='type1' mode='index'/>" +
- " </documents>" +
- " <nodes count='3' required='true'/>" +
- " </content>" +
- "</services>";
-
- int numberOfHosts = 2;
- VespaModelTester tester = new VespaModelTester();
- tester.addHosts(numberOfHosts);
- tester.createModel(services, false);
+ assertThrows(IllegalArgumentException.class, () -> {
+ String services =
+ "<?xml version='1.0' encoding='utf-8' ?>\n" +
+ "<services>" +
+ " <content version='1.0' id='bar'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document type='type1' mode='index'/>" +
+ " </documents>" +
+ " <nodes count='3' required='true'/>" +
+ " </content>" +
+ "</services>";
+
+ int numberOfHosts = 2;
+ VespaModelTester tester = new VespaModelTester();
+ tester.addHosts(numberOfHosts);
+ tester.createModel(services, false);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testRequiredNodesAndDedicatedClusterControllers() {
- String services =
- "<?xml version='1.0' encoding='utf-8' ?>\n" +
- "<services>" +
- " <content version='1.0' id='foo'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document type='type1' mode='index'/>" +
- " </documents>" +
- " <nodes count='2' required='true'/>" +
- " </content>" +
- "</services>";
-
- int numberOfHosts = 4; // needs 2 for foo and 3 for cluster controllers.
- VespaModelTester tester = new VespaModelTester();
- tester.addHosts(numberOfHosts);
- tester.createModel(services, false);
+ assertThrows(IllegalArgumentException.class, () -> {
+ String services =
+ "<?xml version='1.0' encoding='utf-8' ?>\n" +
+ "<services>" +
+ " <content version='1.0' id='foo'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document type='type1' mode='index'/>" +
+ " </documents>" +
+ " <nodes count='2' required='true'/>" +
+ " </content>" +
+ "</services>";
+
+ int numberOfHosts = 4; // needs 2 for foo and 3 for cluster controllers.
+ VespaModelTester tester = new VespaModelTester();
+ tester.addHosts(numberOfHosts);
+ tester.createModel(services, false);
+ });
}
@Test
@@ -1647,13 +1654,44 @@ public class ModelProvisioningTest {
tester.setHosted(true);
tester.addHosts(4);
VespaModel model = tester.createModel(new Zone(Environment.dev, RegionName.from("us-central-1")), services, true);
- assertEquals("We get 1 node per cluster and no admin node apart from the dedicated cluster controller", 3, model.getHosts().size());
+ assertEquals(3, model.getHosts().size(), "We get 1 node per cluster and no admin node apart from the dedicated cluster controller");
assertEquals(1, model.getContainerClusters().size());
assertEquals(1, model.getContainerClusters().get("foo").getContainers().size());
assertEquals(1, model.getContentClusters().get("bar").getRootGroup().countNodes(true));
assertEquals(1, model.getAdmin().getClusterControllers().getContainers().size());
}
+ @Test
+ public void testThatStandaloneSyntaxWithClusterControllerWorksOnHostedManuallyDeployed() {
+ String services =
+ "<?xml version='1.0' encoding='utf-8' ?>" +
+ "<services>" +
+ " <container id='foo' version='1.0'>" +
+ " <nodes count=\"2\" />" +
+ " </container>" +
+ " <content id='bar' version='1.0'>" +
+ " <documents>" +
+ " <document type='type1' mode='index'/>" +
+ " </documents>" +
+ " <redundancy>1</redundancy>" +
+ " <nodes>" +
+ " <group>" +
+ " <node distribution-key='0' hostalias='node3'/>" +
+ " </group>" +
+ " </nodes>" +
+ " </content>" +
+ "</services>";
+ VespaModelTester tester = new VespaModelTester();
+ tester.setHosted(true);
+ tester.addHosts(4);
+ try {
+ VespaModel model = tester.createModel(new Zone(Environment.staging, RegionName.from("us-central-1")), services, true);
+ fail("expected failure");
+ } catch (IllegalArgumentException e) {
+ assertTrue(e.getMessage().startsWith("Clusters in hosted environments must have a <nodes count='N'> tag"));
+ }
+ }
+
/** Deploying an application with "nodes count" standalone should give a single-node deployment */
@Test
public void testThatHostedSyntaxWorksOnStandalone() {
@@ -1677,10 +1715,12 @@ public class ModelProvisioningTest {
tester.addHosts(3);
VespaModel model = tester.createModel(services, true);
- assertEquals("Nodes in container cluster", 1,
- model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Nodes in content cluster (downscaled)", 1,
- model.getContentClusters().get("content").getRootGroup().getNodes().size());
+ assertEquals(1,
+ model.getContainerClusters().get("container1").getContainers().size(),
+ "Nodes in container cluster");
+ assertEquals(1,
+ model.getContentClusters().get("content").getRootGroup().getNodes().size(),
+ "Nodes in content cluster (downscaled)");
assertEquals(1, model.getAdmin().getSlobroks().size());
@@ -1733,10 +1773,12 @@ public class ModelProvisioningTest {
tester.addHosts(3);
VespaModel model = tester.createModel(services, hosts, true);
- assertEquals("Nodes in container cluster", 1,
- model.getContainerClusters().get("container1").getContainers().size());
- assertEquals("Nodes in content cluster (downscaled)", 1,
- model.getContentClusters().get("content").getRootGroup().getNodes().size());
+ assertEquals(1,
+ model.getContainerClusters().get("container1").getContainers().size(),
+ "Nodes in container cluster");
+ assertEquals(1,
+ model.getContentClusters().get("content").getRootGroup().getNodes().size(),
+ "Nodes in content cluster (downscaled)");
assertEquals(1, model.getAdmin().getSlobroks().size());
@@ -2073,10 +2115,10 @@ public class ModelProvisioningTest {
.collect(Collectors.groupingBy(h -> h.spec().membership().get().cluster().id().value()));
tests.forEach((clusterId, stateful) -> {
List<HostResource> hosts = hostsByCluster.getOrDefault(clusterId, List.of());
- assertFalse("Hosts are provisioned for '" + clusterId + "'", hosts.isEmpty());
- assertEquals("Hosts in cluster '" + clusterId + "' are " + (stateful ? "" : "not ") + "stateful",
- stateful,
- hosts.stream().allMatch(h -> h.spec().membership().get().cluster().isStateful()));
+ assertFalse(hosts.isEmpty(), "Hosts are provisioned for '" + clusterId + "'");
+ assertEquals(stateful,
+ hosts.stream().allMatch(h -> h.spec().membership().get().cluster().isStateful()),
+ "Hosts in cluster '" + clusterId + "' are " + (stateful ? "" : "not ") + "stateful");
});
}
@@ -2118,7 +2160,7 @@ public class ModelProvisioningTest {
ZookeeperServerConfig.Builder config = new ZookeeperServerConfig.Builder();
cluster.getContainers().forEach(c -> c.getConfig(config));
cluster.getConfig(config);
- assertTrue("Initial servers are not joining", config.build().server().stream().noneMatch(ZookeeperServerConfig.Server::joining));
+ assertTrue(config.build().server().stream().noneMatch(ZookeeperServerConfig.Server::joining), "Initial servers are not joining");
}
{
VespaModel nextModel = tester.createModel(Zone.defaultZone(), servicesXml.apply(3), true, false, false, 0, Optional.of(model), new DeployState.Builder(), "node-1-3-50-04", "node-1-3-50-03");
@@ -2126,22 +2168,22 @@ public class ModelProvisioningTest {
ZookeeperServerConfig.Builder config = new ZookeeperServerConfig.Builder();
cluster.getContainers().forEach(c -> c.getConfig(config));
cluster.getConfig(config);
- assertEquals("New nodes are joining",
- Map.of(0, false,
+ assertEquals(Map.of(0, false,
1, false,
2, false,
3, true,
4, true),
config.build().server().stream().collect(Collectors.toMap(ZookeeperServerConfig.Server::id,
- ZookeeperServerConfig.Server::joining)));
- assertEquals("Retired nodes are retired",
- Map.of(0, false,
+ ZookeeperServerConfig.Server::joining)),
+ "New nodes are joining");
+ assertEquals(Map.of(0, false,
1, true,
2, true,
3, false,
4, false),
config.build().server().stream().collect(Collectors.toMap(ZookeeperServerConfig.Server::id,
- ZookeeperServerConfig.Server::retired)));
+ ZookeeperServerConfig.Server::retired)),
+ "Retired nodes are retired");
}
}
@@ -2284,15 +2326,31 @@ public class ModelProvisioningTest {
private static void assertProvisioned(int nodeCount, ClusterSpec.Id id, ClusterSpec.Id combinedId,
ClusterSpec.Type type, VespaModel model) {
- assertEquals("Nodes in cluster " + id + " with type " + type + (combinedId != null ? ", combinedId " + combinedId : ""), nodeCount,
+ assertEquals(nodeCount,
model.hostSystem().getHosts().stream()
.map(h -> h.spec().membership().get().cluster())
.filter(spec -> spec.id().equals(id) && spec.type().equals(type) && spec.combinedId().equals(Optional.ofNullable(combinedId)))
- .count());
+ .count(),
+ "Nodes in cluster " + id + " with type " + type + (combinedId != null ? ", combinedId " + combinedId : ""));
}
private static void assertProvisioned(int nodeCount, ClusterSpec.Id id, ClusterSpec.Type type, VespaModel model) {
assertProvisioned(nodeCount, id, null, type, model);
}
+ record TestLogger(List<LogMessage> msgs) implements DeployLogger {
+
+ public TestLogger() {
+ this(new ArrayList<>());
+ }
+
+ @Override
+ public void log(Level level, String message) {
+ msgs.add(new LogMessage(level, message));
+ }
+
+ record LogMessage(Level level, String message) {}
+
+ }
+
}
diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java
index 446350a734f..e5f6235552f 100644
--- a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java
+++ b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.config.model.api.HostProvisioner;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
@@ -21,7 +21,7 @@ import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue;
public class SingleNodeProvisionerTest {
@Test
- public void require_basic_works() {
+ void require_basic_works() {
SingleNodeProvisioner hostProvisioner = new SingleNodeProvisioner();
// 4 services, 2 host aliases, mapping to 2 host.
@@ -56,16 +56,16 @@ public class SingleNodeProvisionerTest {
}
@Test
- public void require_allocate_clustermembership_works() throws IOException, SAXException {
+ void require_allocate_clustermembership_works() throws IOException, SAXException {
String servicesXml = "<services version='1.0'>"
- + " <admin version='3.0'>"
- + " <nodes count='1' />"
- + " </admin>"
- + " <container version='1.0'>"
- + " <search />"
- + " <nodes count='1' />"
- + " </container>"
- + "</services>";
+ + " <admin version='3.0'>"
+ + " <nodes count='1' />"
+ + " </admin>"
+ + " <container version='1.0'>"
+ + " <search />"
+ + " <nodes count='1' />"
+ + " </container>"
+ + "</services>";
ApplicationPackage app = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(app);
assertThat(model.getHosts().size(), is(1));
@@ -93,7 +93,7 @@ public class SingleNodeProvisionerTest {
return createAliases(new ArrayList<String>());
}
- // Admin services on node1, qrserver on node2 + additional specs
+ // Admin services on node1, container on node2 + additional specs
private List<String> createAliases(Collection<String> additionalAliases) {
List<String> aliases = new ArrayList<>();
aliases.add("node1");
diff --git a/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java b/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java
index 4a3d85c6a76..f484a92e341 100644
--- a/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java
+++ b/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java
@@ -10,12 +10,12 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Thomas Gundersen
@@ -25,7 +25,7 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase {
// Verify that we can register and retrieve fields.
@Test
- public void testSetGet() {
+ void testSetGet() {
SDDocumentType docType = new SDDocumentType("testdoc");
docType.addField("Bongle", DataType.STRING);
docType.addField("nalle", DataType.INT);
@@ -36,7 +36,7 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testInheritance() {
+ void testInheritance() {
SDDocumentType child = new SDDocumentType("child");
Iterator<SDDocumentType> inherited = child.getInheritedTypes().iterator();
assertTrue(inherited.hasNext());
@@ -102,23 +102,23 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testStructInheritance() throws ParseException {
+ void testStructInheritance() throws ParseException {
String schemaLines = joinLines(
"schema test {" +
- " document test {" +
- " struct parent_struct {" +
- " field parent_struct_field_1 type string {}" +
- " }" +
- " struct child_struct inherits parent_struct {" +
- " field child_struct_field_1 type string {}" +
- " }" +
- " field child_array type array<child_struct> {" +
- " indexing: summary\n" +
- " struct-field child_struct_field_1 { indexing: attribute }" +
- " struct-field parent_struct_field_1 { indexing: attribute }" +
- " }" +
- " }" +
- "}");
+ " document test {" +
+ " struct parent_struct {" +
+ " field parent_struct_field_1 type string {}" +
+ " }" +
+ " struct child_struct inherits parent_struct {" +
+ " field child_struct_field_1 type string {}" +
+ " }" +
+ " field child_array type array<child_struct> {" +
+ " indexing: summary\n" +
+ " struct-field child_struct_field_1 { indexing: attribute }" +
+ " struct-field parent_struct_field_1 { indexing: attribute }" +
+ " }" +
+ " }" +
+ "}");
ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub());
builder.addSchema(schemaLines);
diff --git a/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java b/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java
index 6a8645195a5..6a9565d4d16 100644
--- a/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java
+++ b/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.document.test;
import com.yahoo.document.DataType;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.SDDocumentType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Thomas Gundersen
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class SDFieldTestCase extends AbstractSchemaTestCase {
@Test
- public void testIdSettingConflict() {
+ void testIdSettingConflict() {
SDDocumentType doc = new SDDocumentType("testdoc");
doc.addField("one", DataType.STRING, 60);
@@ -30,7 +30,7 @@ public class SDFieldTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testSettingReservedId() {
+ void testSettingReservedId() {
SDDocumentType doc = new SDDocumentType("testdoc");
try {
doc.addField("one", DataType.STRING, 127);
diff --git a/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java b/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java
index dbe827ed67f..18ff1fd8536 100644
--- a/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java
@@ -7,11 +7,11 @@ import com.yahoo.document.Field;
import com.yahoo.document.annotation.AnnotationReferenceDataType;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.config.model.deploy.TestProperties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author arnej
@@ -38,9 +38,9 @@ public class AnnotationReferenceTestCase {
" }",
" }",
"}");
-
+
@Test
- public void noAnnotationReferenceInDocument() throws Exception {
+ void noAnnotationReferenceInDocument() throws Exception {
var builder = new ApplicationBuilder(new TestProperties());
builder.addSchema(sd);
builder.build(true);
@@ -49,7 +49,7 @@ public class AnnotationReferenceTestCase {
var complex = doc.findAnnotation("complex");
var dt = complex.getDataType();
assertTrue(dt instanceof StructDataType);
- var struct = (StructDataType)dt;
+ var struct = (StructDataType) dt;
var field = struct.getField("owner");
assertTrue(field.getDataType() instanceof AnnotationReferenceDataType);
}
diff --git a/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java b/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java
index aab79617556..a03bf3bf8de 100644
--- a/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.document.CollectionDataType;
import com.yahoo.document.DataType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* tests importing of document containing array type fields
@@ -21,15 +21,15 @@ import static org.junit.Assert.assertTrue;
public class ArraysTestCase extends AbstractSchemaTestCase {
@Test
- public void testArrayImporting() throws IOException, ParseException {
+ void testArrayImporting() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/arrays.sd");
SDField tags = (SDField) schema.getDocument().getField("tags");
- assertEquals(DataType.STRING, ((CollectionDataType)tags.getDataType()).getNestedType());
+ assertEquals(DataType.STRING, ((CollectionDataType) tags.getDataType()).getNestedType());
SDField ratings = (SDField) schema.getDocument().getField("ratings");
assertTrue(ratings.getDataType() instanceof ArrayDataType);
- assertEquals(DataType.INT, ((ArrayDataType)ratings.getDataType()).getNestedType());
+ assertEquals(DataType.INT, ((ArrayDataType) ratings.getDataType()).getNestedType());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java b/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java
index 57331bea6bd..7d72cce1401 100644
--- a/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.document.CollectionDataType;
import com.yahoo.document.DataType;
import com.yahoo.document.WeightedSetDataType;
import com.yahoo.schema.document.SDField;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* tests importing of document containing array type fields and weighted set type fields, new syntax.
@@ -18,24 +18,24 @@ import static org.junit.Assert.assertTrue;
*/
public class ArraysWeightedSetsTestCase extends AbstractSchemaTestCase {
@Test
- public void testArrayWeightedSetsImporting() throws java.io.IOException, com.yahoo.schema.parser.ParseException {
+ void testArrayWeightedSetsImporting() throws java.io.IOException, com.yahoo.schema.parser.ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/arraysweightedsets.sd");
SDField tags = (SDField) schema.getDocument().getField("tags");
assertTrue(tags.getDataType() instanceof ArrayDataType);
- assertEquals(DataType.STRING, ((CollectionDataType)tags.getDataType()).getNestedType());
+ assertEquals(DataType.STRING, ((CollectionDataType) tags.getDataType()).getNestedType());
SDField ratings = (SDField) schema.getDocument().getField("ratings");
assertTrue(ratings.getDataType() instanceof ArrayDataType);
- assertEquals(DataType.INT, ((CollectionDataType)ratings.getDataType()).getNestedType());
+ assertEquals(DataType.INT, ((CollectionDataType) ratings.getDataType()).getNestedType());
SDField flags = (SDField) schema.getDocument().getField("flags");
assertTrue(flags.getDataType() instanceof WeightedSetDataType);
- assertEquals(DataType.STRING, ((CollectionDataType)flags.getDataType()).getNestedType());
+ assertEquals(DataType.STRING, ((CollectionDataType) flags.getDataType()).getNestedType());
SDField banners = (SDField) schema.getDocument().getField("banners");
assertTrue(banners.getDataType() instanceof WeightedSetDataType);
- assertEquals(DataType.INT, ((CollectionDataType)banners.getDataType()).getNestedType());
+ assertEquals(DataType.INT, ((CollectionDataType) banners.getDataType()).getNestedType());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java b/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java
index 885cc385dfa..54fb6b0fb52 100644
--- a/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java
@@ -10,16 +10,12 @@ import com.yahoo.schema.parser.ParseException;
import com.yahoo.tensor.TensorType;
import com.yahoo.vespa.config.search.AttributesConfig;
import com.yahoo.vespa.configdefinition.IlscriptsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Attribute settings
@@ -29,10 +25,10 @@ import static org.junit.Assert.fail;
public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
@Test
- public void testAttributeSettings() throws IOException, ParseException {
+ void testAttributeSettings() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesettings.sd");
- SDField f1=(SDField) schema.getDocument().getField("f1");
+ SDField f1 = (SDField) schema.getDocument().getField("f1");
assertEquals(1, f1.getAttributes().size());
Attribute a1 = f1.getAttributes().get(f1.getName());
assertEquals(Attribute.Type.LONG, a1.getType());
@@ -42,7 +38,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
assertFalse(a1.isRemoveIfZero());
assertFalse(a1.isCreateIfNonExistent());
- SDField f2=(SDField) schema.getDocument().getField("f2");
+ SDField f2 = (SDField) schema.getDocument().getField("f2");
assertEquals(1, f2.getAttributes().size());
Attribute a2 = f2.getAttributes().get(f2.getName());
assertEquals(Attribute.Type.LONG, a2.getType());
@@ -52,7 +48,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
assertFalse(a2.isRemoveIfZero());
assertFalse(a2.isCreateIfNonExistent());
assertEquals("f2", f2.getAliasToName().get("f2alias"));
- SDField f3=(SDField) schema.getDocument().getField("f3");
+ SDField f3 = (SDField) schema.getDocument().getField("f3");
assertEquals(1, f3.getAttributes().size());
assertEquals("f3", f3.getAliasToName().get("f3alias"));
@@ -103,7 +99,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatFastAccessCanBeSet() throws IOException, ParseException {
+ void requireThatFastAccessCanBeSet() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesettings.sd");
SDField field = (SDField) schema.getDocument().getField("fast_access");
assertEquals(1, field.getAttributes().size());
@@ -125,7 +121,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatPagedIsDefaultOff() throws ParseException {
+ void requireThatPagedIsDefaultOff() throws ParseException {
Attribute attr = getAttributeF(
"search test {\n" +
" document test { \n" +
@@ -136,8 +132,9 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
"}\n");
assertFalse(attr.isPaged());
}
+
@Test
- public void requireThatPagedCanBeSet() throws ParseException {
+ void requireThatPagedCanBeSet() throws ParseException {
Attribute attr = getAttributeF(
"search test {\n" +
" document test { \n" +
@@ -151,29 +148,29 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatMutableIsDefaultOff() throws ParseException {
+ void requireThatMutableIsDefaultOff() throws ParseException {
Attribute attr = getAttributeF(
"search test {\n" +
- " document test { \n" +
- " field f type int { \n" +
- " indexing: attribute \n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test { \n" +
+ " field f type int { \n" +
+ " indexing: attribute \n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
assertFalse(attr.isMutable());
}
@Test
- public void requireThatMutableCanNotbeSetInDocument() throws ParseException {
+ void requireThatMutableCanNotbeSetInDocument() throws ParseException {
try {
getSchema("search test {\n" +
- " document test {\n" +
- " field f type int {\n" +
- " indexing: attribute\n" +
- " attribute: mutable\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test {\n" +
+ " field f type int {\n" +
+ " indexing: attribute\n" +
+ " attribute: mutable\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
fail();
} catch (IllegalArgumentException e) {
assertEquals("Field 'f' in 'test' can not be marked mutable as it is inside the document clause.", e.getMessage());
@@ -181,7 +178,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatMutableExtraFieldCanBeSet() throws ParseException {
+ void requireThatMutableExtraFieldCanBeSet() throws ParseException {
Attribute attr = getAttributeF(
"search test {\n" +
" document test { \n" +
@@ -216,7 +213,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatMutableConfigIsProperlyPropagated() throws ParseException {
+ void requireThatMutableConfigIsProperlyPropagated() throws ParseException {
AttributeFields attributes = new AttributeFields(getSearchWithMutables());
AttributesConfig.Builder builder = new AttributesConfig.Builder();
attributes.getConfig(builder, AttributeFields.FieldSet.ALL, 13333, true);
@@ -232,7 +229,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireMaxUnCommittedMemoryIsProperlyPropagated() throws ParseException {
+ void requireMaxUnCommittedMemoryIsProperlyPropagated() throws ParseException {
AttributeFields attributes = new AttributeFields(getSearchWithMutables());
AttributesConfig.Builder builder = new AttributesConfig.Builder();
attributes.getConfig(builder, AttributeFields.FieldSet.ALL, 13333, true);
@@ -260,7 +257,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireEnableBitVectorsIsProperlyPropagated() throws ParseException {
+ void requireEnableBitVectorsIsProperlyPropagated() throws ParseException {
Schema schema = getSchema(
"search test {\n" +
" document test { \n" +
@@ -278,7 +275,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatMutableIsAllowedThroughIndexing() throws ParseException {
+ void requireThatMutableIsAllowedThroughIndexing() throws ParseException {
IndexingScript script = new IndexingScript(getSearchWithMutables());
IlscriptsConfig.Builder builder = new IlscriptsConfig.Builder();
script.getConfig(builder);
@@ -293,7 +290,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void attribute_convert_to_array_copies_internal_state() {
+ void attribute_convert_to_array_copies_internal_state() {
StructDataType refType = new StructDataType("my_struct");
Attribute single = new Attribute("foo", Attribute.Type.STRING, Attribute.CollectionType.SINGLE,
Optional.of(TensorType.fromSpec("tensor(x{})")), Optional.of(refType));
diff --git a/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java b/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java
index 4df4ead171b..ca726d8cd57 100644
--- a/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.schema;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests comment handling
@@ -17,11 +17,11 @@ import static org.junit.Assert.assertEquals;
public class CommentTestCase extends AbstractSchemaTestCase {
@Test
- public void testComments() throws IOException, ParseException {
+ void testComments() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/comment.sd");
SDField field = schema.getConcreteField("a");
assertEquals("{ input a | tokenize normalize stem:\"BEST\" | summary a | index a; }",
- field.getIndexingScript().toString());
+ field.getIndexingScript().toString());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java b/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java
index 482bc877081..06b38224c37 100644
--- a/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java
@@ -3,17 +3,17 @@ package com.yahoo.schema;
import com.yahoo.search.query.ranking.Diversity;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
-import static org.junit.Assert.fail;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author baldersheim
*/
public class DiversityTestCase {
@Test
- public void testDiversity() throws ParseException {
+ void testDiversity() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -58,8 +58,9 @@ public class DiversityTestCase {
private static String getMessagePrefix() {
return "In search definition 'test', rank-profile 'parent': diversity attribute 'b' ";
}
+
@Test
- public void requireSingleNumericOrString() throws ParseException {
+ void requireSingleNumericOrString() throws ParseException {
ApplicationBuilder builder = getSearchBuilder("field b type predicate { indexing: attribute }");
try {
@@ -71,7 +72,7 @@ public class DiversityTestCase {
}
@Test
- public void requireSingle() throws ParseException {
+ void requireSingle() throws ParseException {
ApplicationBuilder builder = getSearchBuilder("field b type array<int> { indexing: attribute }");
try {
diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java
index ef4d8e05540..ccfa5c51a16 100644
--- a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java
@@ -6,9 +6,7 @@ import com.yahoo.documentmodel.NewDocumentReferenceDataType;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.TemporarySDField;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -17,20 +15,15 @@ import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
*/
public class DocumentGraphValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void simple_ref_dag_is_allowed() {
+ void simple_ref_dag_is_allowed() {
Schema advertiserSchema = createSearchWithName("advertiser");
Schema campaignSchema = createSearchWithName("campaign");
Schema adSchema = createSearchWithName("ad");
@@ -42,7 +35,7 @@ public class DocumentGraphValidatorTest {
}
@Test
- public void simple_inheritance_dag_is_allowed() {
+ void simple_inheritance_dag_is_allowed() {
Schema grandfather = createSearchWithName("grandfather");
Schema father = createSearchWithName("father", grandfather);
Schema son = createSearchWithName("son", father);
@@ -52,7 +45,7 @@ public class DocumentGraphValidatorTest {
}
@Test
- public void complex_dag_is_allowed() {
+ void complex_dag_is_allowed() {
Schema grandfather = createSearchWithName("grandfather");
Schema father = createSearchWithName("father", grandfather);
Schema mother = createSearchWithName("mother", grandfather);
@@ -70,55 +63,59 @@ public class DocumentGraphValidatorTest {
}
@Test
- public void ref_cycle_is_forbidden() {
- Schema schema1 = createSearchWithName("doc1");
- Schema schema2 = createSearchWithName("doc2");
- Schema schema3 = createSearchWithName("doc3");
- createDocumentReference(schema1, schema2, "ref_2");
- createDocumentReference(schema2, schema3, "ref_3");
- createDocumentReference(schema3, schema1, "ref_1");
-
- DocumentGraphValidator validator = new DocumentGraphValidator();
- exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class);
- exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc2->doc3->doc1.");
- validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ void ref_cycle_is_forbidden() {
+ Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> {
+ Schema schema1 = createSearchWithName("doc1");
+ Schema schema2 = createSearchWithName("doc2");
+ Schema schema3 = createSearchWithName("doc3");
+ createDocumentReference(schema1, schema2, "ref_2");
+ createDocumentReference(schema2, schema3, "ref_3");
+ createDocumentReference(schema3, schema1, "ref_1");
+
+ DocumentGraphValidator validator = new DocumentGraphValidator();
+ validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ });
+ assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc2->doc3->doc1."));
}
@Test
- public void inherit_cycle_is_forbidden() {
- Schema schema1 = createSearchWithName("doc1");
- Schema schema2 = createSearchWithName("doc2", schema1);
- Schema schema3 = createSearchWithName("doc3", schema2);
- schema1.getDocument().inherit(schema3.getDocument());
-
- DocumentGraphValidator validator = new DocumentGraphValidator();
- exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class);
- exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc3->doc2->doc1.");
- validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ void inherit_cycle_is_forbidden() {
+ Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> {
+ Schema schema1 = createSearchWithName("doc1");
+ Schema schema2 = createSearchWithName("doc2", schema1);
+ Schema schema3 = createSearchWithName("doc3", schema2);
+ schema1.getDocument().inherit(schema3.getDocument());
+
+ DocumentGraphValidator validator = new DocumentGraphValidator();
+ validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ });
+ assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc3->doc2->doc1."));
}
@Test
- public void combined_inherit_and_ref_cycle_is_forbidden() {
- Schema schema1 = createSearchWithName("doc1");
- Schema schema2 = createSearchWithName("doc2", schema1);
- Schema schema3 = createSearchWithName("doc3", schema2);
- createDocumentReference(schema1, schema3, "ref_1");
-
- DocumentGraphValidator validator = new DocumentGraphValidator();
- exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class);
- exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc3->doc2->doc1.");
- validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ void combined_inherit_and_ref_cycle_is_forbidden() {
+ Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> {
+ Schema schema1 = createSearchWithName("doc1");
+ Schema schema2 = createSearchWithName("doc2", schema1);
+ Schema schema3 = createSearchWithName("doc3", schema2);
+ createDocumentReference(schema1, schema3, "ref_1");
+
+ DocumentGraphValidator validator = new DocumentGraphValidator();
+ validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3));
+ });
+ assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc3->doc2->doc1."));
}
@Test
- public void self_reference_is_forbidden() {
- Schema adSchema = createSearchWithName("ad");
- createDocumentReference(adSchema, adSchema, "ad_ref");
+ void self_reference_is_forbidden() {
+ Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> {
+ Schema adSchema = createSearchWithName("ad");
+ createDocumentReference(adSchema, adSchema, "ad_ref");
- DocumentGraphValidator validator = new DocumentGraphValidator();
- exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class);
- exceptionRule.expectMessage("Document dependency cycle detected: ad->ad.");
- validator.validateDocumentGraph(documentListOf(adSchema));
+ DocumentGraphValidator validator = new DocumentGraphValidator();
+ validator.validateDocumentGraph(documentListOf(adSchema));
+ });
+ assertTrue(exception.getMessage().contains("Document dependency cycle detected: ad->ad."));
}
/**
@@ -126,7 +123,7 @@ public class DocumentGraphValidatorTest {
* produces a stack overflow before getting to graph validation.
*/
@Test
- public void self_inheritance_forbidden() {
+ void self_inheritance_forbidden() {
try {
Schema adSchema = createSearchWithName("ad");
SDDocumentType document = adSchema.getDocument();
diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java
index 1592060f466..bcf8c6045b3 100644
--- a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java
@@ -6,17 +6,13 @@ import com.yahoo.document.DataType;
import com.yahoo.documentmodel.NewDocumentReferenceDataType;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -25,12 +21,9 @@ public class DocumentReferenceResolverTest {
private static final String BAR = "bar";
private static final String FOO = "foo";
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
@Test
- public void reference_from_one_document_to_another_is_resolved() {
+ void reference_from_one_document_to_another_is_resolved() {
// Create bar document with no fields
Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty());
SDDocumentType barDocument = new SDDocumentType(BAR, barSchema);
@@ -40,7 +33,7 @@ public class DocumentReferenceResolverTest {
Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty());
SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema);
SDField fooRefToBarField = new SDField
- (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType()));
+ (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType()));
AttributeUtils.addAttributeAspect(fooRefToBarField);
SDField irrelevantField = new SDField(fooDocument, "irrelevant_stuff", DataType.INT);
fooDocument.addField(fooRefToBarField);
@@ -59,45 +52,44 @@ public class DocumentReferenceResolverTest {
@SuppressWarnings("deprecation")
@Test
- public void throws_user_friendly_exception_if_referenced_document_does_not_exist() {
- // Create foo document with document reference to non-existing document bar
- Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty());
- SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema);
- SDField fooRefToBarField = new SDField(
- fooDocument,
- "bar_ref", NewDocumentReferenceDataType.forDocumentName("bar"));
- AttributeUtils.addAttributeAspect(fooRefToBarField);
- fooDocument.addField(fooRefToBarField);
- fooSchema.addDocument(fooDocument);
-
- DocumentReferenceResolver resolver = new DocumentReferenceResolver(singletonList(fooSchema));
-
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "Invalid document reference 'bar_ref': Could not find document type 'bar'");
- resolver.resolveReferences(fooDocument);
+ void throws_user_friendly_exception_if_referenced_document_does_not_exist() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ // Create foo document with document reference to non-existing document bar
+ Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty());
+ SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema);
+ SDField fooRefToBarField = new SDField(
+ fooDocument,
+ "bar_ref", NewDocumentReferenceDataType.forDocumentName("bar"));
+ AttributeUtils.addAttributeAspect(fooRefToBarField);
+ fooDocument.addField(fooRefToBarField);
+ fooSchema.addDocument(fooDocument);
+
+ DocumentReferenceResolver resolver = new DocumentReferenceResolver(singletonList(fooSchema));
+ resolver.resolveReferences(fooDocument);
+ });
+ assertTrue(exception.getMessage().contains("Invalid document reference 'bar_ref': Could not find document type 'bar'"));
}
@Test
- public void throws_exception_if_reference_is_not_an_attribute() {
- // Create bar document with no fields
- Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty());
- SDDocumentType barDocument = new SDDocumentType("bar", barSchema);
- barSchema.addDocument(barDocument);
-
- // Create foo document with document reference to bar
- Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty());
- SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema);
- SDField fooRefToBarField = new SDField
- (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType()));
- fooDocument.addField(fooRefToBarField);
- fooSchema.addDocument(fooDocument);
-
- DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema));
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "The field 'bar_ref' is an invalid document reference. The field must be an attribute.");
- resolver.resolveReferences(fooDocument);
+ void throws_exception_if_reference_is_not_an_attribute() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ // Create bar document with no fields
+ Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty());
+ SDDocumentType barDocument = new SDDocumentType("bar", barSchema);
+ barSchema.addDocument(barDocument);
+
+ // Create foo document with document reference to bar
+ Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty());
+ SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema);
+ SDField fooRefToBarField = new SDField
+ (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType()));
+ fooDocument.addField(fooRefToBarField);
+ fooSchema.addDocument(fooDocument);
+
+ DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema));
+ resolver.resolveReferences(fooDocument);
+ });
+ assertTrue(exception.getMessage().contains("The field 'bar_ref' is an invalid document reference. The field must be an attribute."));
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java
index bff4b434408..0bfd1b1e201 100644
--- a/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java
@@ -1,15 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.schema;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.function.Function;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests rank feature names.
@@ -19,7 +17,7 @@ import static org.junit.Assert.assertTrue;
public class FeatureNamesTestCase {
@Test
- public void testArgument() {
+ void testArgument() {
assertFalse(FeatureNames.argumentOf("foo(bar)").isPresent());
assertFalse(FeatureNames.argumentOf("foo(bar.baz)").isPresent());
assertEquals("bar", FeatureNames.argumentOf("query(bar)").get());
@@ -31,25 +29,25 @@ public class FeatureNamesTestCase {
}
@Test
- public void testConstantFeature() {
+ void testConstantFeature() {
assertEquals("constant(foo)",
- FeatureNames.asConstantFeature("foo").toString());
+ FeatureNames.asConstantFeature("foo").toString());
}
@Test
- public void testAttributeFeature() {
+ void testAttributeFeature() {
assertEquals("attribute(foo)",
- FeatureNames.asAttributeFeature("foo").toString());
+ FeatureNames.asAttributeFeature("foo").toString());
}
@Test
- public void testQueryFeature() {
+ void testQueryFeature() {
assertEquals("query(\"foo.bar\")",
- FeatureNames.asQueryFeature("foo.bar").toString());
+ FeatureNames.asQueryFeature("foo.bar").toString());
}
@Test
- public void testLegalFeatureNames() {
+ void testLegalFeatureNames() {
assertTrue(FeatureNames.notNeedQuotes("_"));
assertFalse(FeatureNames.notNeedQuotes("-"));
assertTrue(FeatureNames.notNeedQuotes("_-"));
@@ -57,15 +55,15 @@ public class FeatureNamesTestCase {
assertFalse(FeatureNames.notNeedQuotes("0_-azAZxy98-_+"));
}
- @Test
- @Ignore
/*
* Unignore to verify performance
* 2021/09/05 performance was a factor of 5.25
* 'Identifier handcoded validity check took 4301ms
* Identifier regexp validity check took 22609ms'
*/
- public void benchMarkPatternMatching() {
+ @Test
+ @Disabled
+ void benchMarkPatternMatching() {
Pattern identifierRegexp = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_-]*");
String[] strings = new String[1000];
for (int i = 0; i < strings.length; i++) {
diff --git a/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java b/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java
index 4a590288d53..ed4cb70c3c7 100644
--- a/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java
@@ -8,13 +8,14 @@ import com.yahoo.document.DocumentTypeManagerConfigurer;
import com.yahoo.document.Field;
import com.yahoo.document.config.DocumentmanagerConfig;
import com.yahoo.schema.derived.Deriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Einar M R Rosenvinge
@@ -22,14 +23,14 @@ import static org.junit.Assert.assertSame;
public class FieldOfTypeDocumentTestCase extends AbstractSchemaTestCase {
@Test
- public void testDocument() throws IOException {
+ void testDocument() throws IOException {
List<String> sds = new ArrayList<>();
sds.add("src/test/examples/music.sd");
sds.add("src/test/examples/fieldoftypedocument.sd");
DocumentmanagerConfig.Builder value = Deriver.getDocumentManagerConfig(sds);
assertConfigFile("src/test/examples/fieldoftypedocument.cfg",
- new DocumentmanagerConfig(value).toString() + "\n");
+ new DocumentmanagerConfig(value).toString() + "\n");
DocumentTypeManager manager = new DocumentTypeManager();
DocumentTypeManagerConfigurer.configure(manager, "raw:" + new DocumentmanagerConfig(value).toString());
diff --git a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java
index 92d11b3a18a..092891f1ea1 100644
--- a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java
@@ -6,18 +6,18 @@ import com.yahoo.document.DataType;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.TemporaryImportedField;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ImportedFieldsEnumeratorTest {
@Test
- public void imported_fields_are_enumerated_and_copied_from_correct_search_instance() {
+ void imported_fields_are_enumerated_and_copied_from_correct_search_instance() {
String PARENT = "parent";
Schema parentSchema = new Schema(PARENT, MockApplicationPackage.createEmpty());
SDDocumentType parentDocument = new SDDocumentType(PARENT, parentSchema);
diff --git a/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java b/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java
index 87e168adb66..d70abbd6d3f 100644
--- a/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java
@@ -5,12 +5,12 @@ import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.schema.derived.DerivedConfiguration;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -18,12 +18,12 @@ import static org.junit.Assert.fail;
public class IncorrectRankingExpressionFileRefTestCase extends AbstractSchemaTestCase {
@Test
- public void testIncorrectRef() throws IOException, ParseException {
+ void testIncorrectRef() throws IOException, ParseException {
try {
RankProfileRegistry registry = new RankProfileRegistry();
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/incorrectrankingexpressionfileref.sd",
- registry,
- new QueryProfileRegistry());
+ registry,
+ new QueryProfileRegistry());
new DerivedConfiguration(schema, registry); // cause rank profile parsing
fail("parsing should have failed");
} catch (IllegalArgumentException e) {
diff --git a/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java
index e58cce6472a..acc872f6798 100644
--- a/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java
@@ -2,10 +2,11 @@
package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
/**
* Tests importing a search definition with conflicting summary types
*
@@ -13,20 +14,20 @@ import static org.junit.Assert.fail;
*/
public class IncorrectSummaryTypesTestCase extends AbstractSchemaTestCase {
@Test
- public void testImportingIncorrect() throws ParseException {
+ void testImportingIncorrect() throws ParseException {
try {
ApplicationBuilder.createFromString(
"search incorrectsummarytypes {\n" +
- " document incorrectsummarytypes {\n" +
- " field somestring type string {\n" +
- " indexing: summary\n" +
- " }\n" +
- " }\n" +
- " document-summary incorrect {\n" +
- " summary somestring type int {\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document incorrectsummarytypes {\n" +
+ " field somestring type string {\n" +
+ " indexing: summary\n" +
+ " }\n" +
+ " }\n" +
+ " document-summary incorrect {\n" +
+ " summary somestring type int {\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
fail("processing should have failed");
} catch (RuntimeException e) {
assertEquals("'summary somestring type string' in 'destinations(default )' is inconsistent with 'summary somestring type int' in 'destinations(incorrect )': All declarations of the same summary field must have the same type", e.getMessage());
diff --git a/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java b/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java
index 6082372b428..b1d502dec36 100644
--- a/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java
@@ -4,13 +4,13 @@ package com.yahoo.schema;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.Stemming;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Rank settings
@@ -20,24 +20,24 @@ import static org.junit.Assert.assertTrue;
public class IndexSettingsTestCase extends AbstractSchemaTestCase {
@Test
- public void testStemmingSettings() throws IOException, ParseException {
+ void testStemmingSettings() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/indexsettings.sd");
- SDField usingDefault=(SDField) schema.getDocument().getField("usingdefault");
- assertEquals(Stemming.SHORTEST,usingDefault.getStemming(schema));
+ SDField usingDefault = (SDField) schema.getDocument().getField("usingdefault");
+ assertEquals(Stemming.SHORTEST, usingDefault.getStemming(schema));
- SDField notStemmed=(SDField) schema.getDocument().getField("notstemmed");
- assertEquals(Stemming.NONE,notStemmed.getStemming(schema));
+ SDField notStemmed = (SDField) schema.getDocument().getField("notstemmed");
+ assertEquals(Stemming.NONE, notStemmed.getStemming(schema));
- SDField allStemmed=(SDField) schema.getDocument().getField("allstemmed");
- assertEquals(Stemming.SHORTEST,allStemmed.getStemming(schema));
+ SDField allStemmed = (SDField) schema.getDocument().getField("allstemmed");
+ assertEquals(Stemming.SHORTEST, allStemmed.getStemming(schema));
- SDField multiStemmed=(SDField) schema.getDocument().getField("multiplestems");
+ SDField multiStemmed = (SDField) schema.getDocument().getField("multiplestems");
assertEquals(Stemming.MULTIPLE, multiStemmed.getStemming(schema));
}
@Test
- public void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException {
+ void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException {
ApplicationBuilder builder = ApplicationBuilder.createFromString(joinLines(
"search test {",
" document test {",
diff --git a/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java b/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java
index 6a51000fffe..fcbea179810 100644
--- a/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests that indexing statements are parsed correctly.
@@ -14,12 +14,12 @@ import static org.junit.Assert.assertNotNull;
public class IndexingParsingTestCase extends AbstractSchemaTestCase {
@Test
- public void requireThatIndexingExpressionsCanBeParsed() throws Exception {
+ void requireThatIndexingExpressionsCanBeParsed() throws Exception {
assertNotNull(ApplicationBuilder.buildFromFile("src/test/examples/indexing.sd"));
}
@Test
- public void requireThatParseExceptionPositionIsCorrect() throws Exception {
+ void requireThatParseExceptionPositionIsCorrect() throws Exception {
try {
ApplicationBuilder.buildFromFile("src/test/examples/indexing_invalid_expression.sd");
} catch (ParseException e) {
diff --git a/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java
index 6d6249dc372..fb3257bf4b4 100644
--- a/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,7 +15,7 @@ import java.io.IOException;
public class MultipleSummariesTestCase extends AbstractSchemaTestCase {
@Test
- public void testArrayImporting() throws IOException, ParseException {
+ void testArrayImporting() throws IOException, ParseException {
var builder = new ApplicationBuilder(new TestProperties());
builder.addSchemaFile("src/test/examples/multiplesummaries.sd");
builder.build(true);
diff --git a/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java b/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java
index 9b4b6864309..8de95945a18 100644
--- a/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.schema;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests that "name" is not allowed as name for a field.
@@ -17,20 +15,20 @@ import static org.junit.Assert.fail;
public class NameFieldCheckTestCase extends AbstractSchemaTestCase {
@Test
- public void testNameField() {
+ void testNameField() {
try {
ApplicationBuilder.createFromString(
"search simple {\n" +
- " document name-check {\n" +
- " field title type string {\n" +
- " indexing: summary | index\n" +
- " }\n" +
- " # reserved name, should trigger error\n" +
- " field sddocname type string {\n" +
- " indexing: index\n" +
- " }\n" +
- " }\n" +
- "}");
+ " document name-check {\n" +
+ " field title type string {\n" +
+ " indexing: summary | index\n" +
+ " }\n" +
+ " # reserved name, should trigger error\n" +
+ " field sddocname type string {\n" +
+ " indexing: index\n" +
+ " }\n" +
+ " }\n" +
+ "}");
fail("Should throw exception.");
} catch (Exception expected) {
// Success
@@ -38,39 +36,39 @@ public class NameFieldCheckTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testDuplicateNamesInSearchDifferentType() {
+ void testDuplicateNamesInSearchDifferentType() {
try {
ApplicationBuilder.createFromString(
"search duplicatenamesinsearch {\n" +
- " document {\n" +
- " field grpphotoids64 type string { }\n" +
- " }\n" +
- " field grpphotoids64 type array<long> {\n" +
- " indexing: input grpphotoids64 | split \" \" | for_each {\n" +
- " base64decode } | attribute\n" +
- " }\n" +
- "}");
+ " document {\n" +
+ " field grpphotoids64 type string { }\n" +
+ " }\n" +
+ " field grpphotoids64 type array<long> {\n" +
+ " indexing: input grpphotoids64 | split \" \" | for_each {\n" +
+ " base64decode } | attribute\n" +
+ " }\n" +
+ "}");
fail("Should throw exception.");
} catch (Exception e) {
assertEquals("For schema 'duplicatenamesinsearch', field 'grpphotoids64': " +
- "Incompatible types. Expected Array<long> for index field 'grpphotoids64', got string.", e.getMessage());
+ "Incompatible types. Expected Array<long> for index field 'grpphotoids64', got string.", e.getMessage());
}
}
@Test
- public void testDuplicateNamesInDoc() {
+ void testDuplicateNamesInDoc() {
try {
ApplicationBuilder.createFromString(
"search duplicatenamesindoc {\n" +
- " document {\n" +
- " field foo type int {\n" +
- " indexing: attribute\n" +
- " }\n" +
- " field fOo type string {\n" +
- " indexing: index\n" +
- " }\n" +
- " }\n" +
- "}");
+ " document {\n" +
+ " field foo type int {\n" +
+ " indexing: attribute\n" +
+ " }\n" +
+ " field fOo type string {\n" +
+ " indexing: index\n" +
+ " }\n" +
+ " }\n" +
+ "}");
fail("Should throw exception.");
} catch (Exception e) {
assertTrue(e.getMessage().matches(".*Duplicate.*"));
diff --git a/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java b/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java
index 0c0684e23e3..8509c1972a8 100644
--- a/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java
@@ -2,12 +2,13 @@
package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* Tests settings outside the document
*
@@ -16,16 +17,16 @@ import static org.junit.Assert.assertTrue;
public class OutsideTestCase extends AbstractSchemaTestCase {
@Test
- public void testOutsideIndex() throws IOException, ParseException {
+ void testOutsideIndex() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/outsidedoc.sd");
- Index defaultIndex= schema.getIndex("default");
+ Index defaultIndex = schema.getIndex("default");
assertTrue(defaultIndex.isPrefix());
- assertEquals("default.default",defaultIndex.aliasIterator().next());
+ assertEquals("default.default", defaultIndex.aliasIterator().next());
}
@Test
- public void testOutsideSummary() throws IOException, ParseException {
+ void testOutsideSummary() throws IOException, ParseException {
ApplicationBuilder.buildFromFile("src/test/examples/outsidesummary.sd");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java b/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java
index dbea8fb8aeb..f59938e9a41 100644
--- a/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java
@@ -2,17 +2,12 @@
package com.yahoo.schema;
import com.yahoo.schema.document.ImmutableSDField;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import com.yahoo.document.DataType;
import com.yahoo.schema.parser.ParseException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Lester Solbakken
@@ -52,25 +47,21 @@ public class PredicateDataTypeTestCase {
return "upper-bound: " + bound + "\n";
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
- public void requireThatBuilderSetsIndexParametersCorrectly() throws ParseException {
+ void requireThatBuilderSetsIndexParametersCorrectly() throws ParseException {
int arity = 2;
long lowerBound = -100;
long upperBound = 100;
String sd = searchSd(
- predicateFieldSd(
- attributeFieldSd(
- arityParameter(arity) +
- lowerBoundParameter(lowerBound) +
- upperBoundParameter(upperBound))));
+ predicateFieldSd(
+ attributeFieldSd(
+ arityParameter(arity) +
+ lowerBoundParameter(lowerBound) +
+ upperBoundParameter(upperBound))));
ApplicationBuilder sb = ApplicationBuilder.createFromString(sd);
for (ImmutableSDField field : sb.getSchema().allConcreteFields()) {
- if (field.getDataType() == DataType.PREDICATE) {
+ if (field.getDataType() == DataType.PREDICATE) {
for (Index index : field.getIndices().values()) {
assertTrue(index.getBooleanIndexDefiniton().hasArity());
assertEquals(arity, index.getBooleanIndexDefiniton().getArity());
@@ -84,20 +75,20 @@ public class PredicateDataTypeTestCase {
}
@Test
- public void requireThatBuilderHandlesLongValues() throws ParseException {
+ void requireThatBuilderHandlesLongValues() throws ParseException {
int arity = 2;
long lowerBound = -100000000000000000L;
long upperBound = 1000000000000000000L;
String sd = searchSd(
- predicateFieldSd(
- attributeFieldSd(
- arityParameter(arity) +
- "lower-bound: -100000000000000000L\n" + // +'L'
- upperBoundParameter(upperBound))));
+ predicateFieldSd(
+ attributeFieldSd(
+ arityParameter(arity) +
+ "lower-bound: -100000000000000000L\n" + // +'L'
+ upperBoundParameter(upperBound))));
ApplicationBuilder sb = ApplicationBuilder.createFromString(sd);
for (ImmutableSDField field : sb.getSchema().allConcreteFields()) {
- if (field.getDataType() == DataType.PREDICATE) {
+ if (field.getDataType() == DataType.PREDICATE) {
for (Index index : field.getIndices().values()) {
assertEquals(arity, index.getBooleanIndexDefiniton().getArity());
assertEquals(lowerBound, index.getBooleanIndexDefiniton().getLowerBound());
@@ -108,11 +99,11 @@ public class PredicateDataTypeTestCase {
}
@Test
- public void requireThatBuilderHandlesMissingParameters() throws ParseException {
+ void requireThatBuilderHandlesMissingParameters() throws ParseException {
String sd = searchSd(
- predicateFieldSd(
- attributeFieldSd(
- arityParameter(2))));
+ predicateFieldSd(
+ attributeFieldSd(
+ arityParameter(2))));
ApplicationBuilder sb = ApplicationBuilder.createFromString(sd);
for (ImmutableSDField field : sb.getSchema().allConcreteFields()) {
if (field.getDataType() == DataType.PREDICATE) {
@@ -126,74 +117,74 @@ public class PredicateDataTypeTestCase {
}
@Test
- public void requireThatBuilderFailsIfNoArityValue() throws ParseException {
- String sd = searchSd(predicateFieldSd(attributeFieldSd("")));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Missing arity value in predicate field.");
- ApplicationBuilder.createFromString(sd);
- fail();
+ void requireThatBuilderFailsIfNoArityValue() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(predicateFieldSd(attributeFieldSd("")));
+ ApplicationBuilder.createFromString(sd);
+ fail();
+ });
+ assertTrue(exception.getMessage().contains("Missing arity value in predicate field."));
}
@Test
- public void requireThatBuilderFailsIfBothIndexAndAttribute() throws ParseException {
- String sd = searchSd(predicateFieldSd("indexing: summary | index | attribute\nindex { arity: 2 }"));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded.");
- ApplicationBuilder.createFromString(sd);
+ void requireThatBuilderFailsIfBothIndexAndAttribute() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(predicateFieldSd("indexing: summary | index | attribute\nindex { arity: 2 }"));
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded."));
}
@Test
- public void requireThatBuilderFailsIfIndex() throws ParseException {
- String sd = searchSd(predicateFieldSd("indexing: summary | index \nindex { arity: 2 }"));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded.");
- ApplicationBuilder.createFromString(sd);
+ void requireThatBuilderFailsIfIndex() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(predicateFieldSd("indexing: summary | index \nindex { arity: 2 }"));
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded."));
}
@Test
- public void requireThatBuilderFailsIfIllegalArityValue() throws ParseException {
- String sd = searchSd(predicateFieldSd(attributeFieldSd(arityParameter(0))));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid arity value in predicate field, must be greater than 1.");
- ApplicationBuilder.createFromString(sd);
+ void requireThatBuilderFailsIfIllegalArityValue() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(predicateFieldSd(attributeFieldSd(arityParameter(0))));
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("Invalid arity value in predicate field, must be greater than 1."));
}
@Test
- public void requireThatBuilderFailsIfArityParameterExistButNotPredicateField() throws ParseException {
- String sd = searchSd(stringFieldSd(attributeFieldSd(arityParameter(2))));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Arity parameter is used only for predicate type fields.");
- ApplicationBuilder.createFromString(sd);
+ void requireThatBuilderFailsIfArityParameterExistButNotPredicateField() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(stringFieldSd(attributeFieldSd(arityParameter(2))));
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("Arity parameter is used only for predicate type fields."));
}
@Test
- public void requireThatBuilderFailsIfBoundParametersExistButNotPredicateField() throws ParseException {
- String sd = searchSd(
- stringFieldSd(
+ void requireThatBuilderFailsIfBoundParametersExistButNotPredicateField() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(
+ stringFieldSd(
attributeFieldSd(
lowerBoundParameter(100) + upperBoundParameter(1000))));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Parameters lower-bound and upper-bound are used only for predicate type fields.");
- ApplicationBuilder.createFromString(sd);
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("Parameters lower-bound and upper-bound are used only for predicate type fields."));
}
@Test
- public void requireThatArrayOfPredicateFails() throws ParseException {
- String sd = searchSd(
- arrayPredicateFieldSd(
- attributeFieldSd(
- arityParameter(1))));
-
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Collections of predicates are not allowed.");
- ApplicationBuilder.createFromString(sd);
+ void requireThatArrayOfPredicateFails() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String sd = searchSd(
+ arrayPredicateFieldSd(
+ attributeFieldSd(
+ arityParameter(1))));
+ ApplicationBuilder.createFromString(sd);
+ });
+ assertTrue(exception.getMessage().contains("Collections of predicates are not allowed."));
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java b/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java
index de061defb87..b73f5412bba 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java
@@ -8,13 +8,11 @@ import com.yahoo.config.model.test.TestRoot;
import com.yahoo.searchlib.rankingexpression.ExpressionFunction;
import com.yahoo.searchlib.rankingexpression.RankingExpression;
import com.yahoo.vespa.config.search.RankProfilesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -24,7 +22,7 @@ public class RankProfileRegistryTest {
private static final String TESTDIR = "src/test/cfg/search/data/v2/inherited_rankprofiles";
@Test
- public void testRankProfileInheritance() {
+ void testRankProfileInheritance() {
TestRoot root = new TestDriver().buildModel(FilesApplicationPackage.fromFile(new File(TESTDIR)));
RankProfilesConfig left = root.getConfig(RankProfilesConfig.class, "inherit/search/cluster.inherit/left");
RankProfilesConfig right = root.getConfig(RankProfilesConfig.class, "inherit/search/cluster.inherit/right");
@@ -32,17 +30,19 @@ public class RankProfileRegistryTest {
assertEquals(2, right.rankprofile().size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testRankProfileDuplicateNameIsIllegal() {
- Schema schema = new Schema("foo", MockApplicationPackage.createEmpty());
- RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
- RankProfile barRankProfile = new RankProfile("bar", schema, rankProfileRegistry);
- rankProfileRegistry.add(barRankProfile);
- rankProfileRegistry.add(barRankProfile);
+ @Test
+ void testRankProfileDuplicateNameIsIllegal() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Schema schema = new Schema("foo", MockApplicationPackage.createEmpty());
+ RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
+ RankProfile barRankProfile = new RankProfile("bar", schema, rankProfileRegistry);
+ rankProfileRegistry.add(barRankProfile);
+ rankProfileRegistry.add(barRankProfile);
+ });
}
@Test
- public void testRankProfileDuplicateNameLegalForOverridableRankProfiles() {
+ void testRankProfileDuplicateNameLegalForOverridableRankProfiles() {
Schema schema = new Schema("foo", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
diff --git a/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java
index c66d44556ca..ddca13a2984 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java
@@ -24,17 +24,13 @@ import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests rank profiles
@@ -44,7 +40,7 @@ import static org.junit.Assert.fail;
public class RankProfileTestCase extends AbstractSchemaTestCase {
@Test
- public void testRankProfileInheritance() {
+ void testRankProfileInheritance() {
Schema schema = new Schema("test", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType document = new SDDocumentType("test");
@@ -68,7 +64,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatIllegalInheritanceIsChecked() throws ParseException {
+ void requireThatIllegalInheritanceIsChecked() throws ParseException {
try {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
@@ -85,7 +81,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatSelfInheritanceIsIllegal() throws ParseException {
+ void requireThatSelfInheritanceIsIllegal() throws ParseException {
try {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
@@ -102,7 +98,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatSelfInheritanceIsLegalWhenOverloading() throws ParseException {
+ void requireThatSelfInheritanceIsLegalWhenOverloading() throws ParseException {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
builder.addSchema(joinLines(
@@ -119,7 +115,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatSidewaysInheritanceIsImpossible() throws ParseException {
+ void requireThatSidewaysInheritanceIsImpossible() throws ParseException {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
builder.addSchema(joinLines(
@@ -172,7 +168,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatDefaultInheritingDefaultIsIgnored() throws ParseException {
+ void requireThatDefaultInheritingDefaultIsIgnored() throws ParseException {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
builder.addSchema(joinLines(
@@ -184,7 +180,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatCyclicInheritanceIsIllegal() throws ParseException {
+ void requireThatCyclicInheritanceIsIllegal() throws ParseException {
try {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
@@ -203,7 +199,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatRankProfilesCanInheritNotYetSeenProfiles() throws ParseException
+ void requireThatRankProfilesCanInheritNotYetSeenProfiles() throws ParseException
{
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
@@ -214,9 +210,9 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
" rank-profile not_yet_defined {}",
"}"));
builder.build(true);
- assertNotNull(registry.get("test","p1"));
- assertTrue(registry.get("test","p1").inherits("not_yet_defined"));
- assertNotNull(registry.get("test","not_yet_defined"));
+ assertNotNull(registry.get("test", "p1"));
+ assertTrue(registry.get("test", "p1").inherits("not_yet_defined"));
+ assertNotNull(registry.get("test", "not_yet_defined"));
}
private String createSD(Double termwiseLimit) {
@@ -239,7 +235,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testTermwiseLimitWithDeployOverride() throws ParseException {
+ void testTermwiseLimitWithDeployOverride() throws ParseException {
verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties(), createSD(null), null);
verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties(), createSD(0.78), 0.78);
verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties().setDefaultTermwiseLimit(0.09), createSD(null), 0.09);
@@ -279,7 +275,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatConfigIsDerivedForAttributeTypeSettings() throws ParseException {
+ void requireThatConfigIsDerivedForAttributeTypeSettings() throws ParseException {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry);
builder.addSchema(joinLines(
@@ -303,7 +299,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatDenseDimensionsMustBeBound() throws ParseException {
+ void requireThatDenseDimensionsMustBeBound() throws ParseException {
try {
ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry());
builder.addSchema(joinLines(
@@ -316,7 +312,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Illegal type in field a type tensor(x[]): Dense tensor dimensions must have a size",
- e.getMessage());
+ e.getMessage());
}
}
@@ -332,7 +328,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatConfigIsDerivedForQueryFeatureTypeSettings() throws ParseException {
+ void requireThatConfigIsDerivedForQueryFeatureTypeSettings() throws ParseException {
RankProfileRegistry registry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes());
builder.addSchema(joinLines(
@@ -386,7 +382,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase {
}
@Test
- public void approximate_nearest_neighbor_threshold_settings_are_configurable() throws ParseException {
+ void approximate_nearest_neighbor_threshold_settings_are_configurable() throws ParseException {
verifyApproximateNearestNeighborThresholdSettings(0.7, null);
verifyApproximateNearestNeighborThresholdSettings(null, 0.3);
verifyApproximateNearestNeighborThresholdSettings(0.7, 0.3);
diff --git a/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java
index c3595717220..06fa63707c0 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.parser.ParseException;
import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class RankPropertiesTestCase extends AbstractSchemaTestCase {
@Test
- public void testRankPropertyInheritance() throws ParseException {
+ void testRankPropertyInheritance() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(joinLines(
@@ -69,16 +69,17 @@ public class RankPropertiesTestCase extends AbstractSchemaTestCase {
// Check derived model
RawRankProfile rawChild = new RawRankProfile(rankProfileRegistry.get(schema, "child"),
- new LargeRankExpressions(new MockFileRegistry()),
- new QueryProfileRegistry(),
- new ImportedMlModels(),
- attributeFields,
- new TestProperties());
+ new LargeRankExpressions(new MockFileRegistry()),
+ new QueryProfileRegistry(),
+ new ImportedMlModels(),
+ attributeFields,
+ new TestProperties());
assertEquals("(query(a), 2000)", rawChild.configProperties().get(0).toString());
}
}
+
@Test
- public void testRankProfileMutate() throws ParseException {
+ void testRankProfileMutate() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(joinLines(
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java b/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java
index 883e6b50abb..c963f086ac4 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java
@@ -2,28 +2,20 @@
package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
*/
public class RankingConstantTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
- public void tensor_constant_properties_are_set() throws Exception {
+ void tensor_constant_properties_are_set() throws Exception {
final String TENSOR_NAME = "my_global_tensor";
final String TENSOR_FILE = "path/my-tensor-file.json";
final String TENSOR_TYPE = "tensor(x{})";
@@ -57,39 +49,41 @@ public class RankingConstantTest {
}
@Test
- public void tensor_constant_must_have_a_type() throws Exception {
- RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
- ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("must have a type");
- schemaBuilder.addSchema(joinLines(
- "schema test {",
- " document test { }",
- " constant foo {",
- " file: bar.baz",
- " }",
- "}"
- ));
+ void tensor_constant_must_have_a_type() throws Exception {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
+ ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
+ schemaBuilder.addSchema(joinLines(
+ "schema test {",
+ " document test { }",
+ " constant foo {",
+ " file: bar.baz",
+ " }",
+ "}"
+ ));
+ });
+ assertTrue(exception.getMessage().contains("must have a type"));
}
@Test
- public void tensor_constant_must_have_a_file() throws Exception {
- RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
- ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("must have a file");
- schemaBuilder.addSchema(joinLines(
- "schema test {",
- " document test { }",
- " constant foo {",
- " type: tensor(x[])",
- " }",
- "}"
- ));
+ void tensor_constant_must_have_a_file() throws Exception {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
+ ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
+ schemaBuilder.addSchema(joinLines(
+ "schema test {",
+ " document test { }",
+ " constant foo {",
+ " type: tensor(x[])",
+ " }",
+ "}"
+ ));
+ });
+ assertTrue(exception.getMessage().contains("must have a file"));
}
@Test
- public void constant_file_does_not_need_path_or_ending() throws Exception {
+ void constant_file_does_not_need_path_or_ending() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
schemaBuilder.addSchema(joinLines(
@@ -108,7 +102,7 @@ public class RankingConstantTest {
}
@Test
- public void constant_uri_is_allowed() throws Exception {
+ void constant_uri_is_allowed() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
schemaBuilder.addSchema(joinLines(
@@ -128,7 +122,7 @@ public class RankingConstantTest {
}
@Test
- public void constant_https_uri_is_allowed() throws Exception {
+ void constant_https_uri_is_allowed() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
schemaBuilder.addSchema(joinLines(
@@ -148,7 +142,7 @@ public class RankingConstantTest {
}
@Test
- public void constant_uri_with_port_is_allowed() throws Exception {
+ void constant_uri_with_port_is_allowed() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
schemaBuilder.addSchema(joinLines(
@@ -168,7 +162,7 @@ public class RankingConstantTest {
}
@Test
- public void constant_uri_no_dual_slashes_is_allowed() throws Exception {
+ void constant_uri_no_dual_slashes_is_allowed() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
schemaBuilder.addSchema(joinLines(
@@ -188,7 +182,7 @@ public class RankingConstantTest {
}
@Test
- public void constant_uri_only_supports_http_and_https() {
+ void constant_uri_only_supports_http_and_https() {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry);
String expectedMessage = "Encountered \" <IDENTIFIER> \"ftp\"\" at line 5, column 10.\n\n" +
@@ -205,7 +199,7 @@ public class RankingConstantTest {
"}"
));
} catch (ParseException e) {
- if (! e.getMessage().startsWith(expectedMessage))
+ if (!e.getMessage().startsWith(expectedMessage))
fail("Expected exception with message starting with:\n'" + expectedMessage + "\nBut got:\n'" + e.getMessage());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java
index bd0bd65295c..c915a85a4cf 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java
@@ -10,11 +10,12 @@ import com.yahoo.yolean.Exceptions;
import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -22,7 +23,7 @@ import static org.junit.Assert.*;
public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
@Test
- public void testConstants() throws ParseException {
+ void testConstants() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
QueryProfileRegistry queryProfileRegistry = new QueryProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
@@ -89,7 +90,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testNameCollision() throws ParseException {
+ void testNameCollision() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -118,12 +119,12 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Rank profile 'test' is invalid: Cannot have both a constant and function named 'c'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testNegativeLiteralArgument() throws ParseException {
+ void testNegativeLiteralArgument() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -148,7 +149,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testNegativeConstantArgument() throws ParseException {
+ void testNegativeConstantArgument() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -174,11 +175,11 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
RankProfile profile = rankProfileRegistry.get(s, "test");
assertEquals("safeLog(popShareSlowDecaySignal,myValue)", profile.getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString());
assertEquals("safeLog(popShareSlowDecaySignal,-9.21034037)",
- profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString());
+ profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString());
}
@Test
- public void testConstantDivisorInFunction() throws ParseException {
+ void testConstantDivisorInFunction() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -197,11 +198,11 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
Schema s = builder.getSchema();
RankProfile profile = rankProfileRegistry.get(s, "test");
assertEquals("k1 + (k2 + k3) / 1.0E8",
- profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString());
+ profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString());
}
@Test
- public void test3() throws ParseException {
+ void test3() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -223,7 +224,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase {
Schema s = builder.getSchema();
RankProfile profile = rankProfileRegistry.get(s, "test");
assertEquals("0.5 + 50 * (attribute(rating_yelp) - 3)",
- profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString());
+ profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java
index 79c803e007c..789c4ac5577 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java
@@ -11,15 +11,13 @@ import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.parser.ParseException;
import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Optional;
import java.util.logging.Level;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -27,11 +25,11 @@ import static org.junit.Assert.fail;
public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase {
@Test
- public void testFunctionInliningPreserveArithmeticOrdering() throws ParseException {
+ void testFunctionInliningPreserveArithmeticOrdering() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
- "search test {\n" +
+ "search test {\n" +
" document test { \n" +
" field a type double { \n" +
" indexing: attribute \n" +
@@ -71,14 +69,14 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase {
RankProfile parent = rankProfileRegistry.get(s, "parent").compile(new QueryProfileRegistry(), new ImportedMlModels());
assertEquals("7.0 * (3 + attribute(a) + attribute(b) * (attribute(a) * 3 + if (7.0 < attribute(a), 1, 2) == 0))",
- parent.getFirstPhaseRanking().getRoot().toString());
+ parent.getFirstPhaseRanking().getRoot().toString());
RankProfile child = rankProfileRegistry.get(s, "child").compile(new QueryProfileRegistry(), new ImportedMlModels());
assertEquals("7.0 * (9 + attribute(a))",
- child.getFirstPhaseRanking().getRoot().toString());
+ child.getFirstPhaseRanking().getRoot().toString());
}
@Test
- public void testConstants() throws ParseException {
+ void testConstants() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -149,7 +147,7 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testNonTopLevelInlining() throws ParseException {
+ void testNonTopLevelInlining() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -192,31 +190,31 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testFunctionRedefinitionIsIllegal() throws ParseException {
+ void testFunctionRedefinitionIsIllegal() throws ParseException {
try {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
MockDeployLogger deployLogger = new MockDeployLogger();
ApplicationBuilder builder = new ApplicationBuilder(MockApplicationPackage.createEmpty(),
- new MockFileRegistry(),
- deployLogger,
- new TestProperties(),
- rankProfileRegistry,
- new QueryProfileRegistry());
+ new MockFileRegistry(),
+ deployLogger,
+ new TestProperties(),
+ rankProfileRegistry,
+ new QueryProfileRegistry());
builder.addSchema(
"search test {\n" +
- " document test { }\n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo\n" +
- " }\n" +
- " function foo(x) {\n" +
- " expression: x + x\n" +
- " }\n" +
- " function inline foo() {\n" +
- " expression: foo(2)\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test { }\n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo\n" +
+ " }\n" +
+ " function foo(x) {\n" +
+ " expression: x + x\n" +
+ " }\n" +
+ " function inline foo() {\n" +
+ " expression: foo(2)\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
builder.build(true);
fail("Expected failure");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java
index dd69fb6c591..302fda9d3d7 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -14,232 +14,232 @@ import static org.junit.Assert.fail;
public class RankingExpressionLoopDetectionTestCase {
@Test
- public void testSelfLoop() throws ParseException {
+ void testSelfLoop() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " field a type string { \n" +
- " indexing: index \n" +
- " }\n" +
- " }\n" +
- " \n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo\n" +
- " }\n" +
- " function foo() {\n" +
- " expression: foo\n" +
- " }\n" +
- " }\n" +
- "\n" +
- "}\n");
+ " document test { \n" +
+ " field a type string { \n" +
+ " indexing: index \n" +
+ " }\n" +
+ " }\n" +
+ " \n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo\n" +
+ " }\n" +
+ " function foo() {\n" +
+ " expression: foo\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ "}\n");
try {
builder.build(true);
fail("Excepted exception");
}
catch (IllegalArgumentException e) {
assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: foo is invalid: Invocation loop: foo -> foo",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testNestedLoop() throws ParseException {
+ void testNestedLoop() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " field a type string { \n" +
- " indexing: index \n" +
- " }\n" +
- " }\n" +
- " \n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo\n" +
- " }\n" +
- " function foo() {\n" +
- " expression: arg(5)\n" +
- " }\n" +
- " function arg(a1) {\n" +
- " expression: foo + a1*2\n" +
- " }\n" +
- " }\n" +
- "\n" +
- "}\n");
+ " document test { \n" +
+ " field a type string { \n" +
+ " indexing: index \n" +
+ " }\n" +
+ " }\n" +
+ " \n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo\n" +
+ " }\n" +
+ " function foo() {\n" +
+ " expression: arg(5)\n" +
+ " }\n" +
+ " function arg(a1) {\n" +
+ " expression: foo + a1*2\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ "}\n");
try {
builder.build(true);
fail("Excepted exception");
}
catch (IllegalArgumentException e) {
assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: arg(5) is invalid: foo is invalid: arg(5) is invalid: Invocation loop: arg(5) -> foo -> arg(5)",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testSelfArgumentLoop() throws ParseException {
+ void testSelfArgumentLoop() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " field a type string { \n" +
- " indexing: index \n" +
- " }\n" +
- " }\n" +
- " \n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo\n" +
- " }\n" +
- " function foo() {\n" +
- " expression: arg(foo)\n" +
- " }\n" +
- " function arg(a1) {\n" +
- " expression: a1*2\n" +
- " }\n" +
- " }\n" +
- "\n" +
- "}\n");
+ " document test { \n" +
+ " field a type string { \n" +
+ " indexing: index \n" +
+ " }\n" +
+ " }\n" +
+ " \n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo\n" +
+ " }\n" +
+ " function foo() {\n" +
+ " expression: arg(foo)\n" +
+ " }\n" +
+ " function arg(a1) {\n" +
+ " expression: a1*2\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ "}\n");
try {
builder.build(true);
fail("Excepted exception");
}
catch (IllegalArgumentException e) {
assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: arg(foo) is invalid: a1 is invalid: foo is invalid: arg(foo) is invalid: Invocation loop: arg(foo) -> foo -> arg(foo)",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testNoLoopWithSameLocalArgument() throws ParseException {
+ void testNoLoopWithSameLocalArgument() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " field a type string { \n" +
- " indexing: index \n" +
- " }\n" +
- " }\n" +
- " \n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo(3)\n" +
- " }\n" +
- " function foo(a1) {\n" +
- " expression: bar(3)\n" +
- " }\n" +
- " function bar(a1) {\n" +
- " expression: a1*2\n" +
- " }\n" +
- " }\n" +
- "\n" +
- "}\n");
+ " document test { \n" +
+ " field a type string { \n" +
+ " indexing: index \n" +
+ " }\n" +
+ " }\n" +
+ " \n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo(3)\n" +
+ " }\n" +
+ " function foo(a1) {\n" +
+ " expression: bar(3)\n" +
+ " }\n" +
+ " function bar(a1) {\n" +
+ " expression: a1*2\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ "}\n");
builder.build(true);
}
@Test
- public void testNoLoopWithMultipleInvocations() throws ParseException {
+ void testNoLoopWithMultipleInvocations() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " field a type string { \n" +
- " indexing: index \n" +
- " }\n" +
- " }\n" +
- " \n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo(3)\n" +
- " }\n" +
- " function foo(a1) {\n" +
- " expression: bar(3) + bar(a1)\n" +
- " }\n" +
- " function bar(a1) {\n" +
- " expression: a1*2\n" +
- " }\n" +
- " }\n" +
- "\n" +
- "}\n");
+ " document test { \n" +
+ " field a type string { \n" +
+ " indexing: index \n" +
+ " }\n" +
+ " }\n" +
+ " \n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo(3)\n" +
+ " }\n" +
+ " function foo(a1) {\n" +
+ " expression: bar(3) + bar(a1)\n" +
+ " }\n" +
+ " function bar(a1) {\n" +
+ " expression: a1*2\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ "}\n");
builder.build(true);
}
@Test
- public void testNoLoopWithBoundIdentifiers() throws ParseException {
+ void testNoLoopWithBoundIdentifiers() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " }\n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo(bar(2))\n" +
- " }\n" +
- " function foo(x) {\n" +
- " expression: x * x\n" +
- " }\n" +
- " function bar(x) {\n" +
- " expression: x + x\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test { \n" +
+ " }\n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo(bar(2))\n" +
+ " }\n" +
+ " function foo(x) {\n" +
+ " expression: x * x\n" +
+ " }\n" +
+ " function bar(x) {\n" +
+ " expression: x + x\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
builder.build(true);
}
@Test
- public void testNoLoopWithTheSameNestedIdentifierWhichIsUnbound() throws ParseException {
+ void testNoLoopWithTheSameNestedIdentifierWhichIsUnbound() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " }\n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo()\n" +
- " }\n" +
- " function foo() {\n" +
- " expression: bar(x)\n" +
- " }\n" +
- " function bar(x) {\n" +
- " expression: x + x\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test { \n" +
+ " }\n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo()\n" +
+ " }\n" +
+ " function foo() {\n" +
+ " expression: bar(x)\n" +
+ " }\n" +
+ " function bar(x) {\n" +
+ " expression: x + x\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
builder.build(true);
}
@Test
- public void testNoLoopWithTheSameAlternatingNestedIdentifierWhichIsUnbound() throws ParseException {
+ void testNoLoopWithTheSameAlternatingNestedIdentifierWhichIsUnbound() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
"search test {\n" +
- " document test { \n" +
- " }\n" +
- " rank-profile test {\n" +
- " first-phase {\n" +
- " expression: foo()\n" +
- " }\n" +
- " function foo() {\n" +
- " expression: bar(x)\n" +
- " }\n" +
- " function bar(y) {\n" +
- " expression: baz(y)\n" +
- " }\n" +
- " function baz(x) {\n" +
- " expression: x + x\n" +
- " }\n" +
- " }\n" +
- "}\n");
+ " document test { \n" +
+ " }\n" +
+ " rank-profile test {\n" +
+ " first-phase {\n" +
+ " expression: foo()\n" +
+ " }\n" +
+ " function foo() {\n" +
+ " expression: bar(x)\n" +
+ " }\n" +
+ " function bar(y) {\n" +
+ " expression: baz(y)\n" +
+ " }\n" +
+ " function baz(x) {\n" +
+ " expression: x + x\n" +
+ " }\n" +
+ " }\n" +
+ "}\n");
builder.build(true);
}
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java
index 250879b1570..33bbdb2fd6f 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java
@@ -12,11 +12,11 @@ import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.parser.ParseException;
import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author lesters
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase {
@Test
- public void testBasicFunctionShadowing() throws ParseException {
+ void testBasicFunctionShadowing() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -52,14 +52,14 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase {
assertEquals("(rankingExpression(sin@).rankingScript, 2 * 2)",
censorBindingHash(testRankProperties.get(0).toString()));
assertEquals("(rankingExpression(sin).rankingScript, x * x)",
- testRankProperties.get(1).toString());
+ testRankProperties.get(1).toString());
assertEquals("(vespa.rank.firstphase, rankingExpression(sin@))",
- censorBindingHash(testRankProperties.get(2).toString()));
+ censorBindingHash(testRankProperties.get(2).toString()));
}
@Test
- public void testMultiLevelFunctionShadowing() throws ParseException {
+ void testMultiLevelFunctionShadowing() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -97,21 +97,21 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase {
assertEquals("(rankingExpression(sin@).rankingScript, rankingExpression(cos@))",
censorBindingHash(testRankProperties.get(2).toString()));
assertEquals("(rankingExpression(tan).rankingScript, x * x)",
- testRankProperties.get(3).toString());
+ testRankProperties.get(3).toString());
assertEquals("(rankingExpression(tan@).rankingScript, x * x)",
- censorBindingHash(testRankProperties.get(4).toString()));
+ censorBindingHash(testRankProperties.get(4).toString()));
assertEquals("(rankingExpression(cos).rankingScript, rankingExpression(tan@))",
- censorBindingHash(testRankProperties.get(5).toString()));
+ censorBindingHash(testRankProperties.get(5).toString()));
assertEquals("(rankingExpression(cos@).rankingScript, rankingExpression(tan@))",
censorBindingHash(testRankProperties.get(6).toString()));
assertEquals("(rankingExpression(sin).rankingScript, rankingExpression(cos@))",
- censorBindingHash(testRankProperties.get(7).toString()));
+ censorBindingHash(testRankProperties.get(7).toString()));
assertEquals("(vespa.rank.firstphase, rankingExpression(sin@))",
- censorBindingHash(testRankProperties.get(8).toString()));
+ censorBindingHash(testRankProperties.get(8).toString()));
}
@Test
- public void testFunctionShadowingArguments() throws ParseException {
+ void testFunctionShadowingArguments() throws ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(
@@ -141,15 +141,15 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase {
assertEquals("(rankingExpression(sin@).rankingScript, cos(5.0) * cos(5.0))",
censorBindingHash(testRankProperties.get(1).toString()));
assertEquals("(rankingExpression(sin).rankingScript, x * x)",
- testRankProperties.get(2).toString());
+ testRankProperties.get(2).toString());
assertEquals("(vespa.rank.firstphase, rankingExpression(firstphase))",
- censorBindingHash(testRankProperties.get(3).toString()));
+ censorBindingHash(testRankProperties.get(3).toString()));
assertEquals("(rankingExpression(firstphase).rankingScript, cos(rankingExpression(sin@)) + rankingExpression(sin@))",
- censorBindingHash(testRankProperties.get(4).toString()));
+ censorBindingHash(testRankProperties.get(4).toString()));
}
@Test
- public void testNeuralNetworkSetup() throws ParseException {
+ void testNeuralNetworkSetup() throws ParseException {
// Note: the type assigned to query profile and constant tensors here is not the correct type
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
QueryProfileRegistry queryProfiles = queryProfileWith("query(q)", "tensor(input[1])");
diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java
index e42acee9bed..099b44bd6dd 100644
--- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java
@@ -4,17 +4,18 @@ package com.yahoo.schema;
import com.yahoo.schema.derived.DerivedConfiguration;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
/**
* @author bratseth
*/
public class RankingExpressionValidationTestCase extends AbstractSchemaTestCase {
@Test
- public void testInvalidExpressionProducesException() throws ParseException {
+ void testInvalidExpressionProducesException() throws ParseException {
assertFailsExpression("&/%(/%&");
assertFailsExpression("if(a==b,b)");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java
index df9d4a63650..10cb4e60e0b 100644
--- a/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertNotNull;
public class ReservedWordsAsFieldNamesTestCase extends AbstractSchemaTestCase {
@Test
- public void testIt() throws IOException, ParseException {
+ void testIt() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/reserved_words_as_field_names.sd");
assertNotNull(schema.getDocument().getField("inline"));
assertNotNull(schema.getDocument().getField("constants"));
diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java
index 929c407215a..8245119ffd7 100644
--- a/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java
@@ -13,17 +13,12 @@ import com.yahoo.schema.parser.ParseException;
import com.yahoo.schema.processing.MakeAliases;
import com.yahoo.vespa.documentmodel.SummaryTransform;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests importing of search definitions
@@ -34,7 +29,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testSimpleImporting() throws IOException, ParseException {
+ void testSimpleImporting() throws IOException, ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder sb = new ApplicationBuilder(rankProfileRegistry, new QueryProfileRegistry());
sb.addSchemaFile("src/test/examples/simple.sd");
@@ -62,7 +57,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
assertEquals("aliaz", titleAliases.next());
assertEquals("analias.totitle", titleAliases.next());
assertEquals("analias.todefault",
- schema.getIndex("default").aliasIterator().next());
+ schema.getIndex("default").aliasIterator().next());
assertEquals(RankType.IDENTITY, field.getRankType());
assertEquals(0, field.getAttributes().size());
assertNull(field.getStemming());
@@ -72,9 +67,9 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
field = (SDField) document.getField("description");
assertEquals(RankType.ABOUT, field.getRankType());
assertEquals(SummaryTransform.NONE,
- field.getSummaryField("description").getTransform());
+ field.getSummaryField("description").getTransform());
assertEquals(SummaryTransform.DYNAMICTEASER,
- field.getSummaryField("dyndesc").getTransform());
+ field.getSummaryField("dyndesc").getTransform());
assertNull(field.getStemming());
assertTrue(field.getNormalizing().doRemoveAccents());
assertEquals("hallo", schema.getIndex("description").aliasIterator().next());
@@ -94,7 +89,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
// Fifth field
field = (SDField) document.getField("popularity");
assertEquals("{ input popularity | attribute popularity; }",
- field.getIndexingScript().toString());
+ field.getIndexingScript().toString());
// Sixth field
field = (SDField) document.getField("measurement");
@@ -105,17 +100,17 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
// Seventh field
field = schema.getConcreteField("categories");
assertEquals("{ input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }",
- field.getIndexingScript().toString());
+ field.getIndexingScript().toString());
// Eight field
- field= schema.getConcreteField("categoriesagain");
+ field = schema.getConcreteField("categoriesagain");
assertEquals("{ input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }",
- field.getIndexingScript().toString());
+ field.getIndexingScript().toString());
// Ninth field
- field= schema.getConcreteField("exactemento");
+ field = schema.getConcreteField("exactemento");
assertEquals("{ input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }",
- field.getIndexingScript().toString());
+ field.getIndexingScript().toString());
// Tenth field
field = schema.getConcreteField("category_arr");
@@ -140,12 +135,12 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
assertTrue(profile.inheritedNames().isEmpty());
assertNull(profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE));
assertEquals(RankType.EMPTY,
- profile.getRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue());
+ profile.getRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue());
profile = rankProfileRegistry.get(schema, "experimental");
assertNotNull(profile);
assertEquals("default", profile.inheritedNames().get(0));
assertEquals(RankType.IDENTITY,
- profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue());
+ profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue());
profile = rankProfileRegistry.get(schema, "other");
assertNotNull(profile);
@@ -153,17 +148,17 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
// The extra-document field
SDField exact = schema.getConcreteField("exact");
- assertNotNull("Extra field was parsed", exact);
+ assertNotNull(exact, "Extra field was parsed");
assertEquals("exact", exact.getName());
assertEquals(Stemming.NONE, exact.getStemming());
assertFalse(exact.getNormalizing().doRemoveAccents());
assertEquals("{ input title . \" \" . input category | tokenize | summary exact | index exact; }",
- exact.getIndexingScript().toString());
+ exact.getIndexingScript().toString());
assertEquals(RankType.IDENTITY, exact.getRankType());
}
@Test
- public void testDocumentImporting() throws IOException, ParseException {
+ void testDocumentImporting() throws IOException, ParseException {
try {
// Having two documents in one sd-file is illegal.
ApplicationBuilder.buildFromFile("src/test/examples/documents.sd");
@@ -173,9 +168,9 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testIdImporting() throws IOException, ParseException {
+ void testIdImporting() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/strange.sd");
- SDField idecidemyide = (SDField)schema.getDocument().getField("idecidemyide");
+ SDField idecidemyide = (SDField) schema.getDocument().getField("idecidemyide");
assertEquals(5, idecidemyide.getId());
SDField sodoi = (SDField) schema.getDocument().getField("sodoi");
assertEquals(7, sodoi.getId());
diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java
index 8fe691db802..c8657df23ce 100644
--- a/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java
@@ -5,9 +5,10 @@ import java.io.IOException;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests that search definitions are parsed correctly and that correct line number is reported in
@@ -18,23 +19,23 @@ import static org.junit.Assert.*;
public class SchemaParsingTestCase extends AbstractSchemaTestCase {
@Test
- public void requireThatIndexingExpressionsCanBeParsed() throws Exception {
+ void requireThatIndexingExpressionsCanBeParsed() throws Exception {
assertNotNull(ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"));
}
@Test
- public void requireThatParseExceptionPositionIsCorrect() throws Exception {
+ void requireThatParseExceptionPositionIsCorrect() throws Exception {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_construct.sd");
} catch (ParseException e) {
- if ( ! e.getMessage().contains("at line 5, column 36.")) {
+ if (!e.getMessage().contains("at line 5, column 36.")) {
throw e;
}
}
}
@Test
- public void requireThatParserHandlesLexicalError() throws Exception {
+ void requireThatParserHandlesLexicalError() throws Exception {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_lexical_error.sd");
} catch (ParseException e) {
@@ -45,7 +46,7 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireErrorWhenJunkAfterSearchBlock() throws IOException, ParseException {
+ void requireErrorWhenJunkAfterSearchBlock() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_junk_at_end.sd");
fail("Illegal junk at end of SD passed");
@@ -57,7 +58,7 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireErrorWhenMissingClosingSearchBracket() throws IOException, ParseException {
+ void requireErrorWhenMissingClosingSearchBracket() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_no_closing_bracket.sd");
fail("SD without closing bracket passed");
@@ -69,12 +70,12 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase {
}
@Test
- public void illegalSearchDefinitionName() throws IOException, ParseException {
+ void illegalSearchDefinitionName() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid-name.sd");
fail("Name with dash passed");
} catch (ParseException e) {
- if ( ! e.getMessage().contains("invalid-name")) {
+ if (!e.getMessage().contains("invalid-name")) {
throw e;
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java
index 67d8ce4ff78..54e47dea6bb 100644
--- a/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java
@@ -7,13 +7,10 @@ import com.yahoo.schema.processing.ImportedFieldsResolver;
import com.yahoo.schema.processing.OnnxModelTypeResolver;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Schema tests that don't depend on files.
@@ -23,17 +20,17 @@ import static org.junit.Assert.fail;
public class SchemaTestCase {
@Test
- public void testValidationOfInheritedSchema() throws ParseException {
+ void testValidationOfInheritedSchema() throws ParseException {
try {
String schema = joinLines(
"schema test inherits nonesuch {" +
- " document test inherits nonesuch {" +
- " }" +
- "}");
+ " document test inherits nonesuch {" +
+ " }" +
+ "}");
DeployLoggerStub logger = new DeployLoggerStub();
ApplicationBuilder.createFromStrings(logger, schema);
assertEquals("schema 'test' inherits 'nonesuch', but this schema does not exist",
- logger.entries.get(0).message);
+ logger.entries.get(0).message);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
@@ -42,129 +39,129 @@ public class SchemaTestCase {
}
@Test
- public void testValidationOfSchemaAndDocumentInheritanceConsistency() throws ParseException {
+ void testValidationOfSchemaAndDocumentInheritanceConsistency() throws ParseException {
try {
String parent = joinLines(
"schema parent {" +
- " document parent {" +
- " field pf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- "}");
+ " document parent {" +
+ " field pf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ "}");
String child = joinLines(
"schema child inherits parent {" +
- " document child {" +
- " field cf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- "}");
+ " document child {" +
+ " field cf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ "}");
ApplicationBuilder.createFromStrings(new DeployLoggerStub(), parent, child);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("schema 'child' inherits 'parent', " +
- "but its document type does not inherit the parent's document type"
- , e.getMessage());
+ "but its document type does not inherit the parent's document type"
+ , e.getMessage());
}
}
@Test
- public void testSchemaInheritance() throws ParseException {
+ void testSchemaInheritance() throws ParseException {
String parentLines = joinLines(
"schema parent {" +
- " document parent {" +
- " field pf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " fieldset parent_set {" +
- " fields: pf1" +
- " }" +
- " stemming: none" +
- " index parent_index {" +
- " stemming: best" +
- " }" +
- " field parent_field type string {" +
- " indexing: input pf1 | lowercase | index | attribute | summary" +
- " }" +
- " rank-profile parent_profile {" +
- " }" +
- " constant parent_constant {" +
- " file: constants/my_constant_tensor_file.json" +
- " type: tensor<float>(x{},y{})" +
- " }" +
- " onnx-model parent_model {" +
- " file: models/my_model.onnx" +
- " }" +
- " document-summary parent_summary {" +
- " summary pf1 type string {}" +
- " }" +
- " import field parentschema_ref.name as parent_imported {}" +
- " raw-as-base64-in-summary" +
- "}");
+ " document parent {" +
+ " field pf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " fieldset parent_set {" +
+ " fields: pf1" +
+ " }" +
+ " stemming: none" +
+ " index parent_index {" +
+ " stemming: best" +
+ " }" +
+ " field parent_field type string {" +
+ " indexing: input pf1 | lowercase | index | attribute | summary" +
+ " }" +
+ " rank-profile parent_profile {" +
+ " }" +
+ " constant parent_constant {" +
+ " file: constants/my_constant_tensor_file.json" +
+ " type: tensor<float>(x{},y{})" +
+ " }" +
+ " onnx-model parent_model {" +
+ " file: models/my_model.onnx" +
+ " }" +
+ " document-summary parent_summary {" +
+ " summary pf1 type string {}" +
+ " }" +
+ " import field parentschema_ref.name as parent_imported {}" +
+ " raw-as-base64-in-summary" +
+ "}");
String child1Lines = joinLines(
"schema child1 inherits parent {" +
- " document child1 inherits parent {" +
- " field c1f1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " fieldset child1_set {" +
- " fields: c1f1, pf1" +
- " }" +
- " stemming: shortest" +
- " index child1_index {" +
- " stemming: shortest" +
- " }" +
- " field child1_field type string {" +
- " indexing: input pf1 | lowercase | index | attribute | summary" +
- " }" +
- " rank-profile child1_profile inherits parent_profile {" +
- " constants {" +
- " child1_constant tensor<float>(x{},y{}): file:constants/my_constant_tensor_file.json" +
- " }" +
- " }" +
- " onnx-model child1_model {" +
- " file: models/my_model.onnx" +
- " }" +
- " document-summary child1_summary inherits parent_summary {" +
- " summary c1f1 type string {}" +
- " }" +
- " import field parentschema_ref.name as child1_imported {}" +
- "}");
+ " document child1 inherits parent {" +
+ " field c1f1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " fieldset child1_set {" +
+ " fields: c1f1, pf1" +
+ " }" +
+ " stemming: shortest" +
+ " index child1_index {" +
+ " stemming: shortest" +
+ " }" +
+ " field child1_field type string {" +
+ " indexing: input pf1 | lowercase | index | attribute | summary" +
+ " }" +
+ " rank-profile child1_profile inherits parent_profile {" +
+ " constants {" +
+ " child1_constant tensor<float>(x{},y{}): file:constants/my_constant_tensor_file.json" +
+ " }" +
+ " }" +
+ " onnx-model child1_model {" +
+ " file: models/my_model.onnx" +
+ " }" +
+ " document-summary child1_summary inherits parent_summary {" +
+ " summary c1f1 type string {}" +
+ " }" +
+ " import field parentschema_ref.name as child1_imported {}" +
+ "}");
String child2Lines = joinLines(
"schema child2 inherits parent {" +
- " document child2 inherits parent {" +
- " field c2f1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " fieldset child2_set {" +
- " fields: c2f1, pf1" +
- " }" +
- " stemming: shortest" +
- " index child2_index {" +
- " stemming: shortest" +
- " }" +
- " field child2_field type string {" +
- " indexing: input pf1 | lowercase | index | attribute | summary" +
- " }" +
- " rank-profile child2_profile inherits parent_profile {" +
- " }" +
- " constant child2_constant {" +
- " file: constants/my_constant_tensor_file.json" +
- " type: tensor<float>(x{},y{})" +
- " }" +
- " onnx-model child2_model {" +
- " file: models/my_model.onnx" +
- " }" +
- " document-summary child2_summary inherits parent_summary {" +
- " summary c2f1 type string {}" +
- " }" +
- " import field parentschema_ref.name as child2_imported {}" +
- "}");
+ " document child2 inherits parent {" +
+ " field c2f1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " fieldset child2_set {" +
+ " fields: c2f1, pf1" +
+ " }" +
+ " stemming: shortest" +
+ " index child2_index {" +
+ " stemming: shortest" +
+ " }" +
+ " field child2_field type string {" +
+ " indexing: input pf1 | lowercase | index | attribute | summary" +
+ " }" +
+ " rank-profile child2_profile inherits parent_profile {" +
+ " }" +
+ " constant child2_constant {" +
+ " file: constants/my_constant_tensor_file.json" +
+ " type: tensor<float>(x{},y{})" +
+ " }" +
+ " onnx-model child2_model {" +
+ " file: models/my_model.onnx" +
+ " }" +
+ " document-summary child2_summary inherits parent_summary {" +
+ " summary c2f1 type string {}" +
+ " }" +
+ " import field parentschema_ref.name as child2_imported {}" +
+ "}");
ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub());
builder.processorsToSkip().add(OnnxModelTypeResolver.class); // Avoid discovering the Onnx model referenced does not exist
@@ -259,55 +256,55 @@ public class SchemaTestCase {
}
@Test
- public void testSchemaInheritanceEmptyChildren() throws ParseException {
+ void testSchemaInheritanceEmptyChildren() throws ParseException {
String parentLines = joinLines(
"schema parent {" +
- " document parent {" +
- " field pf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " fieldset parent_set {" +
- " fields: pf1" +
- " }" +
- " stemming: none" +
- " index parent_index {" +
- " stemming: best" +
- " }" +
- " field parent_field type string {" +
- " indexing: input pf1 | lowercase | index | attribute | summary" +
- " }" +
- " rank-profile parent_profile {" +
- " }" +
- " constant parent_constant {" +
- " file: constants/my_constant_tensor_file.json" +
- " type: tensor<float>(x{},y{})" +
- " }" +
- " onnx-model parent_model {" +
- " file: models/my_model.onnx" +
- " }" +
- " document-summary parent_summary {" +
- " summary pf1 type string {}" +
- " }" +
- " import field parentschema_ref.name as parent_imported {}" +
- " raw-as-base64-in-summary" +
- "}");
+ " document parent {" +
+ " field pf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " fieldset parent_set {" +
+ " fields: pf1" +
+ " }" +
+ " stemming: none" +
+ " index parent_index {" +
+ " stemming: best" +
+ " }" +
+ " field parent_field type string {" +
+ " indexing: input pf1 | lowercase | index | attribute | summary" +
+ " }" +
+ " rank-profile parent_profile {" +
+ " }" +
+ " constant parent_constant {" +
+ " file: constants/my_constant_tensor_file.json" +
+ " type: tensor<float>(x{},y{})" +
+ " }" +
+ " onnx-model parent_model {" +
+ " file: models/my_model.onnx" +
+ " }" +
+ " document-summary parent_summary {" +
+ " summary pf1 type string {}" +
+ " }" +
+ " import field parentschema_ref.name as parent_imported {}" +
+ " raw-as-base64-in-summary" +
+ "}");
String childLines = joinLines(
"schema child inherits parent {" +
- " document child inherits parent {" +
- " field cf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- "}");
+ " document child inherits parent {" +
+ " field cf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ "}");
String grandchildLines = joinLines(
"schema grandchild inherits child {" +
- " document grandchild inherits child {" +
- " field gf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- "}");
+ " document grandchild inherits child {" +
+ " field gf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ "}");
ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub());
builder.processorsToSkip().add(OnnxModelTypeResolver.class); // Avoid discovering the Onnx model referenced does not exist
@@ -323,100 +320,100 @@ public class SchemaTestCase {
}
@Test
- public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed1() throws ParseException {
+ void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed1() throws ParseException {
try {
String profile = joinLines(
"schema test {" +
- " document test {" +
- " field title type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " rank-profile r1 {" +
- " first-phase {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r2 {" +
- " first-phase {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r3 inherits r1, r2 {" +
- " }" +
- "}");
+ " document test {" +
+ " field title type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " rank-profile r1 {" +
+ " first-phase {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r2 {" +
+ " first-phase {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r3 inherits r1, r2 {" +
+ " }" +
+ "}");
ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Only one of the profiles inherited by rank profile 'r3' can contain first-phase expression, but it is present in multiple",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsAllowedWhenDefinedInChild() throws ParseException {
+ void testInheritingMultipleRankProfilesWithOverlappingConstructsIsAllowedWhenDefinedInChild() throws ParseException {
String profile = joinLines(
"schema test {" +
- " document test {" +
- " field title type string {" +
- " indexing: summary" +
- " }" +
- " field myFilter type string {" +
- " indexing: attribute\n" +
- " rank: filter" +
- " }" +
- " }" +
- " rank-profile r1 {" +
- " first-phase {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r2 {" +
- " first-phase {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r3 inherits r1, r2 {" +
- " first-phase {" + // Redefined here so this does not cause failure
- " expression: nativeRank" +
- " }" +
- " }" +
- "}");
+ " document test {" +
+ " field title type string {" +
+ " indexing: summary" +
+ " }" +
+ " field myFilter type string {" +
+ " indexing: attribute\n" +
+ " rank: filter" +
+ " }" +
+ " }" +
+ " rank-profile r1 {" +
+ " first-phase {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r2 {" +
+ " first-phase {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r3 inherits r1, r2 {" +
+ " first-phase {" + // Redefined here so this does not cause failure
+ " expression: nativeRank" +
+ " }" +
+ " }" +
+ "}");
var builder = ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile);
var r3 = builder.getRankProfileRegistry().resolve(builder.application().schemas().get("test").getDocument(), "r3");
assertEquals(1, r3.allFilterFields().size());
}
@Test
- public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed2() throws ParseException {
+ void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed2() throws ParseException {
try {
String profile = joinLines(
"schema test {" +
- " document test {" +
- " field title type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " rank-profile r1 {" +
- " function f1() {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r2 {" +
- " function f1() {" +
- " expression: fieldMatch(title)" +
- " }" +
- " }" +
- " rank-profile r3 inherits r1, r2 {" +
- " }" +
- "}");
+ " document test {" +
+ " field title type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " rank-profile r1 {" +
+ " function f1() {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r2 {" +
+ " function f1() {" +
+ " expression: fieldMatch(title)" +
+ " }" +
+ " }" +
+ " rank-profile r3 inherits r1, r2 {" +
+ " }" +
+ "}");
ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("rank profile 'r3' inherits rank profile 'r2' which contains function 'f1', but this function is already defined in another profile this inherits",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java b/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java
index 5dd75166783..e0f1f8dfa1c 100644
--- a/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.schema;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.Stemming;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Stemming settings test
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertNull;
public class StemmingSettingTestCase extends AbstractSchemaTestCase {
@Test
- public void testStemmingSettings() throws IOException, ParseException {
+ void testStemmingSettings() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/stemmingsetting.sd");
SDField artist = (SDField) schema.getDocument().getField("artist");
@@ -42,7 +42,7 @@ public class StemmingSettingTestCase extends AbstractSchemaTestCase {
}
@Test
- public void requireThatStemmingIsDefaultBest() throws IOException, ParseException {
+ void requireThatStemmingIsDefaultBest() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/stemmingdefault.sd");
assertNull(schema.getConcreteField("my_str").getStemming());
assertEquals(Stemming.BEST, schema.getConcreteField("my_str").getStemming(schema));
diff --git a/config-model/src/test/java/com/yahoo/schema/StructTestCase.java b/config-model/src/test/java/com/yahoo/schema/StructTestCase.java
index b140892ed5e..087ce6ee935 100755
--- a/config-model/src/test/java/com/yahoo/schema/StructTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/StructTestCase.java
@@ -6,10 +6,12 @@ import com.yahoo.document.config.DocumenttypesConfig;
import com.yahoo.document.config.DocumentmanagerConfig;
import com.yahoo.schema.derived.Deriver;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
import java.io.IOException;
-import static org.junit.Assert.fail;
+
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests importing of document containing array type fields
@@ -19,25 +21,25 @@ import static org.junit.Assert.fail;
public class StructTestCase extends AbstractSchemaTestCase {
@Test
- public void testStruct() throws IOException {
+ void testStruct() throws IOException {
assertConfigFile("src/test/examples/structresult.cfg",
- new DocumentmanagerConfig(Deriver.getDocumentManagerConfig("src/test/examples/struct.sd")) + "\n");
+ new DocumentmanagerConfig(Deriver.getDocumentManagerConfig("src/test/examples/struct.sd")) + "\n");
}
@Test
- public void testBadStruct() throws IOException {
+ void testBadStruct() throws IOException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/badstruct.sd");
fail("Should throw exception.");
- } catch (IllegalArgumentException|ParseException expected) {
- System.err.println("As expected, with message: "+expected.getMessage());
+ } catch (IllegalArgumentException | ParseException expected) {
+ System.err.println("As expected, with message: " + expected.getMessage());
// success
}
}
@Test
- @Ignore
- public void testStructAndDocumentWithSameNames() {
+ @Disabled
+ void testStructAndDocumentWithSameNames() {
try {
DocumenttypesConfig.Builder dt = Deriver.getDocumentTypesConfig("src/test/examples/structanddocumentwithsamenames.sd");
// while the above line may work, the config generated will fail.
@@ -51,7 +53,7 @@ public class StructTestCase extends AbstractSchemaTestCase {
* Declaring a struct before a document should work
*/
@Test
- public void testStructOutsideDocumentLegal() throws IOException, ParseException {
+ void testStructOutsideDocumentLegal() throws IOException, ParseException {
new ApplicationBuilder().addSchemaFile("src/test/examples/structoutsideofdocument.sd");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java
index 0fab9b381fc..f33dc46f29b 100644
--- a/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java
@@ -5,7 +5,8 @@ import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
import com.yahoo.vespa.objects.FieldBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import static com.yahoo.config.model.test.TestUtil.joinLines;
import java.util.Collection;
@@ -14,9 +15,7 @@ import java.util.Optional;
import java.util.logging.Level;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests summary validation
@@ -26,7 +25,7 @@ import static org.junit.Assert.fail;
public class SummaryTestCase {
@Test
- public void testMemorySummary() throws ParseException {
+ void testMemorySummary() throws ParseException {
String sd = joinLines(
"schema memorysummary {",
" document memorysummary {",
@@ -44,7 +43,7 @@ public class SummaryTestCase {
}
@Test
- public void testDiskSummary() throws ParseException {
+ void testDiskSummary() throws ParseException {
String sd = joinLines(
"schema disksummary {",
" document-summary foobar {",
@@ -65,13 +64,13 @@ public class SummaryTestCase {
assertEquals(1, logger.entries.size());
assertEquals(Level.WARNING, logger.entries.get(0).level);
assertEquals("summary field 'foo2' in document summary 'foobar' references source field 'ondisk', " +
- "which is not an attribute: Using this summary will cause disk accesses. " +
- "Set 'from-disk' on this summary class to silence this warning.",
- logger.entries.get(0).message);
+ "which is not an attribute: Using this summary will cause disk accesses. " +
+ "Set 'from-disk' on this summary class to silence this warning.",
+ logger.entries.get(0).message);
}
@Test
- public void testDiskSummaryExplicit() throws ParseException {
+ void testDiskSummaryExplicit() throws ParseException {
String sd = joinLines(
"schema disksummary {",
" document disksummary {",
@@ -94,7 +93,7 @@ public class SummaryTestCase {
}
@Test
- public void testStructMemorySummary() throws ParseException {
+ void testStructMemorySummary() throws ParseException {
String sd = joinLines(
"schema structmemorysummary {",
" document structmemorysummary {",
@@ -125,7 +124,7 @@ public class SummaryTestCase {
}
@Test
- public void testInheritance() throws Exception {
+ void testInheritance() throws Exception {
String sd = joinLines(
"schema music {",
" document music {",
@@ -174,17 +173,17 @@ public class SummaryTestCase {
);
tests.forEach(testValue -> {
var actualFields = testValue.summary.getSummaryFields().values().stream()
- .map(FieldBase::getName)
- .collect(Collectors.toList());
- assertEquals(testValue.summary.getName() + (testValue.parent == null ? " does not inherit anything" : " inherits " + testValue.parent.getName()),
- Optional.ofNullable(testValue.parent),
- testValue.summary.inherited());
- assertEquals("Summary " + testValue.summary.getName() + " has expected fields", testValue.fields, actualFields);
+ .map(FieldBase::getName)
+ .collect(Collectors.toList());
+ assertEquals(Optional.ofNullable(testValue.parent),
+ testValue.summary.inherited(),
+ testValue.summary.getName() + (testValue.parent == null ? " does not inherit anything" : " inherits " + testValue.parent.getName()));
+ assertEquals(testValue.fields, actualFields, "Summary " + testValue.summary.getName() + " has expected fields");
});
}
@Test
- public void testRedeclaringInheritedFieldFails() throws Exception {
+ void testRedeclaringInheritedFieldFails() throws Exception {
String sd = joinLines(
"schema music {",
" document music {",
@@ -212,25 +211,25 @@ public class SummaryTestCase {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("For schema 'music', summary class 'title2', summary field 'title': Can not use " +
- "source 'title_short' for this summary field, an equally named field in summary class 'title' " +
- "uses a different source: 'title'.", e.getMessage());
+ "source 'title_short' for this summary field, an equally named field in summary class 'title' " +
+ "uses a different source: 'title'.", e.getMessage());
}
}
@Test
- public void testValidationOfInheritedSummary() throws ParseException {
+ void testValidationOfInheritedSummary() throws ParseException {
try {
String schema = joinLines(
"schema test {" +
- " document test {" +
- " }" +
- " document-summary test_summary inherits nonesuch {" +
- " }" +
- "}");
+ " document test {" +
+ " }" +
+ " document-summary test_summary inherits nonesuch {" +
+ " }" +
+ "}");
DeployLoggerStub logger = new DeployLoggerStub();
ApplicationBuilder.createFromStrings(logger, schema);
assertEquals("document summary 'test_summary' inherits nonesuch but this is not present in schema 'test'",
- logger.entries.get(0).message);
+ logger.entries.get(0).message);
// fail("Expected failure");
}
catch (IllegalArgumentException e) {
@@ -240,29 +239,29 @@ public class SummaryTestCase {
}
@Test
- public void testInheritingParentSummary() throws ParseException {
+ void testInheritingParentSummary() throws ParseException {
String parent = joinLines(
"schema parent {" +
- " document parent {" +
- " field pf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " document-summary parent_summary {" +
- " summary pf1 type string {}" +
- " }" +
- "}");
+ " document parent {" +
+ " field pf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " document-summary parent_summary {" +
+ " summary pf1 type string {}" +
+ " }" +
+ "}");
String child = joinLines(
"schema child inherits parent {" +
- " document child inherits parent {" +
- " field cf1 type string {" +
- " indexing: summary" +
- " }" +
- " }" +
- " document-summary child_summary inherits parent_summary {" +
- " summary cf1 type string {}" +
- " }" +
- "}");
+ " document child inherits parent {" +
+ " field cf1 type string {" +
+ " indexing: summary" +
+ " }" +
+ " }" +
+ " document-summary child_summary inherits parent_summary {" +
+ " summary cf1 type string {}" +
+ " }" +
+ "}");
DeployLoggerStub logger = new DeployLoggerStub();
ApplicationBuilder.createFromStrings(logger, parent, child);
logger.entries.forEach(e -> System.out.println(e));
diff --git a/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java
index 83bb0d4548c..1509ca0bf9b 100644
--- a/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.schema;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -14,20 +14,20 @@ import static org.junit.Assert.fail;
public class UrlFieldValidationTestCase {
@Test
- public void requireThatInheritedRiseFieldsStillCanBeInConflictButDontThrowException() throws ParseException {
+ void requireThatInheritedRiseFieldsStillCanBeInConflictButDontThrowException() throws ParseException {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema("search test {" +
- " document test { " +
- " field a type uri { indexing: attribute | summary }" +
- " }" +
- "}");
+ " document test { " +
+ " field a type uri { indexing: attribute | summary }" +
+ " }" +
+ "}");
try {
builder.build(true);
fail("Should have caused an exception");
// success
} catch (IllegalArgumentException e) {
assertEquals("Error in field 'a' in schema 'test': uri type fields cannot be attributes",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java
index 60867261f93..e17634467ac 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,47 +12,47 @@ import java.io.IOException;
public class AnnotationsTestCase extends AbstractExportingTestCase {
@Test
- public void requireThatStructRegistersIfOnlyUsedByAnnotation() throws IOException, ParseException {
+ void requireThatStructRegistersIfOnlyUsedByAnnotation() throws IOException, ParseException {
assertCorrectDeriving("annotationsstruct");
}
@Test
- public void requireThatStructRegistersIfOnlyUsedAsArrayByAnnotation() throws IOException, ParseException {
+ void requireThatStructRegistersIfOnlyUsedAsArrayByAnnotation() throws IOException, ParseException {
assertCorrectDeriving("annotationsstructarray");
}
@Test
- public void testSimpleAnnotationDeriving() throws IOException, ParseException {
+ void testSimpleAnnotationDeriving() throws IOException, ParseException {
assertCorrectDeriving("annotationssimple");
}
@Test
- public void testAnnotationDerivingWithImplicitStruct() throws IOException, ParseException {
+ void testAnnotationDerivingWithImplicitStruct() throws IOException, ParseException {
assertCorrectDeriving("annotationsimplicitstruct");
}
@Test
- public void testAnnotationDerivingInheritance() throws IOException, ParseException {
+ void testAnnotationDerivingInheritance() throws IOException, ParseException {
assertCorrectDeriving("annotationsinheritance");
}
@Test
- public void testAnnotationDerivingInheritance2() throws IOException, ParseException {
+ void testAnnotationDerivingInheritance2() throws IOException, ParseException {
assertCorrectDeriving("annotationsinheritance2");
}
@Test
- public void testSimpleReference() throws IOException, ParseException {
+ void testSimpleReference() throws IOException, ParseException {
assertCorrectDeriving("annotationsreference");
}
@Test
- public void testAdvancedReference() throws IOException, ParseException {
+ void testAdvancedReference() throws IOException, ParseException {
assertCorrectDeriving("annotationsreference2");
}
@Test
- public void testAnnotationsPolymorphy() throws IOException, ParseException {
+ void testAnnotationsPolymorphy() throws IOException, ParseException {
assertCorrectDeriving("annotationspolymorphy");
}
@@ -60,7 +60,7 @@ public class AnnotationsTestCase extends AbstractExportingTestCase {
* An annotation declared before document {} should work.
*/
@Test
- public void testAnnotationOutsideOfDocumentNew() throws IOException, ParseException {
+ void testAnnotationOutsideOfDocumentNew() throws IOException, ParseException {
assertCorrectDeriving("annotationsoutsideofdocument");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java
index 5b138413a7a..a1b7e40d21b 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -16,7 +16,7 @@ import java.io.IOException;
public class ArraysTestCase extends AbstractExportingTestCase {
@Test
- public void testDocumentDeriving() throws IOException, ParseException {
+ void testDocumentDeriving() throws IOException, ParseException {
assertCorrectDeriving("arrays");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java
index 1c51d3ec365..c0886597de7 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.Attribute;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Iterator;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Tests attribute deriving
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertFalse;
public class AttributeListTestCase extends AbstractSchemaTestCase {
@Test
- public void testDeriving() throws IOException, ParseException {
+ void testDeriving() throws IOException, ParseException {
// Test attribute importing
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd");
@@ -31,37 +31,37 @@ public class AttributeListTestCase extends AbstractSchemaTestCase {
AttributeFields attributeFields = new AttributeFields(schema);
Iterator attributes = attributeFields.attributeIterator();
Attribute attribute;
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("popularity", attribute.getName());
assertEquals(Attribute.Type.INTEGER, attribute.getType());
assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("measurement", attribute.getName());
assertEquals(Attribute.Type.INTEGER, attribute.getType());
assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("smallattribute", attribute.getName());
assertEquals(Attribute.Type.BYTE, attribute.getType());
assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("access", attribute.getName());
assertEquals(Attribute.Type.BYTE, attribute.getType());
assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("category_arr", attribute.getName());
assertEquals(Attribute.Type.STRING, attribute.getType());
assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("measurement_arr", attribute.getName());
assertEquals(Attribute.Type.INTEGER, attribute.getType());
assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType());
- attribute = (Attribute)attributes.next();
+ attribute = (Attribute) attributes.next();
assertEquals("popsiness", attribute.getName());
assertEquals(Attribute.Type.INTEGER, attribute.getType());
assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType());
@@ -70,7 +70,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase {
}
@Test
- public void fields_in_array_of_struct_are_derived_into_array_attributes() throws IOException, ParseException {
+ void fields_in_array_of_struct_are_derived_into_array_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/array_of_struct_attribute/test.sd");
Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator();
@@ -80,7 +80,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase {
}
@Test
- public void fields_in_map_of_struct_are_derived_into_array_attributes() throws IOException, ParseException {
+ void fields_in_map_of_struct_are_derived_into_array_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd");
Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator();
@@ -100,15 +100,15 @@ public class AttributeListTestCase extends AbstractSchemaTestCase {
}
@Test
- public void only_zcurve_attribute_is_derived_from_array_of_position_field() throws ParseException {
+ void only_zcurve_attribute_is_derived_from_array_of_position_field() throws ParseException {
Schema schema = ApplicationBuilder.createFromString(
joinLines("search test {",
- " document test {",
- " field pos_array type array<position> {",
- " indexing: attribute",
- " }",
- " }",
- "}")).getSchema();
+ " document test {",
+ " field pos_array type array<position> {",
+ " indexing: attribute",
+ " }",
+ " }",
+ "}")).getSchema();
Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator();
assertAttribute("pos_array_zcurve", Attribute.Type.LONG, Attribute.CollectionType.ARRAY, true, attributes.next());
@@ -116,7 +116,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase {
}
@Test
- public void fields_in_map_of_primitive_are_derived_into_array_attributes() throws IOException, ParseException {
+ void fields_in_map_of_primitive_are_derived_into_array_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_attribute/test.sd");
Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator();
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java
index 3d08805acdf..f8b66c8f41b 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,22 +14,22 @@ import java.io.IOException;
public class AttributesTestCase extends AbstractExportingTestCase {
@Test
- public void testDocumentDeriving() throws IOException, ParseException {
+ void testDocumentDeriving() throws IOException, ParseException {
assertCorrectDeriving("attributes");
}
@Test
- public void testArrayOfStructAttribute() throws IOException, ParseException {
+ void testArrayOfStructAttribute() throws IOException, ParseException {
assertCorrectDeriving("array_of_struct_attribute");
}
@Test
- public void testMapOfStructAttribute() throws IOException, ParseException {
+ void testMapOfStructAttribute() throws IOException, ParseException {
assertCorrectDeriving("map_of_struct_attribute");
}
@Test
- public void testMapOfPrimitiveAttribute() throws IOException, ParseException {
+ void testMapOfPrimitiveAttribute() throws IOException, ParseException {
assertCorrectDeriving("map_attribute");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java
index 80ebcb825f4..1ee0aa76126 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java
@@ -5,11 +5,11 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Correct casing for derived attributes
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class CasingTestCase extends AbstractSchemaTestCase {
@Test
- public void testCasing() throws IOException, ParseException {
+ void testCasing() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/casing.sd");
assertEquals(schema.getIndex("color").getName(), "color");
assertEquals(schema.getIndex("Foo").getName(), "Foo");
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java
index 542320d9670..3e984ade647 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.io.IOException;
public class CombinedAttributeAndIndexSchemaTestCase extends AbstractExportingTestCase {
@Test
- public void testMultipleSummaries() throws IOException, ParseException {
+ void testMultipleSummaries() throws IOException, ParseException {
assertCorrectDeriving("combinedattributeandindexsearch");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java
index 422f4522b26..55767e8f8c0 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java
@@ -5,11 +5,11 @@ import com.yahoo.document.DataType;
import com.yahoo.document.DocumentTypeManager;
import com.yahoo.document.config.DocumentmanagerConfig;
import com.yahoo.schema.AbstractSchemaTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests deriving using the Deriver facade
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class DeriverTestCase extends AbstractSchemaTestCase {
@Test
- public void testDeriveDocManager() {
+ void testDeriveDocManager() {
DocumentTypeManager dtm = new DocumentTypeManager(new DocumentmanagerConfig(
Deriver.getDocumentManagerConfig(List.of(
"src/test/derived/deriver/child.sd",
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java
index 7915a1d7763..7287de68f2f 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author arnej
@@ -10,10 +10,10 @@ import org.junit.Test;
public class DuplicateStructTestCase extends AbstractExportingTestCase {
@Test
- public void exact_duplicate_struct_works() throws Exception {
+ void exact_duplicate_struct_works() throws Exception {
assertCorrectDeriving("duplicate_struct", "foobar",
- new TestProperties(),
- new TestableDeployLogger());
+ new TestProperties(),
+ new TestableDeployLogger());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java
index c3195d1a626..a1df845c97d 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests deriving rank for files from search definitions
@@ -20,7 +20,7 @@ import org.junit.Test;
public class EmptyRankProfileTestCase extends AbstractSchemaTestCase {
@Test
- public void testDeriving() {
+ void testDeriving() {
Schema schema = new Schema("test", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType doc = new SDDocumentType("test");
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java
index 13a0a8201fb..6b7e8bb714d 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -11,7 +11,7 @@ import java.io.IOException;
*/
public class ExactMatchTestCase extends AbstractExportingTestCase {
@Test
- public void testExactString() throws IOException, ParseException {
+ void testExactString() throws IOException, ParseException {
assertCorrectDeriving("exactmatch");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java
index dc10004a631..b5b075ae260 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests exporting
@@ -18,144 +18,144 @@ import static org.junit.Assert.assertEquals;
public class ExportingTestCase extends AbstractExportingTestCase {
@Test
- public void testIndexInfoLowerCase() throws IOException, ParseException {
+ void testIndexInfoLowerCase() throws IOException, ParseException {
assertCorrectDeriving("indexinfo_lowercase");
}
@Test
- public void testPositionArray() throws IOException, ParseException {
+ void testPositionArray() throws IOException, ParseException {
assertCorrectDeriving("position_array",
- new TestProperties().setUseV8GeoPositions(true));
+ new TestProperties().setUseV8GeoPositions(true));
}
@Test
- public void testPositionAttribute() throws IOException, ParseException {
+ void testPositionAttribute() throws IOException, ParseException {
assertCorrectDeriving("position_attribute",
- new TestProperties().setUseV8GeoPositions(true));
+ new TestProperties().setUseV8GeoPositions(true));
}
@Test
- public void testPositionExtra() throws IOException, ParseException {
+ void testPositionExtra() throws IOException, ParseException {
assertCorrectDeriving("position_extra",
- new TestProperties().setUseV8GeoPositions(true));
+ new TestProperties().setUseV8GeoPositions(true));
}
@Test
- public void testPositionNoSummary() throws IOException, ParseException {
+ void testPositionNoSummary() throws IOException, ParseException {
assertCorrectDeriving("position_nosummary",
- new TestProperties().setUseV8GeoPositions(true));
+ new TestProperties().setUseV8GeoPositions(true));
}
@Test
- public void testPositionSummary() throws IOException, ParseException {
+ void testPositionSummary() throws IOException, ParseException {
assertCorrectDeriving("position_summary",
- new TestProperties().setUseV8GeoPositions(true));
+ new TestProperties().setUseV8GeoPositions(true));
}
@Test
- public void testUriArray() throws IOException, ParseException {
+ void testUriArray() throws IOException, ParseException {
assertCorrectDeriving("uri_array");
}
@Test
- public void testUriWSet() throws IOException, ParseException {
+ void testUriWSet() throws IOException, ParseException {
assertCorrectDeriving("uri_wset");
}
@Test
- public void testMusic() throws IOException, ParseException {
+ void testMusic() throws IOException, ParseException {
assertCorrectDeriving("music");
}
@Test
- public void testComplexPhysicalExporting() throws IOException, ParseException {
+ void testComplexPhysicalExporting() throws IOException, ParseException {
assertCorrectDeriving("complex");
}
@Test
- public void testAttributePrefetch() throws IOException, ParseException {
+ void testAttributePrefetch() throws IOException, ParseException {
assertCorrectDeriving("attributeprefetch");
}
@Test
- public void testAdvancedIL() throws IOException, ParseException {
+ void testAdvancedIL() throws IOException, ParseException {
assertCorrectDeriving("advanced");
}
@Test
- public void testEmptyDefaultIndex() throws IOException, ParseException {
+ void testEmptyDefaultIndex() throws IOException, ParseException {
assertCorrectDeriving("emptydefault");
}
@Test
- public void testIndexSwitches() throws IOException, ParseException {
+ void testIndexSwitches() throws IOException, ParseException {
assertCorrectDeriving("indexswitches");
}
@Test
- public void testRankTypes() throws IOException, ParseException {
+ void testRankTypes() throws IOException, ParseException {
assertCorrectDeriving("ranktypes");
}
@Test
- public void testAttributeRank() throws IOException, ParseException {
+ void testAttributeRank() throws IOException, ParseException {
assertCorrectDeriving("attributerank");
}
@Test
- public void testNewRank() throws IOException, ParseException {
+ void testNewRank() throws IOException, ParseException {
assertCorrectDeriving("newrank");
}
@Test
- public void testRankingExpression() throws IOException, ParseException {
+ void testRankingExpression() throws IOException, ParseException {
assertCorrectDeriving("rankingexpression");
}
@Test
- public void testAvoidRenamingRankingExpression() throws IOException, ParseException {
+ void testAvoidRenamingRankingExpression() throws IOException, ParseException {
assertCorrectDeriving("renamedfeatures", "foo",
- new TestProperties(),
- new TestableDeployLogger());
+ new TestProperties(),
+ new TestableDeployLogger());
}
@Test
- public void testMlr() throws IOException, ParseException {
+ void testMlr() throws IOException, ParseException {
assertCorrectDeriving("mlr");
}
@Test
- public void testMusic3() throws IOException, ParseException {
+ void testMusic3() throws IOException, ParseException {
assertCorrectDeriving("music3");
}
@Test
- public void testIndexSchema() throws IOException, ParseException {
+ void testIndexSchema() throws IOException, ParseException {
assertCorrectDeriving("indexschema");
}
@Test
- public void testIndexinfoFieldsets() throws IOException, ParseException {
+ void testIndexinfoFieldsets() throws IOException, ParseException {
assertCorrectDeriving("indexinfo_fieldsets");
}
@Test
- public void testStreamingJuniper() throws IOException, ParseException {
+ void testStreamingJuniper() throws IOException, ParseException {
assertCorrectDeriving("streamingjuniper");
}
@Test
- public void testPredicateAttribute() throws IOException, ParseException {
+ void testPredicateAttribute() throws IOException, ParseException {
assertCorrectDeriving("predicate_attribute");
}
@Test
- public void testTensor() throws IOException, ParseException {
+ void testTensor() throws IOException, ParseException {
assertCorrectDeriving("tensor");
}
@Test
- public void testTensor2() throws IOException, ParseException {
+ void testTensor2() throws IOException, ParseException {
String dir = "src/test/derived/tensor2/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "first.sd");
@@ -166,29 +166,29 @@ public class ExportingTestCase extends AbstractExportingTestCase {
}
@Test
- public void testHnswIndex() throws IOException, ParseException {
+ void testHnswIndex() throws IOException, ParseException {
assertCorrectDeriving("hnsw_index");
}
@Test
- public void testRankProfileInheritance() throws IOException, ParseException {
+ void testRankProfileInheritance() throws IOException, ParseException {
assertCorrectDeriving("rankprofileinheritance", "child", new TestableDeployLogger());
}
@Test
- public void testLanguage() throws IOException, ParseException {
+ void testLanguage() throws IOException, ParseException {
TestableDeployLogger logger = new TestableDeployLogger();
assertCorrectDeriving("language", logger);
assertEquals(0, logger.warnings.size());
}
@Test
- public void testRankProfileModularity() throws IOException, ParseException {
+ void testRankProfileModularity() throws IOException, ParseException {
assertCorrectDeriving("rankprofilemodularity");
}
@Test
- public void testStructAndFieldSet() throws IOException, ParseException {
+ void testStructAndFieldSet() throws IOException, ParseException {
assertCorrectDeriving("structandfieldset");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java
index d2020305bc1..31dfd240538 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.io.IOException;
public class ExpressionsAsArgsTestCase extends AbstractExportingTestCase {
@Test
- public void testDocumentDeriving() throws IOException, ParseException {
+ void testDocumentDeriving() throws IOException, ParseException {
assertCorrectDeriving("function_arguments");
assertCorrectDeriving("function_arguments_with_expressions");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java
index fdab49c9fff..c223152e3da 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java
@@ -2,14 +2,14 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
public class FieldsetTestCase extends AbstractExportingTestCase {
@Test
- public void testRankProfiles() throws IOException, ParseException {
+ void testRankProfiles() throws IOException, ParseException {
assertCorrectDeriving("fieldset");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java
index 5531fb65942..3a809d190bc 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java
@@ -3,21 +3,22 @@ package com.yahoo.schema.derived;
import com.yahoo.collections.Pair;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* @author bratseth
*/
public class GeminiTestCase extends AbstractExportingTestCase {
@Test
- public void testRanking2() throws IOException, ParseException {
+ void testRanking2() throws IOException, ParseException {
DerivedConfiguration c = assertCorrectDeriving("gemini2");
RawRankProfile p = c.getRankProfileList().getRankProfiles().get("test");
Map<String, String> ranking = removePartKeySuffixes(asMap(p.configProperties()));
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java
index 1e57d52e3b0..f2614e9e85b 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java
@@ -10,12 +10,12 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.processing.Processing;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests that documents ids are treated as they should
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertNull;
public class IdTestCase extends AbstractExportingTestCase {
@Test
- public void testExplicitUpperCaseIdField() {
+ void testExplicitUpperCaseIdField() {
Schema schema = new Schema("test", MockApplicationPackage.createEmpty());
SDDocumentType document = new SDDocumentType("test");
schema.addDocument(document);
@@ -34,7 +34,7 @@ public class IdTestCase extends AbstractExportingTestCase {
document.addField(uri);
new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(),
- true, false, Set.of());
+ true, false, Set.of());
assertNull(document.getField("uri"));
assertNull(document.getField("Uri"));
@@ -42,7 +42,7 @@ public class IdTestCase extends AbstractExportingTestCase {
}
@Test
- public void testCompleteDeriving() throws Exception {
+ void testCompleteDeriving() throws Exception {
assertCorrectDeriving("id");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java
index 5578a1a602b..fb87137cc2e 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -13,29 +13,29 @@ import java.io.IOException;
public class ImportedFieldsTestCase extends AbstractExportingTestCase {
@Test
- public void configs_for_imported_fields_are_derived() throws IOException, ParseException {
+ void configs_for_imported_fields_are_derived() throws IOException, ParseException {
assertCorrectDeriving("importedfields", "child", new TestableDeployLogger());
}
@Test
- public void configs_for_imported_struct_fields_are_derived() throws IOException, ParseException {
+ void configs_for_imported_struct_fields_are_derived() throws IOException, ParseException {
assertCorrectDeriving("imported_struct_fields", "child",
- new TestProperties(),
- new TestableDeployLogger());
+ new TestProperties(),
+ new TestableDeployLogger());
}
@Test
- public void configs_for_imported_position_field_are_derived() throws IOException, ParseException {
+ void configs_for_imported_position_field_are_derived() throws IOException, ParseException {
assertCorrectDeriving("imported_position_field", "child", new TestableDeployLogger());
}
@Test
- public void configs_for_imported_position_field_summary_are_derived() throws IOException, ParseException {
+ void configs_for_imported_position_field_summary_are_derived() throws IOException, ParseException {
assertCorrectDeriving("imported_position_field_summary", "child", new TestableDeployLogger());
}
@Test
- public void derives_configs_for_imported_fields_when_reference_fields_are_inherited() throws IOException, ParseException {
+ void derives_configs_for_imported_fields_when_reference_fields_are_inherited() throws IOException, ParseException {
assertCorrectDeriving("imported_fields_inherited_reference", "child_c", new TestableDeployLogger());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java
index 1f40c6bcb50..39d436f6676 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java
@@ -4,15 +4,15 @@ package com.yahoo.schema.derived;
import com.yahoo.document.DataType;
import com.yahoo.document.Field;
import com.yahoo.document.StructDataType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class IndexSchemaTestCase {
@Test
- public void requireThatPrimitiveIsNotFlattened() {
+ void requireThatPrimitiveIsNotFlattened() {
assertFlat(new Field("foo", DataType.BYTE), new Field("foo", DataType.BYTE));
assertFlat(new Field("foo", DataType.DOUBLE), new Field("foo", DataType.DOUBLE));
assertFlat(new Field("foo", DataType.FLOAT), new Field("foo", DataType.FLOAT));
@@ -33,29 +33,29 @@ public class IndexSchemaTestCase {
}
@Test
- public void requireThatArrayOfPrimitiveIsNotFlattened() {
+ void requireThatArrayOfPrimitiveIsNotFlattened() {
assertFlat(new Field("foo", DataType.getArray(DataType.BYTE)),
- new Field("foo", DataType.getArray(DataType.BYTE)));
+ new Field("foo", DataType.getArray(DataType.BYTE)));
assertFlat(new Field("foo", DataType.getArray(DataType.DOUBLE)),
- new Field("foo", DataType.getArray(DataType.DOUBLE)));
+ new Field("foo", DataType.getArray(DataType.DOUBLE)));
assertFlat(new Field("foo", DataType.getArray(DataType.FLOAT)),
- new Field("foo", DataType.getArray(DataType.FLOAT)));
+ new Field("foo", DataType.getArray(DataType.FLOAT)));
assertFlat(new Field("foo", DataType.getArray(DataType.INT)),
- new Field("foo", DataType.getArray(DataType.INT)));
+ new Field("foo", DataType.getArray(DataType.INT)));
assertFlat(new Field("foo", DataType.getArray(DataType.LONG)),
- new Field("foo", DataType.getArray(DataType.LONG)));
+ new Field("foo", DataType.getArray(DataType.LONG)));
assertFlat(new Field("foo", DataType.getArray(DataType.RAW)),
- new Field("foo", DataType.getArray(DataType.RAW)));
+ new Field("foo", DataType.getArray(DataType.RAW)));
assertFlat(new Field("foo", DataType.getArray(DataType.STRING)),
- new Field("foo", DataType.getArray(DataType.STRING)));
+ new Field("foo", DataType.getArray(DataType.STRING)));
assertFlat(new Field("foo", DataType.getArray(DataType.URI)),
- new Field("foo", DataType.getArray(DataType.URI)));
+ new Field("foo", DataType.getArray(DataType.URI)));
assertFlat(new Field("foo", DataType.getArray(DataType.PREDICATE)),
- new Field("foo", DataType.getArray(DataType.PREDICATE)));
+ new Field("foo", DataType.getArray(DataType.PREDICATE)));
}
@Test
- public void requireThatStructIsFlattened() {
+ void requireThatStructIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.BYTE));
type.addField(new Field("my_double", DataType.DOUBLE));
@@ -67,18 +67,18 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.URI));
assertFlat(new Field("foo", type),
- new Field("foo.my_byte", DataType.BYTE),
- new Field("foo.my_double", DataType.DOUBLE),
- new Field("foo.my_float", DataType.FLOAT),
- new Field("foo.my_int", DataType.INT),
- new Field("foo.my_long", DataType.LONG),
- new Field("foo.my_raw", DataType.RAW),
- new Field("foo.my_string", DataType.STRING),
- new Field("foo.my_uri", DataType.URI));
+ new Field("foo.my_byte", DataType.BYTE),
+ new Field("foo.my_double", DataType.DOUBLE),
+ new Field("foo.my_float", DataType.FLOAT),
+ new Field("foo.my_int", DataType.INT),
+ new Field("foo.my_long", DataType.LONG),
+ new Field("foo.my_raw", DataType.RAW),
+ new Field("foo.my_string", DataType.STRING),
+ new Field("foo.my_uri", DataType.URI));
}
@Test
- public void requireThatArrayOfStructIsFlattened() {
+ void requireThatArrayOfStructIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.BYTE));
type.addField(new Field("my_double", DataType.DOUBLE));
@@ -90,18 +90,18 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.URI));
assertFlat(new Field("foo", DataType.getArray(type)),
- new Field("foo.my_byte", DataType.getArray(DataType.BYTE)),
- new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)),
- new Field("foo.my_float", DataType.getArray(DataType.FLOAT)),
- new Field("foo.my_int", DataType.getArray(DataType.INT)),
- new Field("foo.my_long", DataType.getArray(DataType.LONG)),
- new Field("foo.my_raw", DataType.getArray(DataType.RAW)),
- new Field("foo.my_string", DataType.getArray(DataType.STRING)),
- new Field("foo.my_uri", DataType.getArray(DataType.URI)));
+ new Field("foo.my_byte", DataType.getArray(DataType.BYTE)),
+ new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)),
+ new Field("foo.my_float", DataType.getArray(DataType.FLOAT)),
+ new Field("foo.my_int", DataType.getArray(DataType.INT)),
+ new Field("foo.my_long", DataType.getArray(DataType.LONG)),
+ new Field("foo.my_raw", DataType.getArray(DataType.RAW)),
+ new Field("foo.my_string", DataType.getArray(DataType.STRING)),
+ new Field("foo.my_uri", DataType.getArray(DataType.URI)));
}
@Test
- public void requireThatArrayOfArrayOfStructIsFlattened() {
+ void requireThatArrayOfArrayOfStructIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.BYTE));
type.addField(new Field("my_double", DataType.DOUBLE));
@@ -113,18 +113,18 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.URI));
assertFlat(new Field("foo", DataType.getArray(DataType.getArray(type))),
- new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
- new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
- new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
- new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
- new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
- new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
- new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
- new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
+ new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
+ new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
+ new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
+ new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
+ new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
+ new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
+ new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
+ new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
}
@Test
- public void requireThatStructWithArrayFieldIsFlattened() {
+ void requireThatStructWithArrayFieldIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.getArray(DataType.BYTE)));
type.addField(new Field("my_double", DataType.getArray(DataType.DOUBLE)));
@@ -136,18 +136,18 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.getArray(DataType.URI)));
assertFlat(new Field("foo", type),
- new Field("foo.my_byte", DataType.getArray(DataType.BYTE)),
- new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)),
- new Field("foo.my_float", DataType.getArray(DataType.FLOAT)),
- new Field("foo.my_int", DataType.getArray(DataType.INT)),
- new Field("foo.my_long", DataType.getArray(DataType.LONG)),
- new Field("foo.my_raw", DataType.getArray(DataType.RAW)),
- new Field("foo.my_string", DataType.getArray(DataType.STRING)),
- new Field("foo.my_uri", DataType.getArray(DataType.URI)));
+ new Field("foo.my_byte", DataType.getArray(DataType.BYTE)),
+ new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)),
+ new Field("foo.my_float", DataType.getArray(DataType.FLOAT)),
+ new Field("foo.my_int", DataType.getArray(DataType.INT)),
+ new Field("foo.my_long", DataType.getArray(DataType.LONG)),
+ new Field("foo.my_raw", DataType.getArray(DataType.RAW)),
+ new Field("foo.my_string", DataType.getArray(DataType.STRING)),
+ new Field("foo.my_uri", DataType.getArray(DataType.URI)));
}
@Test
- public void requireThatStructWithArrayOfArrayFieldIsFlattened() {
+ void requireThatStructWithArrayOfArrayFieldIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))));
type.addField(new Field("my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))));
@@ -159,18 +159,18 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
assertFlat(new Field("foo", type),
- new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
- new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
- new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
- new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
- new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
- new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
- new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
- new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
+ new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
+ new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
+ new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
+ new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
+ new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
+ new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
+ new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
+ new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
}
@Test
- public void requireThatArrayOfStructWithArrayFieldIsFlattened() {
+ void requireThatArrayOfStructWithArrayFieldIsFlattened() {
StructDataType type = new StructDataType("my_struct");
type.addField(new Field("my_byte", DataType.getArray(DataType.BYTE)));
type.addField(new Field("my_double", DataType.getArray(DataType.DOUBLE)));
@@ -182,14 +182,14 @@ public class IndexSchemaTestCase {
type.addField(new Field("my_uri", DataType.getArray(DataType.URI)));
assertFlat(new Field("foo", DataType.getArray(type)),
- new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
- new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
- new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
- new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
- new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
- new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
- new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
- new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
+ new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))),
+ new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))),
+ new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))),
+ new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))),
+ new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))),
+ new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))),
+ new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))),
+ new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI))));
}
private static void assertFlat(Field fieldToFlatten, Field... expectedFields) {
@@ -202,7 +202,7 @@ public class IndexSchemaTestCase {
fail("Unexpected field: " + field);
}
}
- assertTrue("Missing fields: " + expected, expected.isEmpty());
+ assertTrue(expected.isEmpty(), "Missing fields: " + expected);
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java
index 1c433237fd8..66833233341 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java
@@ -12,19 +12,15 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.configmodel.producers.DocumentManager;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
-import org.junit.rules.TemporaryFolder;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests inheritance
@@ -33,11 +29,11 @@ import static org.junit.Assert.assertNull;
*/
public class InheritanceTestCase extends AbstractExportingTestCase {
- @Rule
- public TemporaryFolder tmpDir = new TemporaryFolder();
+ @TempDir
+ public File tmpDir;
@Test
- public void requireThatIndexedStructFieldCanBeInherited() throws IOException, ParseException {
+ void requireThatIndexedStructFieldCanBeInherited() throws IOException, ParseException {
String dir = "src/test/derived/inheritstruct/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "parent.sd");
@@ -48,7 +44,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void requireThatInheritFromNullIsCaught() throws IOException, ParseException {
+ void requireThatInheritFromNullIsCaught() throws IOException, ParseException {
try {
assertCorrectDeriving("inheritfromnull");
} catch (IllegalArgumentException e) {
@@ -57,7 +53,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void requireThatStructTypesAreInheritedThroughDiamond() throws IOException, ParseException {
+ void requireThatStructTypesAreInheritedThroughDiamond() throws IOException, ParseException {
String dir = "src/test/derived/inheritdiamond/";
{
ApplicationBuilder builder = new ApplicationBuilder();
@@ -70,7 +66,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
assertCorrectConfigFiles("inheritdiamond");
}
List<String> files = Arrays.asList("grandparent.sd", "mother.sd", "father.sd", "child.sd");
- File outDir = tmpDir.newFolder("out");
+ File outDir = newFolder(tmpDir, "out");
for (int startIdx = 0; startIdx < files.size(); ++startIdx) {
var builder = new ApplicationBuilder(new TestProperties());
for (int fileIdx = startIdx; fileIdx < startIdx + files.size(); ++fileIdx) {
@@ -80,7 +76,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
builder.build(true);
DocumentmanagerConfig.Builder b = new DocumentmanagerConfig.Builder();
DerivedConfiguration.exportDocuments(new DocumentManager().
- produce(builder.getModel(), b), outDir.getPath());
+ produce(builder.getModel(), b), outDir.getPath());
DocumentmanagerConfig dc = b.build();
assertEquals(5, dc.doctype().size());
@@ -120,9 +116,9 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
return null;
}
-
+
@Test
- public void requireThatStructTypesAreInheritedFromParent() throws IOException, ParseException {
+ void requireThatStructTypesAreInheritedFromParent() throws IOException, ParseException {
String dir = "src/test/derived/inheritfromparent/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "parent.sd");
@@ -133,7 +129,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void requireThatStructTypesAreInheritedFromGrandParent() throws IOException, ParseException {
+ void requireThatStructTypesAreInheritedFromGrandParent() throws IOException, ParseException {
String dir = "src/test/derived/inheritfromgrandparent/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "grandparent.sd");
@@ -145,7 +141,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void testInheritance() throws IOException, ParseException {
+ void testInheritance() throws IOException, ParseException {
String dir = "src/test/derived/inheritance/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "grandparent.sd");
@@ -158,7 +154,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void testIndexSettingInheritance() {
+ void testIndexSettingInheritance() {
SDDocumentType parent = new SDDocumentType("parent");
Schema parentSchema = new Schema("parent", MockApplicationPackage.createEmpty());
parentSchema.addDocument(parent);
@@ -171,13 +167,13 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
Schema childSchema = new Schema("child", MockApplicationPackage.createEmpty());
childSchema.addDocument(child);
- prefixed = (SDField)child.getField("prefixed");
+ prefixed = (SDField) child.getField("prefixed");
assertNotNull(prefixed);
assertEquals(new Index("prefixed", true), childSchema.getIndex("prefixed"));
}
@Test
- public void testInheritStructDiamondNew() throws IOException, ParseException {
+ void testInheritStructDiamondNew() throws IOException, ParseException {
String dir = "src/test/derived/declstruct/";
List<String> files = Arrays.asList("common.sd", "foo.sd", "bar.sd", "foobar.sd");
var builder = new ApplicationBuilder(new TestProperties());
@@ -189,4 +185,13 @@ public class InheritanceTestCase extends AbstractExportingTestCase {
assertCorrectConfigFiles("declstruct");
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java
index b5f222673ab..8a77bd714fd 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -11,7 +11,7 @@ import java.io.IOException;
*/
public class IntegerAttributeToStringIndexTestCase extends AbstractExportingTestCase {
@Test
- public void testIt() throws IOException, ParseException {
+ void testIt() throws IOException, ParseException {
assertCorrectDeriving("integerattributetostringindex");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java
index c5090c88a1b..c32f5f2b3a4 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java
@@ -13,13 +13,13 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.processing.Processing;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -30,7 +30,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
* Tests adding of literal boost constructs
*/
@Test
- public void testLiteralBoost() {
+ void testLiteralBoost() {
Schema schema = new Schema("literalboost", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType document = new SDDocumentType("literalboost");
@@ -43,7 +43,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
other.addRankSetting(new RankProfile.RankSetting("a", RankProfile.RankSetting.Type.LITERALBOOST, 333));
new Processing().process(schema, new BaseDeployLogger(), rankProfileRegistry, new QueryProfiles(),
- true, false, Set.of());
+ true, false, Set.of());
DerivedConfiguration derived = new DerivedConfiguration(schema, rankProfileRegistry);
// Check attribute fields
@@ -51,8 +51,8 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
// Check il script addition
assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }",
- "clear_state | guard { input a | tokenize | index a_literal; }"),
- schema);
+ "clear_state | guard { input a | tokenize | index a_literal; }"),
+ schema);
// Check index info addition
IndexInfo indexInfo = derived.getIndexInfo();
@@ -63,7 +63,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
* Tests adding a literal boost in a non-default rank profile only
*/
@Test
- public void testNonDefaultRankLiteralBoost() {
+ void testNonDefaultRankLiteralBoost() {
Schema schema = new Schema("literalboost", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType document = new SDDocumentType("literalboost");
@@ -79,17 +79,17 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
// Check il script addition
assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }",
- "clear_state | guard { input a | tokenize | index a_literal; }"),
- schema);
+ "clear_state | guard { input a | tokenize | index a_literal; }"),
+ schema);
// Check index info addition
IndexInfo indexInfo = derived.getIndexInfo();
- assertTrue(indexInfo.hasCommand("a","literal-boost"));
+ assertTrue(indexInfo.hasCommand("a", "literal-boost"));
}
/** Tests literal boosts in two fields going to the same index */
@Test
- public void testTwoLiteralBoostFields() {
+ void testTwoLiteralBoostFields() {
Schema schema = new Schema("msb", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType document = new SDDocumentType("msb");
@@ -104,10 +104,10 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase {
schema = ApplicationBuilder.buildFromRawSchema(schema, rankProfileRegistry, new QueryProfileRegistry());
new DerivedConfiguration(schema, rankProfileRegistry);
assertIndexing(Arrays.asList("clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }",
- "clear_state | guard { input body | tokenize normalize stem:\"BEST\" | summary body | index body; }",
- "clear_state | guard { input title | tokenize | index title_literal; }",
- "clear_state | guard { input body | tokenize | index body_literal; }"),
- schema);
+ "clear_state | guard { input body | tokenize normalize stem:\"BEST\" | summary body | index body; }",
+ "clear_state | guard { input title | tokenize | index title_literal; }",
+ "clear_state | guard { input body | tokenize | index body_literal; }"),
+ schema);
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java
index f234a9cc324..198de997f94 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,7 +12,7 @@ import java.io.IOException;
public class LowercaseTestCase extends AbstractExportingTestCase {
@Test
- public void testDeriving() throws IOException, ParseException {
+ void testDeriving() throws IOException, ParseException {
assertCorrectDeriving("lowercase");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java
index c48c44554ed..48aca401694 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java
@@ -3,7 +3,8 @@ package com.yahoo.schema.derived;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.io.IOException;
/**
@@ -14,7 +15,7 @@ import java.io.IOException;
public class MailTestCase extends AbstractExportingTestCase {
@Test
- public void testMail() throws IOException, ParseException {
+ void testMail() throws IOException, ParseException {
String dir = "src/test/derived/mail/";
ApplicationBuilder sb = new ApplicationBuilder();
sb.addSchemaFile(dir + "mail.sd");
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java
index a7df862134a..ea79766ed8a 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -13,49 +13,49 @@ import java.io.IOException;
public class MatchSettingsResolvingTestCase extends AbstractExportingTestCase {
@Test
- public void testSimpleDefaults() throws IOException, ParseException {
+ void testSimpleDefaults() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_simple_def", new TestProperties());
}
@Test
- public void testSimpleWithStructSettings() throws IOException, ParseException {
+ void testSimpleWithStructSettings() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_simple_wss",
- new TestProperties());
+ new TestProperties());
}
@Test
- public void testSimpleWithFieldSettings() throws IOException, ParseException {
+ void testSimpleWithFieldSettings() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_simple_wfs", new TestProperties());
}
@Test
- public void testSimpleStructAndFieldSettings() throws IOException, ParseException {
+ void testSimpleStructAndFieldSettings() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_simple_wss_wfs", new TestProperties());
}
@Test
- public void testMapDefaults() throws IOException, ParseException {
+ void testMapDefaults() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_map_def", new TestProperties());
}
@Test
- public void testMapWithStructSettings() throws IOException, ParseException {
+ void testMapWithStructSettings() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_map_wss", new TestProperties());
}
@Test
- public void testMapWithFieldSettings() throws IOException, ParseException {
+ void testMapWithFieldSettings() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_map_wfs", new TestProperties());
}
@Test
- public void testMapAfter() throws IOException, ParseException {
+ void testMapAfter() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_map_after", new TestProperties());
}
@Test
- public void testMapInStruct() throws IOException, ParseException {
+ void testMapInStruct() throws IOException, ParseException {
assertCorrectDeriving("matchsettings_map_in_struct", new TestProperties());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java
index 66b3698b38c..7276a5be445 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.application.provider.MockFileRegistry;
import com.yahoo.schema.ApplicationBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests deriving a configuration with structs in multiple .sd files
@@ -14,11 +14,11 @@ import org.junit.Test;
public class MultiStructTestCase extends AbstractExportingTestCase {
@Test
- public void testDocTypeConfigs() throws Exception {
+ void testDocTypeConfigs() throws Exception {
var logger = new TestableDeployLogger();
var props = new TestProperties();
ApplicationBuilder builder = ApplicationBuilder.createFromDirectory
- ("src/test/derived/multi_struct/", new MockFileRegistry(), logger, props);
+ ("src/test/derived/multi_struct/", new MockFileRegistry(), logger, props);
derive("multi_struct", builder, builder.getSchema("shop"));
assertCorrectConfigFiles("multi_struct");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java
index d434673e43a..8642c45f16d 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,7 +15,7 @@ import java.io.IOException;
public class MultipleSummariesTestCase extends AbstractExportingTestCase {
@Test
- public void testMultipleSummariesNew() throws IOException, ParseException {
+ void testMultipleSummariesNew() throws IOException, ParseException {
assertCorrectDeriving("multiplesummaries", new TestProperties());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java
index 689ff9814cc..260dc9e4fdd 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java
@@ -5,8 +5,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.document.DocumentTypeManager;
-import org.junit.Test;
-import static org.junit.Assert.assertThrows;
+import org.junit.jupiter.api.Test;
/**
* Verifies that a struct in a document type is preferred over another document type
@@ -17,10 +16,10 @@ import static org.junit.Assert.assertThrows;
public class NameCollisionTestCase extends AbstractExportingTestCase {
@Test
- public void testNameCollision() throws Exception {
+ void testNameCollision() throws Exception {
assertCorrectDeriving("namecollision", "collisionstruct",
- new TestProperties(),
- new TestableDeployLogger());
+ new TestProperties(),
+ new TestableDeployLogger());
DocumentTypeManager.fromFile("temp/namecollision/documentmanager.cfg");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java
index f628420556a..c51567b6629 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.schema.derived;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.RankType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Testing stuff related to native rank type definitions
@@ -16,15 +16,16 @@ import static org.junit.Assert.*;
*/
public class NativeRankTypeDefinitionsTestCase extends AbstractSchemaTestCase {
@Test
- public void testTables() {
+ void testTables() {
assertEquals(NativeTable.Type.FIRST_OCCURRENCE.getName(), "firstOccurrenceTable");
assertEquals(NativeTable.Type.OCCURRENCE_COUNT.getName(), "occurrenceCountTable");
assertEquals(NativeTable.Type.PROXIMITY.getName(), "proximityTable");
assertEquals(NativeTable.Type.REVERSE_PROXIMITY.getName(), "reverseProximityTable");
assertEquals(NativeTable.Type.WEIGHT.getName(), "weightTable");
}
+
@Test
- public void testDefinitions() {
+ void testDefinitions() {
NativeRankTypeDefinitionSet defs = new NativeRankTypeDefinitionSet("default");
NativeRankTypeDefinition rank;
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java
index 2f3ad7cfc69..b3a0b8d4558 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java
@@ -6,24 +6,25 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class NearestNeighborTestCase extends AbstractExportingTestCase {
@Test
- public void testNearestNeighbor() throws IOException, ParseException {
+ void testNearestNeighbor() throws IOException, ParseException {
try {
ComponentId.resetGlobalCountersForTests();
DerivedConfiguration c = assertCorrectDeriving("nearestneighbor");
- CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {}).getConfig());
+ CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {
+ }).getConfig());
Query q = new Query("?ranking.features.query(q_vec)=[1,2,3,4,5,6]", // length is 6, not 5
- queryProfiles.getComponent("default"));
+ queryProfiles.getComponent("default"));
fail("This should fail when q_vec is parsed as a tensor");
} catch (IllegalArgumentException e) {
// success
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java
index 56248c02a51..18dddff3984 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java
@@ -6,27 +6,28 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import com.yahoo.component.ComponentId;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NeuralNetTestCase extends AbstractExportingTestCase {
@Test
- public void testNeuralNet() throws IOException, ParseException {
+ void testNeuralNet() throws IOException, ParseException {
ComponentId.resetGlobalCountersForTests();
DerivedConfiguration c = assertCorrectDeriving("neuralnet");
// Verify that query profiles end up correct when passed through the same intermediate forms as a full system
- CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {}).getConfig());
+ CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {
+ }).getConfig());
assertNeuralNetQuery(c, queryProfiles.getComponent("default"));
}
@Test
- public void testNeuralNet_noQueryProfiles() throws IOException, ParseException {
+ void testNeuralNet_noQueryProfiles() throws IOException, ParseException {
ComponentId.resetGlobalCountersForTests();
DerivedConfiguration c = assertCorrectDeriving("neuralnet_noqueryprofile");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java
index 210c8a9bdd4..4f30169713a 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java
@@ -2,8 +2,8 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,8 +15,8 @@ import java.io.IOException;
public class NuwaTestCase extends AbstractExportingTestCase {
@Test
- @Ignore
- public void testNuwa() throws IOException, ParseException {
+ @Disabled
+ void testNuwa() throws IOException, ParseException {
System.gc();
long freeBytesBefore = Runtime.getRuntime().freeMemory();
long totalBytesBefore = Runtime.getRuntime().totalMemory();
@@ -27,7 +27,7 @@ public class NuwaTestCase extends AbstractExportingTestCase {
long freeBytesAfter = Runtime.getRuntime().freeMemory();
long totalBytesAfter = Runtime.getRuntime().totalMemory();
long additionalAllocated = totalBytesAfter - totalBytesBefore;
- System.out.println("Consumed " + ((freeBytesBefore - (freeBytesAfter - additionalAllocated) ) / 1000000) + " Mb");
+ System.out.println("Consumed " + ((freeBytesBefore - (freeBytesAfter - additionalAllocated)) / 1000000) + " Mb");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java
index 8af0d0a21d3..741f1fd7e02 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,7 +12,7 @@ import java.io.IOException;
public class OrderIlscriptsTestCase extends AbstractExportingTestCase {
@Test
- public void testOrderIlscripts() throws IOException, ParseException {
+ void testOrderIlscripts() throws IOException, ParseException {
assertCorrectDeriving("orderilscripts");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java
index fdcb71432e4..7faea410da2 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.io.IOException;
public class PrefixExactAttributeTestCase extends AbstractExportingTestCase {
@Test
- public void testTypes() throws IOException, ParseException {
+ void testTypes() throws IOException, ParseException {
assertCorrectDeriving("prefixexactattribute");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java
index a83db0caf5a..5c24b32e275 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.io.IOException;
*/
public class RankProfilesTestCase extends AbstractExportingTestCase {
@Test
- public void testRankProfiles() throws IOException, ParseException {
+ void testRankProfiles() throws IOException, ParseException {
assertCorrectDeriving("rankprofiles", null, new TestProperties(), new TestableDeployLogger());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java
index 8db880e56fe..c46cd5e53c6 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,7 +12,7 @@ import java.io.IOException;
public class RankPropertiesTestCase extends AbstractExportingTestCase {
@Test
- public void testRankProperties() throws IOException, ParseException {
+ void testRankProperties() throws IOException, ParseException {
assertCorrectDeriving("rankproperties");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java
index 99d0cf8bf6d..2d9487d4a5e 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,7 +12,7 @@ import java.io.IOException;
public class ReferenceFieldsTestCase extends AbstractExportingTestCase {
@Test
- public void configs_related_to_reference_fields_are_derived() throws IOException, ParseException {
+ void configs_related_to_reference_fields_are_derived() throws IOException, ParseException {
assertCorrectDeriving("reference_fields", "ad", new TestableDeployLogger());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java
index ff4506a7f57..caa5bf1b4a9 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.application.provider.MockFileRegistry;
import com.yahoo.schema.ApplicationBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests deriving a configuration with references from multiple .sd files
@@ -14,11 +14,11 @@ import org.junit.Test;
public class ReferenceFromSeveralTestCase extends AbstractExportingTestCase {
@Test
- public void testDocManConfigs() throws Exception {
+ void testDocManConfigs() throws Exception {
var logger = new TestableDeployLogger();
var props = new TestProperties();
ApplicationBuilder builder = ApplicationBuilder.createFromDirectory
- ("src/test/derived/reference_from_several/", new MockFileRegistry(), logger, props);
+ ("src/test/derived/reference_from_several/", new MockFileRegistry(), logger, props);
derive("reference_from_several", builder, builder.getSchema("foo"));
assertCorrectConfigFiles("reference_from_several");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java
index 1b5d55158b5..f115f69cc8f 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java
@@ -6,7 +6,7 @@ import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.io.IOUtils;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -17,12 +17,12 @@ import java.io.IOException;
public class SchemaInheritanceTestCase extends AbstractExportingTestCase {
@Test
- public void testIt() throws IOException, ParseException {
+ void testIt() throws IOException, ParseException {
try {
ApplicationBuilder builder = ApplicationBuilder.createFromDirectory("src/test/derived/schemainheritance/",
- new MockFileRegistry(),
- new TestableDeployLogger(),
- new TestProperties());
+ new MockFileRegistry(),
+ new TestableDeployLogger(),
+ new TestProperties());
derive("schemainheritance", builder, builder.getSchema("child"));
assertCorrectConfigFiles("schemainheritance");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java
index 4683bccb0ad..16001d3912d 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.TemporarySDField;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -20,7 +20,7 @@ import java.util.Objects;
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -102,45 +102,45 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase {
@Test
- public void testPerfectOrderingIsKept() {
+ void testPerfectOrderingIsKept() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone"));
+ Arrays.asList("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone"));
}
@Test
- public void testOneLevelReordering() {
+ void testOneLevelReordering() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone"));
+ Arrays.asList("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone"));
}
@Test
- public void testMultiLevelReordering() {
+ void testMultiLevelReordering() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone"));
+ Arrays.asList("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone"));
}
@Test
- public void testAloneIsKeptInPlaceWithMultiLevelReordering() {
+ void testAloneIsKeptInPlaceWithMultiLevelReordering() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product"));
+ Arrays.asList("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product"));
}
@Test
- public void testPartialMultiLevelReordering() {
+ void testPartialMultiLevelReordering() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone"));
+ Arrays.asList("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone"));
}
@Test
- public void testMultilevelReorderingAccrossHierarchies() {
+ void testMultilevelReorderingAccrossHierarchies() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"),
- Arrays.asList("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone"));
+ Arrays.asList("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone"));
}
@Test
- public void referees_are_ordered_before_referrer() {
+ void referees_are_ordered_before_referrer() {
assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "accessory-pc", "son"),
- Arrays.asList("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone"));
+ Arrays.asList("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone"));
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java
index d8b39bfd978..e5b95e8a6ca 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.schema.derived;
import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -15,7 +15,7 @@ import java.io.IOException;
public class SimpleInheritTestCase extends AbstractExportingTestCase {
@Test
- public void testEmptyChild() throws IOException, ParseException {
+ void testEmptyChild() throws IOException, ParseException {
String name = "emptychild";
final String expectedResultsDirName = "src/test/derived/" + name + "/";
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java
index 2aad47dae6c..9ef664bd287 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java
@@ -3,19 +3,17 @@ package com.yahoo.schema.derived;
import com.yahoo.component.ComponentId;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-
/**
* @author bratseth
*/
public class SliceTestCase extends AbstractExportingTestCase {
@Test
- public void testSlice() throws IOException, ParseException {
+ void testSlice() throws IOException, ParseException {
ComponentId.resetGlobalCountersForTests();
DerivedConfiguration c = assertCorrectDeriving("slice");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java
index 0c091a7a367..a4590075a79 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,7 +15,7 @@ import java.io.IOException;
public class SortingTestCase extends AbstractExportingTestCase {
@Test
- public void testDocumentDerivingNewParser() throws IOException, ParseException {
+ void testDocumentDerivingNewParser() throws IOException, ParseException {
assertCorrectDeriving("sorting", new TestProperties());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java
index 6f27930e239..1524801bad7 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,12 +14,12 @@ import java.io.IOException;
public class StreamingStructTestCase extends AbstractExportingTestCase {
@Test
- public void testStreamingStruct() throws IOException, ParseException {
+ void testStreamingStruct() throws IOException, ParseException {
assertCorrectDeriving("streamingstruct");
}
@Test
- public void testStreamingStructExplicitDefaultSummaryClass() throws IOException, ParseException {
+ void testStreamingStructExplicitDefaultSummaryClass() throws IOException, ParseException {
assertCorrectDeriving("streamingstructdefault");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java
index 865b5da87cf..9a1bba88cc6 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -11,7 +11,7 @@ import java.io.IOException;
*/
public class StructAnyOrderTestCase extends AbstractExportingTestCase {
@Test
- public void testStructAnyOrder() throws IOException, ParseException {
+ void testStructAnyOrder() throws IOException, ParseException {
assertCorrectDeriving("structanyorder");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java
index 092e64420e8..60be9dc9016 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java
@@ -5,14 +5,14 @@ package com.yahoo.schema.derived;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
-
-import org.junit.rules.TemporaryFolder;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests struct inheritance
@@ -21,15 +21,11 @@ import org.junit.rules.TemporaryFolder;
*/
public class StructInheritanceTestCase extends AbstractExportingTestCase {
- @Rule
- public TemporaryFolder tmpDir = new TemporaryFolder();
-
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
+ @TempDir
+ public File tmpDir;
@Test
- public void requireThatStructCanInherit() throws IOException, ParseException {
+ void requireThatStructCanInherit() throws IOException, ParseException {
String dir = "src/test/derived/structinheritance/";
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchemaFile(dir + "simple.sd");
@@ -39,14 +35,15 @@ public class StructInheritanceTestCase extends AbstractExportingTestCase {
}
@Test
- public void requireThatRedeclareIsNotAllowed() throws IOException, ParseException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("cannot inherit from base and redeclare field name");
- String dir = "src/test/derived/structinheritance/";
- ApplicationBuilder builder = new ApplicationBuilder();
- builder.addSchemaFile(dir + "bad.sd");
- builder.build(true);
- derive("structinheritance", builder, builder.getSchema("bad"));
+ void requireThatRedeclareIsNotAllowed() throws IOException, ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ String dir = "src/test/derived/structinheritance/";
+ ApplicationBuilder builder = new ApplicationBuilder();
+ builder.addSchemaFile(dir + "bad.sd");
+ builder.build(true);
+ derive("structinheritance", builder, builder.getSchema("bad"));
+ });
+ assertTrue(exception.getMessage().contains("cannot inherit from base and redeclare field name"));
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java
index f0fc58b97e5..577bcf6efcc 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java
@@ -12,16 +12,15 @@ import com.yahoo.schema.parser.ParseException;
import com.yahoo.schema.processing.Processing;
import com.yahoo.vespa.documentmodel.SummaryTransform;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Tests summary map extraction
*
@@ -29,7 +28,7 @@ import static org.junit.Assert.assertTrue;
*/
public class SummaryMapTestCase extends AbstractSchemaTestCase {
@Test
- public void testDeriving() throws IOException, ParseException {
+ void testDeriving() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd");
SummaryMap summaryMap = new SummaryMap(schema);
@@ -70,10 +69,15 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
assertEquals("access", transform.getFieldName());
assertEquals(SummaryTransform.ATTRIBUTE, transform.getTransform());
+ transform = transforms.next();
+ assertEquals("documentid", transform.getFieldName());
+ assertEquals(SummaryTransform.DOCUMENT_ID, transform.getTransform());
+
assertFalse(transforms.hasNext());
}
+
@Test
- public void testPositionDeriving() {
+ void testPositionDeriving() {
Schema schema = new Schema("store", MockApplicationPackage.createEmpty());
SDDocumentType document = new SDDocumentType("store");
schema.addDocument(document);
@@ -81,7 +85,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
SDField field = document.addField(fieldName, PositionDataType.INSTANCE);
field.parseIndexingScript("{ attribute | summary }");
new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(),
- true, false, Set.of());
+ true, false, Set.of());
SummaryMap summaryMap = new SummaryMap(schema);
Iterator<FieldResultTransform> transforms = summaryMap.resultTransforms().values().iterator();
@@ -101,16 +105,20 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
transform = transforms.next();
assertEquals("location_zcurve", transform.getFieldName());
- assertEquals(SummaryTransform.ATTRIBUTE,transform.getTransform());
+ assertEquals(SummaryTransform.ATTRIBUTE, transform.getTransform());
+
+ transform = transforms.next();
+ assertEquals("documentid", transform.getFieldName());
+ assertEquals(SummaryTransform.DOCUMENT_ID, transform.getTransform());
assertFalse(transforms.hasNext());
SummarymapConfig.Builder scb = new SummarymapConfig.Builder();
summaryMap.getConfig(scb);
SummarymapConfig c = scb.build();
-
+
assertEquals(-1, c.defaultoutputclass());
- assertEquals(c.override().size(), 4);
+ assertEquals(c.override().size(), 5);
assertEquals(c.override(0).field(), fieldName);
assertEquals(c.override(0).command(), "geopos");
@@ -119,7 +127,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
assertEquals(c.override(1).field(), "rankfeatures");
assertEquals(c.override(1).command(), "rankfeatures");
assertEquals(c.override(1).arguments(), "");
-
+
assertEquals(c.override(2).field(), "summaryfeatures");
assertEquals(c.override(2).command(), "summaryfeatures");
assertEquals(c.override(2).arguments(), "");
@@ -130,7 +138,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testFailOnSummaryFieldSourceCollision() {
+ void testFailOnSummaryFieldSourceCollision() {
try {
ApplicationBuilder.buildFromFile("src/test/examples/summaryfieldcollision.sd");
} catch (Exception e) {
@@ -139,7 +147,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
}
@Test
- public void source_field_is_passed_as_argument_in_matched_elements_filter_transforms() throws ParseException {
+ void source_field_is_passed_as_argument_in_matched_elements_filter_transforms() throws ParseException {
assertOverride(joinLines("field my_field type map<string, string> {",
" indexing: summary",
" summary: matched-elements-only",
@@ -155,30 +163,49 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase {
}
@Test
- public void commands_that_are_dynamic_and_require_the_query() {
+ void commands_that_are_dynamic_and_require_the_query() {
assertTrue(SummaryMap.isDynamicCommand("dynamicteaser"));
assertTrue(SummaryMap.isDynamicCommand(SummaryTransform.MATCHED_ELEMENTS_FILTER.getName()));
assertTrue(SummaryMap.isDynamicCommand(SummaryTransform.MATCHED_ATTRIBUTE_ELEMENTS_FILTER.getName()));
assertFalse(SummaryMap.isDynamicCommand(SummaryTransform.ATTRIBUTE.getName()));
}
+ @Test
+ void documentid_summary_field_has_corresponding_summary_transform() throws ParseException {
+ var schema = buildSchema("field foo type string { indexing: summary }",
+ joinLines("document-summary bar {",
+ " summary documentid type string {}",
+ "}"));
+ assertOverride(schema, "documentid", SummaryTransform.DOCUMENT_ID.getName(), "");
+ }
+
+ @Test
+ void documentid_summary_transform_requires_disk_access() {
+ assertFalse(SummaryTransform.DOCUMENT_ID.isInMemory());
+ }
+
private void assertOverride(String fieldContent, String expFieldName, String expCommand) throws ParseException {
- var summaryMap = new SummaryMap(buildSearch(fieldContent));
+ assertOverride(buildSchema(fieldContent, ""), expFieldName, expCommand, expFieldName);
+ }
+
+ private void assertOverride(Schema schema, String expFieldName, String expCommand, String expArguments) throws ParseException {
+ var summaryMap = new SummaryMap(schema);
var cfgBuilder = new SummarymapConfig.Builder();
summaryMap.getConfig(cfgBuilder);
var cfg = new SummarymapConfig(cfgBuilder);
var override = cfg.override(0);
assertEquals(expFieldName, override.field());
assertEquals(expCommand, override.command());
- assertEquals(expFieldName, override.arguments());
+ assertEquals(expArguments, override.arguments());
}
- private Schema buildSearch(String field) throws ParseException {
+ private Schema buildSchema(String field, String documentSummary) throws ParseException {
var builder = new ApplicationBuilder(new RankProfileRegistry());
builder.addSchema(joinLines("search test {",
" document test {",
field,
" }",
+ documentSummary,
"}"));
builder.build(true);
return builder.getSchema();
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java
index 73713319cfe..a9a230c94a2 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java
@@ -7,15 +7,14 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.config.search.SummaryConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Iterator;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests summary extraction
@@ -25,7 +24,7 @@ import static org.junit.Assert.assertTrue;
public class SummaryTestCase extends AbstractSchemaTestCase {
@Test
- public void deriveRawAsBase64() throws ParseException {
+ void deriveRawAsBase64() throws ParseException {
String sd = joinLines(
"schema s {",
" document s {",
@@ -40,7 +39,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase {
}
@Test
- public void deriveRawAsLegacy() throws ParseException {
+ void deriveRawAsLegacy() throws ParseException {
String sd = joinLines(
"schema s {",
" raw-as-base64-in-summary: false",
@@ -56,7 +55,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testDeriving() throws IOException, ParseException {
+ void testDeriving() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd");
SummaryClass summary = new SummaryClass(schema, schema.getSummary("default"), new BaseDeployLogger());
assertEquals("default", summary.getName());
@@ -121,7 +120,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase {
}
@Test
- public void reference_fields_can_be_part_of_summary_classes() throws ParseException {
+ void reference_fields_can_be_part_of_summary_classes() throws ParseException {
Schema adSchema = buildCampaignAdModel();
SummaryClass defaultClass = new SummaryClass(adSchema, adSchema.getSummary("default"), new BaseDeployLogger());
@@ -154,7 +153,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase {
}
@Test
- public void omit_summary_features_specified_for_document_summary() throws ParseException {
+ void omit_summary_features_specified_for_document_summary() throws ParseException {
String sd = joinLines(
"schema test {",
" document test {",
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java
index ac6acf172e9..c8a2279a407 100755
--- a/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,7 +12,7 @@ import java.io.IOException;
public class TokenizationTestCase extends AbstractExportingTestCase {
@Test
- public void testTokenizationScripts() throws IOException, ParseException {
+ void testTokenizationScripts() throws IOException, ParseException {
assertCorrectDeriving("tokenization");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java
index 72411fa1770..5db9a00ce69 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.schema.derived;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,7 +15,7 @@ import java.io.IOException;
public class TwoStreamingStructsTestCase extends AbstractExportingTestCase {
@Test
- public void testTwoStreamingStructsExporting() throws ParseException, IOException {
+ void testTwoStreamingStructsExporting() throws ParseException, IOException {
String root = "src/test/derived/twostreamingstructs";
ApplicationBuilder builder = new ApplicationBuilder();
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java
index 84a561924ca..fd9f2164b86 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java
@@ -11,11 +11,12 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.processing.Processing;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
/**
* Tests automatic type conversion using multifield indices
*
@@ -25,7 +26,7 @@ public class TypeConversionTestCase extends AbstractSchemaTestCase {
/** Tests that exact-string stuff is not spilled over to the default index */
@Test
- public void testExactStringToStringTypeConversion() {
+ void testExactStringToStringTypeConversion() {
Schema schema = new Schema("test", MockApplicationPackage.createEmpty());
RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema);
SDDocumentType document = new SDDocumentType("test");
@@ -35,7 +36,7 @@ public class TypeConversionTestCase extends AbstractSchemaTestCase {
document.addField(a);
new Processing().process(schema, new BaseDeployLogger(), rankProfileRegistry, new QueryProfiles(),
- true, false, Set.of());
+ true, false, Set.of());
DerivedConfiguration derived = new DerivedConfiguration(schema, rankProfileRegistry);
IndexInfo indexInfo = derived.getIndexInfo();
assertFalse(indexInfo.hasCommand("default", "compact-to-term"));
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java
index 7443ef01c95..348d156a5f9 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.derived;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.io.IOException;
public class TypesTestCase extends AbstractExportingTestCase {
@Test
- public void testTypes() throws IOException, ParseException {
+ void testTypes() throws IOException, ParseException {
assertCorrectDeriving("types");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java
index c59f82a2c12..4b478d7da35 100644
--- a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java
@@ -10,9 +10,9 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.TemporarySDField;
import com.yahoo.vespa.config.search.vsm.VsmfieldsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -21,7 +21,7 @@ public class VsmFieldsTestCase {
@SuppressWarnings("deprecation")
@Test
- public void reference_type_field_is_unsearchable() {
+ void reference_type_field_is_unsearchable() {
Schema schema = new Schema("test", MockApplicationPackage.createEmpty(), new MockFileRegistry(), new TestableDeployLogger(), new TestProperties());
var sdoc = new SDDocumentType("test");
schema.addDocument(sdoc);
diff --git a/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java b/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java
index ea3f207df91..7a89f52268f 100644
--- a/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.schema.document;
import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ComplexAttributeFieldUtilsTestCase {
@@ -77,7 +77,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void array_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void array_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
Fixture f = new Fixture("elem_array",
joinLines("field elem_array type array<elem> {",
" indexing: summary",
@@ -90,7 +90,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void array_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void array_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
Fixture f = new Fixture("elem_array",
joinLines("field elem_array type array<elem> {",
" indexing: summary",
@@ -102,7 +102,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void map_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void map_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
Fixture f = new Fixture("elem_map",
joinLines("field elem_map type map<string, elem> {",
" indexing: summary",
@@ -117,7 +117,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void map_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void map_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
{
Fixture f = new Fixture("elem_map",
joinLines("field elem_map type map<int, elem> {",
@@ -145,7 +145,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void map_of_primitive_type_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void map_of_primitive_type_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException {
Fixture f = new Fixture("str_map",
joinLines("field str_map type map<string, string> {",
" indexing: summary",
@@ -159,7 +159,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void map_of_primitive_type_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
+ void map_of_primitive_type_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException {
{
Fixture f = new Fixture("int_map",
joinLines("field int_map type map<int, int> {",
@@ -185,7 +185,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void unsupported_complex_field_is_tagged_as_such() throws ParseException {
+ void unsupported_complex_field_is_tagged_as_such() throws ParseException {
{
ComplexFixture f = new ComplexFixture("elem_array",
joinLines("field elem_array type array<elem> {",
@@ -214,7 +214,7 @@ public class ComplexAttributeFieldUtilsTestCase {
}
@Test
- public void only_struct_field_attributes_are_considered_when_tagging_a_complex_field() throws ParseException {
+ void only_struct_field_attributes_are_considered_when_tagging_a_complex_field() throws ParseException {
{
ComplexFixture f = new ComplexFixture("elem_array",
joinLines("field elem_array type array<elem> {",
diff --git a/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java b/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java
index 8ef51369ecb..51affaa0cc4 100644
--- a/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java
@@ -3,7 +3,7 @@
package com.yahoo.schema.document;
import java.util.Optional;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -11,7 +11,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class HnswIndexParamsTestCase {
@Test
- public void override_from() throws Exception {
+ void override_from() throws Exception {
var empty = new HnswIndexParams();
var builder = new HnswIndexParams.Builder();
builder.setMaxLinksPerNode(7);
diff --git a/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java
index 516c259013f..8f9f8032054 100644
--- a/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.schema.parser;
import com.yahoo.document.DocumentTypeManager;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertThrows;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author arnej
@@ -15,12 +15,12 @@ import static org.junit.Assert.assertThrows;
public class ConvertIntermediateTestCase {
@Test
- public void can_convert_minimal_schema() throws Exception {
+ void can_convert_minimal_schema() throws Exception {
String input = joinLines
- ("schema foo {",
- " document foo {",
- " }",
- "}");
+ ("schema foo {",
+ " document foo {",
+ " }",
+ "}");
var collection = new IntermediateCollection();
ParsedSchema schema = collection.addSchemaFromString(input);
assertEquals("foo", schema.getDocument().name());
@@ -32,7 +32,7 @@ public class ConvertIntermediateTestCase {
}
@Test
- public void can_convert_schema_files() throws Exception {
+ void can_convert_schema_files() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromFile("src/test/derived/deriver/child.sd");
collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd");
@@ -50,7 +50,7 @@ public class ConvertIntermediateTestCase {
}
@Test
- public void can_convert_structs_and_annotations() throws Exception {
+ void can_convert_structs_and_annotations() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromFile("src/test/converter/child.sd");
collection.addSchemaFromFile("src/test/converter/other.sd");
@@ -62,34 +62,34 @@ public class ConvertIntermediateTestCase {
var dt = docMan.getDocumentType("child");
assertTrue(dt != null);
for (var parent : dt.getInheritedTypes()) {
- System.err.println("dt "+dt.getName()+" inherits from "+parent.getName());
+ System.err.println("dt " + dt.getName() + " inherits from " + parent.getName());
}
for (var field : dt.fieldSetAll()) {
- System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType());
+ System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType());
}
dt = docMan.getDocumentType("parent");
assertTrue(dt != null);
for (var parent : dt.getInheritedTypes()) {
- System.err.println("dt "+dt.getName()+" inherits from "+parent.getName());
+ System.err.println("dt " + dt.getName() + " inherits from " + parent.getName());
}
for (var field : dt.fieldSetAll()) {
- System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType());
+ System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType());
}
dt = docMan.getDocumentType("grandparent");
assertTrue(dt != null);
for (var parent : dt.getInheritedTypes()) {
- System.err.println("dt "+dt.getName()+" inherits from "+parent.getName());
+ System.err.println("dt " + dt.getName() + " inherits from " + parent.getName());
}
for (var field : dt.fieldSetAll()) {
- System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType());
+ System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType());
}
dt = docMan.getDocumentType("other");
assertTrue(dt != null);
for (var parent : dt.getInheritedTypes()) {
- System.err.println("dt "+dt.getName()+" inherits from "+parent.getName());
+ System.err.println("dt " + dt.getName() + " inherits from " + parent.getName());
}
for (var field : dt.fieldSetAll()) {
- System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType());
+ System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType());
}
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java
index c4ee1d27c8c..6ebfea41d84 100644
--- a/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java
@@ -10,10 +10,9 @@ import java.io.File;
import java.io.FileReader;
import java.util.List;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertThrows;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author arnej
@@ -21,12 +20,12 @@ import static org.junit.Assert.assertThrows;
public class IntermediateCollectionTestCase {
@Test
- public void can_add_minimal_schema() throws Exception {
+ void can_add_minimal_schema() throws Exception {
String input = joinLines
- ("schema foo {",
- " document foo {",
- " }",
- "}");
+ ("schema foo {",
+ " document foo {",
+ " }",
+ "}");
var collection = new IntermediateCollection();
ParsedSchema schema = collection.addSchemaFromString(input);
assertEquals("foo", schema.name());
@@ -35,12 +34,12 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void names_may_differ() throws Exception {
+ void names_may_differ() throws Exception {
String input = joinLines
- ("schema foo_search {",
- " document foo {",
- " }",
- "}");
+ ("schema foo_search {",
+ " document foo {",
+ " }",
+ "}");
var collection = new IntermediateCollection();
ParsedSchema schema = collection.addSchemaFromString(input);
assertEquals("foo_search", schema.name());
@@ -49,7 +48,7 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void can_add_schema_files() throws Exception {
+ void can_add_schema_files() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromFile("src/test/derived/deriver/child.sd");
collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd");
@@ -75,7 +74,7 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void can_add_schemas() throws Exception {
+ void can_add_schemas() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromReader(readerOf("src/test/derived/deriver/child.sd"));
collection.addSchemaFromReader(readerOf("src/test/derived/deriver/grandparent.sd"));
@@ -101,7 +100,7 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void can_add_extra_rank_profiles() throws Exception {
+ void can_add_extra_rank_profiles() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromFile("src/test/derived/rankprofilemodularity/test.sd");
collection.addRankProfileFile("test", "src/test/derived/rankprofilemodularity/test/outside_schema1.profile");
@@ -128,32 +127,32 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void name_mismatch_throws() throws Exception {
+ void name_mismatch_throws() throws Exception {
var collection = new IntermediateCollection();
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.addSchemaFromReader(readerOf("src/test/cfg/application/sdfilenametest/schemas/notmusic.sd")));
+ collection.addSchemaFromReader(readerOf("src/test/cfg/application/sdfilenametest/schemas/notmusic.sd")));
assertEquals("The file containing schema 'music' must be named 'music.sd', was 'notmusic.sd'",
- ex.getMessage());
+ ex.getMessage());
}
@Test
- public void bad_parse_throws() throws Exception {
+ void bad_parse_throws() throws Exception {
var collection = new IntermediateCollection();
var ex = assertThrows(ParseException.class, () ->
- collection.addSchemaFromFile("src/test/examples/badparse.sd"));
+ collection.addSchemaFromFile("src/test/examples/badparse.sd"));
assertTrue(ex.getMessage().startsWith("Failed parsing schema from src/test/examples/badparse.sd: Encountered"));
ex = assertThrows(ParseException.class, () ->
- collection.addSchemaFromReader(readerOf("src/test/examples/badparse.sd")));
+ collection.addSchemaFromReader(readerOf("src/test/examples/badparse.sd")));
assertTrue(ex.getMessage().startsWith("Failed parsing schema from src/test/examples/badparse.sd: Encountered"));
collection.addSchemaFromFile("src/test/derived/rankprofilemodularity/test.sd");
collection.addRankProfileFile("test", "src/test/derived/rankprofilemodularity/test/outside_schema1.profile");
ex = assertThrows(ParseException.class, () ->
- collection.addRankProfileFile("test", "src/test/examples/badparse.sd"));
+ collection.addRankProfileFile("test", "src/test/examples/badparse.sd"));
assertTrue(ex.getMessage().startsWith("Failed parsing rank-profile from src/test/examples/badparse.sd: Encountered"));
}
@Test
- public void can_resolve_document_inheritance() throws Exception {
+ void can_resolve_document_inheritance() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromFile("src/test/derived/deriver/child.sd");
collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd");
@@ -172,63 +171,63 @@ public class IntermediateCollectionTestCase {
}
@Test
- public void can_detect_schema_inheritance_cycles() throws Exception {
+ void can_detect_schema_inheritance_cycles() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromString("schema foo inherits bar { document foo {} }");
collection.addSchemaFromString("schema bar inherits qux { document bar {} }");
collection.addSchemaFromString("schema qux inherits foo { document qux {} }");
assertEquals(collection.getParsedSchemas().size(), 3);
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.resolveInternalConnections());
+ collection.resolveInternalConnections());
assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for schemas: "));
}
@Test
- public void can_detect_document_inheritance_cycles() throws Exception {
+ void can_detect_document_inheritance_cycles() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromString("schema foo { document foo inherits bar {} }");
collection.addSchemaFromString("schema bar { document bar inherits qux {} }");
collection.addSchemaFromString("schema qux { document qux inherits foo {} }");
assertEquals(collection.getParsedSchemas().size(), 3);
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.resolveInternalConnections());
- System.err.println("ex: "+ex.getMessage());
+ collection.resolveInternalConnections());
+ System.err.println("ex: " + ex.getMessage());
assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: "));
}
@Test
- public void can_detect_missing_doc() throws Exception {
+ void can_detect_missing_doc() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromString("schema foo { document foo inherits bar {} }");
collection.addSchemaFromString("schema qux { document qux inherits foo {} }");
assertEquals(collection.getParsedSchemas().size(), 2);
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.resolveInternalConnections());
+ collection.resolveInternalConnections());
assertEquals("document foo inherits from unavailable document bar", ex.getMessage());
}
@Test
- public void can_detect_document_reference_cycle() throws Exception {
+ void can_detect_document_reference_cycle() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromString("schema foo { document foo { field oneref type reference<bar> {} } }");
collection.addSchemaFromString("schema bar { document bar { field tworef type reference<foo> {} } }");
assertEquals(collection.getParsedSchemas().size(), 2);
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.resolveInternalConnections());
- System.err.println("ex: "+ex.getMessage());
+ collection.resolveInternalConnections());
+ System.err.println("ex: " + ex.getMessage());
assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: "));
}
@Test
- public void can_detect_cycles_with_reference() throws Exception {
+ void can_detect_cycles_with_reference() throws Exception {
var collection = new IntermediateCollection();
collection.addSchemaFromString("schema foo { document foodoc inherits bardoc {} }");
collection.addSchemaFromString("schema bar { document bardoc { field myref type reference<qux> { } } }");
collection.addSchemaFromString("schema qux inherits foo { document qux inherits foodoc {} }");
assertEquals(collection.getParsedSchemas().size(), 3);
var ex = assertThrows(IllegalArgumentException.class, () ->
- collection.resolveInternalConnections());
- System.err.println("ex: "+ex.getMessage());
+ collection.resolveInternalConnections());
+ System.err.println("ex: " + ex.getMessage());
assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: "));
}
diff --git a/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java
index 9245b64b09e..a594f9ae535 100644
--- a/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java
@@ -1,9 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.schema.parser;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author arnej
@@ -11,7 +12,7 @@ import static org.junit.Assert.assertThrows;
public class ParsedDocumentTestCase {
@Test
- public void fields_can_be_added_once() throws Exception {
+ void fields_can_be_added_once() throws Exception {
var doc = new ParsedDocument("foo");
var stringType = ParsedType.fromName("string");
doc.addField(new ParsedField("bar1", stringType));
@@ -19,11 +20,11 @@ public class ParsedDocumentTestCase {
doc.addField(new ParsedField("bar2", stringType));
doc.addField(new ParsedField("bar3", stringType));
var e = assertThrows(IllegalArgumentException.class, () ->
- doc.addField(new ParsedField("zap", stringType)));
- System.err.println("As expected: "+e);
+ doc.addField(new ParsedField("zap", stringType)));
+ System.err.println("As expected: " + e);
assertEquals("document 'foo' error: Duplicate (case insensitively) field 'zap' in document type 'foo'", e.getMessage());
e = assertThrows(IllegalArgumentException.class, () ->
- doc.addField(new ParsedField("ZAP", stringType)));
+ doc.addField(new ParsedField("ZAP", stringType)));
assertEquals("document 'foo' error: Duplicate (case insensitively) field 'ZAP' in document type 'foo'", e.getMessage());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java
index 77d1b55019d..150c237bbba 100644
--- a/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java
@@ -8,12 +8,9 @@ import static com.yahoo.config.model.test.TestUtil.joinLines;
import java.io.File;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertThrows;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author arnej
@@ -38,12 +35,12 @@ public class SchemaParserTestCase {
}
@Test
- public void minimal_schema_can_be_parsed() throws Exception {
+ void minimal_schema_can_be_parsed() throws Exception {
String input = joinLines
- ("schema foo {",
- " document foo {",
- " }",
- "}");
+ ("schema foo {",
+ " document foo {",
+ " }",
+ "}");
ParsedSchema schema = parseString(input);
assertEquals("foo", schema.name());
assertTrue(schema.hasDocument());
@@ -51,10 +48,10 @@ public class SchemaParserTestCase {
}
@Test
- public void document_only_can_be_parsed() throws Exception {
+ void document_only_can_be_parsed() throws Exception {
String input = joinLines
- ("document bar {",
- "}");
+ ("document bar {",
+ "}");
ParsedSchema schema = parseString(input);
assertEquals("bar", schema.name());
assertTrue(schema.hasDocument());
@@ -62,28 +59,28 @@ public class SchemaParserTestCase {
}
@Test
- public void multiple_documents_disallowed() {
+ void multiple_documents_disallowed() {
String input = joinLines
("schema foo {",
- " document foo {",
- " }",
- " document foo2 {",
- " }",
- "}");
+ " document foo {",
+ " }",
+ " document foo2 {",
+ " }",
+ "}");
var e = assertThrows(IllegalArgumentException.class, () -> parseString(input));
assertEquals("schema 'foo' error: already has document 'foo' so cannot add document 'foo2'", e.getMessage());
}
@Test
- public void backwards_path_is_disallowed() {
+ void backwards_path_is_disallowed() {
assertEquals("'..' is not allowed in path",
- assertThrows(IllegalArgumentException.class,
- () -> parseString("schema foo {\n" +
- " constant my_constant_tensor {\n" +
- " file: foo/../bar\n" +
- " type: tensor<float>(x{},y{})\n" +
- " }\n" +
- "}\n")).getMessage());
+ assertThrows(IllegalArgumentException.class,
+ () -> parseString("schema foo {\n" +
+ " constant my_constant_tensor {\n" +
+ " file: foo/../bar\n" +
+ " type: tensor<float>(x{},y{})\n" +
+ " }\n" +
+ "}\n")).getMessage());
}
void checkFileParses(String fileName) throws Exception {
@@ -95,7 +92,7 @@ public class SchemaParserTestCase {
// TODO: Many (all)? of the files below are parsed from other tests and can be removed from here
@Test
- public void parse_various_old_sdfiles() throws Exception {
+ void parse_various_old_sdfiles() throws Exception {
checkFileParses("src/test/cfg/search/data/travel/schemas/TTData.sd");
checkFileParses("src/test/cfg/search/data/travel/schemas/TTEdge.sd");
checkFileParses("src/test/cfg/search/data/travel/schemas/TTPOI.sd");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java b/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java
index 0d64dd5c953..fe7edf5e433 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java
@@ -17,11 +17,11 @@ import com.yahoo.schema.document.SDField;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -33,7 +33,7 @@ public class AddAttributeTransformToSummaryOfImportedFieldsTest {
private static final String SUMMARY_NAME = "mysummary";
@Test
- public void attribute_summary_transform_applied_to_summary_field_of_imported_field() {
+ void attribute_summary_transform_applied_to_summary_field_of_imported_field() {
Schema schema = createSearchWithDocument(DOCUMENT_NAME);
schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME));
schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, schema));
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java
index 103d08b39a8..06d6e347f29 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java
@@ -7,19 +7,14 @@ import com.yahoo.schema.Schema;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
public class AdjustPositionSummaryFieldsTestCase {
@Test
- public void test_pos_summary() {
+ void test_pos_summary() {
SearchModel model = new SearchModel(false);
model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
model.resolve();
@@ -29,7 +24,7 @@ public class AdjustPositionSummaryFieldsTestCase {
}
@Test
- public void test_imported_pos_summary() {
+ void test_imported_pos_summary() {
SearchModel model = new SearchModel();
model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
model.resolve();
@@ -39,7 +34,7 @@ public class AdjustPositionSummaryFieldsTestCase {
}
@Test
- public void test_imported_pos_summary_bad_source() {
+ void test_imported_pos_summary_bad_source() {
SearchModel model = new SearchModel();
model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
model.resolve();
@@ -50,7 +45,7 @@ public class AdjustPositionSummaryFieldsTestCase {
}
@Test
- public void test_imported_pos_summary_bad_datatype() {
+ void test_imported_pos_summary_bad_datatype() {
SearchModel model = new SearchModel();
model.addSummaryField("my_pos", DataType.getArray(PositionDataType.INSTANCE), null, "pos");
model.resolve();
@@ -60,7 +55,7 @@ public class AdjustPositionSummaryFieldsTestCase {
}
@Test
- public void test_pos_summary_no_attr_no_rename() {
+ void test_pos_summary_no_attr_no_rename() {
SearchModel model = new SearchModel(false, false, false);
model.addSummaryField("pos", PositionDataType.INSTANCE, null, "pos");
model.resolve();
@@ -70,14 +65,14 @@ public class AdjustPositionSummaryFieldsTestCase {
}
@Test
- public void test_pos_default_summary_no_attr_no_rename() {
+ void test_pos_default_summary_no_attr_no_rename() {
SearchModel model = new SearchModel(false, false, false);
model.resolve();
assertNull(model.childSchema.getSummary("default")); // ImplicitSummaries processing not run in this test
}
@Test
- public void test_pos_summary_no_rename() {
+ void test_pos_summary_no_rename() {
SearchModel model = new SearchModel(false, true, false);
model.addSummaryField("pos", PositionDataType.INSTANCE, null, "pos");
model.resolve();
@@ -86,79 +81,82 @@ public class AdjustPositionSummaryFieldsTestCase {
model.assertSummaryField("pos.distance", DataType.INT, SummaryTransform.DISTANCE, "pos_zcurve");
}
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void test_pos_summary_no_attr() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'");
- SearchModel model = new SearchModel(false, false, false);
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
- model.resolve();
+ void test_pos_summary_no_attr() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel(false, false, false);
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'"));
}
@Test
- public void test_pos_summary_bad_attr() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'");
- SearchModel model = new SearchModel(false, false, true);
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
- model.resolve();
+ void test_pos_summary_bad_attr() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel(false, false, true);
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos");
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'"));
}
@Test
- public void test_imported_pos_summary_no_attr() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', import field 'my_pos_zcurve': "
- + "Field 'pos_zcurve' via reference field 'ref': Not found");
- SearchModel model = new SearchModel(true, false, false);
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
- model.resolve();
+ void test_imported_pos_summary_no_attr() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel(true, false, false);
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_pos_zcurve': "
+ + "Field 'pos_zcurve' via reference field 'ref': Not found"));
}
@Test
- public void test_imported_pos_summary_bad_attr() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos': "
- + "No position attribute 'my_pos_zcurve'");
- SearchModel model = new SearchModel(true, false, true);
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
- model.resolve();
+ void test_imported_pos_summary_bad_attr() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel(true, false, true);
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': "
+ + "No position attribute 'my_pos_zcurve'"));
}
@Test
- public void test_my_pos_position_summary_bad_datatype() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': "
- + "exists with type 'datatype string (code: 2)', should be of type 'datatype Array<string> (code: -1486737430)");
- SearchModel model = new SearchModel();
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
- model.addSummaryField("my_pos.position", DataType.STRING, null, "pos");
- model.resolve();
+ void test_my_pos_position_summary_bad_datatype() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel();
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
+ model.addSummaryField("my_pos.position", DataType.STRING, null, "pos");
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': "
+ + "exists with type 'datatype string (code: 2)', should be of type 'datatype Array<string> (code: -1486737430)"));
}
@Test
- public void test_my_pos_position_summary_bad_transform() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': "
- + "has summary transform 'none', should have transform 'positions'");
- SearchModel model = new SearchModel();
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
- model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), null, "pos");
- model.resolve();
+ void test_my_pos_position_summary_bad_transform() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel();
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
+ model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), null, "pos");
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': "
+ + "has summary transform 'none', should have transform 'positions'"));
}
@Test
- public void test_my_pos_position_summary_bad_source() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': "
- + "has source '[source field 'pos']', should have source 'source field 'my_pos_zcurve''");
- SearchModel model = new SearchModel();
- model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
- model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), SummaryTransform.POSITIONS, "pos");
- model.resolve();
+ void test_my_pos_position_summary_bad_source() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SearchModel model = new SearchModel();
+ model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null);
+ model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), SummaryTransform.POSITIONS, "pos");
+ model.resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': "
+ + "has source '[source field 'pos']', should have source 'source field 'my_pos_zcurve''"));
}
static class SearchModel extends ParentChildSearchModel {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java b/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java
index 82650598f29..f9c1e992347 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java
@@ -9,8 +9,8 @@ import com.yahoo.vespa.indexinglanguage.parser.ParseException;
import java.util.LinkedList;
import java.util.List;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -36,8 +36,8 @@ public abstract class AssertIndexingScript {
}
for (Expression actualExp : actual) {
String str = actualExp.toString();
- assertTrue("Unexpected: " + str, parsedExpected.remove(str));
+ assertTrue(parsedExpected.remove(str), "Unexpected: " + str);
}
- assertTrue("Missing: " + parsedExpected.toString(), parsedExpected.isEmpty());
+ assertTrue(parsedExpected.isEmpty(), "Missing: " + parsedExpected.toString());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java b/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java
index 0b4d7c3a2b6..12da3f0797b 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java
@@ -6,7 +6,7 @@ import com.yahoo.schema.parser.ParseException;
import java.io.IOException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java
index 40ebe458c74..a01aa11264b 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java
@@ -6,12 +6,13 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.MatchType;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
/**
* Attributes should be implicitly exact-match in some cases
* @author vegardh
@@ -19,7 +20,7 @@ import static org.junit.Assert.assertFalse;
*/
public class AttributesExactMatchTestCase extends AbstractSchemaTestCase {
@Test
- public void testAttributesExactMatch() throws IOException, ParseException {
+ void testAttributesExactMatch() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesexactmatch.sd");
assertEquals(schema.getConcreteField("color").getMatching().getType(), MatchType.EXACT);
assertEquals(schema.getConcreteField("artist").getMatching().getType(), MatchType.WORD);
@@ -28,12 +29,12 @@ public class AttributesExactMatchTestCase extends AbstractSchemaTestCase {
assertEquals(schema.getConcreteField("saxophonist_arr").getMatching().getType(), MatchType.WORD);
assertEquals(schema.getConcreteField("flutist").getMatching().getType(), MatchType.TEXT);
- assertFalse(schema.getConcreteField("genre").getMatching().getType().equals(MatchType.EXACT));
- assertFalse(schema.getConcreteField("title").getMatching().getType().equals(MatchType.EXACT));
- assertFalse(schema.getConcreteField("trumpetist").getMatching().getType().equals(MatchType.EXACT));
- assertFalse(schema.getConcreteField("genre").getMatching().getType().equals(MatchType.WORD));
- assertFalse(schema.getConcreteField("title").getMatching().getType().equals(MatchType.WORD));
- assertFalse(schema.getConcreteField("trumpetist").getMatching().getType().equals(MatchType.WORD));
+ assertNotEquals(schema.getConcreteField("genre").getMatching().getType(), MatchType.EXACT);
+ assertNotEquals(schema.getConcreteField("title").getMatching().getType(), MatchType.EXACT);
+ assertNotEquals(schema.getConcreteField("trumpetist").getMatching().getType(), MatchType.EXACT);
+ assertNotEquals(schema.getConcreteField("genre").getMatching().getType(), MatchType.WORD);
+ assertNotEquals(schema.getConcreteField("title").getMatching().getType(), MatchType.WORD);
+ assertNotEquals(schema.getConcreteField("trumpetist").getMatching().getType(), MatchType.WORD);
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java
index c37bc8085c7..fe38ea1f1b1 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -29,13 +29,13 @@ public class BoldingTestCase extends AbstractSchemaTestCase {
"}\n";
@Test
- public void testBoldOnNonString() throws ParseException {
+ void testBoldOnNonString() throws ParseException {
try {
ApplicationBuilder.createFromString(boldonnonstring);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("'bolding: on' for non-text field 'year4' (datatype int (code: 0)) is not allowed",
- e.getMessage());
+ e.getMessage());
}
}
@@ -50,13 +50,13 @@ public class BoldingTestCase extends AbstractSchemaTestCase {
"}\n";
@Test
- public void testBoldOnArray() throws ParseException {
+ void testBoldOnArray() throws ParseException {
try {
ApplicationBuilder.createFromString(boldonarray);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("'bolding: on' for non-text field 'myarray' (datatype Array<string> (code: -1486737430)) is not allowed",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java
index 287cc6559d1..f19b1f43115 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java
@@ -2,12 +2,12 @@
package com.yahoo.schema.processing;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.schema.ApplicationBuilder.createFromString;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author geirst
@@ -15,19 +15,19 @@ import static org.junit.Assert.fail;
public class BoolAttributeValidatorTestCase {
@Test
- public void array_of_bool_attribute_is_not_supported() throws ParseException {
+ void array_of_bool_attribute_is_not_supported() throws ParseException {
try {
createFromString(getSd("field b type array<bool> { indexing: attribute }"));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'b': Only single value bool attribute fields are supported",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void weigtedset_of_bool_attribute_is_not_supported() throws ParseException {
+ void weigtedset_of_bool_attribute_is_not_supported() throws ParseException {
try {
createFromString(getSd("field b type weightedset<bool> { indexing: attribute }"));
fail("Expected exception");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java
index 45a546259ae..ef1716c80e6 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java
@@ -11,11 +11,9 @@ import com.yahoo.schema.document.Dictionary;
import com.yahoo.schema.document.ImmutableSDField;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.config.search.AttributesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test configuration of dictionary control.
@@ -33,19 +31,20 @@ public class DictionaryTestCase {
ApplicationBuilder sb = ApplicationBuilder.createFromString(def);
return sb.getSchema();
}
+
@Test
- public void testDefaultDictionarySettings() throws ParseException {
+ void testDefaultDictionarySettings() throws ParseException {
String def = TestUtil.joinLines(
- "search test {",
- " document test {",
- " field s1 type string {",
- " indexing: attribute | summary",
- " }",
- " field n1 type int {",
- " indexing: summary | attribute",
- " }",
- " }",
- "}");
+ "search test {",
+ " document test {",
+ " field s1 type string {",
+ " indexing: attribute | summary",
+ " }",
+ " field n1 type int {",
+ " indexing: summary | attribute",
+ " }",
+ " }",
+ "}");
Schema schema = createSearch(def);
assertNull(schema.getAttribute("s1").getDictionary());
assertNull(schema.getAttribute("n1").getDictionary());
@@ -103,64 +102,75 @@ public class DictionaryTestCase {
}
@Test
- public void testCasedBtreeSettings() throws ParseException {
+ void testCasedBtreeSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.BTREE, "int", "dictionary:cased");
}
@Test
- public void testNumericBtreeSettings() throws ParseException {
+ void testNumericBtreeSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.BTREE, "int", "dictionary:btree");
}
+
@Test
- public void testNumericHashSettings() throws ParseException {
+ void testNumericHashSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.HASH, "int", "dictionary:hash");
}
+
@Test
- public void testNumericBtreeAndHashSettings() throws ParseException {
+ void testNumericBtreeAndHashSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "int", "dictionary:btree", "dictionary:hash");
}
+
@Test
- public void testNumericArrayBtreeAndHashSettings() throws ParseException {
+ void testNumericArrayBtreeAndHashSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "array<int>", "dictionary:btree", "dictionary:hash");
}
+
@Test
- public void testNumericWSetBtreeAndHashSettings() throws ParseException {
+ void testNumericWSetBtreeAndHashSettings() throws ParseException {
verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "weightedset<int>", "dictionary:btree", "dictionary:hash");
}
+
@Test
- public void testStringBtreeSettings() throws ParseException {
+ void testStringBtreeSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.UNCASED, Case.UNCASED, "dictionary:btree");
}
+
@Test
- public void testStringBtreeUnCasedSettings() throws ParseException {
+ void testStringBtreeUnCasedSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.UNCASED, Case.UNCASED, "dictionary { btree\nuncased\n}");
}
+
@Test
- public void testStringBtreeCasedSettings() throws ParseException {
+ void testStringBtreeCasedSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.CASED, Case.CASED, "dictionary { btree\ncased\n}", "match:cased");
}
+
@Test
- public void testStringHashSettings() throws ParseException {
+ void testStringHashSettings() throws ParseException {
try {
verifyStringDictionaryControl(Dictionary.Type.HASH, Case.UNCASED, Case.UNCASED, "dictionary:hash");
} catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'n1': hash dictionary require cased match", e.getMessage());
}
}
+
@Test
- public void testStringHashUnCasedSettings() throws ParseException {
+ void testStringHashUnCasedSettings() throws ParseException {
try {
verifyStringDictionaryControl(Dictionary.Type.HASH, Case.UNCASED, Case.UNCASED, "dictionary { hash\nuncased\n}");
} catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'n1': hash dictionary require cased match", e.getMessage());
}
}
+
@Test
- public void testStringHashBothCasedSettings() throws ParseException {
+ void testStringHashBothCasedSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.HASH, Case.CASED, Case.CASED, "dictionary { hash\ncased\n}", "match:cased");
}
+
@Test
- public void testStringHashCasedSettings() throws ParseException {
+ void testStringHashCasedSettings() throws ParseException {
try {
verifyStringDictionaryControl(Dictionary.Type.HASH, Case.CASED, Case.CASED, "dictionary { hash\ncased\n}");
fail();
@@ -168,24 +178,28 @@ public class DictionaryTestCase {
assertEquals("For schema 'test', field 'n1': Dictionary casing 'CASED' does not match field match casing 'UNCASED'", e.getMessage());
}
}
+
@Test
- public void testStringBtreeHashSettings() throws ParseException {
+ void testStringBtreeHashSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.UNCASED, Case.UNCASED, "dictionary{hash\nbtree\n}");
}
+
@Test
- public void testStringBtreeHashUnCasedSettings() throws ParseException {
+ void testStringBtreeHashUnCasedSettings() throws ParseException {
verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.UNCASED, Case.UNCASED, "dictionary { hash\nbtree\nuncased\n}");
}
+
@Test
- public void testStringBtreeHashCasedSettings() throws ParseException {
+ void testStringBtreeHashCasedSettings() throws ParseException {
try {
verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.CASED, Case.CASED, "dictionary { btree\nhash\ncased\n}");
} catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'n1': Dictionary casing 'CASED' does not match field match casing 'UNCASED'", e.getMessage());
}
}
+
@Test
- public void testNonNumericFieldsFailsDictionaryControl() throws ParseException {
+ void testNonNumericFieldsFailsDictionaryControl() throws ParseException {
String def = TestUtil.joinLines(
"schema test {",
" document test {",
@@ -202,8 +216,9 @@ public class DictionaryTestCase {
assertEquals("For schema 'test', field 'n1': You can only specify 'dictionary:' for numeric or string fields", e.getMessage());
}
}
+
@Test
- public void testNonFastSearchNumericFieldsFailsDictionaryControl() throws ParseException {
+ void testNonFastSearchNumericFieldsFailsDictionaryControl() throws ParseException {
String def = TestUtil.joinLines(
"schema test {",
" document test {",
@@ -222,7 +237,7 @@ public class DictionaryTestCase {
}
@Test
- public void testCasingForNonFastSearch() throws ParseException {
+ void testCasingForNonFastSearch() throws ParseException {
String def = TestUtil.joinLines(
"schema test {",
" document test {",
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java
index 64b0a437b1d..4efd20a06f1 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java
@@ -4,41 +4,53 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.RankProfileRegistry;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author lesters
*/
public class DisallowComplexMapAndWsetKeyTypesTestCase {
- @Test(expected = IllegalArgumentException.class)
- public void requireThatComplexTypesForMapKeysFail() throws ParseException {
- testFieldType("map<mystruct,string>");
+ @Test
+ void requireThatComplexTypesForMapKeysFail() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ testFieldType("map<mystruct,string>");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatComplexTypesForWsetFail() throws ParseException {
- testFieldType("weightedset<mystruct>");
+ @Test
+ void requireThatComplexTypesForWsetFail() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ testFieldType("weightedset<mystruct>");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatNestedComplexTypesForMapFail() throws ParseException {
- testFieldType("array<map<mystruct,string>>");
+ @Test
+ void requireThatNestedComplexTypesForMapFail() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ testFieldType("array<map<mystruct,string>>");
+ });
}
@Test
- public void requireThatNestedComplexValuesForMapSucceed() throws ParseException {
+ void requireThatNestedComplexValuesForMapSucceed() throws ParseException {
testFieldType("array<map<string,mystruct>>");
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatNestedComplexTypesForWsetFail() throws ParseException {
- testFieldType("array<weightedset<mystruct>>");
+ @Test
+ void requireThatNestedComplexTypesForWsetFail() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ testFieldType("array<weightedset<mystruct>>");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatDeepNestedComplexTypesForMapFail() throws ParseException {
- testFieldType("map<string,map<mystruct,string>>");
+ @Test
+ void requireThatDeepNestedComplexTypesForMapFail() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ testFieldType("map<string,map<mystruct,string>>");
+ });
}
private void testFieldType(String fieldType) throws ParseException {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java b/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java
index b249b407c7b..ebf79a4a7d5 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java
@@ -5,57 +5,54 @@ import com.yahoo.config.model.test.TestUtil;
import com.yahoo.schema.RankProfileRegistry;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
*/
public class FastAccessValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void throws_exception_on_incompatible_use_of_fastaccess() throws ParseException {
- ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry());
- builder.addSchema(
- TestUtil.joinLines(
- "schema parent {",
- " document parent {",
- " field int_field type int { indexing: attribute }",
- " }",
- "}"));
- builder.addSchema(
- TestUtil.joinLines(
- "schema test {",
- " document test { ",
- " field int_attribute type int { ",
- " indexing: attribute ",
- " attribute: fast-access",
- " }",
- " field predicate_attribute type predicate {",
- " indexing: attribute ",
- " attribute: fast-access",
- " }",
- " field tensor_attribute type tensor(x[5]) {",
- " indexing: attribute ",
- " attribute: fast-access",
- " }",
- " field reference_attribute type reference<parent> {",
- " indexing: attribute ",
- " attribute: fast-access",
- " }",
- " }",
- "}"));
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "For schema 'test': The following attributes have a type that is incompatible " +
- "with fast-access: predicate_attribute, tensor_attribute, reference_attribute. " +
- "Predicate, tensor and reference attributes are incompatible with fast-access.");
- builder.build(true);
+ void throws_exception_on_incompatible_use_of_fastaccess() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry());
+ builder.addSchema(
+ TestUtil.joinLines(
+ "schema parent {",
+ " document parent {",
+ " field int_field type int { indexing: attribute }",
+ " }",
+ "}"));
+ builder.addSchema(
+ TestUtil.joinLines(
+ "schema test {",
+ " document test { ",
+ " field int_attribute type int { ",
+ " indexing: attribute ",
+ " attribute: fast-access",
+ " }",
+ " field predicate_attribute type predicate {",
+ " indexing: attribute ",
+ " attribute: fast-access",
+ " }",
+ " field tensor_attribute type tensor(x[5]) {",
+ " indexing: attribute ",
+ " attribute: fast-access",
+ " }",
+ " field reference_attribute type reference<parent> {",
+ " indexing: attribute ",
+ " attribute: fast-access",
+ " }",
+ " }",
+ "}"));
+ builder.build(true);
+ });
+ assertTrue(exception.getMessage().contains("For schema 'test': The following attributes have a type that is incompatible " +
+ "with fast-access: predicate_attribute, tensor_attribute, reference_attribute. " +
+ "Predicate, tensor and reference attributes are incompatible with fast-access."));
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java
index 594124c9500..c758d49f79f 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java
@@ -7,17 +7,17 @@ import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.derived.DerivedConfiguration;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
@Test
- public void testRequireThatExtraFieldsAreIncluded() throws IOException, ParseException {
+ void testRequireThatExtraFieldsAreIncluded() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/extrafield.sd");
assertNotNull(schema);
@@ -29,7 +29,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testRequireThatSummaryFieldsAreIncluded() throws IOException, ParseException {
+ void testRequireThatSummaryFieldsAreIncluded() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/summaryfield.sd");
assertNotNull(schema);
@@ -44,7 +44,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testRequireThatBoldedSummaryFieldsAreIncluded() throws IOException, ParseException {
+ void testRequireThatBoldedSummaryFieldsAreIncluded() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/boldedsummaryfields.sd");
assertNotNull(schema);
@@ -58,7 +58,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testRequireThatUntransformedSummaryFieldsAreIgnored() throws IOException, ParseException {
+ void testRequireThatUntransformedSummaryFieldsAreIgnored() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/untransformedsummaryfields.sd");
assertNotNull(schema);
@@ -71,7 +71,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testRequireThatDynamicSummaryFieldsAreIgnored() throws IOException, ParseException {
+ void testRequireThatDynamicSummaryFieldsAreIgnored() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/dynamicsummaryfields.sd");
assertNotNull(schema);
@@ -83,7 +83,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testRequireThatDerivedConfigurationWorks() throws IOException, ParseException {
+ void testRequireThatDerivedConfigurationWorks() throws IOException, ParseException {
ApplicationBuilder sb = new ApplicationBuilder();
sb.addSchemaFile("src/test/examples/nextgen/simple.sd");
sb.build(true);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java
index 111ed266d74..243ec0243c8 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java
@@ -8,14 +8,15 @@ import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
+
public class ImplicitStructTypesTestCase extends AbstractSchemaTestCase {
@Test
- public void testRequireThatImplicitStructsAreCreated() throws IOException, ParseException {
+ void testRequireThatImplicitStructsAreCreated() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/toggleon.sd");
assertNotNull(schema);
@@ -23,8 +24,9 @@ public class ImplicitStructTypesTestCase extends AbstractSchemaTestCase {
assertNotNull(docType);
assertStruct(docType, PositionDataType.INSTANCE);
}
+
@Test
- public void testRequireThatImplicitStructsAreUsed() throws IOException, ParseException {
+ void testRequireThatImplicitStructsAreUsed() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/implicitstructtypes.sd");
assertNotNull(schema);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java
index 50deb5d5b42..37bc064c19e 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@@ -15,9 +15,7 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -25,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class ImplicitSummariesTestCase {
@Test
- public void requireThatSummaryFromAttributeDoesNotWarn() throws IOException, ParseException {
+ void requireThatSummaryFromAttributeDoesNotWarn() throws IOException, ParseException {
LogHandler log = new LogHandler();
Logger.getLogger("").addHandler(log);
@@ -59,19 +57,19 @@ public class ImplicitSummariesTestCase {
}
@Test
- public void attribute_combiner_transform_is_set_on_array_of_struct_with_only_struct_field_attributes() throws IOException, ParseException {
+ void attribute_combiner_transform_is_set_on_array_of_struct_with_only_struct_field_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/array_of_struct_attribute/test.sd");
assertEquals(SummaryTransform.ATTRIBUTECOMBINER, schema.getSummaryField("elem_array").getTransform());
}
@Test
- public void attribute_combiner_transform_is_set_on_map_of_struct_with_only_struct_field_attributes() throws IOException, ParseException {
+ void attribute_combiner_transform_is_set_on_map_of_struct_with_only_struct_field_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd");
assertEquals(SummaryTransform.ATTRIBUTECOMBINER, schema.getSummaryField("str_elem_map").getTransform());
}
@Test
- public void attribute_combiner_transform_is_not_set_when_map_of_struct_has_some_struct_field_attributes() throws IOException, ParseException {
+ void attribute_combiner_transform_is_not_set_when_map_of_struct_has_some_struct_field_attributes() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd");
assertEquals(SummaryTransform.NONE, schema.getSummaryField("int_elem_map").getTransform());
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java
index f32c9079d36..bc7513b4662 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java
@@ -6,17 +6,17 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.documentmodel.DocumentSummary;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ImplicitSummaryFieldsTestCase extends AbstractSchemaTestCase {
@Test
- public void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException {
+ void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/implicitsummaryfields.sd");
assertNotNull(schema);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java
index 5baa64d06d4..853cb1d1a79 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java
@@ -11,24 +11,15 @@ import com.yahoo.schema.document.ImportedFields;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.TemporarySDField;
import com.yahoo.tensor.TensorType;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
*/
public class ImportedFieldsResolverTestCase {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
private void resolve_imported_field(String fieldName, String targetFieldName) {
SearchModel model = new SearchModel();
model.addImportedField(fieldName, "ref", targetFieldName).resolve();
@@ -52,54 +43,57 @@ public class ImportedFieldsResolverTestCase {
}
@Test
- public void valid_imported_fields_are_resolved() {
+ void valid_imported_fields_are_resolved() {
resolve_imported_field("my_attribute_field", "attribute_field");
resolve_imported_field("my_tensor_field", "tensor_field");
resolve_imported_field("my_ancient_field", "ancient_field");
}
@Test
- public void resolver_fails_if_document_reference_is_not_found() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', import field 'my_attribute_field': "
- + "Reference field 'not_ref' not found");
- new SearchModel().addImportedField("my_attribute_field", "not_ref", "budget").resolve();
+ void resolver_fails_if_document_reference_is_not_found() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new SearchModel().addImportedField("my_attribute_field", "not_ref", "budget").resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_field': "
+ + "Reference field 'not_ref' not found"));
}
@Test
- public void resolver_fails_if_referenced_field_is_not_found() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', import field 'my_attribute_field': "
- + "Field 'not_existing' via reference field 'ref': Not found");
- new SearchModel().addImportedField("my_attribute_field", "ref", "not_existing").resolve();
+ void resolver_fails_if_referenced_field_is_not_found() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new SearchModel().addImportedField("my_attribute_field", "ref", "not_existing").resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_field': "
+ + "Field 'not_existing' via reference field 'ref': Not found"));
}
@Test
- public void resolver_fails_if_imported_field_is_not_an_attribute() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'child', import field 'my_not_attribute': "
- + "Field 'not_attribute' via reference field 'ref': Is not an attribute field. Only attribute fields supported");
- new SearchModel().addImportedField("my_not_attribute", "ref", "not_attribute").resolve();
+ void resolver_fails_if_imported_field_is_not_an_attribute() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new SearchModel().addImportedField("my_not_attribute", "ref", "not_attribute").resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_not_attribute': "
+ + "Field 'not_attribute' via reference field 'ref': Is not an attribute field. Only attribute fields supported"));
}
@Test
- public void resolver_fails_if_imported_field_is_indexing() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "For schema 'child', import field 'my_attribute_and_index': " +
- "Field 'attribute_and_index' via reference field 'ref': Is an index field. Not supported");
- new SearchModel()
- .addImportedField("my_attribute_and_index", "ref", "attribute_and_index")
- .resolve();
+ void resolver_fails_if_imported_field_is_indexing() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new SearchModel()
+ .addImportedField("my_attribute_and_index", "ref", "attribute_and_index")
+ .resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_and_index': " +
+ "Field 'attribute_and_index' via reference field 'ref': Is an index field. Not supported"));
}
@Test
- public void resolver_fails_if_imported_field_is_of_type_predicate() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "For schema 'child', import field 'my_predicate_field': " +
- "Field 'predicate_field' via reference field 'ref': Is of type 'predicate'. Not supported");
- new SearchModel().addImportedField("my_predicate_field", "ref", "predicate_field").resolve();
+ void resolver_fails_if_imported_field_is_of_type_predicate() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new SearchModel().addImportedField("my_predicate_field", "ref", "predicate_field").resolve();
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_predicate_field': " +
+ "Field 'predicate_field' via reference field 'ref': Is of type 'predicate'. Not supported"));
}
static class SearchModel extends ParentChildSearchModel {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java
index ab702154527..6c23d1ecf91 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java
@@ -7,15 +7,10 @@ import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.document.ImportedComplexField;
import com.yahoo.schema.document.ImportedField;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
@@ -23,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class ImportedFieldsTestCase {
@Test
- public void fields_can_be_imported_from_referenced_document_types() throws ParseException {
+ void fields_can_be_imported_from_referenced_document_types() throws ParseException {
Schema schema = buildAdSearch(joinLines(
"search ad {",
" document ad {",
@@ -38,33 +33,31 @@ public class ImportedFieldsTestCase {
assertSearchContainsImportedField("my_name", "person_ref", "person", "name", schema);
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
- public void field_reference_spec_must_include_dot() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Illegal field reference spec 'campaignrefbudget': Does not include a single '.'");
- buildAdSearch(joinLines(
- "search ad {",
- " document ad {}",
- " import field campaignrefbudget as budget {}",
- "}"));
+ void field_reference_spec_must_include_dot() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ buildAdSearch(joinLines(
+ "search ad {",
+ " document ad {}",
+ " import field campaignrefbudget as budget {}",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Illegal field reference spec 'campaignrefbudget': Does not include a single '.'"));
}
@Test
- public void fail_duplicate_import() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'ad', import field as 'my_budget': Field already imported");
- Schema schema = buildAdSearch(joinLines(
- "schema ad {",
- " document ad {",
- " field campaign_ref type reference<campaign> { indexing: attribute }",
- " }",
- " import field campaign_ref.budget as my_budget {}",
- " import field campaign_ref.budget as my_budget {}",
- "}"));
+ void fail_duplicate_import() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ Schema schema = buildAdSearch(joinLines(
+ "schema ad {",
+ " document ad {",
+ " field campaign_ref type reference<campaign> { indexing: attribute }",
+ " }",
+ " import field campaign_ref.budget as my_budget {}",
+ " import field campaign_ref.budget as my_budget {}",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'ad', import field as 'my_budget': Field already imported"));
}
private static Schema buildAdSearch(String sdContent) throws ParseException {
@@ -113,52 +106,57 @@ public class ImportedFieldsTestCase {
}
@Test
- public void check_struct_import() throws ParseException {
+ void check_struct_import() throws ParseException {
checkStructImport(new ParentStructSdBuilder());
checkStructImport(new ParentStructSdBuilder().elem_array_weight_attr(false).elem_map_value_weight_attr(false));
checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_map_value_name_attr(false));
}
@Test
- public void check_nested_struct_import() throws ParseException {
+ void check_nested_struct_import() throws ParseException {
checkNestedStructImport(new GrandParentStructSdBuilder());
checkNestedStructImport(new GrandParentStructSdBuilder().elem_array_weight_attr(false).elem_map_value_weight_attr(false));
checkNestedStructImport(new GrandParentStructSdBuilder().elem_array_name_attr(false).elem_map_value_name_attr(false));
}
@Test
- public void check_illegal_struct_import_missing_array_of_struct_attributes() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_elem_array': Field 'elem_array' via reference field 'parent_ref': Is not a struct containing an attribute field.");
- checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_array_weight_attr(false));
+ void check_illegal_struct_import_missing_array_of_struct_attributes() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_array_weight_attr(false));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_array': Field 'elem_array' via reference field 'parent_ref': Is not a struct containing an attribute field."));
}
@Test
- public void check_illegal_struct_import_missing_map_of_struct_key_attribute() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.key'): Field 'elem_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported");
- checkStructImport(new ParentStructSdBuilder().elem_map_key_attr(false));
+ void check_illegal_struct_import_missing_map_of_struct_key_attribute() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkStructImport(new ParentStructSdBuilder().elem_map_key_attr(false));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.key'): Field 'elem_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"));
}
@Test
- public void check_illegal_struct_import_missing_map_of_struct_value_attributes() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.value'): Field 'elem_map.value' via reference field 'parent_ref': Is not a struct containing an attribute field.");
- checkStructImport(new ParentStructSdBuilder().elem_map_value_name_attr(false).elem_map_value_weight_attr(false));
+ void check_illegal_struct_import_missing_map_of_struct_value_attributes() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkStructImport(new ParentStructSdBuilder().elem_map_value_name_attr(false).elem_map_value_weight_attr(false));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.value'): Field 'elem_map.value' via reference field 'parent_ref': Is not a struct containing an attribute field."));
}
@Test
- public void check_illegal_struct_import_missing_map_of_primitive_key_attribute() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.key'): Field 'str_int_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported");
- checkStructImport(new ParentStructSdBuilder().str_int_map_key_attr(false));
+ void check_illegal_struct_import_missing_map_of_primitive_key_attribute() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkStructImport(new ParentStructSdBuilder().str_int_map_key_attr(false));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.key'): Field 'str_int_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"));
}
@Test
- public void check_illegal_struct_import_missing_map_of_primitive_value_attribute() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.value'): Field 'str_int_map.value' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported");
- checkStructImport(new ParentStructSdBuilder().str_int_map_value_attr(false));
+ void check_illegal_struct_import_missing_map_of_primitive_value_attribute() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkStructImport(new ParentStructSdBuilder().str_int_map_value_attr(false));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.value'): Field 'str_int_map.value' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"));
}
private static class NamedSdBuilder {
@@ -408,20 +406,21 @@ public class ImportedFieldsTestCase {
}
@Test
- public void check_pos_import() throws ParseException {
+ void check_pos_import() throws ParseException {
checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder());
}
@Test
- public void check_nested_pos_import() throws ParseException {
+ void check_nested_pos_import() throws ParseException {
checkNestedPosImport(new GrandParentPosSdBuilder(), new ChildPosSdBuilder());
}
@Test
- public void check_pos_import_after_pos_zcurve_import() throws ParseException {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("For schema 'child', import field 'my_pos_zcurve': Field 'pos_zcurve' via reference field 'parent_ref': Field already imported");
- checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder().import_pos_zcurve_before(true));
+ void check_pos_import_after_pos_zcurve_import() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder().import_pos_zcurve_before(true));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_pos_zcurve': Field 'pos_zcurve' via reference field 'parent_ref': Field already imported"));
}
private static ImportedField getImportedField(String name, Schema schema) {
@@ -466,7 +465,7 @@ public class ImportedFieldsTestCase {
}
@Test
- public void field_with_struct_field_attributes_can_be_imported_from_parents_that_use_inheritance() throws ParseException {
+ void field_with_struct_field_attributes_can_be_imported_from_parents_that_use_inheritance() throws ParseException {
var builder = buildParentsUsingInheritance();
assertParentContainsEntriesAttributes(builder.getSchema("parent_a"));
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java
index 71c79feedc1..893ee3b1ea4 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.processing;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -14,32 +14,32 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails;
public class IndexingInputsTestCase {
@Test
- public void requireThatExtraFieldInputExtraFieldThrows() throws IOException, ParseException {
+ void requireThatExtraFieldInputExtraFieldThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_extra_field_input_extra_field.sd",
- "For schema 'indexing_extra_field_input_extra_field', field 'bar': Indexing script refers " +
- "to field 'bar' which does not exist in document type " +
- "'indexing_extra_field_input_extra_field', and is not a mutable attribute.");
+ "For schema 'indexing_extra_field_input_extra_field', field 'bar': Indexing script refers " +
+ "to field 'bar' which does not exist in document type " +
+ "'indexing_extra_field_input_extra_field', and is not a mutable attribute.");
}
@Test
- public void requireThatExtraFieldInputImplicitThrows() throws IOException, ParseException {
+ void requireThatExtraFieldInputImplicitThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_extra_field_input_implicit.sd",
- "For schema 'indexing_extra_field_input_implicit', field 'foo': Indexing script refers to " +
- "field 'foo' which does not exist in document type 'indexing_extra_field_input_implicit', and is not a mutable attribute.");
+ "For schema 'indexing_extra_field_input_implicit', field 'foo': Indexing script refers to " +
+ "field 'foo' which does not exist in document type 'indexing_extra_field_input_implicit', and is not a mutable attribute.");
}
@Test
- public void requireThatExtraFieldInputNullThrows() throws IOException, ParseException {
+ void requireThatExtraFieldInputNullThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_extra_field_input_null.sd",
- "For schema 'indexing_extra_field_input_null', field 'foo': Indexing script refers to field " +
- "'foo' which does not exist in document type 'indexing_extra_field_input_null', and is not a mutable attribute.");
+ "For schema 'indexing_extra_field_input_null', field 'foo': Indexing script refers to field " +
+ "'foo' which does not exist in document type 'indexing_extra_field_input_null', and is not a mutable attribute.");
}
@Test
- public void requireThatExtraFieldInputSelfThrows() throws IOException, ParseException {
+ void requireThatExtraFieldInputSelfThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_extra_field_input_self.sd",
- "For schema 'indexing_extra_field_input_self', field 'foo': Indexing script refers to field " +
- "'foo' which does not exist in document type 'indexing_extra_field_input_self', and is not a mutable attribute.");
+ "For schema 'indexing_extra_field_input_self', field 'foo': Indexing script refers to field " +
+ "'foo' which does not exist in document type 'indexing_extra_field_input_self', and is not a mutable attribute.");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java
index 687549f920e..e707d203381 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.processing;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,16 +15,16 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails;
public class IndexingOutputsTestCase {
@Test
- public void requireThatOutputOtherFieldThrows() throws IOException, ParseException {
+ void requireThatOutputOtherFieldThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_output_other_field.sd",
- "For schema 'indexing_output_other_field', field 'foo': Indexing expression 'index bar' " +
- "attempts to write to a field other than 'foo'.");
+ "For schema 'indexing_output_other_field', field 'foo': Indexing expression 'index bar' " +
+ "attempts to write to a field other than 'foo'.");
}
@Test
- public void requireThatOutputConflictThrows() throws IOException, ParseException {
+ void requireThatOutputConflictThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_output_conflict.sd",
- "For schema 'indexing_output_confict', field 'bar': For expression 'index bar': Attempting " +
- "to assign conflicting values to field 'bar'.");
+ "For schema 'indexing_output_confict', field 'bar': For expression 'index bar': Attempting " +
+ "to assign conflicting values to field 'bar'.");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java
index 76cb6a5505c..54a50d2ce93 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java
@@ -16,7 +16,7 @@ import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
import com.yahoo.vespa.indexinglanguage.expressions.ScriptExpression;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.OptionalDouble;
@@ -25,7 +25,7 @@ import java.util.OptionalLong;
import java.util.Set;
import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -33,108 +33,108 @@ import static org.junit.Assert.assertEquals;
public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase {
@Test
- public void testSetLanguageRewriting() {
+ void testSetLanguageRewriting() {
assertIndexingScript("{ input test | set_language; }",
- createField("test", DataType.STRING, "{ set_language }"));
+ createField("test", DataType.STRING, "{ set_language }"));
}
@Test
- public void testSummaryRewriting() {
+ void testSummaryRewriting() {
assertIndexingScript("{ input test | summary test; }",
- createField("test", DataType.STRING, "{ summary }"));
+ createField("test", DataType.STRING, "{ summary }"));
}
@Test
- public void testDynamicSummaryRewriting() {
+ void testDynamicSummaryRewriting() {
SDField field = createField("test", DataType.STRING, "{ summary }");
field.addSummaryField(createDynamicSummaryField(field, "dyn"));
assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary dyn; }", field);
}
@Test
- public void testSummaryRewritingWithIndexing() {
+ void testSummaryRewritingWithIndexing() {
assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary test | index test; }",
- createField("test", DataType.STRING, "{ summary | index }"));
+ createField("test", DataType.STRING, "{ summary | index }"));
}
@Test
- public void testDynamicAndStaticSummariesRewritingWithIndexing() {
+ void testDynamicAndStaticSummariesRewritingWithIndexing() {
SDField field = createField("test", DataType.STRING, "{ summary | index }");
field.addSummaryField(createDynamicSummaryField(field, "dyn"));
field.addSummaryField(createStaticSummaryField(field, "test"));
field.addSummaryField(createStaticSummaryField(field, "other"));
field.addSummaryField(createDynamicSummaryField(field, "dyn2"));
assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary dyn | summary dyn2 | summary other | " +
- "summary test | index test; }", field);
+ "summary test | index test; }", field);
}
@Test
- public void testIntSummaryRewriting() {
+ void testIntSummaryRewriting() {
assertIndexingScript("{ input test | summary test | attribute test; }",
- createField("test", DataType.INT, "{ summary | index }"));
+ createField("test", DataType.INT, "{ summary | index }"));
}
@Test
- public void testStringAttributeSummaryRewriting() {
+ void testStringAttributeSummaryRewriting() {
assertIndexingScript("{ input test | summary test | attribute test; }",
- createField("test", DataType.STRING, "{ summary | attribute }"));
+ createField("test", DataType.STRING, "{ summary | attribute }"));
}
@Test
- public void testMultiblockTokenize() {
+ void testMultiblockTokenize() {
SDField field = createField("test", DataType.STRING,
- "{ input test | tokenize | { summary test; }; }");
+ "{ input test | tokenize | { summary test; }; }");
assertIndexingScript("{ input test | tokenize | { summary test; }; }", field);
}
@Test
- public void requireThatOutputDefaultsToCurrentField() {
+ void requireThatOutputDefaultsToCurrentField() {
assertIndexingScript("{ input test | attribute test; }",
- createField("test", DataType.STRING, "{ attribute; }"));
+ createField("test", DataType.STRING, "{ attribute; }"));
assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | index test; }",
- createField("test", DataType.STRING, "{ index; }"));
+ createField("test", DataType.STRING, "{ index; }"));
assertIndexingScript("{ input test | summary test; }",
- createField("test", DataType.STRING, "{ summary; }"));
+ createField("test", DataType.STRING, "{ summary; }"));
}
@Test
- public void testTokenizeComparisonDisregardsConfig() {
+ void testTokenizeComparisonDisregardsConfig() {
assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary test | index test; }",
- createField("test", DataType.STRING, "{ summary | tokenize | index; }"));
+ createField("test", DataType.STRING, "{ summary | tokenize | index; }"));
}
@Test
- public void testDerivingFromSimple() throws Exception {
+ void testDerivingFromSimple() throws Exception {
assertIndexing(Arrays.asList("clear_state | guard { input access | attribute access; }",
- "clear_state | guard { input category | split \";\" | attribute category_arr; }",
- "clear_state | guard { input category | tokenize | index category; }",
- "clear_state | guard { input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }",
- "clear_state | guard { input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }",
- "clear_state | guard { input chatter | tokenize normalize stem:\"BEST\" | index chatter; }",
- "clear_state | guard { input description | tokenize normalize stem:\"BEST\" | summary description | summary dyndesc | index description; }",
- "clear_state | guard { input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }",
- "clear_state | guard { input longdesc | tokenize normalize stem:\"BEST\" | summary dyndesc2 | summary dynlong | summary longdesc | summary longstat; }",
- "clear_state | guard { input measurement | attribute measurement | summary measurement; }",
- "clear_state | guard { input measurement | to_array | attribute measurement_arr; }",
- "clear_state | guard { input popularity | attribute popularity; }",
- "clear_state | guard { input popularity * input measurement | attribute popsiness; }",
- "clear_state | guard { input smallattribute | attribute smallattribute; }",
- "clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }",
- "clear_state | guard { input title . \" \" . input category | tokenize | summary exact | index exact; }"),
- ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"));
+ "clear_state | guard { input category | split \";\" | attribute category_arr; }",
+ "clear_state | guard { input category | tokenize | index category; }",
+ "clear_state | guard { input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }",
+ "clear_state | guard { input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }",
+ "clear_state | guard { input chatter | tokenize normalize stem:\"BEST\" | index chatter; }",
+ "clear_state | guard { input description | tokenize normalize stem:\"BEST\" | summary description | summary dyndesc | index description; }",
+ "clear_state | guard { input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }",
+ "clear_state | guard { input longdesc | tokenize normalize stem:\"BEST\" | summary dyndesc2 | summary dynlong | summary longdesc | summary longstat; }",
+ "clear_state | guard { input measurement | attribute measurement | summary measurement; }",
+ "clear_state | guard { input measurement | to_array | attribute measurement_arr; }",
+ "clear_state | guard { input popularity | attribute popularity; }",
+ "clear_state | guard { input popularity * input measurement | attribute popsiness; }",
+ "clear_state | guard { input smallattribute | attribute smallattribute; }",
+ "clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }",
+ "clear_state | guard { input title . \" \" . input category | tokenize | summary exact | index exact; }"),
+ ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"));
}
@Test
- public void testIndexRewrite() throws Exception {
+ void testIndexRewrite() throws Exception {
assertIndexing(
Arrays.asList("clear_state | guard { input title_src | lowercase | normalize | " +
- " tokenize | index title; }",
- "clear_state | guard { input title_src | summary title_s; }"),
+ " tokenize | index title; }",
+ "clear_state | guard { input title_src | summary title_s; }"),
ApplicationBuilder.buildFromFile("src/test/examples/indexrewrite.sd"));
}
@Test
- public void requireThatPredicateFieldsGetOptimization() {
+ void requireThatPredicateFieldsGetOptimization() {
assertIndexingScript("{ 10 | set_var arity | { input test | optimize_predicate | attribute test; }; }",
createPredicateField(
"test", DataType.PREDICATE, "{ attribute; }", 10, OptionalLong.empty(), OptionalLong.empty()));
@@ -143,7 +143,7 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase {
"test", DataType.PREDICATE, "{ summary | attribute ; }", 10, OptionalLong.empty(), OptionalLong.empty()));
assertIndexingScript(
"{ 2 | set_var arity | 0L | set_var lower_bound | 1023L | set_var upper_bound | " +
- "{ input test | optimize_predicate | attribute test; }; }",
+ "{ input test | optimize_predicate | attribute test; }; }",
createPredicateField("test", DataType.PREDICATE, "{ attribute; }", 2, OptionalLong.of(0L), OptionalLong.of(1023L)));
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java
index 4da6880aa26..aa8a2922e8f 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.derived.AbstractExportingTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
@@ -18,59 +18,59 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails;
public class IndexingValidationTestCase extends AbstractExportingTestCase {
@Test
- public void testAttributeChanged() throws IOException, ParseException {
+ void testAttributeChanged() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_attribute_changed.sd",
- "For schema 'indexing_attribute_changed', field 'foo': For expression 'attribute foo': " +
- "Attempting to assign conflicting values to field 'foo'.");
+ "For schema 'indexing_attribute_changed', field 'foo': For expression 'attribute foo': " +
+ "Attempting to assign conflicting values to field 'foo'.");
}
@Test
- public void testAttributeOther() throws IOException, ParseException {
+ void testAttributeOther() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_attribute_other.sd",
- "For schema 'indexing_attribute_other', field 'foo': Indexing expression 'attribute bar' " +
- "attempts to write to a field other than 'foo'.");
+ "For schema 'indexing_attribute_other', field 'foo': Indexing expression 'attribute bar' " +
+ "attempts to write to a field other than 'foo'.");
}
@Test
- public void testIndexChanged() throws IOException, ParseException {
+ void testIndexChanged() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_index_changed.sd",
- "For schema 'indexing_index_changed', field 'foo': For expression 'index foo': " +
- "Attempting to assign conflicting values to field 'foo'.");
+ "For schema 'indexing_index_changed', field 'foo': For expression 'index foo': " +
+ "Attempting to assign conflicting values to field 'foo'.");
}
@Test
- public void testIndexOther() throws IOException, ParseException {
+ void testIndexOther() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_index_other.sd",
- "For schema 'indexing_index_other', field 'foo': Indexing expression 'index bar' " +
- "attempts to write to a field other than 'foo'.");
+ "For schema 'indexing_index_other', field 'foo': Indexing expression 'index bar' " +
+ "attempts to write to a field other than 'foo'.");
}
@Test
- public void testSummaryChanged() throws IOException, ParseException {
+ void testSummaryChanged() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_summary_changed.sd",
- "For schema 'indexing_summary_fail', field 'foo': For expression 'summary foo': Attempting " +
- "to assign conflicting values to field 'foo'.");
+ "For schema 'indexing_summary_fail', field 'foo': For expression 'summary foo': Attempting " +
+ "to assign conflicting values to field 'foo'.");
}
@Test
- public void testSummaryOther() throws IOException, ParseException {
+ void testSummaryOther() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_summary_other.sd",
- "For schema 'indexing_summary_other', field 'foo': Indexing expression 'summary bar' " +
- "attempts to write to a field other than 'foo'.");
+ "For schema 'indexing_summary_other', field 'foo': Indexing expression 'summary bar' " +
+ "attempts to write to a field other than 'foo'.");
}
@Test
- public void testExtraField() throws IOException, ParseException {
+ void testExtraField() throws IOException, ParseException {
assertIndexing(
Arrays.asList("clear_state | guard { input my_index | tokenize normalize stem:\"BEST\" | index my_index | summary my_index }",
- "clear_state | guard { input my_input | tokenize normalize stem:\"BEST\" | index my_extra | summary my_extra }"),
+ "clear_state | guard { input my_input | tokenize normalize stem:\"BEST\" | index my_extra | summary my_extra }"),
ApplicationBuilder.buildFromFile("src/test/examples/indexing_extra.sd"));
}
@Test
- public void requireThatMultilineOutputConflictThrows() throws IOException, ParseException {
+ void requireThatMultilineOutputConflictThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_multiline_output_conflict.sd",
- "For schema 'indexing_multiline_output_confict', field 'cox': For expression 'index cox': " +
- "Attempting to assign conflicting values to field 'cox'.");
+ "For schema 'indexing_multiline_output_confict', field 'cox': For expression 'index cox': " +
+ "Attempting to assign conflicting values to field 'cox'.");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java
index 2784fe69b28..1f723924db6 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.schema.processing;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -15,16 +15,16 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuilds;
public class IndexingValuesTestCase {
@Test
- public void requireThatModifyFieldNoOutputDoesNotThrow() throws IOException, ParseException {
+ void requireThatModifyFieldNoOutputDoesNotThrow() throws IOException, ParseException {
assertBuilds("src/test/examples/indexing_modify_field_no_output.sd");
}
@Test
- public void requireThatInputOtherFieldThrows() throws IOException, ParseException {
+ void requireThatInputOtherFieldThrows() throws IOException, ParseException {
assertBuildFails("src/test/examples/indexing_input_other_field.sd",
- "For schema 'indexing_input_other_field', field 'bar': Indexing expression 'input foo' " +
- "attempts to modify the value of the document field 'bar'. " +
- "Use a field outside the document block instead.");
+ "For schema 'indexing_input_other_field', field 'bar': Indexing expression 'input foo' " +
+ "attempts to modify the value of the document field 'bar'. " +
+ "Use a field outside the document block instead.");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java
index f36effab146..d3bfe7a8f55 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java
@@ -9,13 +9,11 @@ import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class IntegerIndex2AttributeTestCase extends AbstractSchemaTestCase {
@Test
- public void testIntegerIndex2Attribute() throws IOException, ParseException {
+ void testIntegerIndex2Attribute() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/integerindex2attribute.sd");
new IntegerIndex2Attribute(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles()).process(true, false);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java
index 530b6a95ce8..cbddea8ea6a 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.schema.processing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails;
@@ -12,25 +12,25 @@ public class MatchPhaseSettingsValidatorTestCase {
}
@Test
- public void requireThatAttributeMustExists() throws Exception {
+ void requireThatAttributeMustExists() throws Exception {
assertBuildFails("src/test/examples/matchphase/non_existing_attribute.sd",
getMessagePrefix() + "does not exists");
}
@Test
- public void requireThatAttributeMustBeNumeric() throws Exception {
+ void requireThatAttributeMustBeNumeric() throws Exception {
assertBuildFails("src/test/examples/matchphase/wrong_data_type_attribute.sd",
getMessagePrefix() + "must be single value numeric, but it is 'string'");
}
@Test
- public void requireThatAttributeMustBeSingleValue() throws Exception {
+ void requireThatAttributeMustBeSingleValue() throws Exception {
assertBuildFails("src/test/examples/matchphase/wrong_collection_type_attribute.sd",
getMessagePrefix() + "must be single value numeric, but it is 'Array<int>'");
}
@Test
- public void requireThatAttributeMustHaveFastSearch() throws Exception {
+ void requireThatAttributeMustHaveFastSearch() throws Exception {
assertBuildFails("src/test/examples/matchphase/non_fast_search_attribute.sd",
getMessagePrefix() + "must be fast-search, but it is not");
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java
index c401376ac3a..bd93a70d7cb 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java
@@ -7,24 +7,18 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
*/
public class MatchedElementsOnlyResolverTestCase {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void complex_field_with_some_struct_field_attributes_gets_default_transform() throws ParseException {
+ void complex_field_with_some_struct_field_attributes_gets_default_transform() throws ParseException {
assertSummaryField(joinLines("field my_field type map<string, string> {",
" indexing: summary",
" summary: matched-elements-only",
@@ -48,7 +42,7 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void complex_field_with_only_struct_field_attributes_gets_attribute_transform() throws ParseException {
+ void complex_field_with_only_struct_field_attributes_gets_attribute_transform() throws ParseException {
assertSummaryField(joinLines("field my_field type map<string, string> {",
" indexing: summary",
" summary: matched-elements-only",
@@ -76,7 +70,7 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void explicit_complex_summary_field_can_use_filter_transform_with_reference_to_source_field() throws ParseException {
+ void explicit_complex_summary_field_can_use_filter_transform_with_reference_to_source_field() throws ParseException {
String documentSummary = joinLines("document-summary my_summary {",
" summary my_filter_field type map<string, string> {",
" source: my_field",
@@ -109,7 +103,7 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void primitive_array_attribute_field_gets_attribute_transform() throws ParseException {
+ void primitive_array_attribute_field_gets_attribute_transform() throws ParseException {
assertSummaryField(joinLines("field my_field type array<string> {",
" indexing: attribute | summary",
" summary: matched-elements-only",
@@ -118,7 +112,7 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void primitive_weighted_set_attribute_field_gets_attribute_transform() throws ParseException {
+ void primitive_weighted_set_attribute_field_gets_attribute_transform() throws ParseException {
assertSummaryField(joinLines("field my_field type weightedset<string> {",
" indexing: attribute | summary",
" summary: matched-elements-only",
@@ -127,7 +121,7 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void explicit_summary_field_can_use_filter_transform_with_reference_to_attribute_source_field() throws ParseException {
+ void explicit_summary_field_can_use_filter_transform_with_reference_to_attribute_source_field() throws ParseException {
String documentSummary = joinLines("document-summary my_summary {",
" summary my_filter_field type array<string> {",
" source: my_field",
@@ -147,17 +141,18 @@ public class MatchedElementsOnlyResolverTestCase {
}
@Test
- public void unsupported_field_type_throws() throws ParseException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For schema 'test', document summary 'default', summary field 'my_field': " +
+ void unsupported_field_type_throws() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ buildSearch(joinLines("field my_field type string {",
+ " indexing: summary",
+ " summary: matched-elements-only",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("For schema 'test', document summary 'default', summary field 'my_field': " +
"'matched-elements-only' is not supported for this field type. " +
"Supported field types are: array of primitive, weighted set of primitive, " +
"array of simple struct, map of primitive type to simple struct, " +
- "and map of primitive type to primitive type");
- buildSearch(joinLines("field my_field type string {",
- " indexing: summary",
- " summary: matched-elements-only",
- "}"));
+ "and map of primitive type to primitive type"));
}
private void assertSummaryField(String fieldContent, String fieldName, SummaryTransform expTransform) throws ParseException {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java
index 912e6fcf030..c143aa43d53 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java
@@ -8,15 +8,12 @@ import com.yahoo.schema.document.MatchType;
import com.yahoo.schema.document.SDField;
import com.yahoo.schema.document.Stemming;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -24,7 +21,7 @@ import static org.junit.Assert.fail;
public class NGramTestCase extends AbstractSchemaTestCase {
@Test
- public void testNGram() throws IOException, ParseException {
+ void testNGram() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/ngram.sd");
assertNotNull(schema);
@@ -36,8 +33,8 @@ public class NGramTestCase extends AbstractSchemaTestCase {
assertEquals(MatchType.GRAM, gram2.getMatching().getType());
assertEquals(-1, gram2.getMatching().getGramSize()); // Not set explicitly
- SDField gram3= schema.getConcreteField("gram_3");
- assertEquals(MatchType.GRAM,gram3.getMatching().getType());
+ SDField gram3 = schema.getConcreteField("gram_3");
+ assertEquals(MatchType.GRAM, gram3.getMatching().getType());
assertEquals(3, gram3.getMatching().getGramSize());
assertEquals("input gram_1 | ngram 1 | index gram_1 | summary gram_1", gram1.getIndexingScript().iterator().next().toString());
@@ -53,7 +50,7 @@ public class NGramTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testInvalidNGramSetting1() throws IOException, ParseException {
+ void testInvalidNGramSetting1() throws IOException, ParseException {
try {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram1.sd");
fail("Should cause an exception");
@@ -64,7 +61,7 @@ public class NGramTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testInvalidNGramSetting2() throws IOException, ParseException {
+ void testInvalidNGramSetting2() throws IOException, ParseException {
try {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram2.sd");
fail("Should cause an exception");
@@ -75,7 +72,7 @@ public class NGramTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testInvalidNGramSetting3() throws IOException, ParseException {
+ void testInvalidNGramSetting3() throws IOException, ParseException {
try {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram3.sd");
fail("Should cause an exception");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java
index a291dda24b9..2a3a3ff93e9 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java
@@ -3,27 +3,24 @@ package com.yahoo.schema.processing;
import com.yahoo.config.model.application.provider.BaseDeployLogger;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.schema.ApplicationBuilder.createFromString;
import static com.yahoo.schema.ApplicationBuilder.createFromStrings;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class PagedAttributeValidatorTestCase {
@Test
- public void dense_tensor_attribute_supports_paged_setting() throws ParseException {
+ void dense_tensor_attribute_supports_paged_setting() throws ParseException {
assertPagedSupported("tensor(x[2],y[2])");
}
@Test
- public void primitive_attribute_types_support_paged_setting() throws ParseException {
+ void primitive_attribute_types_support_paged_setting() throws ParseException {
assertPagedSupported("int");
assertPagedSupported("array<int>");
assertPagedSupported("weightedset<int>");
@@ -34,7 +31,7 @@ public class PagedAttributeValidatorTestCase {
}
@Test
- public void struct_field_attributes_support_paged_setting() throws ParseException {
+ void struct_field_attributes_support_paged_setting() throws ParseException {
var sd = joinLines("schema test {",
" document test {",
" struct elem {",
@@ -68,17 +65,17 @@ public class PagedAttributeValidatorTestCase {
}
@Test
- public void non_dense_tensor_attribute_does_not_support_paged_setting() throws ParseException {
+ void non_dense_tensor_attribute_does_not_support_paged_setting() throws ParseException {
assertPagedSettingNotSupported("tensor(x{},y[2])");
}
@Test
- public void predicate_attribute_does_not_support_paged_setting() throws ParseException {
+ void predicate_attribute_does_not_support_paged_setting() throws ParseException {
assertPagedSettingNotSupported("predicate");
}
@Test
- public void reference_attribute_does_not_support_paged_setting() throws ParseException {
+ void reference_attribute_does_not_support_paged_setting() throws ParseException {
assertPagedSettingNotSupported("reference<parent>", Optional.of(getSd("parent", "int")));
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java
index e4f32fff41d..1b950523588 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java
@@ -11,12 +11,12 @@ import com.yahoo.schema.document.FieldSet;
import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test Position processor.
@@ -26,7 +26,7 @@ import static org.junit.Assert.*;
public class PositionTestCase {
@Test
- public void inherited_position_zcurve_field_is_not_added_to_document_fieldset() throws Exception {
+ void inherited_position_zcurve_field_is_not_added_to_document_fieldset() throws Exception {
ApplicationBuilder sb = ApplicationBuilder.createFromFiles(Arrays.asList(
"src/test/examples/position_base.sd",
"src/test/examples/position_inherited.sd"));
@@ -37,7 +37,7 @@ public class PositionTestCase {
}
@Test
- public void requireThatPositionCanBeAttribute() throws Exception {
+ void requireThatPositionCanBeAttribute() throws Exception {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_attribute.sd");
assertNull(schema.getAttribute("pos"));
assertNull(schema.getAttribute("pos.x"));
@@ -48,18 +48,18 @@ public class PositionTestCase {
}
@Test
- public void requireThatPositionCanNotBeIndex() throws Exception {
+ void requireThatPositionCanNotBeIndex() throws Exception {
try {
ApplicationBuilder.buildFromFile("src/test/examples/position_index.sd");
fail();
} catch (IllegalArgumentException e) {
assertEquals("For schema 'position_index', field 'pos': Indexing of data type 'position' is not " +
- "supported, replace 'index' statement with 'attribute'.", e.getMessage());
+ "supported, replace 'index' statement with 'attribute'.", e.getMessage());
}
}
@Test
- public void requireThatSummaryAloneDoesNotCreateZCurve() throws Exception {
+ void requireThatSummaryAloneDoesNotCreateZCurve() throws Exception {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_summary.sd");
assertNull(schema.getAttribute("pos"));
assertNull(schema.getAttribute("pos.x"));
@@ -78,7 +78,7 @@ public class PositionTestCase {
}
@Test
- public void requireThatExtraFieldCanBePositionAttribute() throws Exception {
+ void requireThatExtraFieldCanBePositionAttribute() throws Exception {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_extra.sd");
assertNull(schema.getAttribute("pos_ext"));
assertNull(schema.getAttribute("pos_ext.x"));
@@ -89,7 +89,7 @@ public class PositionTestCase {
}
@Test
- public void requireThatPositionArrayIsSupported() throws Exception {
+ void requireThatPositionArrayIsSupported() throws Exception {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_array.sd");
assertNull(schema.getAttribute("pos"));
assertNull(schema.getAttribute("pos.x"));
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java
index 69bf62be84b..f49b1df8cea 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -16,7 +16,7 @@ import java.io.IOException;
*/
public class RankModifierTestCase extends AbstractSchemaTestCase {
@Test
- public void testLiteral() throws IOException, ParseException {
+ void testLiteral() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/rankmodifier/literal.sd");
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java b/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java
index e380b1ab9af..15fe8250b71 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java
@@ -27,7 +27,7 @@ import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Helper class for setting up and asserting over a Search instance with a rank profile given literally
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java
index dab1d9e6e95..077017cc70e 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java
@@ -9,22 +9,22 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
public class RankPropertyVariablesTestCase extends AbstractSchemaTestCase {
@Test
- public void testRankPropVariables() throws IOException, ParseException {
+ void testRankPropVariables() throws IOException, ParseException {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/rankpropvars.sd",
- new BaseDeployLogger(),
- rankProfileRegistry,
- new QueryProfileRegistry());
+ new BaseDeployLogger(),
+ rankProfileRegistry,
+ new QueryProfileRegistry());
assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvar1", "foo");
assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvar_2", "bar");
assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvarOne23", "baz");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java
index 4b6a22fc81a..c6d6332b4c0 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java
@@ -11,7 +11,7 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode;
import com.yahoo.tensor.TensorType;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -20,10 +20,7 @@ import java.util.logging.Level;
import java.util.stream.Collectors;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -31,7 +28,7 @@ import static org.junit.Assert.fail;
public class RankingExpressionTypeResolverTestCase {
@Test
- public void tensorFirstPhaseMustProduceDouble() throws Exception {
+ void tensorFirstPhaseMustProduceDouble() throws Exception {
try {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
@@ -53,13 +50,13 @@ public class RankingExpressionTypeResolverTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x[10],y[3])",
- Exceptions.toMessageString(expected));
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void tensorFirstPhaseFromConstantMustProduceDouble() throws Exception {
+ void tensorFirstPhaseFromConstantMustProduceDouble() throws Exception {
try {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
@@ -95,14 +92,13 @@ public class RankingExpressionTypeResolverTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x{},y{},z{})",
- Exceptions.toMessageString(expected));
+ Exceptions.toMessageString(expected));
}
}
-
@Test
- public void tensorSecondPhaseMustProduceDouble() throws Exception {
+ void tensorSecondPhaseMustProduceDouble() throws Exception {
try {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
@@ -127,12 +123,12 @@ public class RankingExpressionTypeResolverTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("In schema 'test', rank profile 'my_rank_profile': The second-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x[10],y[3])",
- Exceptions.toMessageString(expected));
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void tensorConditionsMustHaveTypeCompatibleBranches() throws Exception {
+ void tensorConditionsMustHaveTypeCompatibleBranches() throws Exception {
try {
ApplicationBuilder schemaBuilder = new ApplicationBuilder();
schemaBuilder.addSchema(joinLines(
@@ -157,14 +153,14 @@ public class RankingExpressionTypeResolverTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression is invalid: An if expression must produce compatible types in both alternatives, but the 'true' type is tensor(x[10],y[5]) while the 'false' type is tensor(z[10])" +
- "\n'true' branch: attribute(a)" +
- "\n'false' branch: attribute(b)",
- Exceptions.toMessageString(expected));
+ "\n'true' branch: attribute(a)" +
+ "\n'false' branch: attribute(b)",
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testFunctionInvocationTypes() throws Exception {
+ void testFunctionInvocationTypes() throws Exception {
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry);
builder.addSchema(joinLines(
@@ -192,13 +188,13 @@ public class RankingExpressionTypeResolverTestCase {
RankProfile profile =
builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile");
assertEquals(TensorType.fromSpec("tensor(x[10],y[3])"),
- summaryFeatures(profile).get("macro1(a)").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("macro1(a)").type(profile.typeContext(builder.getQueryProfileRegistry())));
assertEquals(TensorType.fromSpec("tensor(z[10])"),
- summaryFeatures(profile).get("macro1(b)").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("macro1(b)").type(profile.typeContext(builder.getQueryProfileRegistry())));
}
@Test
- public void testTensorFunctionInvocationTypes_Nested() throws Exception {
+ void testTensorFunctionInvocationTypes_Nested() throws Exception {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
"search test {",
@@ -234,52 +230,52 @@ public class RankingExpressionTypeResolverTestCase {
RankProfile profile =
builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile");
assertEquals(TensorType.fromSpec("tensor(x[10],y[1])"),
- summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry())));
assertEquals(TensorType.fromSpec("tensor(z[10])"),
- summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry())));
}
@Test
- public void testAttributeInvocationViaBoundIdentifier() throws Exception {
+ void testAttributeInvocationViaBoundIdentifier() throws Exception {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
- "search newsarticle {",
- " document newsarticle {",
- " field title type string {",
- " indexing {",
- " input title | index",
- " }",
- " weight: 30",
- " }",
- " field usstaticrank type int {",
- " indexing: summary | attribute",
- " }",
- " field eustaticrank type int {",
- " indexing: summary | attribute",
- " }",
- " }",
- " rank-profile default {",
- " macro newsboost() { ",
- " expression: 200 * matches(title)",
- " }",
- " macro commonboost(mystaticrank) { ",
- " expression: attribute(mystaticrank) + newsboost",
- " }",
- " macro commonfirstphase(mystaticrank) { ",
- " expression: nativeFieldMatch(title) + commonboost(mystaticrank) ",
- " }",
- " first-phase { expression: commonfirstphase(usstaticrank) }",
- " }",
- " rank-profile eurank inherits default {",
- " first-phase { expression: commonfirstphase(eustaticrank) }",
- " }",
- "}"));
+ "search newsarticle {",
+ " document newsarticle {",
+ " field title type string {",
+ " indexing {",
+ " input title | index",
+ " }",
+ " weight: 30",
+ " }",
+ " field usstaticrank type int {",
+ " indexing: summary | attribute",
+ " }",
+ " field eustaticrank type int {",
+ " indexing: summary | attribute",
+ " }",
+ " }",
+ " rank-profile default {",
+ " macro newsboost() { ",
+ " expression: 200 * matches(title)",
+ " }",
+ " macro commonboost(mystaticrank) { ",
+ " expression: attribute(mystaticrank) + newsboost",
+ " }",
+ " macro commonfirstphase(mystaticrank) { ",
+ " expression: nativeFieldMatch(title) + commonboost(mystaticrank) ",
+ " }",
+ " first-phase { expression: commonfirstphase(usstaticrank) }",
+ " }",
+ " rank-profile eurank inherits default {",
+ " first-phase { expression: commonfirstphase(eustaticrank) }",
+ " }",
+ "}"));
builder.build(true);
RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "eurank");
}
@Test
- public void testTensorFunctionInvocationTypes_NestedSameName() throws Exception {
+ void testTensorFunctionInvocationTypes_NestedSameName() throws Exception {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
"search test {",
@@ -318,35 +314,35 @@ public class RankingExpressionTypeResolverTestCase {
RankProfile profile =
builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile");
assertEquals(TensorType.fromSpec("tensor(x[10],y[1])"),
- summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry())));
assertEquals(TensorType.fromSpec("tensor(z[10])"),
- summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry())));
}
@Test
- public void testTensorFunctionInvocationTypes_viaFuncWithExpr() throws Exception {
+ void testTensorFunctionInvocationTypes_viaFuncWithExpr() throws Exception {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
- "search test {",
- " document test {",
- " field t1 type tensor<float>(y{}) { indexing: attribute | summary }",
- " field t2 type tensor<float>(x{}) { indexing: attribute | summary }",
- " }",
- " rank-profile test {",
- " function my_func(t) { expression: sum(t, x) + 1 }",
- " function test_func_via_func_with_expr() { expression: call_func_with_expr( attribute(t1), attribute(t2) ) }",
- " function call_func_with_expr(a, b) { expression: my_func( a * b ) }",
- " summary-features { test_func_via_func_with_expr }",
- " }",
- "}"));
+ "search test {",
+ " document test {",
+ " field t1 type tensor<float>(y{}) { indexing: attribute | summary }",
+ " field t2 type tensor<float>(x{}) { indexing: attribute | summary }",
+ " }",
+ " rank-profile test {",
+ " function my_func(t) { expression: sum(t, x) + 1 }",
+ " function test_func_via_func_with_expr() { expression: call_func_with_expr( attribute(t1), attribute(t2) ) }",
+ " function call_func_with_expr(a, b) { expression: my_func( a * b ) }",
+ " summary-features { test_func_via_func_with_expr }",
+ " }",
+ "}"));
builder.build(true);
RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "test");
assertEquals(TensorType.fromSpec("tensor<float>(y{})"),
- summaryFeatures(profile).get("test_func_via_func_with_expr").type(profile.typeContext(builder.getQueryProfileRegistry())));
+ summaryFeatures(profile).get("test_func_via_func_with_expr").type(profile.typeContext(builder.getQueryProfileRegistry())));
}
@Test
- public void importedFieldsAreAvailable() throws Exception {
+ void importedFieldsAreAvailable() throws Exception {
ApplicationBuilder builder = new ApplicationBuilder();
builder.addSchema(joinLines(
"search parent {",
@@ -361,7 +357,7 @@ public class RankingExpressionTypeResolverTestCase {
"search child {",
" document child { ",
" field ref type reference<parent> {",
- "indexing: attribute | summary",
+ "indexing: attribute | summary",
" }",
" }",
" import field ref.a as imported_a {}",
@@ -376,14 +372,14 @@ public class RankingExpressionTypeResolverTestCase {
}
@Test
- public void undeclaredQueryFeaturesAreAccepted() throws Exception {
+ void undeclaredQueryFeaturesAreAccepted() throws Exception {
InspectableDeployLogger logger = new InspectableDeployLogger();
ApplicationBuilder builder = new ApplicationBuilder(logger);
builder.addSchema(joinLines(
"search test {",
" document test { ",
" field anyfield type double {" +
- " indexing: attribute",
+ " indexing: attribute",
" }",
" }",
" rank-profile my_rank_profile {",
@@ -402,7 +398,7 @@ public class RankingExpressionTypeResolverTestCase {
}
@Test
- public void undeclaredQueryFeaturesAreNotAcceptedWhenStrict() throws Exception {
+ void undeclaredQueryFeaturesAreNotAcceptedWhenStrict() throws Exception {
try {
InspectableDeployLogger logger = new InspectableDeployLogger();
ApplicationBuilder builder = new ApplicationBuilder(logger);
@@ -410,12 +406,12 @@ public class RankingExpressionTypeResolverTestCase {
"search test {",
" document test { ",
" field anyfield type double {" +
- " indexing: attribute",
+ " indexing: attribute",
" }",
" }",
" rank-profile my_rank_profile {",
" strict: true" +
- " first-phase {",
+ " first-phase {",
" expression: query(foo) + f() + sum(attribute(anyfield))",
" }",
" function f() {",
@@ -428,12 +424,12 @@ public class RankingExpressionTypeResolverTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("In schema 'test', rank profile 'my_rank_profile': rank profile 'my_rank_profile' is strict but is missing a query profile type declaration of features [query(bar), query(baz), query(foo)]",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void undeclaredQueryFeaturesAreAcceptedWithWarningWhenUsingTensors() throws Exception {
+ void undeclaredQueryFeaturesAreAcceptedWithWarningWhenUsingTensors() throws Exception {
InspectableDeployLogger logger = new InspectableDeployLogger();
ApplicationBuilder builder = new ApplicationBuilder(logger);
builder.addSchema(joinLines(
@@ -456,25 +452,25 @@ public class RankingExpressionTypeResolverTestCase {
builder.build(true);
String message = logger.findMessage("The following query features");
assertNotNull(message);
- assertEquals("WARNING: The following query features used in rank profile 'my_rank_profile' are not declared in query profile types and " +
- "will be interpreted as scalars, not tensors: [query(bar), query(baz), query(foo)]",
- message);
+ assertEquals("WARNING: The following query features used in rank profile 'my_rank_profile' are not declared and " +
+ "will be interpreted as scalars, not tensors: [query(bar), query(baz), query(foo)]",
+ message);
}
@Test
- public void noWarningWhenUsingTensorsWhenQueryFeaturesAreDeclared() throws Exception {
+ void noWarningWhenUsingTensorsWhenQueryFeaturesAreDeclared() throws Exception {
InspectableDeployLogger logger = new InspectableDeployLogger();
ApplicationBuilder builder = new ApplicationBuilder(logger);
QueryProfileType myType = new QueryProfileType("mytype");
myType.addField(new FieldDescription("rank.feature.query(foo)",
- new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
- builder.getQueryProfileRegistry().getTypeRegistry());
+ new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
+ builder.getQueryProfileRegistry().getTypeRegistry());
myType.addField(new FieldDescription("rank.feature.query(bar)",
- new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
- builder.getQueryProfileRegistry().getTypeRegistry());
+ new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
+ builder.getQueryProfileRegistry().getTypeRegistry());
myType.addField(new FieldDescription("rank.feature.query(baz)",
- new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
- builder.getQueryProfileRegistry().getTypeRegistry());
+ new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))),
+ builder.getQueryProfileRegistry().getTypeRegistry());
builder.getQueryProfileRegistry().getTypeRegistry().register(myType);
builder.addSchema(joinLines(
"search test {",
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java
index 4df0a09ec2e..50cc12e9b33 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java
@@ -5,8 +5,8 @@ import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.schema.parser.ParseException;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -20,25 +20,25 @@ public class RankingExpressionWithLightGBMTestCase {
private final static String lightGBMExpression =
"if (!(numerical_2 >= 0.46643291586559305), 2.1594397038037663, if (categorical_2 in [\"k\", \"l\", \"m\"], 2.235297305276056, 2.1792953471546546)) + if (categorical_1 in [\"d\", \"e\"], 0.03070842919354316, if (!(numerical_1 >= 0.5102250691730842), -0.04439151147520909, 0.005117411709368601)) + if (!(numerical_2 >= 0.668665477622446), if (!(numerical_2 >= 0.008118820676863816), -0.15361238490967524, -0.01192330846157292), 0.03499044894987518) + if (!(numerical_1 >= 0.5201391072644542), -0.02141000620783247, if (categorical_1 in [\"a\", \"b\"], -0.004121485787596721, 0.04534090904886873)) + if (categorical_2 in [\"k\", \"l\", \"m\"], if (!(numerical_2 >= 0.27283279016959255), -0.01924803254356527, 0.03643772842347651), -0.02701711918923075)";
- @After
+ @AfterEach
public void removeGeneratedModelFiles() {
IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
}
@Test
- public void testLightGBMReference() {
+ void testLightGBMReference() {
RankProfileSearchFixture search = fixtureWith("lightgbm('regression.json')");
search.assertFirstPhaseExpression(lightGBMExpression, "my_profile");
}
@Test
- public void testNestedLightGBMReference() {
+ void testNestedLightGBMReference() {
RankProfileSearchFixture search = fixtureWith("5 + sum(lightgbm('regression.json'))");
search.assertFirstPhaseExpression("5 + reduce(" + lightGBMExpression + ", sum)", "my_profile");
}
@Test
- public void testImportingFromStoredExpressions() throws IOException {
+ void testImportingFromStoredExpressions() throws IOException {
RankProfileSearchFixture search = fixtureWith("lightgbm('regression.json')");
search.assertFirstPhaseExpression(lightGBMExpression, "my_profile");
@@ -47,7 +47,7 @@ public class RankingExpressionWithLightGBMTestCase {
try {
storedApplicationDirectory.toFile().mkdirs();
IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(),
- storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
+ storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
RankingExpressionWithOnnxTestCase.StoringApplicationPackage storedApplication = new RankingExpressionWithOnnxTestCase.StoringApplicationPackage(storedApplicationDirectory);
RankProfileSearchFixture searchFromStored = fixtureWith("lightgbm('regression.json')");
searchFromStored.assertFirstPhaseExpression(lightGBMExpression, "my_profile");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java
index 1280895bfc0..22681858fc3 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java
@@ -12,23 +12,23 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.search.DocumentDatabase;
import com.yahoo.vespa.model.search.IndexedSearchCluster;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class RankingExpressionWithOnnxModelTestCase {
private final Path applicationDir = Path.fromString("src/test/integration/onnx-model/");
- @After
+ @AfterEach
public void removeGeneratedModelFiles() {
IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
}
@Test
- public void testOnnxModelFeature() throws Exception {
+ void testOnnxModelFeature() throws Exception {
VespaModel model = loadModel(applicationDir);
assertTransformedFeature(model);
assertGeneratedConfig(model);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java
index 94a51d25717..83d19b010bb 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java
@@ -12,8 +12,8 @@ import com.yahoo.schema.FeatureNames;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.tensor.TensorType;
import com.yahoo.yolean.Exceptions;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileReader;
@@ -23,10 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class RankingExpressionWithOnnxTestCase {
@@ -35,13 +32,13 @@ public class RankingExpressionWithOnnxTestCase {
private final static String name = "mnist_softmax";
private final static String vespaExpression = "join(reduce(join(rename(Placeholder, (d0, d1), (d0, d2)), constant(mnist_softmax_layer_Variable), f(a,b)(a * b)), sum, d2) * 1.0, constant(mnist_softmax_layer_Variable_1) * 1.0, f(a,b)(a + b))";
- @After
+ @AfterEach
public void removeGeneratedModelFiles() {
IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
}
@Test
- public void testOnnxReferenceWithConstantFeature() {
+ void testOnnxReferenceWithConstantFeature() {
RankProfileSearchFixture search = fixtureWith("constant(mytensor)",
"onnx_vespa('mnist_softmax.onnx')",
"constant mytensor { file: ignored\ntype: tensor<float>(d0[1],d1[784]) }",
@@ -50,12 +47,12 @@ public class RankingExpressionWithOnnxTestCase {
}
@Test
- public void testOnnxReferenceWithQueryFeature() {
+ void testOnnxReferenceWithQueryFeature() {
String queryProfile = "<query-profile id='default' type='root'/>";
String queryProfileType =
"<query-profile-type id='root'>" +
- " <field name='query(mytensor)' type='tensor&lt;float&gt;(d0[1],d1[784])'/>" +
- "</query-profile-type>";
+ " <field name='query(mytensor)' type='tensor&lt;float&gt;(d0[1],d1[784])'/>" +
+ "</query-profile-type>";
StoringApplicationPackage application = new StoringApplicationPackage(applicationDir,
queryProfile,
queryProfileType);
@@ -69,7 +66,7 @@ public class RankingExpressionWithOnnxTestCase {
}
@Test
- public void testOnnxReferenceWithDocumentFeature() {
+ void testOnnxReferenceWithDocumentFeature() {
StoringApplicationPackage application = new StoringApplicationPackage(applicationDir);
RankProfileSearchFixture search = fixtureWith("attribute(mytensor)",
"onnx_vespa('mnist_softmax.onnx')",
@@ -82,12 +79,12 @@ public class RankingExpressionWithOnnxTestCase {
@Test
- public void testOnnxReferenceWithFeatureCombination() {
+ void testOnnxReferenceWithFeatureCombination() {
String queryProfile = "<query-profile id='default' type='root'/>";
String queryProfileType =
"<query-profile-type id='root'>" +
- " <field name='query(mytensor)' type='tensor&lt;float&gt;(d0[1],d1[784],d2[10])'/>" +
- "</query-profile-type>";
+ " <field name='query(mytensor)' type='tensor&lt;float&gt;(d0[1],d1[784],d2[10])'/>" +
+ "</query-profile-type>";
StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType);
RankProfileSearchFixture search = fixtureWith("sum(query(mytensor) * attribute(mytensor) * constant(mytensor),d2)",
"onnx_vespa('mnist_softmax.onnx')",
@@ -100,28 +97,28 @@ public class RankingExpressionWithOnnxTestCase {
@Test
- public void testNestedOnnxReference() {
+ void testNestedOnnxReference() {
RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)",
"5 + sum(onnx_vespa('mnist_softmax.onnx'))");
search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile");
}
@Test
- public void testOnnxReferenceWithSpecifiedOutput() {
+ void testOnnxReferenceWithSpecifiedOutput() {
RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)",
"onnx_vespa('mnist_softmax.onnx', 'layer_add')");
search.assertFirstPhaseExpression(vespaExpression, "my_profile");
}
@Test
- public void testOnnxReferenceWithSpecifiedOutputAndSignature() {
+ void testOnnxReferenceWithSpecifiedOutputAndSignature() {
RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)",
"onnx_vespa('mnist_softmax.onnx', 'default.layer_add')");
search.assertFirstPhaseExpression(vespaExpression, "my_profile");
}
@Test
- public void testOnnxReferenceMissingFunction() throws ParseException {
+ void testOnnxReferenceMissingFunction() throws ParseException {
try {
RankProfileSearchFixture search = new RankProfileSearchFixture(
new StoringApplicationPackage(applicationDir),
@@ -137,15 +134,15 @@ public class RankingExpressionWithOnnxTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " +
- "onnx_vespa(\"mnist_softmax.onnx\"): " +
- "Model refers input 'Placeholder' of type tensor<float>(d0[1],d1[784]) but this function is " +
- "not present in rank profile 'my_profile'",
+ "onnx_vespa(\"mnist_softmax.onnx\"): " +
+ "Model refers input 'Placeholder' of type tensor<float>(d0[1],d1[784]) but this function is " +
+ "not present in rank profile 'my_profile'",
Exceptions.toMessageString(expected));
}
}
@Test
- public void testOnnxReferenceWithWrongFunctionType() {
+ void testOnnxReferenceWithWrongFunctionType() {
try {
RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d5[10])(0.0)",
"onnx_vespa('mnist_softmax.onnx')");
@@ -154,15 +151,15 @@ public class RankingExpressionWithOnnxTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " +
- "onnx_vespa(\"mnist_softmax.onnx\"): " +
- "Model refers input 'Placeholder'. The required type of this is tensor<float>(d0[1],d1[784]), " +
- "but this function returns tensor(d0[1],d5[10])",
+ "onnx_vespa(\"mnist_softmax.onnx\"): " +
+ "Model refers input 'Placeholder'. The required type of this is tensor<float>(d0[1],d1[784]), " +
+ "but this function returns tensor(d0[1],d5[10])",
Exceptions.toMessageString(expected));
}
}
@Test
- public void testOnnxReferenceSpecifyingNonExistingOutput() {
+ void testOnnxReferenceSpecifyingNonExistingOutput() {
try {
RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[2],d1[784])(0.0)",
"onnx_vespa('mnist_softmax.onnx', 'y')");
@@ -171,14 +168,14 @@ public class RankingExpressionWithOnnxTestCase {
}
catch (IllegalArgumentException expected) {
assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " +
- "onnx_vespa(\"mnist_softmax.onnx\",\"y\"): " +
- "No expressions named 'y' in model 'mnist_softmax.onnx'. Available expressions: default.layer_add",
- Exceptions.toMessageString(expected));
+ "onnx_vespa(\"mnist_softmax.onnx\",\"y\"): " +
+ "No expressions named 'y' in model 'mnist_softmax.onnx'. Available expressions: default.layer_add",
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testImportingFromStoredExpressions() throws IOException {
+ void testImportingFromStoredExpressions() throws IOException {
RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)",
"onnx_vespa(\"mnist_softmax.onnx\")");
search.assertFirstPhaseExpression(vespaExpression, "my_profile");
@@ -206,7 +203,7 @@ public class RankingExpressionWithOnnxTestCase {
}
@Test
- public void testImportingFromStoredExpressionsWithFunctionOverridingConstantAndInheritance() throws IOException {
+ void testImportingFromStoredExpressionsWithFunctionOverridingConstantAndInheritance() throws IOException {
String rankProfile =
" rank-profile my_profile {\n" +
" function Placeholder() {\n" +
@@ -230,8 +227,8 @@ public class RankingExpressionWithOnnxTestCase {
search.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile");
search.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile_child");
- assertNull("Constant overridden by function is not added",
- search.search().constants().get(name + "_Variable"));
+ assertNull(search.search().constants().get(name + "_Variable"),
+ "Constant overridden by function is not added");
// At this point the expression is stored - copy application to another location which do not have a models dir
Path storedApplicationDirectory = applicationDir.getParentPath().append("copy");
@@ -245,18 +242,18 @@ public class RankingExpressionWithOnnxTestCase {
searchFromStored.compileRankProfile("my_profile_child", applicationDir.append("models"));
searchFromStored.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile");
searchFromStored.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile_child");
- assertNull("Constant overridden by function is not added",
- searchFromStored.search().constants().get(name + "_Variable"));
+ assertNull(searchFromStored.search().constants().get(name + "_Variable"),
+ "Constant overridden by function is not added");
} finally {
IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile());
}
}
@Test
- public void testFunctionGeneration() {
+ void testFunctionGeneration() {
final String name = "small_constants_and_functions";
final String rankProfiles =
- " rank-profile my_profile {\n" +
+ " rank-profile my_profile {\n" +
" function input() {\n" +
" expression: tensor<float>(d0[3])(0.0)\n" +
" }\n" +
@@ -275,7 +272,7 @@ public class RankingExpressionWithOnnxTestCase {
}
@Test
- public void testImportingFromStoredExpressionsWithSmallConstantsAndInheritance() throws IOException {
+ void testImportingFromStoredExpressionsWithSmallConstantsAndInheritance() throws IOException {
final String name = "small_constants_and_functions";
final String rankProfiles =
" rank-profile my_profile {\n" +
@@ -391,7 +388,7 @@ public class RankingExpressionWithOnnxTestCase {
@Override
public ApplicationFile getFile(Path file) {
- return new MockApplicationFile(file, Path.fromString(root().toString()));
+ return new MockApplicationFile(file, root());
}
@Override
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java
index 1f065bc7a20..c5bd0821007 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.schema.processing;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author geirst
@@ -13,16 +13,16 @@ import static org.junit.Assert.fail;
public class RankingExpressionWithTensorTestCase {
@Test
- public void requireThatSingleLineConstantMappedTensorCanBeParsed() throws ParseException {
+ void requireThatSingleLineConstantMappedTensorCanBeParsed() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x{},y{}):{ {x:1,y:2}:1, {x:2,y:1}:2 }\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x{},y{}):{ {x:1,y:2}:1, {x:2,y:1}:2 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile");
@@ -30,16 +30,16 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatSingleLineConstantIndexedTensorCanBeParsed() throws ParseException {
+ void requireThatSingleLineConstantIndexedTensorCanBeParsed() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x[3]):{ {x:0}:1, {x:1}:2, {x:2}:3 }\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x[3]):{ {x:0}:1, {x:1}:2, {x:2}:3 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x[3]):[1.0, 2.0, 3.0]", "constant(my_tensor).value", "my_profile");
@@ -47,16 +47,16 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatSingleLineConstantIndexedTensorShortFormCanBeParsed() throws ParseException {
+ void requireThatSingleLineConstantIndexedTensorShortFormCanBeParsed() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x[3]):[1, 2, 3]\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x[3]):[1, 2, 3]\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x[3]):[1.0, 2.0, 3.0]", "constant(my_tensor).value", "my_profile");
@@ -64,16 +64,16 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireConstantTensorCanBeReferredViaConstantFeature() throws ParseException {
+ void requireConstantTensorCanBeReferredViaConstantFeature() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: sum(constant(my_tensor))\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x{},y{}):{{x:1,y:2}:1, {x:2,y:1}:2}\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: sum(constant(my_tensor))\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x{},y{}):{{x:1,y:2}:1, {x:2,y:1}:2}\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile");
@@ -81,18 +81,18 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatMultiLineConstantTensorAndTypeCanBeParsed() throws ParseException {
+ void requireThatMultiLineConstantTensorAndTypeCanBeParsed() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x{},y{}):\n" +
- " { {x:1,y:2}:1,\n" +
- " {x:2,y:1}:2 }\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x{},y{}):\n" +
+ " { {x:1,y:2}:1,\n" +
+ " {x:2,y:1}:2 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile");
@@ -100,16 +100,16 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatConstantTensorsCanBeUsedInSecondPhaseExpression() throws ParseException {
+ void requireThatConstantTensorsCanBeUsedInSecondPhaseExpression() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " second-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
- " }\n" +
- " }");
+ " second-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertSecondPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile");
@@ -117,20 +117,20 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatConstantTensorsCanBeUsedInInheritedRankProfile() throws ParseException {
+ void requireThatConstantTensorsCanBeUsedInInheritedRankProfile() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile parent {\n" +
- " constants {\n" +
- " my_tensor {\n" +
- " value: { {x:1}:1 }\n" +
- " }\n" +
- " }\n" +
- " }\n" +
- " rank-profile my_profile inherits parent {\n" +
- " first-phase {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " }");
+ " constants {\n" +
+ " my_tensor {\n" +
+ " value: { {x:1}:1 }\n" +
+ " }\n" +
+ " }\n" +
+ " }\n" +
+ " rank-profile my_profile inherits parent {\n" +
+ " first-phase {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile");
f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile");
@@ -138,19 +138,19 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatConstantTensorsCanBeUsedInFunction() throws ParseException {
+ void requireThatConstantTensorsCanBeUsedInFunction() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " function my_macro() {\n" +
- " expression: sum(my_tensor)\n" +
- " }\n" +
- " first-phase {\n" +
- " expression: 5.0 + my_macro\n" +
- " }\n" +
- " constants {\n" +
- " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
- " }\n" +
- " }");
+ " function my_macro() {\n" +
+ " expression: sum(my_tensor)\n" +
+ " }\n" +
+ " first-phase {\n" +
+ " expression: 5.0 + my_macro\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("5.0 + my_macro", "my_profile");
f.assertFunction("reduce(constant(my_tensor), sum)", "my_macro", "my_profile");
@@ -159,18 +159,18 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatCombinationOfConstantTensorsAndConstantValuesCanBeUsed() throws ParseException {
+ void requireThatCombinationOfConstantTensorsAndConstantValuesCanBeUsed() throws ParseException {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " first-phase {\n" +
- " expression: my_number_1 + sum(my_tensor) + my_number_2\n" +
- " }\n" +
- " constants {\n" +
- " my_number_1 double: 3.0\n" +
- " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
- " my_number_2 double: 5.0\n" +
- " }\n" +
- " }");
+ " first-phase {\n" +
+ " expression: my_number_1 + sum(my_tensor) + my_number_2\n" +
+ " }\n" +
+ " constants {\n" +
+ " my_number_1 double: 3.0\n" +
+ " my_tensor tensor(x{}):{ {x:1}:1 }\n" +
+ " my_number_2 double: 5.0\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
f.assertFirstPhaseExpression("3.0 + reduce(constant(my_tensor), sum) + 5.0", "my_profile");
f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile");
@@ -178,20 +178,20 @@ public class RankingExpressionWithTensorTestCase {
}
@Test
- public void requireThatInvalidTensorTypeSpecThrowsException() throws ParseException {
+ void requireThatInvalidTensorTypeSpecThrowsException() throws ParseException {
try {
RankProfileSearchFixture f = new RankProfileSearchFixture(
" rank-profile my_profile {\n" +
- " constants {\n" +
- " my_tensor tensor(x):{ {x:1}:1 }\n" +
- " }\n" +
- " }");
+ " constants {\n" +
+ " my_tensor tensor(x):{ {x:1}:1 }\n" +
+ " }\n" +
+ " }");
f.compileRankProfile("my_profile");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertStartsWith("Type of constant(my_tensor): Illegal tensor type spec: A tensor type spec must be on the form",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java
index f8086fb3bc6..5c82be0745e 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java
@@ -17,16 +17,16 @@ import com.yahoo.searchlib.rankingexpression.RankingExpression;
import com.yahoo.searchlib.rankingexpression.evaluation.MapContext;
import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue;
import com.yahoo.tensor.Tensor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class RankingExpressionWithTransformerTokensTestCase {
@Test
- public void testTokenInputIds() throws Exception {
+ void testTokenInputIds() throws Exception {
String expected = "tensor(d0[1],d1[12]):[101,1,2,102,3,4,5,102,6,7,102,0]";
String a = "tensor(d0[2]):[1,2]";
String b = "tensor(d0[3]):[3,4,5]";
@@ -37,7 +37,7 @@ public class RankingExpressionWithTransformerTokensTestCase {
}
@Test
- public void testTokenTypeIds() throws Exception {
+ void testTokenTypeIds() throws Exception {
String expected = "tensor(d0[1],d1[10]):[0,0,0,0,1,1,1,1,0,0]";
String a = "tensor(d0[2]):[1,2]";
String b = "tensor(d0[3]):[3,4,5]";
@@ -47,7 +47,7 @@ public class RankingExpressionWithTransformerTokensTestCase {
}
@Test
- public void testAttentionMask() throws Exception {
+ void testAttentionMask() throws Exception {
String expected = "tensor(d0[1],d1[10]):[1,1,1,1,1,1,1,1,0,0]";
String a = "tensor(d0[2]):[1,2]";
String b = "tensor(d0[3]):[3,4,5]";
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java
index e1b1473a59a..d01bb1be377 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java
@@ -5,8 +5,8 @@ import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.schema.parser.ParseException;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -22,25 +22,25 @@ public class RankingExpressionWithXGBoostTestCase {
"if (f29 < -0.1234567, if (!(f56 >= -0.242398), 1.71218, -1.70044), if (f109 < 0.8723473, -1.94071, 1.85965)) + " +
"if (!(f60 >= -0.482947), if (f29 < -4.2387498, 0.784718, -0.96853), -6.23624)";
- @After
+ @AfterEach
public void removeGeneratedModelFiles() {
IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
}
@Test
- public void testXGBoostReference() {
+ void testXGBoostReference() {
RankProfileSearchFixture search = fixtureWith("xgboost('xgboost.2.2.json')");
search.assertFirstPhaseExpression(vespaExpression, "my_profile");
}
@Test
- public void testNestedXGBoostReference() {
+ void testNestedXGBoostReference() {
RankProfileSearchFixture search = fixtureWith("5 + sum(xgboost('xgboost.2.2.json'))");
search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile");
}
@Test
- public void testImportingFromStoredExpressions() throws IOException {
+ void testImportingFromStoredExpressions() throws IOException {
RankProfileSearchFixture search = fixtureWith("xgboost('xgboost.2.2.json')");
search.assertFirstPhaseExpression(vespaExpression, "my_profile");
@@ -49,7 +49,7 @@ public class RankingExpressionWithXGBoostTestCase {
try {
storedApplicationDirectory.toFile().mkdirs();
IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(),
- storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
+ storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
RankingExpressionWithOnnxTestCase.StoringApplicationPackage storedApplication = new RankingExpressionWithOnnxTestCase.StoringApplicationPackage(storedApplicationDirectory);
RankProfileSearchFixture searchFromStored = fixtureWith("xgboost('xgboost.2.2.json')");
searchFromStored.assertFirstPhaseExpression(vespaExpression, "my_profile");
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java
index c985d427a5a..526576c9e0b 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java
@@ -18,15 +18,14 @@ import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.derived.TestableDeployLogger;
import com.yahoo.schema.parser.ParseException;
import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class RankingExpressionsTestCase extends AbstractSchemaTestCase {
@@ -35,7 +34,7 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testFunctions() throws IOException, ParseException {
+ void testFunctions() throws IOException, ParseException {
ModelContext.Properties deployProperties = new TestProperties();
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
Schema schema = createSearch("src/test/examples/rankingexpressionfunction", deployProperties, rankProfileRegistry);
@@ -46,13 +45,13 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase {
assertEquals("var2", functions.get("titlematch").function().arguments().get(1));
assertEquals("var1 * var2 + 890", functions.get("titlematch").function().getBody().getRoot().toString());
assertEquals("0.8 + 0.2 * titlematch(4,5) + 0.8 * titlematch(7,8) * closeness(distance)",
- functionsRankProfile.getFirstPhaseRanking().getRoot().toString());
+ functionsRankProfile.getFirstPhaseRanking().getRoot().toString());
assertEquals("78 + closeness(distance)",
- functions.get("artistmatch").function().getBody().getRoot().toString());
+ functions.get("artistmatch").function().getBody().getRoot().toString());
assertEquals(0, functions.get("artistmatch").function().arguments().size());
RawRankProfile rawRankProfile = new RawRankProfile(functionsRankProfile, new LargeRankExpressions(new MockFileRegistry()), new QueryProfileRegistry(),
- new ImportedMlModels(), new AttributeFields(schema), deployProperties);
+ new ImportedMlModels(), new AttributeFields(schema), deployProperties);
List<Pair<String, String>> rankProperties = rawRankProfile.configProperties();
assertEquals(6, rankProperties.size());
@@ -72,11 +71,13 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase {
assertEquals("4 * 5 + 890", rankProperties.get(0).getSecond());
}
- @Test(expected = IllegalArgumentException.class)
- public void testThatIncludingFileInSubdirFails() throws IOException, ParseException {
- RankProfileRegistry registry = new RankProfileRegistry();
- Schema schema = createSearch("src/test/examples/rankingexpressioninfile", new TestProperties(), registry);
- new DerivedConfiguration(schema, registry); // rank profile parsing happens during deriving
+ @Test
+ void testThatIncludingFileInSubdirFails() throws IOException, ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ RankProfileRegistry registry = new RankProfileRegistry();
+ Schema schema = createSearch("src/test/examples/rankingexpressioninfile", new TestProperties(), registry);
+ new DerivedConfiguration(schema, registry); // rank profile parsing happens during deriving
+ }); // rank profile parsing happens during deriving
}
private void verifyProfile(RankProfile profile, List<String> expectedFunctions, List<Pair<String, String>> rankProperties,
@@ -114,7 +115,7 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testLargeInheritedFunctions() throws IOException, ParseException {
+ void testLargeInheritedFunctions() throws IOException, ParseException {
ModelContext.Properties properties = new TestProperties();
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
LargeRankExpressions largeExpressions = new LargeRankExpressions(new MockFileRegistry(), 50);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java
index 57b4d928a52..5f26e7b2964 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java
@@ -9,43 +9,35 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
*/
public class ReferenceFieldTestCase {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void reference_fields_are_parsed_from_search_definition() throws ParseException {
+ void reference_fields_are_parsed_from_search_definition() throws ParseException {
ApplicationBuilder builder = new ApplicationBuilder();
String campaignSdContent =
"schema campaign {\n" +
- " document campaign {\n" +
- " }\n" +
- "}";
+ " document campaign {\n" +
+ " }\n" +
+ "}";
String salespersonSdContent =
"schema salesperson {\n" +
- " document salesperson {\n" +
- " }\n" +
- "}";
+ " document salesperson {\n" +
+ " }\n" +
+ "}";
String adSdContent =
"schema ad {\n" +
- " document ad {\n" +
- " field campaign_ref type reference<campaign> { indexing: attribute }\n" +
- " field salesperson_ref type reference<salesperson> { indexing: attribute }\n" +
- " }\n" +
- "}";
+ " document ad {\n" +
+ " field campaign_ref type reference<campaign> { indexing: attribute }\n" +
+ " field salesperson_ref type reference<salesperson> { indexing: attribute }\n" +
+ " }\n" +
+ "}";
builder.addSchema(campaignSdContent);
builder.addSchema(salespersonSdContent);
builder.addSchema(adSdContent);
@@ -56,37 +48,38 @@ public class ReferenceFieldTestCase {
}
@Test
- public void cyclic_document_dependencies_are_detected() throws ParseException {
- var builder = new ApplicationBuilder(new TestProperties());
- String campaignSdContent =
- "schema campaign {\n" +
- " document campaign {\n" +
- " field ad_ref type reference<ad> { indexing: attribute }\n" +
- " }\n" +
- "}";
- String adSdContent =
- "schema ad {\n" +
- " document ad {\n" +
- " field campaign_ref type reference<campaign> { indexing: attribute }\n" +
- " }\n" +
- "}";
- builder.addSchema(campaignSdContent);
- builder.addSchema(adSdContent);
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("reference cycle for documents");
- builder.build(true);
+ void cyclic_document_dependencies_are_detected() throws ParseException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ var builder = new ApplicationBuilder(new TestProperties());
+ String campaignSdContent =
+ "schema campaign {\n" +
+ " document campaign {\n" +
+ " field ad_ref type reference<ad> { indexing: attribute }\n" +
+ " }\n" +
+ "}";
+ String adSdContent =
+ "schema ad {\n" +
+ " document ad {\n" +
+ " field campaign_ref type reference<campaign> { indexing: attribute }\n" +
+ " }\n" +
+ "}";
+ builder.addSchema(campaignSdContent);
+ builder.addSchema(adSdContent);
+ builder.build(true);
+ });
+ assertTrue(exception.getMessage().contains("reference cycle for documents"));
}
private static void assertSearchContainsReferenceField(String expectedFieldname,
String referencedDocType,
SDDocumentType documentType) {
Field field = documentType.getDocumentType().getField(expectedFieldname);
- assertNotNull("Field does not exist in document type: " + expectedFieldname, field);
+ assertNotNull(field, "Field does not exist in document type: " + expectedFieldname);
DataType dataType = field.getDataType();
assertTrue(dataType instanceof NewDocumentReferenceDataType);
NewDocumentReferenceDataType refField = (NewDocumentReferenceDataType) dataType;
assertEquals(referencedDocType, refField.getTargetTypeName());
- assertTrue(! refField.isTemporary());
+ assertFalse(refField.isTemporary());
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java
index 974d8c261ca..404b8f648cf 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java
@@ -3,12 +3,12 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.derived.AbstractExportingTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class ReservedDocumentNamesTestCase extends AbstractExportingTestCase {
@Test
- public void requireThatPositionIsAReservedDocumentName() throws IOException, ParseException {
+ void requireThatPositionIsAReservedDocumentName() throws IOException, ParseException {
try {
assertCorrectDeriving("reserved_position");
fail();
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java
index e405a105f3c..f657efffde7 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java
@@ -5,12 +5,12 @@ import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.schema.RankProfileRegistry;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.logging.Level;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author lesters
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class ReservedRankingExpressionFunctionNamesTestCase {
@Test
- public void requireThatFunctionsWithReservedNamesIssueAWarning() throws ParseException {
+ void requireThatFunctionsWithReservedNamesIssueAWarning() throws ParseException {
TestDeployLogger deployLogger = new TestDeployLogger();
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
ApplicationBuilder builder = new ApplicationBuilder(deployLogger, rankProfileRegistry);
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java b/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java
index 03f9d7c5960..6e5e17398d9 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java
@@ -3,11 +3,11 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author hmusum
@@ -15,13 +15,13 @@ import static org.junit.Assert.fail;
public class SchemaMustHaveDocumentTest {
@Test
- public void requireErrorWhenMissingDocument() throws IOException, ParseException {
+ void requireErrorWhenMissingDocument() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_missing_document.sd");
fail("SD without document");
} catch (IllegalArgumentException e) {
if (!e.getMessage()
- .contains("For schema 'imageconfig': A search specification must have an equally named document inside of it.")) {
+ .contains("For schema 'imageconfig': A search specification must have an equally named document inside of it.")) {
throw e;
}
}
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java
index 76132a4d09f..c5f0fb49946 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java
@@ -5,15 +5,15 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.documentmodel.SummaryTransform;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class SummaryConsistencyTestCase {
@Test
- public void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException {
+ void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException {
String sd = joinLines(
"search structmemorysummary {",
" document structmemorysummary {",
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java
index d94815015d7..22151063eb7 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java
@@ -9,17 +9,17 @@ import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTestCase {
@Test
- public void requireThatInvalidSourceIsCaught() throws IOException, ParseException {
+ void requireThatInvalidSourceIsCaught() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalidsummarysource.sd");
fail("This should throw and never get here");
@@ -29,7 +29,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest
}
@Test
- public void requireThatInvalidImplicitSourceIsCaught() throws IOException, ParseException {
+ void requireThatInvalidImplicitSourceIsCaught() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalidimplicitsummarysource.sd");
fail("This should throw and never get here");
@@ -39,7 +39,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest
}
@Test
- public void requireThatInvalidSelfReferingSingleSource() throws IOException, ParseException {
+ void requireThatInvalidSelfReferingSingleSource() throws IOException, ParseException {
try {
ApplicationBuilder.buildFromFile("src/test/examples/invalidselfreferringsummary.sd");
fail("This should throw and never get here");
@@ -49,7 +49,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest
}
@Test
- public void requireThatDocumentIdIsAllowedToPass() throws IOException, ParseException {
+ void requireThatDocumentIdIsAllowedToPass() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/documentidinsummary.sd");
BaseDeployLogger deployLogger = new BaseDeployLogger();
RankProfileRegistry rankProfileRegistry = new RankProfileRegistry();
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java
index 9164f361a92..60e1e35fb2e 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java
@@ -3,15 +3,12 @@ package com.yahoo.schema.processing;
import com.yahoo.schema.document.Attribute;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.schema.ApplicationBuilder.createFromString;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
@@ -19,32 +16,32 @@ import static org.junit.Assert.fail;
public class TensorFieldTestCase {
@Test
- public void requireThatTensorFieldCannotBeOfCollectionType() throws ParseException {
+ void requireThatTensorFieldCannotBeOfCollectionType() throws ParseException {
try {
createFromString(getSd("field f1 type array<tensor(x{})> {}"));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'f1': A field with collection type of tensor is not supported. Use simple type 'tensor' instead.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatTensorFieldCannotBeIndexField() throws ParseException {
+ void requireThatTensorFieldCannotBeIndexField() throws ParseException {
try {
createFromString(getSd("field f1 type tensor(x{}) { indexing: index }"));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("For schema 'test', field 'f1': A tensor of type 'tensor(x{})' does not support having an 'index'. " +
- "Currently, only tensors with 1 indexed dimension supports that.",
- e.getMessage());
+ "Currently, only tensors with 1 indexed dimension supports that.",
+ e.getMessage());
}
}
@Test
- public void requireThatIndexedTensorAttributeCannotBeFastSearch() throws ParseException {
+ void requireThatIndexedTensorAttributeCannotBeFastSearch() throws ParseException {
try {
createFromString(getSd("field f1 type tensor(x[3]) { indexing: attribute \n attribute: fast-search }"));
fail("Expected exception");
@@ -55,7 +52,7 @@ public class TensorFieldTestCase {
}
@Test
- public void requireThatIndexedTensorAttributeCannotBeFastRank() throws ParseException {
+ void requireThatIndexedTensorAttributeCannotBeFastRank() throws ParseException {
try {
createFromString(getSd("field f1 type tensor(x[3]) { indexing: attribute \n attribute: fast-rank }"));
fail("Expected exception");
@@ -66,7 +63,7 @@ public class TensorFieldTestCase {
}
@Test
- public void requireThatIllegalTensorTypeSpecThrowsException() throws ParseException {
+ void requireThatIllegalTensorTypeSpecThrowsException() throws ParseException {
try {
createFromString(getSd("field f1 type tensor(invalid) { indexing: attribute }"));
fail("Expected exception");
@@ -77,19 +74,19 @@ public class TensorFieldTestCase {
}
@Test
- public void hnsw_index_is_default_turned_off() throws ParseException {
+ void hnsw_index_is_default_turned_off() throws ParseException {
var attr = getAttributeFromSd("field t1 type tensor(x[64]) { indexing: attribute }", "t1");
assertFalse(attr.hnswIndexParams().isPresent());
}
@Test
- public void hnsw_index_gets_default_parameters_if_not_specified() throws ParseException {
+ void hnsw_index_gets_default_parameters_if_not_specified() throws ParseException {
assertHnswIndexParams("", 16, 200);
assertHnswIndexParams("index: hnsw", 16, 200);
}
@Test
- public void hnsw_index_parameters_can_be_specified() throws ParseException {
+ void hnsw_index_parameters_can_be_specified() throws ParseException {
assertHnswIndexParams("index { hnsw { max-links-per-node: 32 } }", 32, 200);
assertHnswIndexParams("index { hnsw { neighbors-to-explore-at-insert: 300 } }", 16, 300);
assertHnswIndexParams(joinLines("index {",
@@ -102,7 +99,7 @@ public class TensorFieldTestCase {
}
@Test
- public void tensor_with_hnsw_index_must_be_an_attribute() throws ParseException {
+ void tensor_with_hnsw_index_must_be_an_attribute() throws ParseException {
try {
createFromString(getSd("field t1 type tensor(x[64]) { indexing: index }"));
fail("Expected exception");
@@ -113,7 +110,7 @@ public class TensorFieldTestCase {
}
@Test
- public void tensor_with_hnsw_index_parameters_must_be_an_index() throws ParseException {
+ void tensor_with_hnsw_index_parameters_must_be_an_index() throws ParseException {
try {
createFromString(getSd(joinLines(
"field t1 type tensor(x[64]) {",
@@ -132,7 +129,7 @@ public class TensorFieldTestCase {
}
@Test
- public void tensors_with_at_least_one_mapped_dimension_can_be_direct() throws ParseException {
+ void tensors_with_at_least_one_mapped_dimension_can_be_direct() throws ParseException {
assertTrue(getAttributeFromSd(
"field t1 type tensor(x{}) { indexing: attribute \n attribute: fast-search }", "t1").isFastSearch());
assertTrue(getAttributeFromSd(
@@ -140,7 +137,7 @@ public class TensorFieldTestCase {
}
@Test
- public void tensors_with_at_least_one_mapped_dimension_can_be_fast_rank() throws ParseException {
+ void tensors_with_at_least_one_mapped_dimension_can_be_fast_rank() throws ParseException {
assertTrue(getAttributeFromSd(
"field t1 type tensor(x{}) { indexing: attribute \n attribute: fast-rank }", "t1").isFastRank());
assertTrue(getAttributeFromSd(
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java
index aaf5f381c62..028ad5dea86 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java
@@ -20,109 +20,109 @@ import com.yahoo.schema.derived.AttributeFields;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.schema.parser.ParseException;
import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class TensorTransformTestCase extends AbstractSchemaTestCase {
@Test
- public void requireThatNormalMaxAndMinAreNotReplaced() throws ParseException {
+ void requireThatNormalMaxAndMinAreNotReplaced() throws ParseException {
assertTransformedExpression("max(1.0,2.0)",
- "max(1.0,2.0)");
+ "max(1.0,2.0)");
assertTransformedExpression("min(attribute(double_field),x)",
- "min(attribute(double_field),x)");
+ "min(attribute(double_field),x)");
assertTransformedExpression("max(attribute(double_field),attribute(double_array_field))",
- "max(attribute(double_field),attribute(double_array_field))");
+ "max(attribute(double_field),attribute(double_array_field))");
assertTransformedExpression("min(attribute(tensor_field_1),attribute(double_field))",
- "min(attribute(tensor_field_1),attribute(double_field))");
+ "min(attribute(tensor_field_1),attribute(double_field))");
assertTransformedExpression("reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)",
- "reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)");
+ "reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)");
assertTransformedExpression("min(constant(test_constant_tensor),1.0)",
- "min(test_constant_tensor,1.0)");
+ "min(test_constant_tensor,1.0)");
assertTransformedExpression("max(constant(base_constant_tensor),1.0)",
- "max(base_constant_tensor,1.0)");
+ "max(base_constant_tensor,1.0)");
assertTransformedExpression("min(constant(file_constant_tensor),1.0)",
- "min(constant(file_constant_tensor),1.0)");
+ "min(constant(file_constant_tensor),1.0)");
assertTransformedExpression("max(query(q),1.0)",
- "max(query(q),1.0)");
+ "max(query(q),1.0)");
assertTransformedExpression("max(query(n),1.0)",
- "max(query(n),1.0)");
+ "max(query(n),1.0)");
}
@Test
- public void requireThatMaxAndMinWithTensorAttributesAreReplaced() throws ParseException {
+ void requireThatMaxAndMinWithTensorAttributesAreReplaced() throws ParseException {
assertTransformedExpression("reduce(attribute(tensor_field_1),max,x)",
- "max(attribute(tensor_field_1),x)");
+ "max(attribute(tensor_field_1),x)");
assertTransformedExpression("1+reduce(attribute(tensor_field_1),max,x)",
- "1 + max(attribute(tensor_field_1),x)");
+ "1 + max(attribute(tensor_field_1),x)");
assertTransformedExpression("if(attribute(double_field),1+reduce(attribute(tensor_field_1),max,x),reduce(attribute(tensor_field_1),sum,x))",
- "if(attribute(double_field),1 + max(attribute(tensor_field_1),x),reduce(attribute(tensor_field_1), sum, x))");
+ "if(attribute(double_field),1 + max(attribute(tensor_field_1),x),reduce(attribute(tensor_field_1), sum, x))");
assertTransformedExpression("reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),max,x)",
- "max(max(attribute(tensor_field_1),attribute(tensor_field_2)),x)");
+ "max(max(attribute(tensor_field_1),attribute(tensor_field_2)),x)");
assertTransformedExpression("reduce(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),max,x)",
- "max(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),x)");
+ "max(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),x)");
assertTransformedExpression("max(reduce(attribute(tensor_field_1),max,x),x)",
- "max(max(attribute(tensor_field_1),x),x)"); // will result in deploy error.
+ "max(max(attribute(tensor_field_1),x),x)"); // will result in deploy error.
assertTransformedExpression("reduce(reduce(attribute(tensor_field_2),max,x),max,y)",
- "max(max(attribute(tensor_field_2),x),y)");
+ "max(max(attribute(tensor_field_2),x),y)");
}
@Test
- public void requireThatMaxAndMinWithConstantTensorsAreReplaced() throws ParseException {
+ void requireThatMaxAndMinWithConstantTensorsAreReplaced() throws ParseException {
assertTransformedExpression("reduce(constant(test_constant_tensor),max,x)",
- "max(test_constant_tensor,x)");
+ "max(test_constant_tensor,x)");
assertTransformedExpression("reduce(constant(base_constant_tensor),max,x)",
- "max(base_constant_tensor,x)");
+ "max(base_constant_tensor,x)");
assertTransformedExpression("reduce(constant(file_constant_tensor),min,x)",
- "min(constant(file_constant_tensor),x)");
+ "min(constant(file_constant_tensor),x)");
}
@Test
- public void requireThatMaxAndMinWithTensorExpressionsAreReplaced() throws ParseException {
+ void requireThatMaxAndMinWithTensorExpressionsAreReplaced() throws ParseException {
assertTransformedExpression("reduce(attribute(double_field)+attribute(tensor_field_1),min,x)",
- "min(attribute(double_field) + attribute(tensor_field_1),x)");
+ "min(attribute(double_field) + attribute(tensor_field_1),x)");
assertTransformedExpression("reduce(attribute(tensor_field_1)*attribute(tensor_field_2),min,x)",
- "min(attribute(tensor_field_1) * attribute(tensor_field_2),x)");
+ "min(attribute(tensor_field_1) * attribute(tensor_field_2),x)");
assertTransformedExpression("reduce(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),min,x)",
- "min(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),x)");
+ "min(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),x)");
assertTransformedExpression("min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)",
- "min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)"); // because tensor fields are not in attribute(...)
+ "min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)"); // because tensor fields are not in attribute(...)
assertTransformedExpression("reduce(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),min,x)",
- "min(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),x)");
+ "min(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),x)");
}
@Test
- public void requireThatMaxAndMinWithTensorFromIsReplaced() throws ParseException {
+ void requireThatMaxAndMinWithTensorFromIsReplaced() throws ParseException {
assertTransformedExpression("reduce(tensorFromLabels(attribute(double_array_field)),max,double_array_field)",
- "max(tensorFromLabels(attribute(double_array_field)),double_array_field)");
+ "max(tensorFromLabels(attribute(double_array_field)),double_array_field)");
assertTransformedExpression("reduce(tensorFromLabels(attribute(double_array_field),x),max,x)",
- "max(tensorFromLabels(attribute(double_array_field),x),x)");
+ "max(tensorFromLabels(attribute(double_array_field),x),x)");
assertTransformedExpression("reduce(tensorFromWeightedSet(attribute(weightedset_field)),max,weightedset_field)",
- "max(tensorFromWeightedSet(attribute(weightedset_field)),weightedset_field)");
+ "max(tensorFromWeightedSet(attribute(weightedset_field)),weightedset_field)");
assertTransformedExpression("reduce(tensorFromWeightedSet(attribute(weightedset_field),x),max,x)",
- "max(tensorFromWeightedSet(attribute(weightedset_field),x),x)");
+ "max(tensorFromWeightedSet(attribute(weightedset_field),x),x)");
}
@Test
- public void requireThatMaxAndMinWithTensorInQueryIsReplaced() throws ParseException {
+ void requireThatMaxAndMinWithTensorInQueryIsReplaced() throws ParseException {
assertTransformedExpression("reduce(query(q),max,x)", "max(query(q),x)");
assertTransformedExpression("max(query(n),x)", "max(query(n),x)");
}
@Test
- public void requireThatMaxAndMinWithTensorsReturnedFromFunctionsAreReplaced() throws ParseException {
+ void requireThatMaxAndMinWithTensorsReturnedFromFunctionsAreReplaced() throws ParseException {
assertTransformedExpression("reduce(rankingExpression(returns_tensor),max,x)",
- "max(returns_tensor,x)");
+ "max(returns_tensor,x)");
assertTransformedExpression("reduce(rankingExpression(wraps_returns_tensor),max,x)",
- "max(wraps_returns_tensor,x)");
+ "max(wraps_returns_tensor,x)");
assertTransformedExpression("reduce(rankingExpression(tensor_inheriting),max,x)",
- "max(tensor_inheriting,x)");
+ "max(tensor_inheriting,x)");
assertTransformedExpression("reduce(rankingExpression(returns_tensor_with_arg@),max,x)",
- "max(returns_tensor_with_arg(attribute(tensor_field_1)),x)");
+ "max(returns_tensor_with_arg(attribute(tensor_field_1)),x)");
}
private void assertTransformedExpression(String expected, String original) throws ParseException {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java
index 87bb2e96042..5f0940f0d2d 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java
@@ -16,12 +16,13 @@ import com.yahoo.schema.document.SDDocumentType;
import com.yahoo.schema.document.SDField;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* @author bjorncs
*/
@@ -30,22 +31,18 @@ public class ValidateFieldTypesTest {
private static final String IMPORTED_FIELD_NAME = "imported_myfield";
private static final String DOCUMENT_NAME = "my_doc";
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void throws_exception_if_type_of_document_field_does_not_match_summary_field() {
- Schema schema = createSearchWithDocument(DOCUMENT_NAME);
- schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME, DataType.INT));
- schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, DataType.STRING, schema));
+ void throws_exception_if_type_of_document_field_does_not_match_summary_field() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ Schema schema = createSearchWithDocument(DOCUMENT_NAME);
+ schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME, DataType.INT));
+ schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, DataType.STRING, schema));
- ValidateFieldTypes validator = new ValidateFieldTypes(schema, null, null, null);
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "For schema '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " +
- "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string.");
- validator.process(true, false);
+ ValidateFieldTypes validator = new ValidateFieldTypes(schema, null, null, null);
+ validator.process(true, false);
+ });
+ assertTrue(exception.getMessage().contains("For schema '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " +
+ "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string."));
}
private static Schema createSearch(String documentType) {
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java
index 016e30e80af..dc72df9fc78 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.path.Path;
import com.yahoo.schema.derived.RawRankProfile;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.ml.ImportedModelTester;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests adding Vespa ranking expression based models in the models/ dir
@@ -37,13 +37,13 @@ public class VespaMlModelTestCase {
/** The model name */
private final String name = "example";
- @After
+ @AfterEach
public void removeGeneratedModelFiles() {
IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
}
@Test
- public void testGlobalVespaModel() throws IOException {
+ void testGlobalVespaModel() throws IOException {
ImportedModelTester tester = new ImportedModelTester(name, applicationDir);
VespaModel model = tester.createVespaModel();
tester.assertLargeConstant("constant1asLarge", model, Optional.of(3L));
@@ -55,7 +55,7 @@ public class VespaMlModelTestCase {
storedAppDir.toFile().mkdirs();
IOUtils.copy(applicationDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString());
IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(),
- storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
+ storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
ImportedModelTester storedTester = new ImportedModelTester(name, storedAppDir);
VespaModel storedModel = storedTester.createVespaModel();
storedTester.assertLargeConstant("constant1asLarge", model, Optional.of(3L));
diff --git a/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java
index 2f62228cc3f..95d01946969 100644
--- a/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java
+++ b/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java
@@ -5,17 +5,17 @@ import com.yahoo.schema.Schema;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/** @author bratseth */
public class WeightedSetSummaryToTestCase extends AbstractSchemaTestCase {
@Test
- public void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException {
+ void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException {
Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/weightedset-summaryto.sd");
assertNotNull(schema);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java
index faf4b67430c..c4037538252 100644
--- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.documentmodel;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -12,17 +12,17 @@ import static com.yahoo.config.model.test.TestUtil.joinLines;
public class DocumentModelBuilderImportedFieldsTestCase extends AbstractReferenceFieldTestCase {
@Test
- public void imported_fields_are_included_in_generated_document_configs() throws ParseException, IOException {
+ void imported_fields_are_included_in_generated_document_configs() throws ParseException, IOException {
assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().addPerson().build(joinLines(
- "search ad {",
- " document ad {",
- " field campaign_ref type reference<campaign> { indexing: attribute }",
- " field person_ref type reference<person> { indexing: attribute }",
- " }",
- " import field campaign_ref.cool_field as my_cool_field {}",
- " import field campaign_ref.swag_field as my_swag_field {}",
- " import field person_ref.name as my_name {}",
- "}")),
+ "search ad {",
+ " document ad {",
+ " field campaign_ref type reference<campaign> { indexing: attribute }",
+ " field person_ref type reference<person> { indexing: attribute }",
+ " }",
+ " import field campaign_ref.cool_field as my_cool_field {}",
+ " import field campaign_ref.swag_field as my_swag_field {}",
+ " import field person_ref.name as my_name {}",
+ "}")),
"multiple_imported_fields");
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java
index 3c2193ca4df..fdacc777eaf 100644
--- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java
@@ -5,12 +5,12 @@ import com.yahoo.documentmodel.NewDocumentReferenceDataType;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.schema.ApplicationBuilder;
import com.yahoo.schema.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -18,31 +18,31 @@ import static org.junit.Assert.assertEquals;
public class DocumentModelBuilderReferenceTypeTestCase extends AbstractReferenceFieldTestCase {
@Test
- public void reference_fields_can_reference_other_document_types() throws ParseException, IOException {
+ void reference_fields_can_reference_other_document_types() throws ParseException, IOException {
assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().addPerson().build(joinLines(
- "search ad {",
- " document ad {",
- " field campaign_ref type reference<campaign> { indexing: attribute }",
- " field person_ref type reference<person> { indexing: attribute }",
- " }",
- "}")),
+ "search ad {",
+ " document ad {",
+ " field campaign_ref type reference<campaign> { indexing: attribute }",
+ " field person_ref type reference<person> { indexing: attribute }",
+ " }",
+ "}")),
"refs_to_other_types");
}
@Test
- public void reference_fields_can_reference_same_document_type_multiple_times() throws ParseException, IOException {
+ void reference_fields_can_reference_same_document_type_multiple_times() throws ParseException, IOException {
assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().build(joinLines(
- "search ad {",
- " document ad {",
- " field campaign_ref type reference<campaign> { indexing: attribute }",
- " field other_campaign_ref type reference<campaign> { indexing: attribute }",
- " }",
- "}")),
+ "search ad {",
+ " document ad {",
+ " field campaign_ref type reference<campaign> { indexing: attribute }",
+ " field other_campaign_ref type reference<campaign> { indexing: attribute }",
+ " }",
+ "}")),
"refs_to_same_type");
}
@Test
- public void reference_data_type_has_a_concrete_target_type() throws ParseException {
+ void reference_data_type_has_a_concrete_target_type() throws ParseException {
DocumentModel model = new TestDocumentModelBuilder().addCampaign().build(joinLines(
"search ad {",
" document ad {",
diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java
index d345c776db3..7fe58c93434 100644
--- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java
@@ -8,24 +8,26 @@ import com.yahoo.schema.AbstractSchemaTestCase;
import com.yahoo.schema.parser.ParseException;
import com.yahoo.vespa.configmodel.producers.DocumentManager;
import com.yahoo.vespa.configmodel.producers.DocumentTypes;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase {
@Test
- public void testDocumentManagerSimple() throws IOException, ParseException {
+ void testDocumentManagerSimple() throws IOException, ParseException {
DocumentModel model = createAndTestModel("src/test/configmodel/types/types.sd");
DocumentmanagerConfig.Builder documentmanagerCfg = new DocumentManager().produce(model, new DocumentmanagerConfig.Builder());
assertConfigFile("src/test/configmodel/types/documentmanager.cfg",
new DocumentmanagerConfig(documentmanagerCfg).toString());
}
- @Test
+
// This is ignored as enums in config are not testable in this way. See bug 4748050
- public void testDocumentTypesSimple() throws IOException, ParseException {
+ @Test
+ void testDocumentTypesSimple() throws IOException, ParseException {
DocumentModel model = createAndTestModel("src/test/configmodel/types/types.sd");
DocumenttypesConfig.Builder documenttypesCfg = new DocumentTypes().produce(model, new DocumenttypesConfig.Builder());
@@ -34,7 +36,7 @@ public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testDocumentTypesWithDocumentField() throws IOException, ParseException {
+ void testDocumentTypesWithDocumentField() throws IOException, ParseException {
ApplicationBuilder search = new ApplicationBuilder();
search.addSchemaFile("src/test/configmodel/types/other_doc.sd");
search.addSchemaFile("src/test/configmodel/types/type_with_doc_field.sd");
@@ -47,7 +49,7 @@ public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase {
}
@Test
- public void testMultipleInheritanceArray() throws IOException, ParseException {
+ void testMultipleInheritanceArray() throws IOException, ParseException {
ApplicationBuilder search = new ApplicationBuilder();
search.addSchemaFile("src/test/cfg/search/data/travel/schemas/TTData.sd");
search.addSchemaFile("src/test/cfg/search/data/travel/schemas/TTEdge.sd");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java
index 31d089d64db..731aa02fd0b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java
@@ -5,13 +5,14 @@ import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.config.provision.NetworkPorts;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.hamcrest.MatcherAssert.assertThat;
/**
@@ -20,13 +21,13 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class HostPortsTest {
@Test
- public void next_available_baseport_is_BASE_PORT_when_no_ports_have_been_reserved() {
+ void next_available_baseport_is_BASE_PORT_when_no_ports_have_been_reserved() {
HostPorts host = new HostPorts("myhostname");
assertThat(host.nextAvailableBaseport(1), is(HostPorts.BASE_PORT));
}
@Test
- public void next_available_baseport_is_BASE_PORT_plus_one_when_one_port_has_been_reserved() {
+ void next_available_baseport_is_BASE_PORT_plus_one_when_one_port_has_been_reserved() {
HostPorts host = new HostPorts("myhostname");
MockRoot root = new MockRoot();
host.reservePort(new TestService(root, 1), HostPorts.BASE_PORT, "foo");
@@ -34,7 +35,7 @@ public class HostPortsTest {
}
@Test
- public void no_available_baseport_when_service_requires_more_consecutive_ports_than_available() {
+ void no_available_baseport_when_service_requires_more_consecutive_ports_than_available() {
HostPorts host = new HostPorts("myhostname");
MockRoot root = new MockRoot();
@@ -51,32 +52,36 @@ public class HostPortsTest {
}
@Test
- public void port_above_vespas_port_range_can_be_reserved() {
+ void port_above_vespas_port_range_can_be_reserved() {
HostPorts host = new HostPorts("myhostname");
MockRoot root = new MockRoot();
host.allocatePorts(new TestService(root, 1), HostPorts.BASE_PORT + HostPorts.MAX_PORTS + 1);
}
- @Test(expected = RuntimeException.class)
- public void allocating_same_port_throws_exception() {
- HostPorts host = new HostPorts("myhostname");
- MockRoot root = new MockRoot();
- TestService service1 = new TestService(root, 1);
- TestService service2 = new TestService(root, 1);
-
- host.allocatePorts(service1, HostPorts.BASE_PORT);
- host.allocatePorts(service2, HostPorts.BASE_PORT);
+ @Test
+ void allocating_same_port_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ HostPorts host = new HostPorts("myhostname");
+ MockRoot root = new MockRoot();
+ TestService service1 = new TestService(root, 1);
+ TestService service2 = new TestService(root, 1);
+
+ host.allocatePorts(service1, HostPorts.BASE_PORT);
+ host.allocatePorts(service2, HostPorts.BASE_PORT);
+ });
}
- @Test(expected = RuntimeException.class)
- public void allocating_overlapping_ports_throws_exception() {
- HostPorts host = new HostPorts("myhostname");
- MockRoot root = new MockRoot();
- TestService service2 = new TestService(root, 2);
- TestService service1 = new TestService(root, 1);
-
- host.allocatePorts(service2, HostPorts.BASE_PORT);
- host.allocatePorts(service1, HostPorts.BASE_PORT + 1);
+ @Test
+ void allocating_overlapping_ports_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ HostPorts host = new HostPorts("myhostname");
+ MockRoot root = new MockRoot();
+ TestService service2 = new TestService(root, 2);
+ TestService service1 = new TestService(root, 1);
+
+ host.allocatePorts(service2, HostPorts.BASE_PORT);
+ host.allocatePorts(service1, HostPorts.BASE_PORT + 1);
+ });
}
NetworkPorts emulOldPorts() {
@@ -87,7 +92,7 @@ public class HostPortsTest {
}
@Test
- public void use_old_port_when_available() {
+ void use_old_port_when_available() {
HostPorts host = new HostPorts("myhostname");
host.addNetworkPorts(emulOldPorts());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java b/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java
index ea075dc1129..d59d0e51b23 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java
@@ -7,13 +7,13 @@ import com.yahoo.config.provision.ClusterMembership;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import static com.yahoo.config.provision.ClusterSpec.Type.container;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class HostResourceTest {
@Test
- public void require_exception_when_no_matching_hostalias() {
+ void require_exception_when_no_matching_hostalias() {
MockRoot root = new MockRoot();
TestService service = new TestService(root, 1);
@@ -34,7 +34,7 @@ public class HostResourceTest {
}
@Test
- public void host_with_membership() {
+ void host_with_membership() {
HostResource host = hostResourceWithMemberships(ClusterMembership.from(clusterSpec(container, "container"), 0));
assertClusterMembership(host, container, "container");
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java b/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java
index 636bfebaaf5..8440951a06f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java
@@ -7,18 +7,18 @@ import com.yahoo.test.FunctionTestConfig.*;
import com.yahoo.test.SimpletypesConfig;
import com.yahoo.config.codegen.*;
import com.yahoo.text.StringUtilities;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class InstanceResolverTest {
@Test
- public void testApplyDefToBuilder() throws Exception {
+ void testApplyDefToBuilder() throws Exception {
FunctionTestConfig.Builder builder = createVariableAccessBuilder();
InnerCNode targetDef = getDef(FunctionTestConfig.CONFIG_DEF_SCHEMA);
@@ -58,7 +58,7 @@ public class InstanceResolverTest {
* Values unset on builder, trying to set them from def file, but type mismatches there
*/
@Test
- public void testApplyDefToBuilderMismatches() throws Exception {
+ void testApplyDefToBuilderMismatches() throws Exception {
FunctionTestConfig.Builder builder = createVariableAccessBuilderManyUnset();
InnerCNode targetDef = getDef(FunctionTestConfig.CONFIG_DEF_SCHEMA);
@@ -223,7 +223,7 @@ public class InstanceResolverTest {
}
@Test
- public void testExtraFieldsAreIgnored() throws Exception {
+ void testExtraFieldsAreIgnored() throws Exception {
try {
SimpletypesConfig.Builder builder = new SimpletypesConfig.Builder();
InnerCNode defWithExtra = new DefParser(SimpletypesConfig.CONFIG_DEF_NAME, new StringReader(StringUtilities.implode(SimpletypesConfig.CONFIG_DEF_SCHEMA, "\n") + "\nnewfield string default=\"foo\"\n")).getTree();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java
index 4042723856f..0cb1ecf6f5e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertTrue;
public class RecentLogFilterTest {
@Test
- public void basic() {
+ void basic() {
RecentLogFilter rlf = new RecentLogFilter();
List<LogRecord> logRecords = new ArrayList<>();
for (int i = 0; i < RecentLogFilter.maxMessages + 1; i++) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java b/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java
index 104fdea0e40..567b44e9544 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java
@@ -19,16 +19,14 @@ import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.ProvisionLogger;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -37,13 +35,13 @@ public class VespaModelFactoryTest {
private ModelContext testModelContext;
- @Before
+ @BeforeEach
public void setupContext() {
testModelContext = new MockModelContext();
}
@Test
- public void testThatFactoryCanBuildModel() {
+ void testThatFactoryCanBuildModel() {
VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
Model model = modelFactory.createModel(testModelContext);
assertNotNull(model);
@@ -51,21 +49,25 @@ public class VespaModelFactoryTest {
}
// Uses an application package that throws IllegalArgumentException when validating
- @Test(expected = IllegalArgumentException.class)
- public void testThatFactoryModelValidationFailsWithIllegalArgumentException() {
- VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
- modelFactory.createAndValidateModel(new MockModelContext(createApplicationPackageThatFailsWhenValidating()), new ValidationParameters());
+ @Test
+ void testThatFactoryModelValidationFailsWithIllegalArgumentException() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
+ modelFactory.createAndValidateModel(new MockModelContext(createApplicationPackageThatFailsWhenValidating()), new ValidationParameters());
+ });
}
// Uses a MockApplicationPackage that throws throws UnsupportedOperationException (rethrown as RuntimeException) when validating
- @Test(expected = RuntimeException.class)
- public void testThatFactoryModelValidationFails() {
- VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
- modelFactory.createAndValidateModel(testModelContext, new ValidationParameters());
+ @Test
+ void testThatFactoryModelValidationFails() {
+ assertThrows(RuntimeException.class, () -> {
+ VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
+ modelFactory.createAndValidateModel(testModelContext, new ValidationParameters());
+ });
}
@Test
- public void testThatFactoryModelValidationCanBeIgnored() {
+ void testThatFactoryModelValidationCanBeIgnored() {
VespaModelFactory modelFactory = VespaModelFactory.createTestFactory();
ModelCreateResult createResult = modelFactory.createAndValidateModel(
new MockModelContext(createApplicationPackageThatFailsWhenValidating()),
@@ -76,7 +78,7 @@ public class VespaModelFactoryTest {
}
@Test
- public void hostedVespaZoneApplicationAllocatesNodesFromNodeRepo() {
+ void hostedVespaZoneApplicationAllocatesNodesFromNodeRepo() {
String hostName = "test-host-name";
String routingClusterName = "routing-cluster";
@@ -103,17 +105,17 @@ public class VespaModelFactoryTest {
@Override
public HostSpec allocateHost(String alias) {
return new HostSpec(hostName,
- NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(),
- ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.admin, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0),
- Optional.empty(), Optional.empty(), Optional.empty());
+ NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(),
+ ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.admin, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0),
+ Optional.empty(), Optional.empty(), Optional.empty());
}
@Override
public List<HostSpec> prepare(ClusterSpec cluster, Capacity capacity, ProvisionLogger logger) {
return List.of(new HostSpec(hostName,
- NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(),
- ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.container, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0),
- Optional.empty(), Optional.empty(), Optional.empty()));
+ NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(),
+ ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.container, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0),
+ Optional.empty(), Optional.empty(), Optional.empty()));
}
};
@@ -125,10 +127,10 @@ public class VespaModelFactoryTest {
HostInfo hostInfo = allocatedHosts.get(0);
assertEquals(hostName, hostInfo.getHostname());
- assertTrue("Routing service should run on host " + hostName,
- hostInfo.getServices().stream()
- .map(ServiceInfo::getConfigId)
- .anyMatch(configId -> configId.contains(routingClusterName)));
+ assertTrue(hostInfo.getServices().stream()
+ .map(ServiceInfo::getConfigId)
+ .anyMatch(configId -> configId.contains(routingClusterName)),
+ "Routing service should run on host " + hostName);
}
private ModelContext createMockModelContext(String hosts, String services, HostProvisioner provisionerToOverride) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java
index 7bdf80706d6..d060fdfd3d2 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java
@@ -22,16 +22,12 @@ import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class AdminTestCase {
@@ -46,7 +42,7 @@ public class AdminTestCase {
* Test that version 2.0 of adminconfig works as expected.
*/
@Test
- public void testAdmin20() {
+ void testAdmin20() {
VespaModel vespaModel = getVespaModel(TESTDIR + "adminconfig20");
// Verify that the admin plugin has been loaded (always loads routing).
@@ -110,7 +106,7 @@ public class AdminTestCase {
* adminserver, logserver, configserver and slobroks
*/
@Test
- public void testOnlyAdminserver() {
+ void testOnlyAdminserver() {
VespaModel vespaModel = getVespaModel(TESTDIR + "simpleadminconfig20");
// Verify that the admin plugin has been loaded (always loads routing).
@@ -150,7 +146,7 @@ public class AdminTestCase {
}
@Test
- public void testTenantAndAppInSentinelConfig() {
+ void testTenantAndAppInSentinelConfig() {
DeployState state = new DeployState.Builder()
.zone(new Zone(Environment.dev, RegionName.from("baz")))
.properties(new TestProperties()
@@ -171,7 +167,7 @@ public class AdminTestCase {
}
@Test
- public void testMultipleConfigServers() {
+ void testMultipleConfigServers() {
VespaModel vespaModel = getVespaModel(TESTDIR + "multipleconfigservers");
// Verify that the admin plugin has been loaded (always loads routing).
@@ -213,7 +209,7 @@ public class AdminTestCase {
}
@Test
- public void testContainerMetricsSnapshotInterval() {
+ void testContainerMetricsSnapshotInterval() {
VespaModel vespaModel = getVespaModel(TESTDIR + "metricconfig");
ApplicationContainerCluster qrCluster = vespaModel.getContainerClusters().get("container");
@@ -224,7 +220,7 @@ public class AdminTestCase {
}
@Test
- public void testLogForwarding() {
+ void testLogForwarding() {
String hosts = "<hosts>"
+ " <host name=\"myhost0\">"
+ " <alias>node0</alias>"
@@ -244,7 +240,7 @@ public class AdminTestCase {
Set<String> configIds = vespaModel.getConfigIds();
// 1 logforwarder on each host
- assertTrue(configIds.toString(), configIds.contains("hosts/myhost0/logforwarder"));
+ assertTrue(configIds.contains("hosts/myhost0/logforwarder"), configIds.toString());
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java
index 8012a00076b..0cb97681f13 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java
@@ -20,6 +20,7 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
+import com.yahoo.container.di.config.PlatformBundlesConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.config.content.StorDistributionConfig;
@@ -29,24 +30,25 @@ import com.yahoo.vespa.model.Service;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.clustercontroller.ClusterControllerContainer;
import com.yahoo.vespa.model.admin.clustercontroller.ClusterControllerContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
+import java.nio.file.Path;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static java.util.stream.Collectors.toSet;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for creating cluster controllers under the admin tag.
@@ -55,13 +57,13 @@ public class ClusterControllerTestCase extends DomBuilderTest {
private List<String> sds;
- @Before
+ @BeforeEach
public void setup() {
sds = ApplicationPackageUtils.generateSchemas("type1", "type2");
}
@Test
- public void testSingleCluster() throws Exception {
+ void testSingleCluster() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
@@ -85,7 +87,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
" <tuning>" +
" <cluster-controller>\n" +
" <init-progress-time>34567s</init-progress-time>" +
- " <transition-time>4000ms</transition-time>" +
+ " <transition-time>4000ms</transition-time>" +
" <stable-state-period>1h</stable-state-period>" +
" </cluster-controller>" +
" </tuning>" +
@@ -110,66 +112,78 @@ public class ClusterControllerTestCase extends DomBuilderTest {
assertEquals(4000, cfg.storage_transition_time());
assertEquals(3600000, cfg.stable_state_time_period());
}
+
+ assertOnlyNecessaryBundles(model);
}
+ private void assertOnlyNecessaryBundles(VespaModel model) {
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, "admin/cluster-controllers");
+ Set<String> unnecessaryBundles = PlatformBundles.VESPA_SECURITY_BUNDLES.stream().map(Path::toString).collect(toSet());
+ assertTrue(config.bundlePaths().stream()
+ .noneMatch(unnecessaryBundles::contains));
+ }
- @Test(expected = IllegalArgumentException.class)
- public void testSeparateHostsRequired() {
- String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<services>\n" +
- "\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"mockhost\" />\n" +
- " <cluster-controllers standalone-zookeeper=\"true\">\n" +
- " <cluster-controller hostalias=\"mockhost\"/>" +
- " <cluster-controller hostalias=\"mockhost\"/>" +
- " <cluster-controller hostalias=\"mockhost\"/>" +
- " </cluster-controllers>\n" +
- " </admin>\n" +
- " <content version='1.0' id='bar'>" +
- " <redundancy>1</redundancy>\n" +
- " <documents>" +
- " </documents>\n" +
- " <group>" +
- " <node hostalias='mockhost' distribution-key='0' />" +
- " </group>" +
- " </content>" +
- "\n" +
- "</services>";
- TestDriver driver = new TestDriver();
- driver.buildModel(xml);
+ @Test
+ void testSeparateHostsRequired() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
+ "<services>\n" +
+ "\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"mockhost\" />\n" +
+ " <cluster-controllers standalone-zookeeper=\"true\">\n" +
+ " <cluster-controller hostalias=\"mockhost\"/>" +
+ " <cluster-controller hostalias=\"mockhost\"/>" +
+ " <cluster-controller hostalias=\"mockhost\"/>" +
+ " </cluster-controllers>\n" +
+ " </admin>\n" +
+ " <content version='1.0' id='bar'>" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>" +
+ " </documents>\n" +
+ " <group>" +
+ " <node hostalias='mockhost' distribution-key='0' />" +
+ " </group>" +
+ " </content>" +
+ "\n" +
+ "</services>";
+ TestDriver driver = new TestDriver();
+ driver.buildModel(xml);
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testSeparateHostsFromConfigServerRequired() {
- String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<services>\n" +
- "\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"mockhost\" />\n" +
- " <configservers>\n" +
- " <configserver hostalias=\"mockhost\" />" +
- " </configservers>" +
- " <cluster-controllers standalone-zookeeper=\"true\">\n" +
- " <cluster-controller hostalias=\"mockhost\"/>" +
- " </cluster-controllers>\n" +
- " </admin>\n" +
- " <content version='1.0' id='bar'>" +
- " <redundancy>1</redundancy>\n" +
- " <documents>" +
- " </documents>\n" +
- " <group>" +
- " <node hostalias='mockhost' distribution-key='0' />" +
- " </group>" +
- " </content>" +
- "\n" +
- "</services>";
- TestDriver driver = new TestDriver();
- driver.buildModel(xml);
+ @Test
+ void testSeparateHostsFromConfigServerRequired() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
+ "<services>\n" +
+ "\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"mockhost\" />\n" +
+ " <configservers>\n" +
+ " <configserver hostalias=\"mockhost\" />" +
+ " </configservers>" +
+ " <cluster-controllers standalone-zookeeper=\"true\">\n" +
+ " <cluster-controller hostalias=\"mockhost\"/>" +
+ " </cluster-controllers>\n" +
+ " </admin>\n" +
+ " <content version='1.0' id='bar'>" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>" +
+ " </documents>\n" +
+ " <group>" +
+ " <node hostalias='mockhost' distribution-key='0' />" +
+ " </group>" +
+ " </content>" +
+ "\n" +
+ "</services>";
+ TestDriver driver = new TestDriver();
+ driver.buildModel(xml);
+ });
}
@Test
- public void testStandaloneZooKeeper() {
+ void testStandaloneZooKeeper() {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
@@ -245,7 +259,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
}
@Test
- public void testUnconfigured() throws Exception {
+ void testUnconfigured() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
@@ -307,7 +321,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
}
@Test
- public void testUnconfiguredMultiple() throws Exception {
+ void testUnconfiguredMultiple() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
@@ -349,7 +363,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
}
@Test
- public void testUnconfiguredNoTuning() throws Exception {
+ void testUnconfiguredNoTuning() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
@@ -404,7 +418,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
}
@Test
- public void testUnconfiguredNoContent() throws Exception {
+ void testUnconfiguredNoContent() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
" <admin version=\"2.0\">\n" +
@@ -425,7 +439,7 @@ public class ClusterControllerTestCase extends DomBuilderTest {
}
@Test
- public void testUsingOldStyle() throws Exception {
+ void testUsingOldStyle() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<services>\n" +
"\n" +
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java
index eee4d29cc6e..a8ffc625ee6 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java
@@ -18,7 +18,7 @@ import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.monitoring.Metric;
import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer;
import com.yahoo.vespa.model.admin.monitoring.Monitoring;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
@@ -29,9 +29,7 @@ import java.util.stream.IntStream;
import static com.yahoo.config.model.api.container.ContainerServiceType.LOGSERVER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -52,7 +50,7 @@ public class DedicatedAdminV4Test {
+ "</hosts>";
@Test
- public void testModelBuilding() throws IOException, SAXException {
+ void testModelBuilding() throws IOException, SAXException {
String services = "<services>" +
" <admin version='4.0'>" +
" <slobroks><nodes count='2' dedicated='true'/></slobroks>" +
@@ -74,12 +72,12 @@ public class DedicatedAdminV4Test {
assertEquals(3, model.getHosts().size());
assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd",
- METRICS_PROXY_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName);
assertHostContainsServices(model, "hosts/myhost1", "slobrok", "logd",
- METRICS_PROXY_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName);
// Note: A logserver container is always added on logserver host
assertHostContainsServices(model, "hosts/myhost2", "logserver", "logd",
- METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName);
Monitoring monitoring = model.getAdmin().getMonitoring();
assertEquals("vespa.routing", monitoring.getClustername());
@@ -93,7 +91,7 @@ public class DedicatedAdminV4Test {
}
@Test
- public void testThatThereAre2SlobroksPerContainerCluster() throws IOException, SAXException {
+ void testThatThereAre2SlobroksPerContainerCluster() throws IOException, SAXException {
String hosts = "<hosts>"
+ " <host name=\"myhost0\">"
+ " <alias>node0</alias>"
@@ -110,39 +108,39 @@ public class DedicatedAdminV4Test {
+ "</hosts>";
String servicesWith3JdiscClusters = "<services>" +
- " <admin version='4.0'>" +
- " <nodes count='1' dedicated='true' />" +
- " </admin>" +
- " <container id='a' version='1.0'>" +
- " <search />" +
- " <nodes count='2' dedicated='true' />" +
- " </container>" +
- " <container id='b' version='1.0'>" +
- " <search />" +
- " <nodes count='1' dedicated='true' />" +
- " </container>" +
- " <container id='c' version='1.0'>" +
- " <search />" +
- " <nodes count='1' dedicated='true' />" +
- " </container>" +
- "</services>";
+ " <admin version='4.0'>" +
+ " <nodes count='1' dedicated='true' />" +
+ " </admin>" +
+ " <container id='a' version='1.0'>" +
+ " <search />" +
+ " <nodes count='2' dedicated='true' />" +
+ " </container>" +
+ " <container id='b' version='1.0'>" +
+ " <search />" +
+ " <nodes count='1' dedicated='true' />" +
+ " </container>" +
+ " <container id='c' version='1.0'>" +
+ " <search />" +
+ " <nodes count='1' dedicated='true' />" +
+ " </container>" +
+ "</services>";
VespaModel model = createModel(hosts, servicesWith3JdiscClusters);
assertEquals(4, model.getHosts().size());
// 4 slobroks, 2 per cluster where possible
assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd", "logserver",
- METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
assertHostContainsServices(model, "hosts/myhost1", "slobrok", "logd",
- METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
assertHostContainsServices(model, "hosts/myhost2", "slobrok", "logd",
- METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
assertHostContainsServices(model, "hosts/myhost3", "slobrok", "logd",
- METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName);
}
@Test
- public void testLogForwarding() throws IOException, SAXException {
+ void testLogForwarding() throws IOException, SAXException {
String services = "<services>" +
" <admin version='4.0'>" +
" <slobroks><nodes count='2' dedicated='true'/></slobroks>" +
@@ -157,16 +155,16 @@ public class DedicatedAdminV4Test {
assertEquals(3, model.getHosts().size());
assertHostContainsServices(model, "hosts/myhost0", "logd", "logforwarder", "slobrok",
- METRICS_PROXY_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName);
assertHostContainsServices(model, "hosts/myhost1", "logd", "logforwarder", "slobrok",
- METRICS_PROXY_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName);
// Note: A logserver container is always added on logserver host
assertHostContainsServices(model, "hosts/myhost2", "logd", "logforwarder", "logserver",
- METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName);
Set<String> configIds = model.getConfigIds();
// 1 logforwarder on each host
- IntStream.of(0, 1, 2).forEach(i -> assertTrue(configIds.toString(), configIds.contains("hosts/myhost"+i+"/logforwarder")));
+ IntStream.of(0, 1, 2).forEach(i -> assertTrue(configIds.contains("hosts/myhost" + i + "/logforwarder"), configIds.toString()));
// First forwarder
{
@@ -194,7 +192,7 @@ public class DedicatedAdminV4Test {
}
@Test
- public void testDedicatedLogserverInHostedVespa() throws IOException, SAXException {
+ void testDedicatedLogserverInHostedVespa() throws IOException, SAXException {
String services = "<services>" +
" <admin version='4.0'>" +
" <logservers>" +
@@ -209,7 +207,7 @@ public class DedicatedAdminV4Test {
assertEquals(1, model.getHosts().size());
// Should create a logserver container on the same node as logserver
assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd", "logserver",
- METRICS_PROXY_CONTAINER.serviceName , LOGSERVER_CONTAINER.serviceName);
+ METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName);
}
private Set<String> serviceNames(VespaModel model, String hostname) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java
index b5dd4552023..0a1791b3766 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.monitoring.Metric;
import com.yahoo.vespa.model.admin.monitoring.MetricSet;
import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted;
@@ -22,9 +22,7 @@ import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetri
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.singleton;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for {@link MetricsProxyContainerCluster} related to metrics consumers.
@@ -41,7 +39,7 @@ public class MetricsConsumersTest {
private static final int numMetricsForVespaConsumer = numVespaMetrics + numSystemMetrics + numNetworkMetrics;
@Test
- public void default_public_consumer_is_set_up_for_self_hosted() {
+ void default_public_consumer_is_set_up_for_self_hosted() {
ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), self_hosted);
assertEquals(3, config.consumer().size());
assertEquals(MetricsConsumer.defaultConsumer.id(), config.consumer(2).name());
@@ -50,7 +48,7 @@ public class MetricsConsumersTest {
}
@Test
- public void consumers_are_set_up_for_hosted() {
+ void consumers_are_set_up_for_hosted() {
ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), hosted);
assertEquals(3, config.consumer().size());
assertEquals(MetricsConsumer.vespa.id(), config.consumer(0).name());
@@ -59,14 +57,14 @@ public class MetricsConsumersTest {
}
@Test
- public void vespa_consumer_is_always_present_and_has_all_vespa_metrics_and_all_system_metrics() {
+ void vespa_consumer_is_always_present_and_has_all_vespa_metrics_and_all_system_metrics() {
ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), self_hosted);
assertEquals(MetricsConsumer.vespa.id(), config.consumer(0).name());
assertEquals(numMetricsForVespaConsumer, config.consumer(0).metric().size());
}
@Test
- public void vespa_consumer_can_be_amended_via_admin_object() {
+ void vespa_consumer_can_be_amended_via_admin_object() {
VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
var additionalMetric = new Metric("additional-metric");
model.getAdmin().setAdditionalDefaultMetrics(new MetricSet("amender-metrics", singleton(additionalMetric)));
@@ -75,16 +73,16 @@ public class MetricsConsumersTest {
assertEquals(numMetricsForVespaConsumer + 1, config.consumer(0).metric().size());
ConsumersConfig.Consumer vespaConsumer = config.consumer(0);
- assertTrue("Did not contain additional metric", checkMetric(vespaConsumer, additionalMetric));
+ assertTrue(checkMetric(vespaConsumer, additionalMetric), "Did not contain additional metric");
}
@Test
- public void vespa_is_a_reserved_consumer_id() {
+ void vespa_is_a_reserved_consumer_id() {
assertReservedConsumerId("Vespa");
}
@Test
- public void default_is_a_reserved_consumer_id() {
+ void default_is_a_reserved_consumer_id() {
assertReservedConsumerId("default");
}
@@ -108,18 +106,18 @@ public class MetricsConsumersTest {
}
@Test
- public void vespa_consumer_id_is_allowed_for_hosted_infrastructure_applications() {
+ void vespa_consumer_id_is_allowed_for_hosted_infrastructure_applications() {
String services = String.join("\n",
- "<services application-type='hosted-infrastructure'>",
- " <admin version='4.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='Vespa'>",
- " <metric id='custom.metric1'/>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services application-type='hosted-infrastructure'>",
+ " <admin version='4.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='Vespa'>",
+ " <metric id='custom.metric1'/>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
VespaModel hostedModel = getModel(services, hosted);
ConsumersConfig config = consumersConfigFromModel(hostedModel);
@@ -130,21 +128,21 @@ public class MetricsConsumersTest {
assertEquals(numMetricsForVespaConsumer + 1, vespaConsumer.metric().size());
Metric customMetric1 = new Metric("custom.metric1");
- assertTrue("Did not contain metric: " + customMetric1, checkMetric(vespaConsumer, customMetric1));
+ assertTrue(checkMetric(vespaConsumer, customMetric1), "Did not contain metric: " + customMetric1);
}
@Test
- public void consumer_id_is_case_insensitive() {
+ void consumer_id_is_case_insensitive() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='A'/>",
- " <consumer id='a'/>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='A'/>",
+ " <consumer id='a'/>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
try {
@@ -156,18 +154,18 @@ public class MetricsConsumersTest {
}
@Test
- public void non_existent_metric_set_causes_exception() {
+ void non_existent_metric_set_causes_exception() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='consumer-with-non-existent-default-set'>",
- " <metric-set id='non-existent'/>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='consumer-with-non-existent-default-set'>",
+ " <metric-set id='non-existent'/>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
try {
consumersConfigFromXml(services, self_hosted);
@@ -178,19 +176,19 @@ public class MetricsConsumersTest {
}
@Test
- public void consumer_with_no_metric_set_has_its_own_metrics_plus_system_metrics_plus_default_vespa_metrics() {
+ void consumer_with_no_metric_set_has_its_own_metrics_plus_system_metrics_plus_default_vespa_metrics() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='consumer-with-metrics-only'>",
- " <metric id='custom.metric1'/>",
- " <metric id='custom.metric2'/>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='consumer-with-metrics-only'>",
+ " <metric id='custom.metric1'/>",
+ " <metric id='custom.metric2'/>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
ConsumersConfig.Consumer consumer = getCustomConsumer(services);
@@ -198,53 +196,53 @@ public class MetricsConsumersTest {
Metric customMetric1 = new Metric("custom.metric1");
Metric customMetric2 = new Metric("custom.metric2");
- assertTrue("Did not contain metric: " + customMetric1, checkMetric(consumer, customMetric1));
- assertTrue("Did not contain metric: " + customMetric2, checkMetric(consumer, customMetric2));
+ assertTrue(checkMetric(consumer, customMetric1), "Did not contain metric: " + customMetric1);
+ assertTrue(checkMetric(consumer, customMetric2), "Did not contain metric: " + customMetric2);
}
@Test
- public void consumer_with_default_metric_set_has_all_its_metrics_plus_all_system_metrics_plus_its_own() {
+ void consumer_with_default_metric_set_has_all_its_metrics_plus_all_system_metrics_plus_its_own() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='consumer-with-public-default-set'>",
- " <metric-set id='default'/>",
- " <metric id='custom.metric'/>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='consumer-with-public-default-set'>",
+ " <metric-set id='default'/>",
+ " <metric id='custom.metric'/>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
ConsumersConfig.Consumer consumer = getCustomConsumer(services);
assertEquals(numPublicDefaultMetrics + numSystemMetrics + 1, consumer.metric().size());
Metric customMetric = new Metric("custom.metric");
- assertTrue("Did not contain metric: " + customMetric, checkMetric(consumer, customMetric));
+ assertTrue(checkMetric(consumer, customMetric), "Did not contain metric: " + customMetric);
}
@Test
- public void consumer_with_vespa_metric_set_has_all_vespa_metrics_plus_all_system_metrics_plus_its_own() {
+ void consumer_with_vespa_metric_set_has_all_vespa_metrics_plus_all_system_metrics_plus_its_own() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='consumer-with-vespa-set'>",
- " <metric-set id='vespa'/>",
- " <metric id='my.extra.metric'/>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='consumer-with-vespa-set'>",
+ " <metric-set id='vespa'/>",
+ " <metric id='my.extra.metric'/>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
ConsumersConfig.Consumer consumer = getCustomConsumer(services);
assertEquals(numVespaMetrics + numSystemMetrics + 1, consumer.metric().size());
Metric customMetric = new Metric("my.extra.metric");
- assertTrue("Did not contain metric: " + customMetric, checkMetric(consumer, customMetric));
+ assertTrue(checkMetric(consumer, customMetric), "Did not contain metric: " + customMetric);
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java
index 7bf08461df7..0eb1db1acaa 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java
@@ -15,12 +15,15 @@ import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.di.config.PlatformBundlesConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.AppDimensionNames;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.Handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import java.nio.file.Path;
import java.util.Collection;
-import java.util.stream.Collectors;
+import java.util.Set;
+import java.util.stream.Stream;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.METRICS_PROXY_BUNDLE_FILE;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.zoneString;
@@ -35,9 +38,9 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.g
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.servicesWithAdminOnly;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static java.util.stream.Collectors.toSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -45,32 +48,40 @@ import static org.junit.Assert.assertTrue;
public class MetricsProxyContainerClusterTest {
@Test
- public void metrics_proxy_bundle_is_included_in_bundles_config() {
+ void metrics_proxy_bundle_is_included_in_bundles_config() {
VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
- var builder = new PlatformBundlesConfig.Builder();
- model.getConfig(builder, CLUSTER_CONFIG_ID);
- PlatformBundlesConfig config = builder.build();
- assertFalse(config.bundlePaths().stream()
- .filter(p -> p.endsWith(METRICS_PROXY_BUNDLE_FILE.toString()))
- .collect(Collectors.toList())
- .isEmpty());
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID);
+ assertTrue(config.bundlePaths().stream()
+ .anyMatch(p -> p.equals(METRICS_PROXY_BUNDLE_FILE.toString())));
}
@Test
- public void cluster_is_prepared_so_that_application_metadata_config_is_produced() {
+ void unnecessary_bundles_are_not_installed() {
VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
- var builder = new ApplicationMetadataConfig.Builder();
- model.getConfig(builder, CLUSTER_CONFIG_ID);
- ApplicationMetadataConfig config = builder.build();
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID);
+
+ Set<String> unnecessaryBundles = Stream.concat
+ (
+ PlatformBundles.VESPA_SECURITY_BUNDLES.stream(),
+ PlatformBundles.VESPA_ZK_BUNDLES.stream()
+ ).map(Path::toString).collect(toSet());
+
+ assertTrue(config.bundlePaths().stream()
+ .noneMatch(unnecessaryBundles::contains));
+ }
+
+ @Test
+ void cluster_is_prepared_so_that_application_metadata_config_is_produced() {
+ VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
+ ApplicationMetadataConfig config = model.getConfig(ApplicationMetadataConfig.class, CLUSTER_CONFIG_ID);
assertEquals(MockApplicationPackage.APPLICATION_GENERATION, config.generation());
assertEquals(MockApplicationPackage.APPLICATION_NAME, config.name());
- assertEquals(MockApplicationPackage.DEPLOYED_BY_USER, config.user());
}
@Test
- public void http_handlers_are_set_up() {
+ void http_handlers_are_set_up() {
VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
- Collection<Handler<?>> handlers = model.getAdmin().getMetricsProxyCluster().getHandlers();
+ Collection<Handler> handlers = model.getAdmin().getMetricsProxyCluster().getHandlers();
Collection<ComponentSpecification> handlerClasses = handlers.stream().map(Component::getClassId).collect(toList());
assertTrue(handlerClasses.contains(ComponentSpecification.fromString(MetricsV1Handler.class.getName())));
@@ -80,7 +91,7 @@ public class MetricsProxyContainerClusterTest {
}
@Test
- public void hosted_application_propagates_application_dimensions() {
+ void hosted_application_propagates_application_dimensions() {
VespaModel hostedModel = getModel(servicesWithAdminOnly(), hosted);
ApplicationDimensionsConfig config = getApplicationDimensionsConfig(hostedModel);
@@ -94,7 +105,7 @@ public class MetricsProxyContainerClusterTest {
}
@Test
- public void all_nodes_are_included_in_metrics_nodes_config() {
+ void all_nodes_are_included_in_metrics_nodes_config() {
VespaModel hostedModel = getModel(servicesWithTwoNodes(), hosted);
MetricsNodesConfig config = getMetricsNodesConfig(hostedModel);
assertEquals(2, config.node().size());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java
index 9b1ff54482b..5394b807861 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java
@@ -8,7 +8,7 @@ import ai.vespa.metricsproxy.rpc.RpcConnectorConfig;
import ai.vespa.metricsproxy.service.VespaServicesConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.VespaModelTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CONTAINER_CONFIG_ID;
@@ -20,9 +20,7 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.g
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getNodeDimensionsConfig;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getRpcConnectorConfig;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getVespaServicesConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -30,7 +28,7 @@ import static org.junit.Assert.assertTrue;
public class MetricsProxyContainerTest {
@Test
- public void one_metrics_proxy_container_is_added_to_every_node() {
+ void one_metrics_proxy_container_is_added_to_every_node() {
var numberOfHosts = 7;
var tester = new VespaModelTester();
tester.addHosts(numberOfHosts);
@@ -42,14 +40,14 @@ public class MetricsProxyContainerTest {
assertNotNull(host.getService(METRICS_PROXY_CONTAINER.serviceName));
long metricsProxies = host.getServices().stream()
- .filter(s -> s.getClass().equals(MetricsProxyContainer.class))
- .count();
+ .filter(s -> s.getClass().equals(MetricsProxyContainer.class))
+ .count();
assertEquals(1, metricsProxies);
}
}
@Test
- public void one_metrics_proxy_container_is_added_to_every_node_also_when_dedicated_CCC() {
+ void one_metrics_proxy_container_is_added_to_every_node_also_when_dedicated_CCC() {
var numberOfHosts = 7;
var tester = new VespaModelTester();
tester.addHosts(numberOfHosts);
@@ -61,16 +59,16 @@ public class MetricsProxyContainerTest {
assertNotNull(host.getService(METRICS_PROXY_CONTAINER.serviceName));
long metricsProxies = host.getServices().stream()
- .filter(s -> s.getClass().equals(MetricsProxyContainer.class))
- .count();
+ .filter(s -> s.getClass().equals(MetricsProxyContainer.class))
+ .count();
assertEquals(1, metricsProxies);
}
}
@Test
- public void http_server_is_running_on_expected_port() {
+ void http_server_is_running_on_expected_port() {
VespaModel model = getModel(hostedServicesWithContent(), self_hosted);
- MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID);
+ MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID);
assertEquals(19092, container.getSearchPort());
assertEquals(19092, container.getHealthPort());
@@ -79,9 +77,9 @@ public class MetricsProxyContainerTest {
}
@Test
- public void metrics_rpc_server_is_running_on_expected_port() {
+ void metrics_rpc_server_is_running_on_expected_port() {
VespaModel model = getModel(hostedServicesWithContent(), self_hosted);
- MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID);
+ MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID);
int offset = 3;
assertEquals(2, container.getPortsMeta().getTagsAt(offset).size());
@@ -93,9 +91,9 @@ public class MetricsProxyContainerTest {
}
@Test
- public void admin_rpc_server_is_running() {
+ void admin_rpc_server_is_running() {
VespaModel model = getModel(hostedServicesWithContent(), self_hosted);
- MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID);
+ MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID);
int offset = 2;
assertEquals(2, container.getPortsMeta().getTagsAt(offset).size());
@@ -104,15 +102,15 @@ public class MetricsProxyContainerTest {
}
@Test
- public void preload_is_empty() {
+ void preload_is_empty() {
VespaModel model = getModel(hostedServicesWithContent(), self_hosted);
- MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID);
+ MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID);
assertEquals("", container.getPreLoad());
}
@Test
- public void hosted_application_propagates_node_dimensions() {
+ void hosted_application_propagates_node_dimensions() {
String services = hostedServicesWithContent();
VespaModel hostedModel = getModel(services, hosted);
assertEquals(4, hostedModel.getHosts().size());
@@ -124,11 +122,11 @@ public class MetricsProxyContainerTest {
}
@Test
- public void metrics_v2_handler_is_set_up_with_node_info_config() {
+ void metrics_v2_handler_is_set_up_with_node_info_config() {
String services = hostedServicesWithContent();
VespaModel hostedModel = getModel(services, hosted);
- var container = (MetricsProxyContainer)hostedModel.id2producer().get(containerConfigId(hostedModel, hosted));
+ var container = (MetricsProxyContainer) hostedModel.id2producer().get(containerConfigId(hostedModel, hosted));
var handlers = container.getHandlers().getComponents();
assertEquals(1, handlers.size());
@@ -140,13 +138,13 @@ public class MetricsProxyContainerTest {
}
@Test
- public void vespa_services_config_has_all_services() {
+ void vespa_services_config_has_all_services() {
VespaServicesConfig vespaServicesConfig = getVespaServicesConfig(hostedServicesWithContent());
assertEquals(9, vespaServicesConfig.service().size());
for (var service : vespaServicesConfig.service()) {
if (service.configId().equals("admin/cluster-controllers/0")) {
- assertEquals("Wrong service name", "container-clustercontroller", service.name());
+ assertEquals("container-clustercontroller", service.name(), "Wrong service name");
assertEquals(1, service.dimension().size());
assertEquals("clustername", service.dimension(0).key());
assertEquals("cluster-controllers", service.dimension(0).value());
@@ -155,7 +153,7 @@ public class MetricsProxyContainerTest {
}
@Test
- public void vespa_services_config_has_service_dimensions() {
+ void vespa_services_config_has_service_dimensions() {
VespaServicesConfig vespaServicesConfig = getVespaServicesConfig(hostedServicesWithContent());
for (var service : vespaServicesConfig.service()) {
if (service.configId().equals("admin/cluster-controllers/0")) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java
index 734844c9c7c..2109359be91 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.model.admin.metricsproxy;
import ai.vespa.metricsproxy.core.MonitoringConfig;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CLUSTER_CONFIG_ID;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author gjoranv
@@ -18,7 +18,7 @@ import static org.junit.Assert.fail;
public class MonitoringElementTest {
@Test
- public void monitoring_element_is_disallowed_for_hosted_vespa() {
+ void monitoring_element_is_disallowed_for_hosted_vespa() {
String services = servicesWithMonitoringElement();
try {
getModel(services, hosted);
@@ -29,20 +29,20 @@ public class MonitoringElementTest {
}
@Test
- public void monitoring_element_is_allowed_for_hosted_infrastructure_apps() {
+ void monitoring_element_is_allowed_for_hosted_infrastructure_apps() {
String services = String.join("\n",
- "<services application-type='hosted-infrastructure'>",
- " <admin version='4.0'>",
- " <monitoring interval='300' systemname='my-system' />",
- " </admin>",
- "</services>"
+ "<services application-type='hosted-infrastructure'>",
+ " <admin version='4.0'>",
+ " <monitoring interval='300' systemname='my-system' />",
+ " </admin>",
+ "</services>"
);
VespaModel model = getModel(services, hosted);
assertMonitoringConfig(model);
}
@Test
- public void monitoring_element_is_allowed_for_self_hosted_vespa() {
+ void monitoring_element_is_allowed_for_self_hosted_vespa() {
String services = servicesWithMonitoringElement();
VespaModel model = getModel(services, self_hosted);
assertMonitoringConfig(model);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java
index 5bd364f4e21..5a6a65b5a82 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java
@@ -6,15 +6,13 @@ import ai.vespa.metricsproxy.telegraf.TelegrafConfig;
import ai.vespa.metricsproxy.telegraf.TelegrafRegistry;
import com.yahoo.component.ComponentId;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CLUSTER_CONFIG_ID;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -22,7 +20,7 @@ import static org.junit.Assert.assertTrue;
public class TelegrafTest {
@Test
- public void telegraf_components_are_set_up_when_cloudwatch_is_configured() {
+ void telegraf_components_are_set_up_when_cloudwatch_is_configured() {
String services = servicesWithCloudwatch();
VespaModel hostedModel = getModel(services, hosted);
@@ -32,16 +30,16 @@ public class TelegrafTest {
}
@Test
- public void telegraf_components_are_not_set_up_when_no_external_systems_are_added_in_services() {
+ void telegraf_components_are_not_set_up_when_no_external_systems_are_added_in_services() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='foo' />",
- " </metrics>",
- " </admin>",
- "</services>");
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='foo' />",
+ " </metrics>",
+ " </admin>",
+ "</services>");
VespaModel hostedModel = getModel(services, hosted);
var clusterComponents = hostedModel.getAdmin().getMetricsProxyCluster().getComponentsMap();
@@ -50,7 +48,7 @@ public class TelegrafTest {
}
@Test
- public void telegraf_config_is_generated_for_cloudwatch_in_services() {
+ void telegraf_config_is_generated_for_cloudwatch_in_services() {
String services = servicesWithCloudwatch();
VespaModel hostedModel = getModel(services, hosted);
TelegrafConfig config = hostedModel.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID);
@@ -85,25 +83,25 @@ public class TelegrafTest {
}
@Test
- public void multiple_cloudwatches_are_allowed_for_the_same_consumer() {
+ void multiple_cloudwatches_are_allowed_for_the_same_consumer() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='cloudwatch-consumer'>",
- " <metric id='my-metric'/>",
- " <cloudwatch region='us-east-1' namespace='namespace-1' >",
- " <credentials access-key-name='access-key-1' ",
- " secret-key-name='secret-key-1' />",
- " </cloudwatch>",
- " <cloudwatch region='us-east-1' namespace='namespace-2' >",
- " <shared-credentials profile='profile-2' />",
- " </cloudwatch>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='cloudwatch-consumer'>",
+ " <metric id='my-metric'/>",
+ " <cloudwatch region='us-east-1' namespace='namespace-1' >",
+ " <credentials access-key-name='access-key-1' ",
+ " secret-key-name='secret-key-1' />",
+ " </cloudwatch>",
+ " <cloudwatch region='us-east-1' namespace='namespace-2' >",
+ " <shared-credentials profile='profile-2' />",
+ " </cloudwatch>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
VespaModel hostedModel = getModel(services, hosted);
TelegrafConfig config = hostedModel.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID);
@@ -126,21 +124,21 @@ public class TelegrafTest {
}
@Test
- public void profile_named_default_is_used_when_no_profile_is_given_in_shared_credentials() {
+ void profile_named_default_is_used_when_no_profile_is_given_in_shared_credentials() {
String services = String.join("\n",
- "<services>",
- " <admin version='2.0'>",
- " <adminserver hostalias='node1'/>",
- " <metrics>",
- " <consumer id='cloudwatch-consumer'>",
- " <metric id='my-metric'/>",
- " <cloudwatch region='us-east-1' namespace='foo' >",
- " <shared-credentials file='/path/to/file' />",
- " </cloudwatch>",
- " </consumer>",
- " </metrics>",
- " </admin>",
- "</services>"
+ "<services>",
+ " <admin version='2.0'>",
+ " <adminserver hostalias='node1'/>",
+ " <metrics>",
+ " <consumer id='cloudwatch-consumer'>",
+ " <metric id='my-metric'/>",
+ " <cloudwatch region='us-east-1' namespace='foo' >",
+ " <shared-credentials file='/path/to/file' />",
+ " </cloudwatch>",
+ " </consumer>",
+ " </metrics>",
+ " </admin>",
+ "</services>"
);
VespaModel model = getModel(services, self_hosted);
TelegrafConfig config = model.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java
index b78d7b9723f..8a15d87b6c5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java
@@ -4,13 +4,13 @@ package com.yahoo.vespa.model.admin.monitoring;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author gjoranv
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull;
public class MetricSetTest {
@Test
- public void metrics_from_children_are_added() {
+ void metrics_from_children_are_added() {
MetricSet child1 = new MetricSet("child1", ImmutableList.of(new Metric("child1_metric")));
MetricSet child2 = new MetricSet("child2", ImmutableList.of(new Metric("child2_metric")));
MetricSet parent = new MetricSet("parent", emptyList(), ImmutableList.of(child1, child2));
@@ -30,7 +30,7 @@ public class MetricSetTest {
}
@Test
- public void adding_the_same_child_set_twice_has_no_effect() {
+ void adding_the_same_child_set_twice_has_no_effect() {
MetricSet child = new MetricSet("child", ImmutableList.of(new Metric("child_metric")));
MetricSet parent = new MetricSet("parent", emptyList(), ImmutableList.of(child, child));
@@ -40,7 +40,7 @@ public class MetricSetTest {
}
@Test
- public void internal_metrics_take_precedence_over_metrics_from_children() {
+ void internal_metrics_take_precedence_over_metrics_from_children() {
String METRIC_NAME = "metric1";
String COMMON_DIMENSION_KEY = "commonKey";
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java
index efb0f337198..e87bb90c36b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.model.admin.monitoring;
import com.google.common.collect.ImmutableMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class MetricTest {
@Test
- public void this_metric_takes_precedence_when_combined_with_another_metric() {
+ void this_metric_takes_precedence_when_combined_with_another_metric() {
String COMMON_DIMENSION_KEY = "commonKey";
Map<String, String> thisDimensions = ImmutableMap.<String, String>builder()
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java
index 86d4c527670..d9f0a80e1cb 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java
@@ -7,13 +7,13 @@ import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.model.test.ModelBuilderAddingAccessControlFilter;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bjorncs
@@ -34,7 +34,7 @@ public class AccessControlFilterValidatorTest {
@Test
- public void validator_fails_with_empty_access_control_filter_chain() throws IOException, SAXException {
+ void validator_fails_with_empty_access_control_filter_chain() throws IOException, SAXException {
DeployState deployState = createDeployState();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -47,7 +47,7 @@ public class AccessControlFilterValidatorTest {
}
@Test
- public void validator_accepts_non_empty_access_control_filter_chain() throws IOException, SAXException {
+ void validator_accepts_non_empty_access_control_filter_chain() throws IOException, SAXException {
DeployState deployState = createDeployState();
VespaModel model = new VespaModel(
MapConfigModelRegistry.createFromList(new ModelBuilderAddingAccessControlFilter()),
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java
index 107ee8aef72..8ca973dc59f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java
@@ -8,7 +8,7 @@ import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
@@ -19,9 +19,7 @@ import java.time.format.DateTimeFormatter;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.config.provision.Environment.prod;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -50,7 +48,7 @@ public abstract class AccessControlValidatorTestBase {
" </handler>");
@Test
- public void cluster_with_protection_passes_validation() throws IOException, SAXException {
+ void cluster_with_protection_passes_validation() throws IOException, SAXException {
DeployState deployState = deployState(servicesXml(true, true));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -58,7 +56,7 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void cluster_with_no_handlers_passes_validation_without_protection() throws IOException, SAXException{
+ void cluster_with_no_handlers_passes_validation_without_protection() throws IOException, SAXException {
DeployState deployState = deployState(servicesXml(false, false));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -66,10 +64,10 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void cluster_without_custom_components_passes_validation_without_protection() throws IOException, SAXException{
+ void cluster_without_custom_components_passes_validation_without_protection() throws IOException, SAXException {
String servicesXml = joinLines("<services version='1.0'>",
- " <container id='default' version='1.0' />",
- "</services>");
+ " <container id='default' version='1.0' />",
+ "</services>");
DeployState deployState = deployState(servicesXml);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -77,7 +75,7 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void cluster_with_handler_fails_validation_without_protection() throws IOException, SAXException{
+ void cluster_with_handler_fails_validation_without_protection() throws IOException, SAXException {
DeployState deployState = deployState(servicesXml(true, false));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -91,12 +89,12 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void no_http_element_has_same_effect_as_no_write_protection() throws IOException, SAXException{
+ void no_http_element_has_same_effect_as_no_write_protection() throws IOException, SAXException {
String servicesXml = joinLines("<services version='1.0'>",
- " <container id='default' version='1.0'>",
- httpHandlerXml,
- " </container>",
- "</services>");
+ " <container id='default' version='1.0'>",
+ httpHandlerXml,
+ " </container>",
+ "</services>");
DeployState deployState = deployState(servicesXml);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -110,14 +108,14 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void cluster_with_mbus_handler_passes_validation_without_write_protection() throws IOException, SAXException{
+ void cluster_with_mbus_handler_passes_validation_without_write_protection() throws IOException, SAXException {
String servicesXml = joinLines("<services version='1.0'>",
- " <container id='default' version='1.0'>",
- " <handler id='foo'>",
- " <binding>mbus://*/foo</binding>",
- " </handler>",
- " </container>",
- "</services>");
+ " <container id='default' version='1.0'>",
+ " <handler id='foo'>",
+ " <binding>mbus://*/foo</binding>",
+ " </handler>",
+ " </container>",
+ "</services>");
DeployState deployState = deployState(servicesXml);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -125,12 +123,12 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void write_protection_is_not_required_for_non_default_application_type() throws IOException, SAXException{
+ void write_protection_is_not_required_for_non_default_application_type() throws IOException, SAXException {
String servicesXml = joinLines("<services version='1.0' application-type='hosted-infrastructure'>",
- " <container id='default' version='1.0'>",
- httpHandlerXml,
- " </container>",
- "</services>");
+ " <container id='default' version='1.0'>",
+ httpHandlerXml,
+ " </container>",
+ "</services>");
DeployState deployState = deployState(servicesXml);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -138,10 +136,10 @@ public abstract class AccessControlValidatorTestBase {
}
@Test
- public void write_protection_is_not_required_with_validation_override() throws IOException, SAXException{
+ void write_protection_is_not_required_with_validation_override() throws IOException, SAXException {
DeployState deployState = deployState(servicesXml(true, false),
- "<validation-overrides><allow until='2000-01-30'>access-control</allow></validation-overrides>",
- LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_DATE).atStartOfDay().atZone(ZoneOffset.UTC).toInstant());
+ "<validation-overrides><allow until='2000-01-30'>access-control</allow></validation-overrides>",
+ LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_DATE).atStartOfDay().atZone(ZoneOffset.UTC).toInstant());
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
validator.validate(model, deployState);
@@ -164,8 +162,8 @@ public abstract class AccessControlValidatorTestBase {
.now(now);
final DeployState deployState = builder.build();
- assertTrue("Test must emulate a hosted deployment.", deployState.isHosted());
- assertEquals("Test must emulate a prod environment.", prod, deployState.zone().environment());
+ assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment.");
+ assertEquals(prod, deployState.zone().environment(), "Test must emulate a prod environment.");
return deployState;
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java
index facd3cfdff4..e26a8e8bac6 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java
@@ -3,10 +3,10 @@ package com.yahoo.vespa.model.application.validation;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.deploy.DeployState;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -17,15 +17,15 @@ import java.util.jar.JarOutputStream;
import static com.yahoo.yolean.Exceptions.uncheck;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class BundleValidatorTest {
- @Rule
- public TemporaryFolder tempDir = new TemporaryFolder();
+ @TempDir
+ public File tempDir;
@Test
- public void basicBundleValidation() throws Exception {
+ void basicBundleValidation() throws Exception {
// Valid jar file
JarFile ok = createTemporaryJarFile("ok");
BundleValidator bundleValidator = new BundleValidator();
@@ -42,12 +42,12 @@ public class BundleValidatorTest {
bundleValidator.validateJarFile(DeployState.createTestState(), jarFile);
assert (false);
} catch (IllegalArgumentException e) {
- assertEquals(e.getMessage(), exceptionMessage);
+ assertEquals(exceptionMessage, e.getMessage());
}
}
@Test
- public void require_that_deploying_snapshot_bundle_gives_warning() throws IOException {
+ void require_that_deploying_snapshot_bundle_gives_warning() throws IOException {
final StringBuffer buffer = new StringBuffer();
DeployState state = createDeployState(buffer);
@@ -57,7 +57,7 @@ public class BundleValidatorTest {
}
@Test
- public void outputs_deploy_warning_on_import_of_packages_from_deprecated_artifact() throws IOException {
+ void outputs_deploy_warning_on_import_of_packages_from_deprecated_artifact() throws IOException {
final StringBuffer buffer = new StringBuffer();
DeployState state = createDeployState(buffer);
BundleValidator validator = new BundleValidator();
@@ -78,7 +78,7 @@ public class BundleValidatorTest {
}
private JarFile createTemporaryJarFile(String testArtifact) throws IOException {
- Path jarFile = tempDir.newFile(testArtifact + ".jar").toPath();
+ Path jarFile = Paths.get(tempDir.toString(), testArtifact + ".jar");
Path artifactDirectory = Paths.get("src/test/cfg/application/validation/testjars/" + testArtifact);
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jarFile))) {
Files.walk(artifactDirectory).forEach(path -> {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java
index 92aa3151d91..f600900d3cd 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java
@@ -11,15 +11,13 @@ import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
import static com.yahoo.config.provision.Environment.prod;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -28,7 +26,7 @@ import static org.junit.Assert.fail;
public class CloudWatchValidatorTest {
@Test
- public void cloudwatch_in_public_zones_passes_validation() throws IOException, SAXException {
+ void cloudwatch_in_public_zones_passes_validation() throws IOException, SAXException {
DeployState deployState = deployState(servicesWithCloudwatch(), true, true);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -36,7 +34,7 @@ public class CloudWatchValidatorTest {
}
@Test
- public void cloudwatch_passes_validation_for_self_hosted_vespa() throws IOException, SAXException {
+ void cloudwatch_passes_validation_for_self_hosted_vespa() throws IOException, SAXException {
DeployState deployState = deployState(servicesWithCloudwatch(), false, false);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -44,7 +42,7 @@ public class CloudWatchValidatorTest {
}
@Test
- public void cloudwatch_in_non_public_zones_fails_validation() throws IOException, SAXException {
+ void cloudwatch_in_non_public_zones_fails_validation() throws IOException, SAXException {
DeployState deployState = deployState(servicesWithCloudwatch(), true, false);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -72,8 +70,8 @@ public class CloudWatchValidatorTest {
final DeployState deployState = builder.build();
if (isHosted) {
- assertTrue("Test must emulate a hosted deployment.", deployState.isHosted());
- assertEquals("Test must emulate a prod environment.", prod, deployState.zone().environment());
+ assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment.");
+ assertEquals(prod, deployState.zone().environment(), "Test must emulate a prod environment.");
}
return deployState;
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidatorTestCase.java
deleted file mode 100644
index 85050aa0cf9..00000000000
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexAttributeFieldsValidatorTestCase.java
+++ /dev/null
@@ -1,124 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.vespa.model.application.validation;
-
-import com.yahoo.config.application.api.ApplicationPackage;
-import com.yahoo.config.model.NullConfigModelRegistry;
-import com.yahoo.config.model.api.ValidationParameters;
-import com.yahoo.config.model.api.ValidationParameters.CheckRouting;
-import com.yahoo.config.model.deploy.DeployState;
-import com.yahoo.config.model.test.MockApplicationPackage;
-import com.yahoo.vespa.model.VespaModel;
-import com.yahoo.vespa.model.content.utils.ContentClusterBuilder;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.xml.sax.SAXException;
-
-import java.io.IOException;
-import java.util.List;
-
-import static com.yahoo.config.model.test.TestUtil.joinLines;
-
-/**
- * @author geirst
- */
-public class ComplexAttributeFieldsValidatorTestCase {
-
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
-
- @Test
- public void throws_exception_when_unsupported_complex_fields_have_struct_field_attributes() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(getExpectedMessage("struct_array (struct_array.f1), struct_map (struct_map.value.f1)"));
- createModelAndValidate(joinLines("search test {",
- " document test {",
- " struct s { field f1 type array<int> {} }",
- " field struct_array type array<s> {",
- " struct-field f1 { indexing: attribute }",
- " }",
- " field struct_map type map<string,s> {",
- " struct-field key { indexing: attribute }",
- " struct-field value.f1 { indexing: attribute }",
- " }",
- " }",
- "}"));
- }
-
- @Test
- public void throws_exception_when_nested_struct_array_is_specified_as_struct_field_attribute() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(getExpectedMessage("docTopics (docTopics.topics)"));
- createModelAndValidate(joinLines(
- "schema test {",
- "document test {",
- "struct topic {",
- " field id type string {}",
- " field label type string {}",
- "}",
- "struct docTopic {",
- " field id type string {}",
- " field topics type array<topic> {}",
- "}",
- "field docTopics type array<docTopic> {",
- " indexing: summary",
- " struct-field id { indexing: attribute }",
- " struct-field topics { indexing: attribute }",
- "}",
- "}",
- "}"));
- }
-
- private String getExpectedMessage(String unsupportedFields) {
- return "For cluster 'mycluster', search 'test': " +
- "The following complex fields do not support using struct field attributes: " +
- unsupportedFields + ". " +
- "Only supported for the following complex field types: array or map of struct with primitive types, map of primitive types";
- }
-
- @Test
- public void validation_passes_when_only_supported_struct_field_attributes_are_used() throws IOException, SAXException {
- createModelAndValidate(joinLines("search test {",
- " document test {",
- " struct s1 {",
- " field f1 type string {}",
- " field f2 type int {}",
- " }",
- " struct s2 {",
- " field f3 type string {}",
- " field f4 type array<int> {}",
- " field f5 type array<s1> {}",
- " }",
- " field struct_array type array<s2> {",
- " struct-field f3 { indexing: attribute }",
- " }",
- " field struct_map type map<string,s2> {",
- " struct-field key { indexing: attribute }",
- " struct-field value.f3 { indexing: attribute }",
- " }",
- " }",
- "}"));
- }
-
- private static void createModelAndValidate(String schema) throws IOException, SAXException {
- DeployState deployState = createDeployState(servicesXml(), schema);
- VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
- ValidationParameters validationParameters = new ValidationParameters(CheckRouting.FALSE);
- new Validation().validate(model, validationParameters, deployState);
- }
-
- private static DeployState createDeployState(String servicesXml, String schema) {
- ApplicationPackage app = new MockApplicationPackage.Builder()
- .withServices(servicesXml)
- .withSchemas(List.of(schema))
- .build();
- return new DeployState.Builder().applicationPackage(app).build();
- }
-
- private static String servicesXml() {
- return joinLines("<services version='1.0'>",
- new ContentClusterBuilder().getXml(),
- "</services>");
- }
-}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java
new file mode 100644
index 00000000000..c673d5899e8
--- /dev/null
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java
@@ -0,0 +1,167 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.model.application.validation;
+
+import com.yahoo.config.application.api.ApplicationPackage;
+import com.yahoo.config.application.api.DeployLogger;
+import com.yahoo.config.model.NullConfigModelRegistry;
+import com.yahoo.config.model.api.ValidationParameters;
+import com.yahoo.config.model.api.ValidationParameters.CheckRouting;
+import com.yahoo.config.model.deploy.DeployState;
+import com.yahoo.config.model.test.MockApplicationPackage;
+import com.yahoo.vespa.model.VespaModel;
+import com.yahoo.vespa.model.content.utils.ContentClusterBuilder;
+import org.junit.jupiter.api.Test;
+import org.xml.sax.SAXException;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Level;
+
+import static com.yahoo.config.model.test.TestUtil.joinLines;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * @author geirst
+ */
+public class ComplexFieldsValidatorTestCase {
+
+ @Test
+ void throws_exception_when_unsupported_complex_fields_have_struct_field_attributes() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ createModelAndValidate(joinLines("search test {",
+ " document test {",
+ " struct s { field f1 type array<int> {} }",
+ " field struct_array type array<s> {",
+ " struct-field f1 { indexing: attribute }",
+ " }",
+ " field struct_map type map<string,s> {",
+ " struct-field key { indexing: attribute }",
+ " struct-field value.f1 { indexing: attribute }",
+ " }",
+ " }",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains(getExpectedMessage("struct_array (struct_array.f1), struct_map (struct_map.value.f1)")));
+ }
+
+ @Test
+ void throws_exception_when_nested_struct_array_is_specified_as_struct_field_attribute() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ createModelAndValidate(joinLines(
+ "schema test {",
+ "document test {",
+ "struct topic {",
+ " field id type string {}",
+ " field label type string {}",
+ "}",
+ "struct docTopic {",
+ " field id type string {}",
+ " field topics type array<topic> {}",
+ "}",
+ "field docTopics type array<docTopic> {",
+ " indexing: summary",
+ " struct-field id { indexing: attribute }",
+ " struct-field topics { indexing: attribute }",
+ "}",
+ "}",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains(getExpectedMessage("docTopics (docTopics.topics)")));
+ }
+
+ private String getExpectedMessage(String unsupportedFields) {
+ return "For cluster 'mycluster', search 'test': " +
+ "The following complex fields do not support using struct field attributes: " +
+ unsupportedFields + ". " +
+ "Only supported for the following complex field types: array or map of struct with primitive types, map of primitive types";
+ }
+
+ private class MyLogger implements DeployLogger {
+ public StringBuilder message = new StringBuilder();
+ @Override
+ public void log(Level level, String message) {
+ this.message.append(message);
+ }
+ }
+
+ @Test
+ void logs_warning_when_complex_fields_have_struct_fields_with_index() throws IOException, SAXException {
+ var logger = new MyLogger();
+ createModelAndValidate(joinLines(
+ "schema test {",
+ "document test {",
+ "struct topic {",
+ " field id type string {}",
+ " field label type string {}",
+ " field desc type string {}",
+ "}",
+ "field topics type array<topic> {",
+ " indexing: summary",
+ " struct-field id { indexing: index }",
+ " struct-field label { indexing: index | attribute }",
+ " struct-field desc { indexing: attribute }",
+ "}",
+ "}",
+ "}"), logger);
+ assertThat(logger.message.toString().contains(
+ "For cluster 'mycluster', schema 'test': " +
+ "The following complex fields have struct fields with 'indexing: index' which is not supported and has no effect: " +
+ "topics (topics.id, topics.label). " +
+ "Remove setting or change to 'indexing: attribute' if needed for matching."));
+ }
+
+ @Test
+ void validation_passes_when_only_supported_struct_field_attributes_are_used() throws IOException, SAXException {
+ createModelAndValidate(joinLines("search test {",
+ " document test {",
+ " struct s1 {",
+ " field f1 type string {}",
+ " field f2 type int {}",
+ " }",
+ " struct s2 {",
+ " field f3 type string {}",
+ " field f4 type array<int> {}",
+ " field f5 type array<s1> {}",
+ " }",
+ " field struct_array type array<s2> {",
+ " struct-field f3 { indexing: attribute }",
+ " }",
+ " field struct_map type map<string,s2> {",
+ " struct-field key { indexing: attribute }",
+ " struct-field value.f3 { indexing: attribute }",
+ " }",
+ " }",
+ "}"));
+ }
+
+ private static void createModelAndValidate(String schema) throws IOException, SAXException {
+ createModelAndValidate(schema, null);
+ }
+
+ private static void createModelAndValidate(String schema, DeployLogger logger) throws IOException, SAXException {
+ DeployState deployState = createDeployState(servicesXml(), schema, logger);
+ VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
+ ValidationParameters validationParameters = new ValidationParameters(CheckRouting.FALSE);
+ new Validation().validate(model, validationParameters, deployState);
+ }
+
+ private static DeployState createDeployState(String servicesXml, String schema, DeployLogger logger) {
+ ApplicationPackage app = new MockApplicationPackage.Builder()
+ .withServices(servicesXml)
+ .withSchemas(List.of(schema))
+ .build();
+ var builder = new DeployState.Builder().applicationPackage(app);
+ if (logger != null) {
+ builder.deployLogger(logger);
+ }
+ return builder.build();
+ }
+
+ private static String servicesXml() {
+ return joinLines("<services version='1.0'>",
+ new ContentClusterBuilder().getXml(),
+ "</services>");
+ }
+}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java
index 3b5c621a581..80643917a58 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.model.application.validation;
import com.yahoo.tensor.TensorType;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.Reader;
import java.io.StringReader;
import static com.yahoo.test.json.JsonTestHelper.inputJson;
import static com.yahoo.vespa.model.application.validation.ConstantTensorJsonValidator.InvalidConstantTensorException;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ConstantTensorJsonValidatorTest {
@@ -22,12 +22,8 @@ public class ConstantTensorJsonValidatorTest {
new ConstantTensorJsonValidator().validate("dummy.json", tensorType, jsonTensorReader);
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
- public void ensure_that_unbounded_tensor_works() {
+ void ensure_that_unbounded_tensor_works() {
validateTensorJson(
TensorType.fromSpec("tensor(x[], y[])"),
inputJsonToReader(
@@ -42,7 +38,7 @@ public class ConstantTensorJsonValidatorTest {
}
@Test
- public void ensure_that_bounded_tensor_within_limits_works() {
+ void ensure_that_bounded_tensor_within_limits_works() {
validateTensorJson(
TensorType.fromSpec("tensor(x[5], y[10])"),
inputJsonToReader(
@@ -57,7 +53,7 @@ public class ConstantTensorJsonValidatorTest {
}
@Test
- public void ensure_that_multiple_cells_work() {
+ void ensure_that_multiple_cells_work() {
validateTensorJson(
TensorType.fromSpec("tensor(x[], y[])"),
inputJsonToReader(
@@ -77,7 +73,7 @@ public class ConstantTensorJsonValidatorTest {
@Test
- public void ensure_that_no_cells_work() {
+ void ensure_that_no_cells_work() {
validateTensorJson(
TensorType.fromSpec("tensor(x[], y[])"),
inputJsonToReader(
@@ -87,25 +83,26 @@ public class ConstantTensorJsonValidatorTest {
}
@Test
- public void ensure_that_bound_tensor_outside_limits_is_disallowed() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Index 5 not within limits of bound dimension 'x'");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[5], y[10])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': '5', 'y': '2' },",
- " 'value': 1e47",
- " }",
- " ]",
- "}"));
+ void ensure_that_bound_tensor_outside_limits_is_disallowed() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[5], y[10])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': '5', 'y': '2' },",
+ " 'value': 1e47",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Index 5 not within limits of bound dimension 'x'"));
}
@Test
- public void ensure_that_mapped_tensor_works() {
+ void ensure_that_mapped_tensor_works() {
validateTensorJson(
TensorType.fromSpec("tensor(x{}, y{})"),
inputJsonToReader(
@@ -120,162 +117,171 @@ public class ConstantTensorJsonValidatorTest {
}
@Test
- public void ensure_that_non_integer_strings_in_address_points_are_disallowed_unbound() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Index 'a' for dimension 'x' is not an integer");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': 'a' },",
- " 'value': 47.0",
- " }",
- " ]",
- "}"));
+ void ensure_that_non_integer_strings_in_address_points_are_disallowed_unbound() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': 'a' },",
+ " 'value': 47.0",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Index 'a' for dimension 'x' is not an integer"));
}
@Test
- public void ensure_that_tensor_coordinates_are_strings() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Tensor label is not a string (VALUE_NUMBER_INT)");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': 47 },",
- " 'value': 33.0",
- " }",
- " ]",
- "}"));
+ void ensure_that_tensor_coordinates_are_strings() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': 47 },",
+ " 'value': 33.0",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Tensor label is not a string (VALUE_NUMBER_INT)"));
}
@Test
- public void ensure_that_non_integer_strings_in_address_points_are_disallowed_bounded() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Index 'a' for dimension 'x' is not an integer");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[5])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': 'a' },",
- " 'value': 41.0",
- " }",
- " ]",
- "}"));
+ void ensure_that_non_integer_strings_in_address_points_are_disallowed_bounded() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[5])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': 'a' },",
+ " 'value': 41.0",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Index 'a' for dimension 'x' is not an integer"));
}
@Test
- public void ensure_that_missing_coordinates_fail() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Tensor address missing dimension(s) y, z");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[], y[], z[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': '3' },",
- " 'value': 99.3",
- " }",
- " ]",
- "}"));
+ void ensure_that_missing_coordinates_fail() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[], y[], z[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': '3' },",
+ " 'value': 99.3",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Tensor address missing dimension(s) y, z"));
}
@Test
- public void ensure_that_non_number_values_are_disallowed() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Tensor value is not a number (VALUE_STRING)");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': '3' },",
- " 'value': 'fruit'",
- " }",
- " ]",
- "}"));
+ void ensure_that_non_number_values_are_disallowed() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': '3' },",
+ " 'value': 'fruit'",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Tensor value is not a number (VALUE_STRING)"));
}
@Test
- public void ensure_that_extra_dimensions_are_disallowed() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Tensor dimension 'z' does not exist");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[], y[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': '3', 'y': '2', 'z': '4' },",
- " 'value': 99.3",
- " }",
- " ]",
- "}"));
+ void ensure_that_extra_dimensions_are_disallowed() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[], y[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': '3', 'y': '2', 'z': '4' },",
+ " 'value': 99.3",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Tensor dimension 'z' does not exist"));
}
@Test
- public void ensure_that_duplicate_dimensions_are_disallowed() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Duplicate tensor dimension 'y'");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[], y[])"),
- inputJsonToReader(
- "{",
- " 'cells': [",
- " {",
- " 'address': { 'x': '1', 'y': '2', 'y': '4' },",
- " 'value': 88.1",
- " }",
- " ]",
- "}"));
+ void ensure_that_duplicate_dimensions_are_disallowed() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[], y[])"),
+ inputJsonToReader(
+ "{",
+ " 'cells': [",
+ " {",
+ " 'address': { 'x': '1', 'y': '2', 'y': '4' },",
+ " 'value': 88.1",
+ " }",
+ " ]",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Duplicate tensor dimension 'y'"));
}
@Test
- public void ensure_that_invalid_json_fails() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Failed to parse JSON stream");
-
- validateTensorJson(
- TensorType.fromSpec("tensor(x[], y[])"),
- inputJsonToReader(
- "{",
- " cells': [",
- " {",
- " 'address': { 'x': '3' 'y': '2' }",
- " 'value': 2.0",
- " }",
- " ",
- "}"));
+ void ensure_that_invalid_json_fails() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(
+ TensorType.fromSpec("tensor(x[], y[])"),
+ inputJsonToReader(
+ "{",
+ " cells': [",
+ " {",
+ " 'address': { 'x': '3' 'y': '2' }",
+ " 'value': 2.0",
+ " }",
+ " ",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Failed to parse JSON stream"));
}
@Test
- public void ensure_that_invalid_json_not_in_tensor_format_fails() {
- expectedException.expect(InvalidConstantTensorException.class);
- expectedException.expectMessage("Expected field name 'cells', got 'stats'");
-
- validateTensorJson(TensorType.fromSpec("tensor(x[], y[])"),
- inputJsonToReader(
- "{",
- " 'stats': {",
- " '\u30d1\u30fc\u30d7\u30eb\u30b4\u30e0\u88fd\u306e\u30a2\u30d2\u30eb\u306f\u79c1\u3092\u6bba\u3059\u305f\u3081\u306b\u671b\u3093\u3067\u3044\u307e\u3059': true,",
- " 'points': 47",
- " }",
- "}"));
+ void ensure_that_invalid_json_not_in_tensor_format_fails() {
+ Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> {
+
+ validateTensorJson(TensorType.fromSpec("tensor(x[], y[])"),
+ inputJsonToReader(
+ "{",
+ " 'stats': {",
+ " '\u30d1\u30fc\u30d7\u30eb\u30b4\u30e0\u88fd\u306e\u30a2\u30d2\u30eb\u306f\u79c1\u3092\u6bba\u3059\u305f\u3081\u306b\u671b\u3093\u3067\u3044\u307e\u3059': true,",
+ " 'points': 47",
+ " }",
+ "}"));
+ });
+ assertTrue(exception.getMessage().contains("Expected field name 'cells', got 'stats'"));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java
index ff45038a051..d3908d19e00 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java
@@ -2,20 +2,20 @@
package com.yahoo.vespa.model.application.validation;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class ConstantValidatorTest {
@Test
- public void ensure_that_valid_ranking_constants_do_not_fail() {
+ void ensure_that_valid_ranking_constants_do_not_fail() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/ranking_constants_ok/").create();
}
@Test
- public void ensure_that_failing_ranking_constants_fails() {
+ void ensure_that_failing_ranking_constants_fails() {
try {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/ranking_constants_fail/").create();
fail();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java
index ff765af1bd8..dba8205c0e7 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java
@@ -5,13 +5,13 @@ import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author hmusum
@@ -19,7 +19,7 @@ import static org.junit.Assert.fail;
public class DeploymentSpecValidatorTest {
@Test
- public void testDeploymentWithNonExistentGlobalId() {
+ void testDeploymentWithNonExistentGlobalId() {
var deploymentXml = "<?xml version='1.0' encoding='UTF-8'?>" +
"<deployment version='1.0'>" +
" <test />" +
@@ -28,23 +28,23 @@ public class DeploymentSpecValidatorTest {
" </prod>" +
"</deployment>";
assertValidationError("Attribute 'globalServiceId' in instance default: 'non-existing' specified in " +
- "deployment.xml does not match any container cluster ID", deploymentXml);
+ "deployment.xml does not match any container cluster ID", deploymentXml);
}
@Test
- public void testEndpointNonExistentContainerId() {
+ void testEndpointNonExistentContainerId() {
var deploymentXml = "<?xml version='1.0' encoding='UTF-8'?>" +
- "<deployment version='1.0'>" +
- " <test />" +
- " <prod>" +
- " <region active='true'>us-east</region>" +
- " </prod>" +
- " <endpoints>" +
- " <endpoint container-id='non-existing'/>" +
- " </endpoints>" +
- "</deployment>";
+ "<deployment version='1.0'>" +
+ " <test />" +
+ " <prod>" +
+ " <region active='true'>us-east</region>" +
+ " </prod>" +
+ " <endpoints>" +
+ " <endpoint container-id='non-existing'/>" +
+ " </endpoints>" +
+ "</deployment>";
assertValidationError("Endpoint 'default' in instance default: 'non-existing' specified in " +
- "deployment.xml does not match any container cluster ID", deploymentXml);
+ "deployment.xml does not match any container cluster ID", deploymentXml);
}
private static void assertValidationError(String message, String deploymentXml) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java
index 51aa6cb6e42..6d230fae23c 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java
@@ -12,22 +12,18 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author andreer
*/
public class EndpointCertificateSecretsValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
private static String servicesXml() {
return joinLines("<services version='1.0'>",
@@ -43,18 +39,18 @@ public class EndpointCertificateSecretsValidatorTest {
}
@Test
- public void missing_certificate_fails_validation() throws Exception {
- DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(EndpointCertificateSecrets.MISSING));
- VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
-
- exceptionRule.expect(CertificateNotReadyException.class);
- exceptionRule.expectMessage("TLS enabled, but could not yet retrieve certificate for application default:default:default");
+ void missing_certificate_fails_validation() throws Exception {
+ Throwable exception = assertThrows(CertificateNotReadyException.class, () -> {
+ DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(EndpointCertificateSecrets.missing(1)));
+ VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
- new EndpointCertificateSecretsValidator().validate(model, deployState);
+ new EndpointCertificateSecretsValidator().validate(model, deployState);
+ });
+ assertTrue(exception.getMessage().contains("TLS enabled, but could not yet retrieve certificate version 1 for application default:default:default"));
}
@Test
- public void validation_succeeds_with_certificate() throws Exception {
+ void validation_succeeds_with_certificate() throws Exception {
DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(new EndpointCertificateSecrets("cert", "key")));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -62,7 +58,7 @@ public class EndpointCertificateSecretsValidatorTest {
}
@Test
- public void validation_succeeds_without_certificate() throws Exception {
+ void validation_succeeds_without_certificate() throws Exception {
DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.empty());
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -83,7 +79,7 @@ public class EndpointCertificateSecretsValidatorTest {
.setEndpointCertificateSecrets(endpointCertificateSecretsSecrets));
final DeployState deployState = builder.build();
- assertTrue("Test must emulate a hosted deployment.", deployState.isHosted());
+ assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment.");
return deployState;
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java
index 5f0296588db..6394d77b67c 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.model.application.validation;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Harald Musum
@@ -13,17 +13,17 @@ import static org.junit.Assert.fail;
public class NoPrefixForIndexesTest {
@Test
- public void requireThatPrefixIsSupported() {
+ void requireThatPrefixIsSupported() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix/").create();
}
@Test
- public void requireThatPrefixIsSupportedForStreaming() {
+ void requireThatPrefixIsSupportedForStreaming() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_streaming/").create();
}
@Test
- public void requireThatPrefixIsIllegalForIndexField() {
+ void requireThatPrefixIsIllegalForIndexField() {
try {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_index/").create();
fail();
@@ -33,7 +33,7 @@ public class NoPrefixForIndexesTest {
}
@Test
- public void requireThatPrefixIsIllegalForMixedAttributeAndIndexField() {
+ void requireThatPrefixIsIllegalForMixedAttributeAndIndexField() {
try {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_index_and_attribute/").create();
fail();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java
index 8750d3caa47..ef22f0b2770 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java
@@ -7,12 +7,12 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author ogronnesby
@@ -24,13 +24,13 @@ public class QuotaValidatorTest {
private final Quota quota = Quota.unlimited().withClusterSize(10).withBudget(BigDecimal.valueOf(1.25));
@Test
- public void test_deploy_under_quota() {
+ void test_deploy_under_quota() {
var tester = new ValidationTester(8, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone));
tester.deploy(null, getServices("testCluster", 4), Environment.prod, null);
}
@Test
- public void test_deploy_above_quota_clustersize() {
+ void test_deploy_above_quota_clustersize() {
var tester = new ValidationTester(14, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone));
try {
tester.deploy(null, getServices("testCluster", 11), Environment.prod, null);
@@ -41,48 +41,48 @@ public class QuotaValidatorTest {
}
@Test
- public void test_deploy_above_quota_budget() {
+ void test_deploy_above_quota_budget() {
var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone));
try {
tester.deploy(null, getServices("testCluster", 10), Environment.prod, null);
fail();
} catch (RuntimeException e) {
- assertEquals("Deployment would make your tenant exceed its quota and has been blocked! Please contact support to update your plan.", e.getMessage());
+ assertEquals("Deployment exceeds its quota and has been blocked! Please contact support to update your plan: Quota is $1.25, but at least $1.63 is required", e.getMessage());
}
}
@Test
- public void test_deploy_above_quota_budget_in_publiccd() {
+ void test_deploy_above_quota_budget_in_publiccd() {
var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota.withBudget(BigDecimal.ONE)).setZone(publicCdZone));
try {
tester.deploy(null, getServices("testCluster", 10), Environment.prod, null);
fail();
} catch (RuntimeException e) {
- assertEquals("publiccd: Deployment would make your tenant exceed its quota and has been blocked! Please contact support to update your plan.", e.getMessage());
+ assertEquals("publiccd: Deployment exceeds its quota and has been blocked! Please contact support to update your plan: Quota is $1.00, but at least $1.63 is required", e.getMessage());
}
}
@Test
- public void test_deploy_max_resources_above_quota() {
+ void test_deploy_max_resources_above_quota() {
var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicCdZone));
try {
tester.deploy(null, getServices("testCluster", 10), Environment.prod, null);
fail();
} catch (RuntimeException e) {
- assertEquals("publiccd: Deployment would make your tenant exceed its quota and has been blocked! Please contact support to update your plan.", e.getMessage());
+ assertEquals("publiccd: Deployment exceeds its quota and has been blocked! Please contact support to update your plan: Quota is $1.25, but at least $1.63 is required", e.getMessage());
}
}
@Test
- public void test_deploy_with_negative_budget() {
+ void test_deploy_with_negative_budget() {
var quota = Quota.unlimited().withBudget(BigDecimal.valueOf(-1));
var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone));
try {
tester.deploy(null, getServices("testCluster", 10), Environment.prod, null);
fail();
} catch (RuntimeException e) {
- assertEquals("Please free up some capacity! This deployment's quota use is ($-.--) and reserved quota is below zero! ($--.--)",
+ assertEquals("Please free up some capacity: Quota is $--.--, but at least $-.-- is required",
ValidationTester.censorNumbers(e.getMessage()));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java
index b7b83dbf68c..2327c986be0 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.model.application.validation;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -13,22 +13,22 @@ import static org.junit.Assert.fail;
public class SchemaDataTypeValidatorTestCase {
@Test
- public void requireThatSupportedTypesAreValidated() {
+ void requireThatSupportedTypesAreValidated() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_alltypes/").create();
}
@Test
- public void requireThatStructsAreLegalInSearchClusters() {
+ void requireThatStructsAreLegalInSearchClusters() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_struct/").create();
}
@Test
- public void requireThatEmptyContentFieldIsLegalInSearchClusters() {
+ void requireThatEmptyContentFieldIsLegalInSearchClusters() {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_empty_content/").create();
}
@Test
- public void requireThatIndexingMapsInNonStreamingClusterIsIllegal() {
+ void requireThatIndexingMapsInNonStreamingClusterIsIllegal() {
try {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/index_struct/").create();
fail();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java
index d30de06c459..0072d9b5d51 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java
@@ -10,20 +10,16 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
*/
public class SecretStoreValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
private static String servicesXml() {
return joinLines("<services version='1.0'>",
@@ -43,7 +39,7 @@ public class SecretStoreValidatorTest {
}
@Test
- public void app_with_athenz_in_deployment_passes_validation() throws Exception {
+ void app_with_athenz_in_deployment_passes_validation() throws Exception {
DeployState deployState = deployState(servicesXml(), deploymentXml(true));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -51,24 +47,25 @@ public class SecretStoreValidatorTest {
}
@Test
- public void app_without_athenz_in_deployment_fails_validation() throws Exception {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "Container cluster 'default' uses a secret store, so an Athenz domain and" +
- " an Athenz service must be declared in deployment.xml.");
+ void app_without_athenz_in_deployment_fails_validation() throws Exception {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
- DeployState deployState = deployState(servicesXml(), deploymentXml(false));
- VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
+ DeployState deployState = deployState(servicesXml(), deploymentXml(false));
+ VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
- new SecretStoreValidator().validate(model, deployState);
+ new SecretStoreValidator().validate(model, deployState);
+
+ });
+ assertTrue(exception.getMessage().contains("Container cluster 'default' uses a secret store, so an Athenz domain and" +
+ " an Athenz service must be declared in deployment.xml."));
}
@Test
- public void app_without_secret_store_passes_validation_without_athenz_in_deployment() throws Exception {
+ void app_without_secret_store_passes_validation_without_athenz_in_deployment() throws Exception {
String servicesXml = joinLines("<services version='1.0'>",
- " <container id='default' version='1.0' />",
- "</services>");
+ " <container id='default' version='1.0' />",
+ "</services>");
DeployState deployState = deployState(servicesXml, deploymentXml(false));
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -86,7 +83,7 @@ public class SecretStoreValidatorTest {
.properties(new TestProperties().setHostedVespa(true));
final DeployState deployState = builder.build();
- assertTrue("Test must emulate a hosted deployment.", deployState.isHosted());
+ assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment.");
return deployState;
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java
index 30a77779347..fd1e6be27fd 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java
@@ -2,25 +2,23 @@
package com.yahoo.vespa.model.application.validation;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
*/
public class StreamingValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exceptionRule = ExpectedException.none();
@Test
- public void document_references_are_forbidden_in_streaming_search() {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage(
- "For streaming search cluster 'content.ad': Attribute 'campaign_ref' has type 'Reference<campaign>'. " +
- "Document references and imported fields are not allowed in streaming search.");
- new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/document_references_validation/")
- .create();
+ void document_references_are_forbidden_in_streaming_search() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/document_references_validation/")
+ .create();
+ });
+ assertTrue(exception.getMessage().contains("For streaming search cluster 'content.ad': Attribute 'campaign_ref' has type 'Reference<campaign>'. " +
+ "Document references and imported fields are not allowed in streaming search."));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java
index d106120073d..7c16d3c99cf 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java
@@ -7,62 +7,63 @@ import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* @author bjorncs
*/
public class UriBindingsValidatorTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException exceptionRule = ExpectedException.none();
-
@Test
- public void fails_on_user_handler_binding_with_port() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For binding 'http://*:4443/my-handler': binding with port is not allowed");
- runUriBindingValidator(true, createServicesXmlWithHandler("http://*:4443/my-handler"));
+ void fails_on_user_handler_binding_with_port() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ runUriBindingValidator(true, createServicesXmlWithHandler("http://*:4443/my-handler"));
+ });
+ assertTrue(exception.getMessage().contains("For binding 'http://*:4443/my-handler': binding with port is not allowed"));
}
@Test
- public void fails_on_user_handler_binding_with_hostname() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For binding 'http://myhostname/my-handler': only binding with wildcard ('*') for hostname is allowed");
- runUriBindingValidator(true, createServicesXmlWithHandler("http://myhostname/my-handler"));
+ void fails_on_user_handler_binding_with_hostname() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ runUriBindingValidator(true, createServicesXmlWithHandler("http://myhostname/my-handler"));
+ });
+ assertTrue(exception.getMessage().contains("For binding 'http://myhostname/my-handler': only binding with wildcard ('*') for hostname is allowed"));
}
@Test
- public void fails_on_user_handler_binding_with_non_http_scheme() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For binding 'ftp://*/my-handler': only 'http' is allowed as scheme");
- runUriBindingValidator(true, createServicesXmlWithHandler("ftp://*/my-handler"));
+ void fails_on_user_handler_binding_with_non_http_scheme() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ runUriBindingValidator(true, createServicesXmlWithHandler("ftp://*/my-handler"));
+ });
+ assertTrue(exception.getMessage().contains("For binding 'ftp://*/my-handler': only 'http' is allowed as scheme"));
}
@Test
- public void fails_on_invalid_filter_binding() throws IOException, SAXException {
- exceptionRule.expect(IllegalArgumentException.class);
- exceptionRule.expectMessage("For binding 'https://*:4443/my-request-filer-chain': binding with port is not allowed");
- runUriBindingValidator(true, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain"));
+ void fails_on_invalid_filter_binding() throws IOException, SAXException {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ runUriBindingValidator(true, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain"));
+ });
+ assertTrue(exception.getMessage().contains("For binding 'https://*:4443/my-request-filer-chain': binding with port is not allowed"));
}
@Test
- public void allows_valid_user_binding() throws IOException, SAXException {
+ void allows_valid_user_binding() throws IOException, SAXException {
runUriBindingValidator(true, createServicesXmlWithHandler("http://*/my-handler"));
}
@Test
- public void allows_user_binding_with_wildcard_port() throws IOException, SAXException {
+ void allows_user_binding_with_wildcard_port() throws IOException, SAXException {
runUriBindingValidator(true, createServicesXmlWithHandler("http://*:*/my-handler"));
}
@Test
- public void only_restricts_user_bindings_on_hosted() throws IOException, SAXException {
+ void only_restricts_user_bindings_on_hosted() throws IOException, SAXException {
runUriBindingValidator(false, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain"));
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java
index 93d42e07dd8..1a7b51980f7 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java
@@ -6,7 +6,7 @@ import com.yahoo.config.model.api.ValidationParameters;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.IOException;
@@ -15,8 +15,8 @@ import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author hmusum
@@ -27,13 +27,13 @@ public class ValidationOverridesValidatorTest {
.withZone(ZoneId.systemDefault());
@Test
- public void testValidationOverride() throws IOException, SAXException {
+ void testValidationOverride() throws IOException, SAXException {
String tenDays = dateTimeFormatter.format(Instant.now().plus(Duration.ofDays(10)));
var validationOverridesXml = "<?xml version='1.0' encoding='UTF-8'?>\n" +
- " <validation-overrides>\n" +
- " <allow until='" + tenDays + "'>deployment-removal</allow>\n" +
- " </validation-overrides>";
+ " <validation-overrides>\n" +
+ " <allow until='" + tenDays + "'>deployment-removal</allow>\n" +
+ " </validation-overrides>";
var deployState = createDeployState(validationOverridesXml);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
@@ -41,17 +41,17 @@ public class ValidationOverridesValidatorTest {
}
@Test
- public void testFailsWhenValidationOverrideIsTooFarInFuture() {
+ void testFailsWhenValidationOverrideIsTooFarInFuture() {
Instant now = Instant.now();
String sixtyDays = dateTimeFormatter.format(now.plus(Duration.ofDays(60)));
String sixtyOneDays = dateTimeFormatter.format(now.plus(Duration.ofDays(61)));
var validationOverrides = "<?xml version='1.0' encoding='UTF-8'?>\n" +
- "<validation-overrides>\n" +
- " <allow until='" + sixtyDays + "'>deployment-removal</allow>\n" +
- "</validation-overrides>";
+ "<validation-overrides>\n" +
+ " <allow until='" + sixtyDays + "'>deployment-removal</allow>\n" +
+ "</validation-overrides>";
assertValidationError("validation-overrides is invalid: allow 'deployment-removal' until " +
- sixtyOneDays + "T00:00:00Z is too far in the future: Max 30 days is allowed", validationOverrides);
+ sixtyOneDays + "T00:00:00Z is too far in the future: Max 30 days is allowed", validationOverrides);
}
private static void assertValidationError(String message, String validationOverridesXml) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java
index 43841aebd8a..7e172171052 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -18,7 +18,7 @@ import static org.junit.Assert.fail;
public class ClusterSizeReductionValidatorTest {
@Test
- public void testSizeReductionValidation() {
+ void testSizeReductionValidation() {
ValidationTester tester = new ValidationTester(33);
VespaModel previous = tester.deploy(null, getServices(30), Environment.prod, null).getFirst();
@@ -28,15 +28,15 @@ public class ClusterSizeReductionValidatorTest {
}
catch (IllegalArgumentException expected) {
assertEquals("cluster-size-reduction: Size reduction in 'default' is too large: " +
- "New min size must be at least 50% of the current min size. " +
- "Current size: 30, new size: 14. " +
- ValidationOverrides.toAllowMessage(ValidationId.clusterSizeReduction),
- Exceptions.toMessageString(expected));
+ "New min size must be at least 50% of the current min size. " +
+ "Current size: 30, new size: 14. " +
+ ValidationOverrides.toAllowMessage(ValidationId.clusterSizeReduction),
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testSizeReductionValidationMinimalDecreaseIsAllowed() {
+ void testSizeReductionValidationMinimalDecreaseIsAllowed() {
ValidationTester tester = new ValidationTester(30);
VespaModel previous = tester.deploy(null, getServices(3), Environment.prod, null).getFirst();
@@ -44,7 +44,7 @@ public class ClusterSizeReductionValidatorTest {
}
@Test
- public void testOverridingSizereductionValidation() {
+ void testOverridingSizereductionValidation() {
ValidationTester tester = new ValidationTester(33);
VespaModel previous = tester.deploy(null, getServices(30), Environment.prod, null).getFirst();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java
index 00a1ec7e6d8..d975618c1db 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java
@@ -10,7 +10,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConfigChangeTestUtils {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java
index 567534ba9f6..83672b6452e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java
@@ -18,8 +18,8 @@ import com.yahoo.vespa.model.application.validation.RestartConfigs;
import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Arrays;
@@ -27,8 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Testing the validator on both a stub model and a real-life Vespa model.
@@ -39,7 +38,7 @@ public class ConfigValueChangeValidatorTest {
private DeployLoggerStub logger;
- @Before
+ @BeforeEach
public void resetLogger() {
logger = new DeployLoggerStub();
}
@@ -54,7 +53,7 @@ public class ConfigValueChangeValidatorTest {
* This test will to a certain degree ensure that the annotations in the VespaModel is correctly applied.
*/
@Test
- public void requireThatValidatorHandlesVespaModel() {
+ void requireThatValidatorHandlesVespaModel() {
List<ConfigChangeAction> changes = getConfigChanges(
createVespaModel(createQrStartConfigSegment(true, 2096)),
createVespaModel(createQrStartConfigSegment(false, 2096))
@@ -66,7 +65,7 @@ public class ConfigValueChangeValidatorTest {
}
@Test
- public void requireThatDocumentTypesCanBeAddedWithoutNeedForRestart() {
+ void requireThatDocumentTypesCanBeAddedWithoutNeedForRestart() {
List<ConfigChangeAction> changes = getConfigChanges(
createVespaModel("", Arrays.asList("foo")),
createVespaModel("", Arrays.asList("foo", "bar")));
@@ -74,7 +73,7 @@ public class ConfigValueChangeValidatorTest {
}
@Test
- public void requireThatValidatorDetectsConfigChangeFromService() {
+ void requireThatValidatorDetectsConfigChangeFromService() {
MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 0)
.withChildren(new ServiceWithAnnotation("s1", 1), new ServiceWithAnnotation("s2", 2)));
MockRoot newRoot = createRootWithChildren(new SimpleConfigProducer("p", 0)
@@ -89,7 +88,7 @@ public class ConfigValueChangeValidatorTest {
}
@Test
- public void requireThatValidatorDetectsConfigChangeFromParentProducer() {
+ void requireThatValidatorDetectsConfigChangeFromParentProducer() {
MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 1)
.withChildren(new ServiceWithAnnotation("s1", 0), new ServiceWithAnnotation("s2", 0)));
MockRoot newRoot = createRootWithChildren(new SimpleConfigProducer("p", 2)
@@ -102,7 +101,7 @@ public class ConfigValueChangeValidatorTest {
}
@Test
- public void requireThatValidatorHandlesModelsWithDifferentTopology() {
+ void requireThatValidatorHandlesModelsWithDifferentTopology() {
MockRoot oldRoot = createRootWithChildren(
new SimpleConfigProducer("p1", 0).withChildren(new ServiceWithAnnotation("s1", 1)),
new SimpleConfigProducer("p2", 0).withChildren(new ServiceWithAnnotation("s2", 1)));
@@ -117,27 +116,31 @@ public class ConfigValueChangeValidatorTest {
assertEmptyLog();
}
- @Test(expected = IllegalStateException.class)
- public void requireThatAnnotationDoesNotHaveEmtpyConfigList() {
- MockRoot root = createRootWithChildren(new EmptyConfigListAnnotationService(""));
- getConfigChanges(root, root);
+ @Test
+ void requireThatAnnotationDoesNotHaveEmtpyConfigList() {
+ assertThrows(IllegalStateException.class, () -> {
+ MockRoot root = createRootWithChildren(new EmptyConfigListAnnotationService(""));
+ getConfigChanges(root, root);
+ });
}
- @Test(expected = IllegalStateException.class)
- public void requireThatConfigHasRestartMethods() {
- MockRoot root = createRootWithChildren(new ConfigWithMissingMethodsAnnotatedService(""));
- getConfigChanges(root, root);
+ @Test
+ void requireThatConfigHasRestartMethods() {
+ assertThrows(IllegalStateException.class, () -> {
+ MockRoot root = createRootWithChildren(new ConfigWithMissingMethodsAnnotatedService(""));
+ getConfigChanges(root, root);
+ });
}
@Test
- public void requireThatServicesAnnotatedWithNonRestartConfigProduceWarningInLog() {
+ void requireThatServicesAnnotatedWithNonRestartConfigProduceWarningInLog() {
MockRoot root = createRootWithChildren(new NonRestartConfigAnnotatedService(""));
getConfigChanges(root, root);
assertEquals(1, logger.entries.size());
}
@Test
- public void requireThatConfigsFromAnnotatedSuperClassesAreDetected() {
+ void requireThatConfigsFromAnnotatedSuperClassesAreDetected() {
MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 1).withChildren(
new ChildServiceWithAnnotation("child1", 0),
new ChildServiceWithoutAnnotation("child2", 0)));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java
index 7cad29cc2c4..7d6e243fba4 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java
@@ -7,15 +7,13 @@ import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerRestartValidatorTest {
@Test
- public void validator_returns_action_for_containers_with_restart_on_deploy_enabled() {
+ void validator_returns_action_for_containers_with_restart_on_deploy_enabled() {
VespaModel current = createModel(true);
VespaModel next = createModel(true);
List<ConfigChangeAction> result = validateModel(current, next);
@@ -31,7 +29,7 @@ public class ContainerRestartValidatorTest {
}
@Test
- public void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled() {
+ void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled() {
VespaModel current = createModel(false);
VespaModel next = createModel(false);
List<ConfigChangeAction> result = validateModel(current, next);
@@ -39,7 +37,7 @@ public class ContainerRestartValidatorTest {
}
@Test
- public void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled_where_previously_enabled() {
+ void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled_where_previously_enabled() {
VespaModel current = createModel(true);
VespaModel next = createModel(false);
List<ConfigChangeAction> result = validateModel(current, next);
@@ -47,7 +45,7 @@ public class ContainerRestartValidatorTest {
}
@Test
- public void restart_on_deploy_is_propagated_to_cluster() {
+ void restart_on_deploy_is_propagated_to_cluster() {
VespaModel model1 = createModel(false);
assertFalse(model1.getContainerClusters().get("cluster1").getDeferChangesUntilRestart());
assertFalse(model1.getContainerClusters().get("cluster2").getDeferChangesUntilRestart());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java
index c0f9e532aa2..25ce7252ea8 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -20,7 +20,7 @@ public class ContentClusterRemovalValidatorTest {
private final ValidationTester tester = new ValidationTester(5);
@Test
- public void testContentRemovalValidation() {
+ void testContentRemovalValidation() {
VespaModel previous = tester.deploy(null, getServices("contentClusterId"), Environment.prod, null).getFirst();
try {
tester.deploy(previous, getServices("newContentClusterId"), Environment.prod, null);
@@ -28,13 +28,13 @@ public class ContentClusterRemovalValidatorTest {
}
catch (IllegalArgumentException expected) {
assertEquals("content-cluster-removal: Content cluster 'contentClusterId' is removed. This will cause loss of all data in this cluster. " +
- ValidationOverrides.toAllowMessage(ValidationId.contentClusterRemoval),
- Exceptions.toMessageString(expected));
+ ValidationOverrides.toAllowMessage(ValidationId.contentClusterRemoval),
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testOverridingContentRemovalValidation() {
+ void testOverridingContentRemovalValidation() {
VespaModel previous = tester.deploy(null, getServices("contentClusterId"), Environment.prod, null).getFirst();
tester.deploy(previous, getServices("newContentClusterId"), Environment.prod, removalOverride); // Allowed due to override
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java
index 3827fa9786e..70c2c7704f3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests validation of removal of a document type.
@@ -21,7 +21,7 @@ import static org.junit.Assert.fail;
public class ContentTypeRemovalValidatorTest {
@Test
- public void testContentTypeRemovalValidation() {
+ void testContentTypeRemovalValidation() {
ValidationTester tester = new ValidationTester();
VespaModel previous = tester.deploy(null, getServices("music"), Environment.prod, null).getFirst();
@@ -31,14 +31,14 @@ public class ContentTypeRemovalValidatorTest {
}
catch (IllegalArgumentException expected) {
assertEquals("content-type-removal: Type 'music' is removed in content cluster 'test'. " +
- "This will cause loss of all data of this type. " +
- ValidationOverrides.toAllowMessage(ValidationId.contentTypeRemoval),
- Exceptions.toMessageString(expected));
+ "This will cause loss of all data of this type. " +
+ ValidationOverrides.toAllowMessage(ValidationId.contentTypeRemoval),
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testOverridingContentTypeRemovalValidation() {
+ void testOverridingContentTypeRemovalValidation() {
ValidationTester tester = new ValidationTester();
VespaModel previous = tester.deploy(null, getServices("music"), Environment.prod, null).getFirst();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java
index f1192dd0f89..fb052e023bb 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java
@@ -4,11 +4,9 @@ package com.yahoo.vespa.model.application.validation.change;
import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test that global attribute changes are detected by change validator.
@@ -16,7 +14,7 @@ import static org.junit.Assert.assertFalse;
public class GlobalDocumentChangeValidatorTest {
@Test
- public void testChangGlobalAttribute() {
+ void testChangGlobalAttribute() {
testChangeGlobalAttribute(true, false, false, null);
testChangeGlobalAttribute(true, true, true, null);
testChangeGlobalAttribute(false, false, true, null);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java
index 7b1474f9754..309ad4094e4 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java
@@ -10,7 +10,7 @@ import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.vespa.model.content.utils.ApplicationPackageBuilder;
import com.yahoo.vespa.model.content.utils.ContentClusterBuilder;
import com.yahoo.vespa.model.content.utils.SchemaBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
@@ -19,7 +19,7 @@ import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTe
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRestartAction;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.normalizeServicesInActions;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class IndexedSchemaClusterChangeValidatorTest {
@@ -99,56 +99,56 @@ public class IndexedSchemaClusterChangeValidatorTest {
new ServiceInfo("searchnode2", "null", null, null, "bar/search/cluster.bar/0", "null"));
@Test
- public void requireThatDocumentDatabaseChangeIsDiscovered() {
+ void requireThatDocumentDatabaseChangeIsDiscovered() {
Fixture.newOneDocFixture(STRING_FIELD, ATTRIBUTE_FIELD).
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE));
+ "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE));
}
@Test
- public void requireThatChangeInSeveralDocumentDatabasesAreDiscovered() {
+ void requireThatChangeInSeveralDocumentDatabasesAreDiscovered() {
Fixture.newTwoDocFixture(STRING_FIELD, ATTRIBUTE_FIELD).
assertValidation(List.of(newRestartAction(ClusterSpec.Id.from("test"),
- "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE),
- newRestartAction(ClusterSpec.Id.from("test"),
- "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE)));
+ "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE),
+ newRestartAction(ClusterSpec.Id.from("test"),
+ "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE)));
}
@Test
- public void requireThatChangeInSeveralContentClustersAreDiscovered() {
+ void requireThatChangeInSeveralContentClustersAreDiscovered() {
Fixture.newTwoClusterFixture(STRING_FIELD, ATTRIBUTE_FIELD).
assertValidation(List.of(newRestartAction(ClusterSpec.Id.from("test"),
- "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE),
- newRestartAction(ClusterSpec.Id.from("test"),
- "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, BAR_SERVICE)));
+ "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE),
+ newRestartAction(ClusterSpec.Id.from("test"),
+ "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, BAR_SERVICE)));
}
@Test
- public void requireThatAddingDocumentDatabaseIsOk() {
+ void requireThatAddingDocumentDatabaseIsOk() {
new Fixture(Fixture.newOneDocModel(STRING_FIELD), Fixture.newTwoDocModel(STRING_FIELD, STRING_FIELD)).assertValidation();
}
@Test
- public void requireThatRemovingDocumentDatabaseIsOk() {
+ void requireThatRemovingDocumentDatabaseIsOk() {
new Fixture(Fixture.newTwoDocModel(STRING_FIELD, STRING_FIELD), Fixture.newOneDocModel(STRING_FIELD)).assertValidation();
}
@Test
- public void requireThatAddingContentClusterIsOk() {
+ void requireThatAddingContentClusterIsOk() {
new Fixture(Fixture.newOneDocModel(STRING_FIELD), Fixture.newTwoClusterModel(STRING_FIELD, STRING_FIELD)).assertValidation();
}
@Test
- public void requireThatRemovingContentClusterIsOk() {
+ void requireThatRemovingContentClusterIsOk() {
new Fixture(Fixture.newTwoClusterModel(STRING_FIELD, STRING_FIELD), Fixture.newOneDocModel(STRING_FIELD)).assertValidation();
}
@Test
- public void requireThatChangingFieldTypeIsDiscovered() {
+ void requireThatChangingFieldTypeIsDiscovered() {
Fixture f = Fixture.newOneDocFixture(STRING_FIELD, INT_FIELD);
f.assertValidation(List.of(newRefeedAction(ClusterSpec.Id.from("test"),
- ValidationId.fieldTypeChange,
- "Document type 'd1': " + FIELD_TYPE_CHANGE_MSG, FOO_SERVICE, "d1")));
+ ValidationId.fieldTypeChange,
+ "Document type 'd1': " + FIELD_TYPE_CHANGE_MSG, FOO_SERVICE, "d1")));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java
index c7ed8309318..5b06cc28919 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java
@@ -7,15 +7,13 @@ import com.yahoo.config.model.api.ConfigChangeReindexAction;
import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.joining;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -24,7 +22,7 @@ import static org.junit.Assert.fail;
public class IndexingModeChangeValidatorTest {
@Test
- public void testChangingIndexModeFromIndexedToStreamingWhenDisallowed() {
+ void testChangingIndexModeFromIndexedToStreamingWhenDisallowed() {
ValidationTester tester = new ValidationTester();
VespaModel oldModel =
@@ -36,14 +34,14 @@ public class IndexingModeChangeValidatorTest {
}
catch (ValidationException e) {
assertEquals("indexing-mode-change:\n" +
- "\tDocument type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'\n" +
- "To allow this add <allow until='yyyy-mm-dd'>indexing-mode-change</allow> to validation-overrides.xml, see https://docs.vespa.ai/en/reference/validation-overrides.html",
- e.getMessage());
+ "\tDocument type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'\n" +
+ "To allow this add <allow until='yyyy-mm-dd'>indexing-mode-change</allow> to validation-overrides.xml, see https://docs.vespa.ai/en/reference/validation-overrides.html",
+ e.getMessage());
}
}
@Test
- public void testChangingIndexModeFromIndexedToStreaming() {
+ void testChangingIndexModeFromIndexedToStreaming() {
ValidationTester tester = new ValidationTester();
VespaModel oldModel =
@@ -52,12 +50,12 @@ public class IndexingModeChangeValidatorTest {
tester.deploy(oldModel, getServices("streaming"), Environment.prod, validationOverrides).getSecond();
assertReindexingChange( // allowed=true due to validation override
- "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'",
- changeActions);
+ "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'",
+ changeActions);
}
@Test
- public void testChangingIndexModeFromStoreOnlyToIndexed() {
+ void testChangingIndexModeFromStoreOnlyToIndexed() {
ValidationTester tester = new ValidationTester();
VespaModel oldModel =
@@ -66,8 +64,8 @@ public class IndexingModeChangeValidatorTest {
tester.deploy(oldModel, getServices("store-only"), Environment.prod, validationOverrides).getSecond();
assertReindexingChange( // allowed=true due to validation override
- "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'store-only'",
- changeActions);
+ "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'store-only'",
+ changeActions);
}
private void assertReindexingChange(String message, List<ConfigChangeAction> changeActions) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java
index 891418c073f..d0cc4a605bc 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java
@@ -13,14 +13,14 @@ import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.ProvisionLogger;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals;
public class NodeResourceChangeValidatorTest {
@Test
- public void test_restart_action_count() {
+ void test_restart_action_count() {
assertEquals(0, validate(model(1, 1, 1, 1), model(1, 1, 1, 1)).size());
assertEquals(1, validate(model(1, 1, 1, 1), model(2, 1, 1, 1)).size());
assertEquals(2, validate(model(1, 1, 1, 1), model(1, 2, 1, 1)).size());
@@ -43,7 +43,7 @@ public class NodeResourceChangeValidatorTest {
}
@Test
- public void test_restart_action_details() {
+ void test_restart_action_details() {
ConfigChangeAction containerAction = validate(model(1, 1, 1, 1), model(2, 1, 1, 1)).get(0);
assertEquals(ConfigChangeAction.Type.RESTART, containerAction.getType());
assertEquals("service 'container' of type container on host0", containerAction.getServices().get(0).toString());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java
index 3249b2cd60e..544ec2b841e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -20,7 +20,7 @@ public class RedundancyIncreaseValidatorTest {
private final ValidationTester tester = new ValidationTester(7);
@Test
- public void testRedundancyIncreaseValidation() {
+ void testRedundancyIncreaseValidation() {
VespaModel previous = tester.deploy(null, getServices(2), Environment.prod, null).getFirst();
try {
tester.deploy(previous, getServices(3), Environment.prod, null);
@@ -28,15 +28,15 @@ public class RedundancyIncreaseValidatorTest {
}
catch (IllegalArgumentException expected) {
assertEquals("redundancy-increase: " +
- "Increasing redundancy from 2 to 3 in 'content cluster 'contentClusterId'. " +
- "This is a safe operation but verify that you have room for a 3/2x increase in content size. " +
- ValidationOverrides.toAllowMessage(ValidationId.redundancyIncrease),
- Exceptions.toMessageString(expected));
+ "Increasing redundancy from 2 to 3 in 'content cluster 'contentClusterId'. " +
+ "This is a safe operation but verify that you have room for a 3/2x increase in content size. " +
+ ValidationOverrides.toAllowMessage(ValidationId.redundancyIncrease),
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testOverridingContentRemovalValidation() {
+ void testOverridingContentRemovalValidation() {
VespaModel previous = tester.deploy(null, getServices(2), Environment.prod, null).getFirst();
tester.deploy(previous, getServices(3), Environment.prod, redundancyIncreaseOverride); // Allowed due to override
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java
index 76398099657..651f87c614b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java
@@ -9,10 +9,10 @@ import com.yahoo.config.provision.NodeResources;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author freva
@@ -23,54 +23,54 @@ public class ResourcesReductionValidatorTest {
private final ValidationTester tester = new ValidationTester(provisioner);
@Test
- public void fail_when_reduction_by_over_50_percent() {
+ void fail_when_reduction_by_over_50_percent() {
VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst();
try {
tester.deploy(previous, getServices(new NodeResources(8, 16, 800, 1)), Environment.prod, null);
fail("Expected exception due to resources reduction");
} catch (IllegalArgumentException expected) {
assertEquals("resources-reduction: Resource reduction in 'default' is too large. " +
- "Current memory GB: 64.00, new: 16.00. New min resources must be at least 50% of the current min resources. " +
- ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction),
+ "Current memory GB: 64.00, new: 16.00. New min resources must be at least 50% of the current min resources. " +
+ ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction),
Exceptions.toMessageString(expected));
}
}
@Test
- public void fail_when_reducing_multiple_resources_by_over_50_percent() {
+ void fail_when_reducing_multiple_resources_by_over_50_percent() {
VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst();
try {
tester.deploy(previous, getServices(new NodeResources(3, 16, 200, 1)), Environment.prod, null);
fail("Expected exception due to resources reduction");
} catch (IllegalArgumentException expected) {
assertEquals("resources-reduction: Resource reduction in 'default' is too large. " +
- "Current vCPU: 8.00, new: 3.00. Current memory GB: 64.00, new: 16.00. Current disk GB: 800.00, new: 200.00. " +
- "New min resources must be at least 50% of the current min resources. " +
- ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction),
+ "Current vCPU: 8.00, new: 3.00. Current memory GB: 64.00, new: 16.00. Current disk GB: 800.00, new: 200.00. " +
+ "New min resources must be at least 50% of the current min resources. " +
+ ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction),
Exceptions.toMessageString(expected));
}
}
@Test
- public void small_resource_decrease_is_allowed() {
+ void small_resource_decrease_is_allowed() {
VespaModel previous = tester.deploy(null, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null).getFirst();
tester.deploy(previous, getServices(new NodeResources(.5, 48, 600, 1)), Environment.prod, null);
}
@Test
- public void overriding_resource_decrease() {
+ void overriding_resource_decrease() {
VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst();
tester.deploy(previous, getServices(new NodeResources(8, 16, 800, 1)), Environment.prod, resourcesReductionOverride); // Allowed due to override
}
@Test
- public void allowed_to_go_to_not_specifying_resources() {
+ void allowed_to_go_to_not_specifying_resources() {
VespaModel previous = tester.deploy(null, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null).getFirst();
tester.deploy(previous, getServices(null), Environment.prod, null);
}
@Test
- public void allowed_to_go_from_not_specifying_resources() {
+ void allowed_to_go_from_not_specifying_resources() {
VespaModel previous = tester.deploy(null, getServices(null), Environment.prod, null).getFirst();
tester.deploy(previous, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java
index 439cb24ba87..cef6f72b94b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java
@@ -9,10 +9,10 @@ import com.yahoo.container.ComponentsConfig;
import com.yahoo.container.QrConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.application.validation.ValidationTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -20,10 +20,10 @@ import static org.junit.Assert.assertTrue;
public class RestartChangesDefersConfigChangesTest {
@Test
- public void changes_requiring_restart_defers_config_changes() {
+ void changes_requiring_restart_defers_config_changes() {
ValidationTester tester = new ValidationTester(new InMemoryProvisioner(5,
- new NodeResources(1, 3, 9, 1),
- true));
+ new NodeResources(1, 3, 9, 1),
+ true));
VespaModel gen1 = tester.deploy(null, getServices(5, 3), Environment.prod, null).getFirst();
// Change node count - no restart
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java
index 952b89a6ab1..8d542ce85f3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java
@@ -9,18 +9,19 @@ import com.yahoo.vespa.model.AbstractService;
import com.yahoo.vespa.model.Host;
import com.yahoo.vespa.model.HostResource;
import com.yahoo.vespa.model.PortAllocBridge;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class StartupCommandChangeValidatorTest {
@Test
- public void requireThatDifferentStartupCommandIsDetected() {
+ void requireThatDifferentStartupCommandIsDetected() {
MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "rm -rf /"));
MockRoot newRoot = createRootWithChildren(new ServiceStub("evilservice", "rm -rf *"));
List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot);
@@ -29,7 +30,7 @@ public class StartupCommandChangeValidatorTest {
}
@Test
- public void requireEmptyResultForEqualStartupCommand() {
+ void requireEmptyResultForEqualStartupCommand() {
MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh"));
MockRoot newRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh"));
List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot);
@@ -37,7 +38,7 @@ public class StartupCommandChangeValidatorTest {
}
@Test
- public void requireEmptyResultForDifferentServices() {
+ void requireEmptyResultForDifferentServices() {
MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh"));
MockRoot newRoot = createRootWithChildren(new ServiceStub("goodservice", "./hax.sh"));
List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java
index 2e5b27bee6f..92f2cf61c36 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.model.content.utils.ApplicationPackageBuilder;
import com.yahoo.vespa.model.content.utils.ContentClusterBuilder;
import com.yahoo.vespa.model.content.utils.DocType;
import com.yahoo.vespa.model.content.utils.SchemaBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Arrays;
@@ -19,7 +19,7 @@ import java.util.List;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.assertEqualActions;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.normalizeServicesInActions;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class StreamingSchemaClusterChangeValidatorTest {
@@ -98,13 +98,13 @@ public class StreamingSchemaClusterChangeValidatorTest {
new ServiceInfo("searchnode2", "null", null, null, "bar/search/0", "null"));
@Test
- public void changing_field_type_requires_refeed() {
+ void changing_field_type_requires_refeed() {
Fixture.withOneDocType(STRING_FIELD, INT_FIELD)
.assertValidation(createFieldTypeChangeRefeedAction("d1", FOO_SERVICE));
}
@Test
- public void changes_in_multiple_streaming_clusters_are_discovered() {
+ void changes_in_multiple_streaming_clusters_are_discovered() {
Fixture.withTwoClusters(STRING_FIELD, INT_FIELD)
.assertValidation(Arrays.asList(
createFieldTypeChangeRefeedAction("d1", FOO_SERVICE),
@@ -112,7 +112,7 @@ public class StreamingSchemaClusterChangeValidatorTest {
}
@Test
- public void changes_in_multiple_document_types_are_discovered() {
+ void changes_in_multiple_document_types_are_discovered() {
Fixture.withTwoDocTypes(STRING_FIELD, INT_FIELD)
.assertValidation(Arrays.asList(
createFieldTypeChangeRefeedAction("d1", FOO_SERVICE),
@@ -120,7 +120,7 @@ public class StreamingSchemaClusterChangeValidatorTest {
}
@Test
- public void adding_fast_access_to_an_attribute_requires_restart() {
+ void adding_fast_access_to_an_attribute_requires_restart() {
Fixture.withOneDocType(INT_FIELD, ATTRIBUTE_FAST_ACCESS_INT_FIELD)
.assertValidation(createAddFastAccessRestartAction());
@@ -129,7 +129,7 @@ public class StreamingSchemaClusterChangeValidatorTest {
}
@Test
- public void removing_fast_access_from_an_attribute_requires_restart() {
+ void removing_fast_access_from_an_attribute_requires_restart() {
Fixture.withOneDocType(ATTRIBUTE_FAST_ACCESS_INT_FIELD, INT_FIELD)
.assertValidation(createRemoveFastAccessRestartAction());
@@ -138,27 +138,27 @@ public class StreamingSchemaClusterChangeValidatorTest {
}
@Test
- public void adding_attribute_field_is_ok() {
+ void adding_attribute_field_is_ok() {
Fixture.withOneDocType(INT_FIELD, ATTRIBUTE_INT_FIELD).assertValidation();
}
@Test
- public void removing_attribute_field_is_ok() {
+ void removing_attribute_field_is_ok() {
Fixture.withOneDocType(ATTRIBUTE_INT_FIELD, INT_FIELD).assertValidation();
}
@Test
- public void unchanged_fast_access_attribute_field_is_ok() {
+ void unchanged_fast_access_attribute_field_is_ok() {
Fixture.withOneDocType(ATTRIBUTE_FAST_ACCESS_INT_FIELD, ATTRIBUTE_FAST_ACCESS_INT_FIELD).assertValidation();
}
@Test
- public void adding_streaming_cluster_is_ok() {
+ void adding_streaming_cluster_is_ok() {
new Fixture(Fixture.createOneDocModel(STRING_FIELD), Fixture.createTwoClusterModel(STRING_FIELD, STRING_FIELD)).assertValidation();
}
@Test
- public void removing_streaming_cluster_is_ok() {
+ void removing_streaming_cluster_is_ok() {
new Fixture(Fixture.createTwoClusterModel(STRING_FIELD, STRING_FIELD), Fixture.createOneDocModel(STRING_FIELD)).assertValidation();
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java
index 8d6f05f40e7..076d78912e8 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java
@@ -6,13 +6,13 @@ import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.test.ManualClock;
import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRestartAction;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class AttributeChangeValidatorTest {
@@ -40,181 +40,181 @@ public class AttributeChangeValidatorTest {
}
@Test
- public void adding_attribute_aspect_require_restart() throws Exception {
+ void adding_attribute_aspect_require_restart() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: summary }",
"field f1 type string { indexing: attribute | summary }");
f.assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute aspect"));
+ "Field 'f1' changed: add attribute aspect"));
}
@Test
- public void removing_attribute_aspect_require_restart() throws Exception {
+ void removing_attribute_aspect_require_restart() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: attribute | summary }",
"field f1 type string { indexing: summary }");
f.assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: remove attribute aspect"));
+ "Field 'f1' changed: remove attribute aspect"));
}
@Test
- public void adding_attribute_field_is_ok() throws Exception {
+ void adding_attribute_field_is_ok() throws Exception {
Fixture f = new Fixture("", "field f1 type string { indexing: attribute | summary \n attribute: fast-search }");
f.assertValidation();
}
@Test
- public void removing_attribute_field_is_ok() throws Exception {
+ void removing_attribute_field_is_ok() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: attribute | summary }", "");
f.assertValidation();
}
@Test
- public void changing_fast_search_require_restart() throws Exception {
+ void changing_fast_search_require_restart() throws Exception {
new Fixture("field f1 type string { indexing: attribute }",
"field f1 type string { indexing: attribute \n attribute: fast-search }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute 'fast-search'"));
+ "Field 'f1' changed: add attribute 'fast-search'"));
}
@Test
- public void changing_fast_rank_require_restart() throws Exception {
+ void changing_fast_rank_require_restart() throws Exception {
new Fixture("field f1 type tensor(x{}) { indexing: attribute }",
"field f1 type tensor(x{}) { indexing: attribute \n attribute: fast-rank }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute 'fast-rank'"));
+ "Field 'f1' changed: add attribute 'fast-rank'"));
}
@Test
- public void changing_btree2hash_require_restart() throws Exception {
+ void changing_btree2hash_require_restart() throws Exception {
new Fixture("field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: btree}",
"field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: hash }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property 'dictionary: btree/hash' from 'BTREE' to 'HASH'"));
+ "Field 'f1' changed: change property 'dictionary: btree/hash' from 'BTREE' to 'HASH'"));
}
@Test
- public void changing_hash2btree_require_restart() throws Exception {
+ void changing_hash2btree_require_restart() throws Exception {
new Fixture("field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: hash}",
"field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: btree }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property 'dictionary: btree/hash' from 'HASH' to 'BTREE'"));
+ "Field 'f1' changed: change property 'dictionary: btree/hash' from 'HASH' to 'BTREE'"));
}
@Test
- public void changing_fast_access_require_restart() throws Exception {
+ void changing_fast_access_require_restart() throws Exception {
new Fixture("field f1 type string { indexing: attribute \n attribute: fast-access }",
"field f1 type string { indexing: attribute }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: remove attribute 'fast-access'"));
+ "Field 'f1' changed: remove attribute 'fast-access'"));
}
@Test
- public void changing_uncased2cased_require_restart() throws Exception {
+ void changing_uncased2cased_require_restart() throws Exception {
new Fixture("field f1 type string { indexing: attribute\n attribute: fast-search\n dictionary { btree\ncased}\nmatch:cased}",
"field f1 type string { indexing: attribute\n attribute: fast-search\n dictionary{ btree\nuncased}\nmatch:uncased }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property 'dictionary: cased/uncased' from 'CASED' to 'UNCASED'"));
+ "Field 'f1' changed: change property 'dictionary: cased/uncased' from 'CASED' to 'UNCASED'"));
}
@Test
- public void changing_dense_posting_list_threshold_require_restart() throws Exception {
+ void changing_dense_posting_list_threshold_require_restart() throws Exception {
new Fixture(
"field f1 type predicate { indexing: attribute \n index { arity: 8 \n dense-posting-list-threshold: 0.2 } }",
"field f1 type predicate { indexing: attribute \n index { arity: 8 \n dense-posting-list-threshold: 0.4 } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property 'dense-posting-list-threshold' from '0.2' to '0.4'"));
+ "Field 'f1' changed: change property 'dense-posting-list-threshold' from '0.2' to '0.4'"));
}
@Test
- public void removing_attribute_aspect_from_index_field_is_ok() throws Exception {
+ void removing_attribute_aspect_from_index_field_is_ok() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: index | attribute }",
"field f1 type string { indexing: index }");
f.assertValidation();
}
@Test
- public void removing_attribute_aspect_from_index_and_summary_field_is_ok() throws Exception {
+ void removing_attribute_aspect_from_index_and_summary_field_is_ok() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: index | attribute | summary }",
"field f1 type string { indexing: index | summary }");
f.assertValidation();
}
@Test
- public void adding_rank_filter_requires_restart() throws Exception {
+ void adding_rank_filter_requires_restart() throws Exception {
new Fixture("field f1 type string { indexing: attribute }",
"field f1 type string { indexing: attribute \n rank: filter }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute 'rank: filter'"));
+ "Field 'f1' changed: add attribute 'rank: filter'"));
}
@Test
- public void removing_rank_filter_requires_restart() throws Exception {
+ void removing_rank_filter_requires_restart() throws Exception {
new Fixture("field f1 type string { indexing: attribute \n rank: filter }",
"field f1 type string { indexing: attribute }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: remove attribute 'rank: filter'"));
+ "Field 'f1' changed: remove attribute 'rank: filter'"));
}
@Test
- public void adding_hnsw_index_requires_restart() throws Exception {
+ void adding_hnsw_index_requires_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute }",
"field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute 'indexing: index'"));
+ "Field 'f1' changed: add attribute 'indexing: index'"));
}
@Test
- public void removing_hnsw_index_requres_restart() throws Exception {
+ void removing_hnsw_index_requres_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }",
"field f1 type tensor(x[2]) { indexing: attribute }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: remove attribute 'indexing: index'"));
+ "Field 'f1' changed: remove attribute 'indexing: index'"));
}
@Test
- public void changing_distance_metric_without_hnsw_index_enabled_requires_restart() throws Exception {
+ void changing_distance_metric_without_hnsw_index_enabled_requires_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute }",
"field f1 type tensor(x[2]) { indexing: attribute \n attribute { " +
"distance-metric: geodegrees \n } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property " +
- "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'"));
+ "Field 'f1' changed: change property " +
+ "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'"));
}
@Test
- public void changing_distance_metric_with_hnsw_index_enabled_requires_restart() throws Exception {
+ void changing_distance_metric_with_hnsw_index_enabled_requires_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }",
"field f1 type tensor(x[2]) { indexing: attribute | index \n attribute { " +
"distance-metric: geodegrees \n } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change property " +
- "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'"));
+ "Field 'f1' changed: change property " +
+ "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'"));
}
@Test
- public void changing_hnsw_index_property_max_links_per_node_requires_restart() throws Exception {
+ void changing_hnsw_index_property_max_links_per_node_requires_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }",
"field f1 type tensor(x[2]) { indexing: attribute | index \n index { " +
"hnsw { max-links-per-node: 4 } } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change hnsw index property " +
- "'max-links-per-node' from '16' to '4'"));
+ "Field 'f1' changed: change hnsw index property " +
+ "'max-links-per-node' from '16' to '4'"));
}
@Test
- public void changing_hnsw_index_property_neighbors_to_explore_at_insert_requires_restart() throws Exception {
+ void changing_hnsw_index_property_neighbors_to_explore_at_insert_requires_restart() throws Exception {
new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }",
"field f1 type tensor(x[2]) { indexing: attribute | index \n index { " +
"hnsw { neighbors-to-explore-at-insert: 100 } } }").
assertValidation(newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: change hnsw index property " +
- "'neighbors-to-explore-at-insert' from '200' to '100'"));
+ "Field 'f1' changed: change hnsw index property " +
+ "'neighbors-to-explore-at-insert' from '200' to '100'"));
}
@Test
- public void removing_paged_requires_override() throws Exception {
+ void removing_paged_requires_override() throws Exception {
try {
new Fixture("field f1 type tensor(x[10]) { indexing: attribute \n attribute: paged }",
- "field f1 type tensor(x[10]) { indexing: attribute }").
+ "field f1 type tensor(x[10]) { indexing: attribute }").
assertValidation();
fail("Expected exception on removal of 'paged'");
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java
index 030f1d7d85d..eae7f4f7b41 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java
@@ -12,8 +12,8 @@ import com.yahoo.vespa.model.search.DocumentDatabase;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test fixture to setup current and next content clusters used for change validation.
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java
index aba5c2aa05c..27a90c73725 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java
@@ -6,7 +6,7 @@ import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.test.ManualClock;
import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Arrays;
@@ -40,34 +40,34 @@ public class DocumentDatabaseChangeValidatorTest {
}
@Test
- public void requireThatAttributeIndexAndDocumentTypeChangesAreDiscovered() throws Exception {
+ void requireThatAttributeIndexAndDocumentTypeChangesAreDiscovered() throws Exception {
Fixture f = new Fixture("struct s { field s1 type string {} } " +
"field f1 type string { indexing: summary } " +
"field f2 type string { indexing: summary } " +
"field f3 type int { indexing: summary } " +
"field f4 type array<s> { } ",
"struct s { field s1 type string {} } " +
- "field f1 type string { indexing: attribute | summary } " +
- "field f2 type string { indexing: index | summary } " +
- "field f3 type string { indexing: summary } " +
- "field f4 type array<s> { struct-field s1 { indexing: attribute } }");
+ "field f1 type string { indexing: attribute | summary } " +
+ "field f2 type string { indexing: index | summary } " +
+ "field f3 type string { indexing: summary } " +
+ "field f4 type array<s> { struct-field s1 { indexing: attribute } }");
Instant.now();
f.assertValidation(Arrays.asList(
newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f1' changed: add attribute aspect"),
+ "Field 'f1' changed: add attribute aspect"),
newRestartAction(ClusterSpec.Id.from("test"),
- "Field 'f4.s1' changed: add attribute aspect"),
+ "Field 'f4.s1' changed: add attribute aspect"),
newReindexAction(ClusterSpec.Id.from("test"),
- ValidationId.indexingChange,
- "Field 'f2' changed: add index aspect, indexing script: '{ input f2 | summary f2; }' -> " +
+ ValidationId.indexingChange,
+ "Field 'f2' changed: add index aspect, indexing script: '{ input f2 | summary f2; }' -> " +
"'{ input f2 | tokenize normalize stem:\"BEST\" | index f2 | summary f2; }'"),
newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 'int' -> 'string'")));
}
@Test
- public void requireThatRemovingAttributeAspectFromIndexFieldIsOk() throws Exception {
+ void requireThatRemovingAttributeAspectFromIndexFieldIsOk() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: index | attribute }",
- "field f1 type string { indexing: index }");
+ "field f1 type string { indexing: index }");
f.assertValidation();
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java
index 859194fae79..639ca820613 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java
@@ -11,7 +11,7 @@ import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.schema.FieldSets;
import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction;
import com.yahoo.vespa.model.application.validation.change.VespaRefeedAction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Arrays;
@@ -20,8 +20,8 @@ import java.util.List;
import java.util.Optional;
import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test validation of changes between a current and next document type used in a document database.
@@ -49,134 +49,134 @@ public class DocumentTypeChangeValidatorTest {
}
@Test
- public void requireThatFieldRemovalIsOK() throws Exception {
+ void requireThatFieldRemovalIsOK() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: summary }",
- "field f2 type string { indexing: summary }");
+ "field f2 type string { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatSameDataTypeIsOK() throws Exception {
+ void requireThatSameDataTypeIsOK() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: summary }",
- "field f1 type string { indexing: summary }");
+ "field f1 type string { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatDataTypeChangeIsNotOK() throws Exception {
+ void requireThatDataTypeChangeIsNotOK() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: summary }",
- "field f1 type int { indexing: summary }");
+ "field f1 type int { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'"));
}
@Test
- public void requireThatAddingCollectionTypeIsNotOK() throws Exception {
+ void requireThatAddingCollectionTypeIsNotOK() throws Exception {
Fixture f = new Fixture("field f1 type string { indexing: summary }",
- "field f1 type array<string> { indexing: summary }");
+ "field f1 type array<string> { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'Array<string>'"));
}
@Test
- public void requireThatSameNestedDataTypeIsOK() throws Exception {
+ void requireThatSameNestedDataTypeIsOK() throws Exception {
Fixture f = new Fixture("field f1 type array<string> { indexing: summary }",
- "field f1 type array<string> { indexing: summary }");
+ "field f1 type array<string> { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatNestedDataTypeChangeIsNotOK() throws Exception {
+ void requireThatNestedDataTypeChangeIsNotOK() throws Exception {
Fixture f = new Fixture("field f1 type array<string> { indexing: summary }",
- "field f1 type array<int> { indexing: summary }");
+ "field f1 type array<int> { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'Array<string>' -> 'Array<int>'"));
}
@Test
- public void requireThatChangedCollectionTypeIsNotOK() throws Exception {
+ void requireThatChangedCollectionTypeIsNotOK() throws Exception {
Fixture f = new Fixture("field f1 type array<string> { indexing: summary }",
- "field f1 type weightedset<string> { indexing: summary }");
+ "field f1 type weightedset<string> { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'Array<string>' -> 'WeightedSet<string>'"));
}
@Test
- public void requireThatMultipleDataTypeChangesIsNotOK() throws Exception {
- Fixture f = new Fixture("field f1 type string { indexing: summary } field f2 type int { indexing: summary }" ,
- "field f2 type string { indexing: summary } field f1 type int { indexing: summary }");
+ void requireThatMultipleDataTypeChangesIsNotOK() throws Exception {
+ Fixture f = new Fixture("field f1 type string { indexing: summary } field f2 type int { indexing: summary }",
+ "field f2 type string { indexing: summary } field f1 type int { indexing: summary }");
Instant.now();
Instant.now();
f.assertValidation(Arrays.asList(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'"),
- newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 'int' -> 'string'")));
+ newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 'int' -> 'string'")));
}
@Test
- public void requireThatSameDataTypeInStructFieldIsOK() throws Exception {
+ void requireThatSameDataTypeInStructFieldIsOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }",
- "struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }");
+ "struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatSameNestedDataTypeChangeInStructFieldIsOK() throws Exception {
+ void requireThatSameNestedDataTypeChangeInStructFieldIsOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }",
- "struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }");
+ "struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatAddingFieldInStructFieldIsOK() throws Exception {
+ void requireThatAddingFieldInStructFieldIsOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }",
- "struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }");
+ "struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatRemovingFieldInStructFieldIsOK() throws Exception {
+ void requireThatRemovingFieldInStructFieldIsOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }",
- "struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }");
+ "struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }");
f.assertValidation();
}
@Test
- public void requireThatDataTypeChangeInStructFieldIsNotOK() throws Exception {
+ void requireThatDataTypeChangeInStructFieldIsNotOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }",
- "struct s1 { field f1 type int {} } field f2 type s1 { indexing: summary }");
+ "struct s1 { field f1 type int {} } field f2 type s1 { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 's1:{f1:string}' -> 's1:{f1:int}'"));
}
@Test
- public void requireThatNestedDataTypeChangeInStructFieldIsNotOK() throws Exception {
+ void requireThatNestedDataTypeChangeInStructFieldIsNotOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }",
- "struct s1 { field f1 type array<int> {} } field f2 type s1 { indexing: summary }");
+ "struct s1 { field f1 type array<int> {} } field f2 type s1 { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 's1:{f1:Array<string>}' -> 's1:{f1:Array<int>}'"));
}
@Test
- public void requireThatDataTypeChangeInNestedStructFieldIsNotOK() throws Exception {
+ void requireThatDataTypeChangeInNestedStructFieldIsNotOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }",
- "struct s1 { field f1 type int {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }");
+ "struct s1 { field f1 type int {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 's2:{s1:{f1:string}}' -> 's2:{s1:{f1:int}}'"));
}
@Test
- public void requireThatMultipleDataTypeChangesInStructFieldIsNotOK() throws Exception {
+ void requireThatMultipleDataTypeChangesInStructFieldIsNotOK() throws Exception {
Fixture f = new Fixture("struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }",
- "struct s1 { field f1 type int {} field f2 type string {} } field f3 type s1 { indexing: summary }");
+ "struct s1 { field f1 type int {} field f2 type string {} } field f3 type s1 { indexing: summary }");
Instant.now();
f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 's1:{f1:string,f2:int}' -> 's1:{f1:int,f2:string}'"));
}
@Test
- public void requireThatChangingTargetTypeOfReferenceFieldIsNotOK() {
+ void requireThatChangingTargetTypeOfReferenceFieldIsNotOK() {
var validator = new DocumentTypeChangeValidator(ClusterSpec.Id.from("test"),
- createDocumentTypeWithReferenceField("oldDoc"),
- createDocumentTypeWithReferenceField("newDoc"));
+ createDocumentTypeWithReferenceField("oldDoc"),
+ createDocumentTypeWithReferenceField("newDoc"));
List<VespaConfigChangeAction> result = validator.validate();
assertEquals(1, result.size());
VespaConfigChangeAction action = result.get(0);
@@ -189,7 +189,7 @@ public class DocumentTypeChangeValidatorTest {
}
@Test
- public void changing_tensor_type_of_tensor_field_requires_refeed() throws Exception {
+ void changing_tensor_type_of_tensor_field_requires_refeed() throws Exception {
Instant.now();
new Fixture(
"field f1 type tensor(x[2]) { indexing: attribute }",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java
index c2438bd82fc..09385f528fb 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java
@@ -8,14 +8,13 @@ import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeActi
import com.yahoo.vespa.model.application.validation.change.VespaReindexAction;
import static com.yahoo.config.model.test.TestUtil.joinLines;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertTrue;
-
public class IndexingScriptChangeValidatorTest {
private static class Fixture extends ContentClusterFixture {
@@ -72,153 +71,153 @@ public class IndexingScriptChangeValidatorTest {
}
@Test
- public void requireThatAddingIndexAspectRequireReindexing() throws Exception {
+ void requireThatAddingIndexAspectRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: summary }",
- FIELD + " { indexing: index | summary }").
- assertValidation(expectedReindexingAction("add index aspect",
+ FIELD + " { indexing: index | summary }").
+ assertValidation(expectedReindexingAction("add index aspect",
"{ input f1 | summary f1; }",
"{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }"));
}
@Test
- public void requireThatRemovingIndexAspectRequireReindexing() throws Exception {
+ void requireThatRemovingIndexAspectRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: index | summary }",
- FIELD + " { indexing: summary }").
+ FIELD + " { indexing: summary }").
assertValidation(expectedReindexingAction("remove index aspect",
- "{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }",
- "{ input f1 | summary f1; }"));
+ "{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }",
+ "{ input f1 | summary f1; }"));
}
@Test
- public void requireThatChangingStemmingRequireReindexing() throws Exception {
+ void requireThatChangingStemmingRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: index }",
- FIELD + " { indexing: index \n stemming: none }").
+ FIELD + " { indexing: index \n stemming: none }").
assertValidation(expectedReindexingAction("stemming: 'best' -> 'none'",
- "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
- "{ input f1 | tokenize normalize | index f1; }"));
+ "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
+ "{ input f1 | tokenize normalize | index f1; }"));
}
@Test
- public void requireThatChangingNormalizingRequireReindexing() throws Exception {
+ void requireThatChangingNormalizingRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: index }",
- FIELD + " { indexing: index \n normalizing: none }").
+ FIELD + " { indexing: index \n normalizing: none }").
assertValidation(expectedReindexingAction("normalizing: 'ACCENT' -> 'NONE'",
- "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
- "{ input f1 | tokenize stem:\"BEST\" | index f1; }"));
+ "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
+ "{ input f1 | tokenize stem:\"BEST\" | index f1; }"));
}
@Test
- public void requireThatChangingMatchingRequireReindexing() throws Exception {
+ void requireThatChangingMatchingRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: index \n match: exact }",
- FIELD + " { indexing: index \n match { gram \n gram-size: 3 } }").
+ FIELD + " { indexing: index \n match { gram \n gram-size: 3 } }").
assertValidation(expectedReindexingAction("matching: 'exact' -> 'gram (size 3)', normalizing: 'LOWERCASE' -> 'CODEPOINT'",
- "{ input f1 | exact | index f1; }",
- "{ input f1 | ngram 3 | index f1; }"));
+ "{ input f1 | exact | index f1; }",
+ "{ input f1 | ngram 3 | index f1; }"));
}
@Test
- public void requireThatSettingDynamicSummaryRequireReindexing() throws Exception {
+ void requireThatSettingDynamicSummaryRequireReindexing() throws Exception {
new Fixture(FIELD + " { indexing: summary }",
- FIELD + " { indexing: summary \n summary: dynamic }").
+ FIELD + " { indexing: summary \n summary: dynamic }").
assertValidation(expectedReindexingAction("summary field 'f1' transform: 'none' -> 'dynamicteaser'",
- "{ input f1 | summary f1; }",
- "{ input f1 | tokenize normalize stem:\"BEST\" | summary f1; }"));
+ "{ input f1 | summary f1; }",
+ "{ input f1 | tokenize normalize stem:\"BEST\" | summary f1; }"));
}
@Test
- public void requireThatMultipleChangesRequireReindexing() throws Exception {
- new Fixture(FIELD + " { indexing: index } " + FIELD_F2 + " { indexing: index }",
- FIELD + " { indexing: index \n stemming: none } " + FIELD_F2 + " { indexing: index \n normalizing: none }").
- assertValidation(Arrays.asList(expectedReindexingAction("f1", "stemming: 'best' -> 'none'",
- "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
- "{ input f1 | tokenize normalize | index f1; }"),
- expectedReindexingAction("f2", "normalizing: 'ACCENT' -> 'NONE'",
- "{ input f2 | tokenize normalize stem:\"BEST\" | index f2; }",
- "{ input f2 | tokenize stem:\"BEST\" | index f2; }")));
+ void requireThatMultipleChangesRequireReindexing() throws Exception {
+ new Fixture(FIELD + " { indexing: index } " + FIELD_F2 + " { indexing: index }",
+ FIELD + " { indexing: index \n stemming: none } " + FIELD_F2 + " { indexing: index \n normalizing: none }").
+ assertValidation(Arrays.asList(expectedReindexingAction("f1", "stemming: 'best' -> 'none'",
+ "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }",
+ "{ input f1 | tokenize normalize | index f1; }"),
+ expectedReindexingAction("f2", "normalizing: 'ACCENT' -> 'NONE'",
+ "{ input f2 | tokenize normalize stem:\"BEST\" | index f2; }",
+ "{ input f2 | tokenize stem:\"BEST\" | index f2; }")));
}
@Test
- public void requireThatAddingDocumentIndexFieldIsOk() throws Exception {
+ void requireThatAddingDocumentIndexFieldIsOk() throws Exception {
new Fixture("", "field f1 type string { indexing: index | summary }").
assertValidation();
}
@Test
- public void requireThatRemovingIndexFieldIsOk() throws Exception {
+ void requireThatRemovingIndexFieldIsOk() throws Exception {
new Fixture("field f1 type string { indexing: index | summary }", "").
assertValidation();
}
@Test
- public void requireThatAddingDocumentFieldIsOk() throws Exception {
+ void requireThatAddingDocumentFieldIsOk() throws Exception {
new Fixture("", FIELD + " { indexing: attribute | summary }").
assertValidation();
}
@Test
- public void requireThatAddingExtraFieldRequiresReindexing() throws Exception {
+ void requireThatAddingExtraFieldRequiresReindexing() throws Exception {
new Fixture(" field f1 type string { indexing: index }",
- " field f1 type string { indexing: index } } " +
- " field f2 type string { indexing: input f1 | summary ")
+ " field f1 type string { indexing: index } } " +
+ " field f2 type string { indexing: input f1 | summary ")
.assertValidation(VespaReindexAction.of(ClusterSpec.Id.from("test"),
- null,
- "Non-document field 'f2' added; this may be populated by reindexing"));
+ null,
+ "Non-document field 'f2' added; this may be populated by reindexing"));
}
@Test
- public void requireThatAddingSummaryAspectIsOk() throws Exception {
+ void requireThatAddingSummaryAspectIsOk() throws Exception {
new Fixture(FIELD + " { indexing: attribute }",
- FIELD + " { indexing: attribute | summary }").
+ FIELD + " { indexing: attribute | summary }").
assertValidation();
}
@Test
- public void requireThatSettingDynamicSummaryOnIndexFieldIsOk() throws Exception {
+ void requireThatSettingDynamicSummaryOnIndexFieldIsOk() throws Exception {
new Fixture(FIELD + " { indexing: index | summary }",
- FIELD + " { indexing: index | summary \n summary: dynamic }").
+ FIELD + " { indexing: index | summary \n summary: dynamic }").
assertValidation();
}
@Test
- public void requireThatOutputExpressionsAreIgnoredInAdvancedScript() throws Exception {
+ void requireThatOutputExpressionsAreIgnoredInAdvancedScript() throws Exception {
assertTrue(new ScriptFixture("{ input foo | switch { case \"audio\": input bar | index; case \"video\": input baz | index; default: 0 | index; }; }",
"{ input foo | switch { case \"audio\": input bar | attribute; case \"video\": input baz | attribute; default: 0 | attribute; }; }").
validate());
}
@Test
- public void requireThatNormalizeIsOk() throws Exception {
+ void requireThatNormalizeIsOk() throws Exception {
String entireSd = joinLines(
- "search test {",
- " document test {",
- " field inside type array<string> {",
- " indexing: summary",
- " }",
- " }",
- " field outside type array<string> {",
- " indexing: input inside | for_each { normalize } | index outside",
- " }",
- "}");
+ "search test {",
+ " document test {",
+ " field inside type array<string> {",
+ " indexing: summary",
+ " }",
+ " }",
+ " field outside type array<string> {",
+ " indexing: input inside | for_each { normalize } | index outside",
+ " }",
+ "}");
new Fixture(entireSd).assertValidation();
}
@Test
- public void requireThatNgramIsOk() throws Exception {
+ void requireThatNgramIsOk() throws Exception {
String entireSd = joinLines(
- "search test {",
- " document test {",
- " field inside type string {",
- " indexing: index",
- " match {",
- " gram",
- " gram-size: 3",
- " }",
- " }",
- " }",
- " field outside type string {",
- " indexing: input inside | ngram 2 | index outside",
- " }",
- "}");
+ "search test {",
+ " document test {",
+ " field inside type string {",
+ " indexing: index",
+ " match {",
+ " gram",
+ " gram-size: 3",
+ " }",
+ " }",
+ " }",
+ " field outside type string {",
+ " indexing: input inside | ngram 2 | index outside",
+ " }",
+ "}");
new Fixture(entireSd).assertValidation();
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java
index b95d0d05c71..60b681f2960 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.model.application.validation.change.search;
import com.yahoo.config.application.api.ValidationOverrides;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -50,36 +50,36 @@ public class StructFieldAttributeChangeValidatorTestCase {
}
@Test
- public void adding_attribute_aspect_to_struct_field_requires_restart() throws Exception {
+ void adding_attribute_aspect_to_struct_field_requires_restart() throws Exception {
validate(arrayOfStruct(oneFieldStruct(), ""),
- arrayOfStruct(oneFieldStruct(), structAttribute("s1")),
- newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.s1' changed: add attribute aspect"));
+ arrayOfStruct(oneFieldStruct(), structAttribute("s1")),
+ newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.s1' changed: add attribute aspect"));
validate(mapOfStruct(oneFieldStruct(), ""),
- mapOfStruct(oneFieldStruct(), structAttribute("key")),
- newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect"));
+ mapOfStruct(oneFieldStruct(), structAttribute("key")),
+ newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect"));
validate(mapOfStruct(oneFieldStruct(), ""),
- mapOfStruct(oneFieldStruct(), structAttribute("value.s1")),
- newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value.s1' changed: add attribute aspect"));
+ mapOfStruct(oneFieldStruct(), structAttribute("value.s1")),
+ newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value.s1' changed: add attribute aspect"));
validate(mapOfPrimitive(""), mapOfPrimitive(structAttribute("key")),
- newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect"));
+ newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect"));
validate(mapOfPrimitive(""), mapOfPrimitive(structAttribute("value")),
- newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value' changed: add attribute aspect"));
+ newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value' changed: add attribute aspect"));
}
@Test
- public void removing_attribute_aspect_from_struct_field_is_ok() throws Exception {
+ void removing_attribute_aspect_from_struct_field_is_ok() throws Exception {
validate(arrayOfStruct(oneFieldStruct(), structAttribute("s1")),
- arrayOfStruct(oneFieldStruct(), ""));
+ arrayOfStruct(oneFieldStruct(), ""));
validate(mapOfStruct(oneFieldStruct(), structAttribute("key")),
- mapOfStruct(oneFieldStruct(), ""));
+ mapOfStruct(oneFieldStruct(), ""));
validate(mapOfStruct(oneFieldStruct(), structAttribute("value.s1")),
- mapOfStruct(oneFieldStruct(), ""));
+ mapOfStruct(oneFieldStruct(), ""));
validate(mapOfPrimitive(structAttribute("key")), mapOfPrimitive(""));
@@ -87,39 +87,39 @@ public class StructFieldAttributeChangeValidatorTestCase {
}
@Test
- public void adding_struct_field_with_attribute_aspect_is_ok() throws Exception {
+ void adding_struct_field_with_attribute_aspect_is_ok() throws Exception {
validate(arrayOfStruct(oneFieldStruct(), ""),
arrayOfStruct(twoFieldStruct(), structAttribute("s2")));
validate(mapOfStruct(oneFieldStruct(), ""),
- mapOfStruct(twoFieldStruct(), structAttribute("value.s2")));
+ mapOfStruct(twoFieldStruct(), structAttribute("value.s2")));
}
@Test
- public void removing_struct_field_with_attribute_aspect_is_ok() throws Exception {
+ void removing_struct_field_with_attribute_aspect_is_ok() throws Exception {
validate(arrayOfStruct(twoFieldStruct(), structAttribute("s2")),
- arrayOfStruct(oneFieldStruct(), ""));
+ arrayOfStruct(oneFieldStruct(), ""));
validate(mapOfStruct(twoFieldStruct(), structAttribute("value.s2")),
- mapOfStruct(oneFieldStruct(), ""));
+ mapOfStruct(oneFieldStruct(), ""));
}
@Test
- public void adding_struct_field_without_attribute_aspect_is_ok() throws Exception {
+ void adding_struct_field_without_attribute_aspect_is_ok() throws Exception {
validate(arrayOfStruct(oneFieldStruct(), ""),
- arrayOfStruct(twoFieldStruct(), ""));
+ arrayOfStruct(twoFieldStruct(), ""));
validate(mapOfStruct(oneFieldStruct(), ""),
- mapOfStruct(twoFieldStruct(), ""));
+ mapOfStruct(twoFieldStruct(), ""));
}
@Test
- public void removing_struct_field_without_attribute_aspect_is_ok() throws Exception {
+ void removing_struct_field_without_attribute_aspect_is_ok() throws Exception {
validate(arrayOfStruct(twoFieldStruct(), ""),
- arrayOfStruct(oneFieldStruct(), ""));
+ arrayOfStruct(oneFieldStruct(), ""));
validate(mapOfStruct(twoFieldStruct(), ""),
- mapOfStruct(oneFieldStruct(), ""));
+ mapOfStruct(oneFieldStruct(), ""));
}
private static String oneFieldStruct() {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java
index baa880e14af..735adfa9187 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java
@@ -7,10 +7,10 @@ import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.provision.Environment;
import com.yahoo.vespa.model.application.validation.ValidationTester;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -22,22 +22,22 @@ public class RedundancyOnFirstDeploymentValidatorTest {
.setHostedVespa(true));
@Test
- public void testRedundancyOnFirstDeploymentValidation() {
+ void testRedundancyOnFirstDeploymentValidation() {
try {
tester.deploy(null, getServices(1), Environment.prod, null);
fail("Expected exception due to redundancy 1");
}
catch (IllegalArgumentException expected) {
assertEquals("redundancy-one: " +
- "content cluster 'contentClusterId' has redundancy 1, which will cause it to lose data if a node fails. " +
- "This requires an override on first deployment in a production zone. " +
- ValidationOverrides.toAllowMessage(ValidationId.redundancyOne),
- Exceptions.toMessageString(expected));
+ "content cluster 'contentClusterId' has redundancy 1, which will cause it to lose data if a node fails. " +
+ "This requires an override on first deployment in a production zone. " +
+ ValidationOverrides.toAllowMessage(ValidationId.redundancyOne),
+ Exceptions.toMessageString(expected));
}
}
@Test
- public void testOverridingRedundancyOnFirstDeploymentValidation() {
+ void testOverridingRedundancyOnFirstDeploymentValidation() {
tester.deploy(null, getServices(1), Environment.prod, redundancyOneOverride); // Allowed due to override
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java
index 55c10a28a01..da01b6ae9f9 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java
@@ -11,16 +11,14 @@ import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.ConfigPayloadBuilder;
import com.yahoo.vespa.configdefinition.SpecialtokensConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.Reader;
import java.io.StringReader;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -30,13 +28,13 @@ public class UserConfigBuilderTest {
private final ConfigDefinitionStore configDefinitionStore = defKey -> Optional.empty();
@Test
- public void require_that_simple_config_is_resolved() {
+ void require_that_simple_config_is_resolved() {
Element configRoot = getDocument("<config name=\"test.simpletypes\">" +
- " <intval>13</intval>" +
- "</config>" +
- "<config name=\"test.simpletypes\" version=\"1\">" +
- " <stringval>foolio</stringval>" +
- "</config>");
+ " <intval>13</intval>" +
+ "</config>" +
+ "<config name=\"test.simpletypes\" version=\"1\">" +
+ " <stringval>foolio</stringval>" +
+ "</config>");
UserConfigRepo map = UserConfigBuilder.build(configRoot, configDefinitionStore, new BaseDeployLogger());
assertFalse(map.isEmpty());
ConfigDefinitionKey key = new ConfigDefinitionKey("simpletypes", "test");
@@ -51,7 +49,7 @@ public class UserConfigBuilderTest {
}
@Test
- public void require_that_arrays_of_structs_are_resolved() {
+ void require_that_arrays_of_structs_are_resolved() {
Element configRoot = getDocument(
" <config name='vespa.configdefinition.specialtokens'>" +
" <tokenlist>" +
@@ -86,7 +84,7 @@ public class UserConfigBuilderTest {
}
@Test
- public void no_exception_when_config_class_does_not_exist() {
+ void no_exception_when_config_class_does_not_exist() {
Element configRoot = getDocument("<config name=\"is.unknown\">" +
" <foo>1</foo>" +
"</config>");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java
index 53d09bdeac3..af950ea2d31 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java
@@ -2,7 +2,9 @@
package com.yahoo.vespa.model.builder.xml.dom;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author <a href="mailto:einarmr@yahoo-inc.com">Einar M R Rosenvinge</a>
@@ -43,9 +45,11 @@ public class Bug6068056Test {
" </content>" +
"</services>";
- @Test(expected = RuntimeException.class)
- public void testContainerClusterCalledDocproc() {
- VespaModelCreatorWithMockPkg creator = new VespaModelCreatorWithMockPkg(HOSTS, SERVICES);
- creator.create();
+ @Test
+ void testContainerClusterCalledDocproc() {
+ assertThrows(RuntimeException.class, () -> {
+ VespaModelCreatorWithMockPkg creator = new VespaModelCreatorWithMockPkg(HOSTS, SERVICES);
+ creator.create();
+ });
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java
index a3360278505..0848b8becb9 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java
@@ -22,47 +22,36 @@ import com.yahoo.vespa.model.search.IndexedSearchCluster;
import com.yahoo.vespa.model.search.SearchNode;
import com.yahoo.vespa.model.search.StreamingSearchCluster;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
*/
public class ContentBuilderTest extends DomBuilderTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
- public void handleSingleNonSearchPersistentDummy() {
+ void handleSingleNonSearchPersistentDummy() {
ContentCluster a = createContent(
- "<content version =\"1.0\" id=\"a\">"+
- " <redundancy>3</redundancy>"+
- " <documents>" +
- " <document type=\"music\" mode=\"store-only\"/>" +
- " </documents>" +
- " <engine>"+
- " <dummy/>"+
- " </engine>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ "<content version =\"1.0\" id=\"a\">" +
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type=\"music\" mode=\"store-only\"/>" +
+ " </documents>" +
+ " <engine>" +
+ " <dummy/>" +
+ " </engine>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = a.getSearch();
assertFalse(s.hasIndexedCluster());
@@ -72,17 +61,17 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleSingleNonSearchPersistentVds() {
+ void handleSingleNonSearchPersistentVds() {
ContentCluster a = createContent(
- "<content version =\"1.0\" id=\"a\">"+
- " <redundancy>3</redundancy>"+
- " <documents>" +
- " <document type=\"music\" mode=\"store-only\"/>" +
- " </documents>" +
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ "<content version =\"1.0\" id=\"a\">" +
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type=\"music\" mode=\"store-only\"/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = a.getSearch();
assertFalse(s.hasIndexedCluster());
@@ -94,20 +83,20 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleSingleNonSearchPersistentProton() {
+ void handleSingleNonSearchPersistentProton() {
ContentCluster a = createContent(
- "<content version =\"1.0\" id=\"a\">"+
- " <redundancy>3</redundancy>"+
- " <documents>" +
- " <document type=\"music\" mode=\"store-only\"/>" +
- " </documents>" +
- " <engine>"+
- " <proton/>"+
- " </engine>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ "<content version =\"1.0\" id=\"a\">" +
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type=\"music\" mode=\"store-only\"/>" +
+ " </documents>" +
+ " <engine>" +
+ " <proton/>" +
+ " </engine>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = a.getSearch();
assertFalse(s.hasIndexedCluster());
@@ -119,17 +108,17 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleSingleNonSearchNonPersistentCluster() {
+ void handleSingleNonSearchNonPersistentCluster() {
ContentCluster a = createContent(
- "<content version =\"1.0\" id=\"a\">"+
- " <redundancy>3</redundancy>"+
- " <documents>" +
- " <document type=\"music\" mode=\"store-only\"/>" +
- " </documents>" +
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ "<content version =\"1.0\" id=\"a\">" +
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type=\"music\" mode=\"store-only\"/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = a.getSearch();
assertFalse(s.hasIndexedCluster());
@@ -148,7 +137,7 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleIndexedOnlyWithoutPersistence() {
+ void handleIndexedOnlyWithoutPersistence() {
VespaModel m = new VespaModelCreatorWithMockPkg(createAppWithMusic(getHosts(), getBasicServices())).create();
ContentCluster c = CollectionUtil.first(m.getContentClusters().values());
@@ -166,7 +155,7 @@ public class ContentBuilderTest extends DomBuilderTest {
assertEquals("clu/storage/0", c.getRootGroup().getNodes().get(0).getConfigId()); // Due to reuse.
assertEquals(1, c.getRoot().hostSystem().getHosts().size());
HostResource h = c.getRoot().hostSystem().getHost("mockhost");
- String [] expectedServices = {"configserver", "logserver", "logd", "container-clustercontroller", "metricsproxy-container", "slobrok", "configproxy","config-sentinel", "container", "storagenode", "searchnode", "distributor", "transactionlogserver"};
+ String [] expectedServices = {"configserver", "logserver", "logd", "container-clustercontroller", "metricsproxy-container", "slobrok", "configproxy", "config-sentinel", "container", "storagenode", "searchnode", "distributor", "transactionlogserver"};
assertServices(h, expectedServices);
assertEquals("clu/storage/0", h.getService("storagenode").getConfigId());
assertEquals("clu/search/cluster.clu/0", h.getService("searchnode").getConfigId());
@@ -174,28 +163,28 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void testMultipleSearchNodesOnSameHost() {
+ void testMultipleSearchNodesOnSameHost() {
String services = getServices("<node hostalias='mockhost' distribution-key='0'/>" +
- "<node hostalias='mockhost' distribution-key='1'/>");
+ "<node hostalias='mockhost' distribution-key='1'/>");
VespaModel m = new VespaModelCreatorWithMockPkg(createAppWithMusic(getHosts(), services)).create();
IndexedSearchCluster sc = m.getContentClusters().get("clu").getSearch().getIndexed();
assertEquals(2, sc.getSearchNodeCount());
}
@Test
- public void handleStreamingOnlyWithoutPersistence() {
+ void handleStreamingOnlyWithoutPersistence() {
final String musicClusterId = "music-cluster-id";
ContentCluster cluster = createContent(
"<content version='1.0' id='" + musicClusterId + "'>" +
- " <redundancy>3</redundancy>"+
- " <documents>"+
- " <document type='music' mode='streaming'/>"+
- " </documents>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='streaming'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = cluster.getSearch();
@@ -204,7 +193,7 @@ public class ContentBuilderTest extends DomBuilderTest {
assertNull(s.getIndexed());
SearchCluster sc = s.getClusters().get(musicClusterId + ".music");
assertEquals(musicClusterId + ".music", sc.getClusterName());
- assertEquals(musicClusterId, ((StreamingSearchCluster)sc).getStorageRouteSpec());
+ assertEquals(musicClusterId, ((StreamingSearchCluster) sc).getStorageRouteSpec());
assertTrue(cluster.getPersistence() instanceof ProtonEngine.Factory);
assertEquals(1, cluster.getStorageCluster().getChildren().size());
@@ -216,35 +205,29 @@ public class ContentBuilderTest extends DomBuilderTest {
HostResource h = cluster.getRoot().hostSystem().getHost("mockhost");
String [] expectedServices = {
"logd", "configproxy", "config-sentinel", "configserver", "logserver",
- "slobrok", "storagenode", "distributor","searchnode","transactionlogserver",
+ "slobrok", "storagenode", "distributor", "searchnode", "transactionlogserver",
CLUSTERCONTROLLER_CONTAINER.serviceName, METRICS_PROXY_CONTAINER.serviceName
};
assertServices(h, expectedServices);
assertEquals(musicClusterId + "/storage/0", h.getService("storagenode").getConfigId());
-
- /* Not yet
- assertNotNull(h.getService("qrserver"));
- assertNotNull(h.getService("docproc"));
- */
-
}
@Test
- public void requireThatContentStreamingHandlesMultipleSchemas() {
+ void requireThatContentStreamingHandlesMultipleSchemas() {
String musicClusterId = "music-cluster-id";
ContentCluster cluster = createContentWithBooksToo(
"<content version='1.0' id='" + musicClusterId + "'>" +
- " <redundancy>3</redundancy>"+
- " <documents>"+
- " <document type='music' mode='streaming'/>"+
- " <document type='book' mode='streaming'/>"+
- " </documents>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='streaming'/>" +
+ " <document type='book' mode='streaming'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = cluster.getSearch();
@@ -271,17 +254,17 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleIndexedWithoutPersistence() {
+ void handleIndexedWithoutPersistence() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>3</redundancy>"+
- " <documents>"+
- " <document type='music' mode='index'/>"+
- " </documents>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+
- " </group>"+
- "</content>");
+ " <redundancy>3</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = b.getSearch();
@@ -302,18 +285,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureMmapNoCoreLimit() {
+ void canConfigureMmapNoCoreLimit() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group mmap-core-limit=\"200000\">" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group mmap-core-limit=\"200000\">" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = b.getSearch();
@@ -329,7 +312,7 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canAddEnvironmentVariable() {
+ void canAddEnvironmentVariable() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
" <redundancy>1</redundancy>" +
@@ -360,7 +343,7 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void addsEnvironmentVariablesfromFeatureFlag() {
+ void addsEnvironmentVariablesfromFeatureFlag() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
" <redundancy>1</redundancy>" +
@@ -385,18 +368,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureCoreOnOOM() {
+ void canConfigureCoreOnOOM() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group core-on-oom=\"true\">" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group core-on-oom=\"true\">" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = b.getSearch();
@@ -412,18 +395,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void defaultCoreOnOOMIsFalse() {
+ void defaultCoreOnOOMIsFalse() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = b.getSearch();
assertTrue(s.hasIndexedCluster());
assertNotNull(s.getIndexed());
@@ -436,18 +419,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureMmapNoCoreLimitPerHost() {
+ void canConfigureMmapNoCoreLimitPerHost() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" mmap-core-limit=\"200000\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" mmap-core-limit=\"200000\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = b.getSearch();
assertTrue(s.hasIndexedCluster());
assertNotNull(s.getIndexed());
@@ -460,18 +443,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureCoreOnOOMPerHost() {
+ void canConfigureCoreOnOOMPerHost() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" core-on-oom=\"true\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" core-on-oom=\"false\"/>" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" core-on-oom=\"true\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" core-on-oom=\"false\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = b.getSearch();
assertTrue(s.hasIndexedCluster());
assertNotNull(s.getIndexed());
@@ -484,20 +467,20 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureVespaMalloc() {
+ void canConfigureVespaMalloc() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group no-vespamalloc=\"proton\" vespamalloc-debug=\"distributord\" vespamalloc-debug-stacktrace=\"all\" vespamalloc=\"storaged\">" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"2\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"3\"/>" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group no-vespamalloc=\"proton\" vespamalloc-debug=\"distributord\" vespamalloc-debug-stacktrace=\"all\" vespamalloc=\"storaged\">" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"2\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"3\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = b.getSearch();
assertTrue(s.hasIndexedCluster());
assertNotNull(s.getIndexed());
@@ -518,20 +501,20 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureVespaMallocPerHost() {
+ void canConfigureVespaMallocPerHost() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\" no-vespamalloc=\"proton\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\" vespamalloc-debug=\"distributord\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"2\" vespamalloc-debug-stacktrace=\"all\"/>" +
- " <node hostalias=\"mockhost\" distribution-key=\"3\" vespamalloc=\"storaged\"/>" +
- " </group>" +
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" no-vespamalloc=\"proton\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" vespamalloc-debug=\"distributord\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"2\" vespamalloc-debug-stacktrace=\"all\"/>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"3\" vespamalloc=\"storaged\"/>" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s = b.getSearch();
assertTrue(s.hasIndexedCluster());
assertNotNull(s.getIndexed());
@@ -549,18 +532,18 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureCpuAffinity() {
+ void canConfigureCpuAffinity() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>"+
- " <documents>"+
- " <document type='music' mode='index'/>"+
- " </documents>"+
- " <group>"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\" cpu-socket=\"0\" />"+
- " <node hostalias=\"mockhost\" distribution-key=\"1\" cpu-socket=\"1\" />"+
- " </group>"+
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" cpu-socket=\"0\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" cpu-socket=\"1\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = b.getSearch();
@@ -580,22 +563,22 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void canConfigureCpuAffinityAutomatically() {
+ void canConfigureCpuAffinityAutomatically() {
ContentCluster b = createContent(
"<content version =\"1.0\" id=\"b\">" +
- " <redundancy>2</redundancy>"+
- " <documents>"+
- " <document type='music' mode='index'/>"+
- " </documents>"+
- " <group cpu-socket-affinity=\"true\">"+
- " <node hostalias=\"mockhost\" distribution-key=\"0\" />"+
- " <node hostalias=\"mockhost\" distribution-key=\"1\" />"+
- " <node hostalias=\"mockhost\" distribution-key=\"2\" />"+
- " <node hostalias=\"mockhost2\" distribution-key=\"3\" />"+
- " <node hostalias=\"mockhost2\" distribution-key=\"4\" />"+
- " <node hostalias=\"mockhost3\" distribution-key=\"5\" />"+
- " </group>"+
- "</content>");
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group cpu-socket-affinity=\"true\">" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\" />" +
+ " <node hostalias=\"mockhost\" distribution-key=\"2\" />" +
+ " <node hostalias=\"mockhost2\" distribution-key=\"3\" />" +
+ " <node hostalias=\"mockhost2\" distribution-key=\"4\" />" +
+ " <node hostalias=\"mockhost3\" distribution-key=\"5\" />" +
+ " </group>" +
+ "</content>");
ContentSearchCluster s;
s = b.getSearch();
@@ -635,21 +618,21 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void requireBug5357273() {
+ void requireBug5357273() {
try {
createContent(
- " <content version='1.0' id='storage'>\n" +
- " <redundancy>3</redundancy>\n" +
- " <documents>"+
- " <document type='music' mode='index'/>"+
- " </documents>" +
- " <group>\n" +
- " <node hostalias='mockhost' distribution-key='0' />\n" +
- " </group>\n" +
- " <engine>\n" +
- " <dummy/>\n" +
- " </engine>\n" +
- " </content>\n");
+ " <content version='1.0' id='storage'>\n" +
+ " <redundancy>3</redundancy>\n" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>\n" +
+ " <node hostalias='mockhost' distribution-key='0' />\n" +
+ " </group>\n" +
+ " <engine>\n" +
+ " <dummy/>\n" +
+ " </engine>\n" +
+ " </content>\n");
fail();
} catch (Exception e) {
@@ -659,39 +642,39 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void handleProtonTuning() {
+ void handleProtonTuning() {
ContentCluster a = createContent(
"<content version =\"1.0\" id=\"a\">" +
- " <redundancy>3</redundancy>" +
- " <engine>" +
- " <proton>" +
- " <tuning>" +
- " <searchnode>" +
- " <summary>" +
- " <store>" +
- " <cache>" +
- " <maxsize>8192</maxsize>" +
- " <compression>" +
- " <type>lz4</type>" +
- " <level>8</level>" +
- " </compression>" +
- " </cache>" +
- " </store>" +
- " <io>" +
- " <read>directio</read>" +
- " </io>" +
- " </summary>" +
- " </searchnode>" +
- " </tuning>" +
- " </proton>" +
- " </engine>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
- " </group>" +
- "</content>"
+ " <redundancy>3</redundancy>" +
+ " <engine>" +
+ " <proton>" +
+ " <tuning>" +
+ " <searchnode>" +
+ " <summary>" +
+ " <store>" +
+ " <cache>" +
+ " <maxsize>8192</maxsize>" +
+ " <compression>" +
+ " <type>lz4</type>" +
+ " <level>8</level>" +
+ " </compression>" +
+ " </cache>" +
+ " </store>" +
+ " <io>" +
+ " <read>directio</read>" +
+ " </io>" +
+ " </summary>" +
+ " </searchnode>" +
+ " </tuning>" +
+ " </proton>" +
+ " </engine>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>"
);
assertTrue(a.getPersistence() instanceof ProtonEngine.Factory);
@@ -706,26 +689,26 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- @Ignore
- public void ensureOverrideAppendedOnlyOnce() {
+ @Disabled
+ void ensureOverrideAppendedOnlyOnce() {
ContentCluster content = createContent(
"<content version='1.0' id='search'>" +
- " <config name=\"vespa.config.search.core.proton\">" +
- " <numthreadspersearch>1</numthreadspersearch>" +
- " <search>" +
- " <mmap>" +
- " <options><item>POPULATE</item></options>" +
- " </mmap>" +
- " </search>" +
- " </config>" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <group>" +
- " <node hostalias='mockhost' distribution-key='0'/>" +
- " </group>" +
- "</content>");
+ " <config name=\"vespa.config.search.core.proton\">" +
+ " <numthreadspersearch>1</numthreadspersearch>" +
+ " <search>" +
+ " <mmap>" +
+ " <options><item>POPULATE</item></options>" +
+ " </mmap>" +
+ " </search>" +
+ " </config>" +
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <group>" +
+ " <node hostalias='mockhost' distribution-key='0'/>" +
+ " </group>" +
+ "</content>");
ProtonConfig.Builder builder = new ProtonConfig.Builder();
content.getSearch().getIndexed().getSearchNode(0).cascadeConfig(builder);
content.getSearch().getIndexed().getSearchNode(0).addUserConfig(builder);
@@ -745,19 +728,20 @@ public class ContentBuilderTest extends DomBuilderTest {
"</content>" +
"</services>";
}
+
@Test
- public void ensurePruneRemovedDocumentsAgeForHostedVespa() {
+ void ensurePruneRemovedDocumentsAgeForHostedVespa() {
{
ContentCluster contentNonHosted = createContent(
"<content version='1.0' id='search'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document type='music' mode='index'/>" +
- " </documents>" +
- " <nodes>" +
- " <node hostalias='mockhost' distribution-key='0'/>" +
- " </nodes>" +
- "</content>");
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document type='music' mode='index'/>" +
+ " </documents>" +
+ " <nodes>" +
+ " <node hostalias='mockhost' distribution-key='0'/>" +
+ " </nodes>" +
+ "</content>");
ProtonConfig configNonHosted = getProtonConfig(contentNonHosted);
ProtonConfig defaultConfig = new ProtonConfig(new ProtonConfig.Builder());
assertEquals(defaultConfig.pruneremoveddocumentsage(), configNonHosted.pruneremoveddocumentsage(), 0.001);
@@ -768,9 +752,9 @@ public class ContentBuilderTest extends DomBuilderTest {
DeployState.Builder deployStateBuilder = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true));
VespaModel model = new VespaModelCreatorWithMockPkg(new MockApplicationPackage.Builder()
- .withServices(hostedXml)
- .withSearchDefinition(MockApplicationPackage.MUSIC_SCHEMA)
- .build())
+ .withServices(hostedXml)
+ .withSearchDefinition(MockApplicationPackage.MUSIC_SCHEMA)
+ .build())
.create(deployStateBuilder);
ProtonConfig config = getProtonConfig(model.getContentClusters().values().iterator().next());
assertEquals(349260.0, config.pruneremoveddocumentsage(), 0.001);
@@ -813,7 +797,7 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void ensureFeedSequencerIsControlledByFlag() {
+ void ensureFeedSequencerIsControlledByFlag() {
verifyFeedSequencer("LATENCY", "LATENCY");
verifyFeedSequencer("ADAPTIVE", "ADAPTIVE");
verifyFeedSequencer("THROUGHPUT", "THROUGHPUT", 0);
@@ -831,26 +815,27 @@ public class ContentBuilderTest extends DomBuilderTest {
}
@Test
- public void verifyThatFeatureFlagControlsVisibilityDelayDefault() {
+ void verifyThatFeatureFlagControlsVisibilityDelayDefault() {
verifyThatFeatureFlagControlsVisibilityDelayDefault(null, 0.0);
verifyThatFeatureFlagControlsVisibilityDelayDefault(0.5, 0.5);
verifyThatFeatureFlagControlsVisibilityDelayDefault(0.6, 0.6);
}
@Test
- public void failWhenNoDocumentsElementSpecified() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The specified content engine requires the <documents> element to be specified.");
- createContent(
- "<content version =\"1.0\" id=\"a\">" +
- " <redundancy>3</redundancy>" +
- " <engine>" +
- " <dummy/>" +
- " </engine>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
- " </group>" +
- "</content>");
+ void failWhenNoDocumentsElementSpecified() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ createContent(
+ "<content version =\"1.0\" id=\"a\">" +
+ " <redundancy>3</redundancy>" +
+ " <engine>" +
+ " <dummy/>" +
+ " </engine>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" +
+ " </group>" +
+ "</content>");
+ });
+ assertTrue(exception.getMessage().contains("The specified content engine requires the <documents> element to be specified."));
}
private ProtonConfig getProtonConfig(ContentCluster content) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java
index 1a41d2689a2..8a2a23a795d 100755
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java
@@ -13,16 +13,14 @@ import com.yahoo.vespa.model.admin.Admin;
import com.yahoo.vespa.model.admin.Configserver;
import com.yahoo.vespa.model.admin.Slobrok;
import com.yahoo.vespa.model.admin.monitoring.Monitoring;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hmusum
@@ -31,21 +29,11 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
private static MockRoot root;
- @Before
+ @BeforeEach
public void prepareTest() {
root = new MockRoot("root");
}
- // Supported for backwards compatibility
- private Element servicesConfigserver() {
- return XML.getDocument(
- "<admin version=\"2.0\">" +
- " <configserver hostalias=\"mockhost\"/>" +
- " <adminserver hostalias=\"mockhost\"/>" +
- "</admin>").getDocumentElement();
-
- }
-
private Element servicesOverride() {
return XML.getDocument(
"<admin version=\"2.0\">" +
@@ -114,7 +102,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
}
@Test
- public void multitenant() {
+ void multitenant() {
List<ConfigServerSpec> configServerSpecs = Arrays.asList(
new TestProperties.Spec("test1", 19070, 2181),
new TestProperties.Spec("test2", 19070, 2181),
@@ -131,25 +119,16 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
}
/**
- * Tests that configserver works (deprecated, but allowed in admin 2.0)
- */
- @Test
- public void adminWithConfigserverElement() {
- Admin admin = buildAdmin(servicesConfigserver());
- assertEquals(1, admin.getConfigservers().size());
- }
-
- /**
* Tests that configservers/configserver works
*/
@Test
- public void adminWithConfigserversElement() {
+ void adminWithConfigserversElement() {
Admin admin = buildAdmin(servicesConfigservers());
assertEquals(1, admin.getConfigservers().size());
}
@Test
- public void basicYamasNoXml() {
+ void basicYamasNoXml() {
Admin admin = buildAdmin(servicesNoYamas());
Monitoring y = admin.getMonitoring();
assertEquals("vespa", y.getClustername());
@@ -157,13 +136,13 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
}
@Test
- public void testAdminServerOnly() {
+ void testAdminServerOnly() {
Admin admin = buildAdmin(servicesAdminServerOnly());
assertEquals(1, admin.getSlobroks().size());
}
@Test
- public void basicYamasXml() {
+ void basicYamasXml() {
Admin admin = buildAdmin(servicesYamas());
Monitoring y = admin.getMonitoring();
assertEquals("foo", y.getClustername());
@@ -171,7 +150,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
}
@Test
- public void yamasWithIntervalOverride() {
+ void yamasWithIntervalOverride() {
Admin admin = buildAdmin(servicesYamasIntervalOverride());
Monitoring y = admin.getMonitoring();
assertEquals("foo", y.getClustername());
@@ -181,18 +160,20 @@ public class DomAdminV2BuilderTest extends DomBuilderTest {
/**
* Test that illegal yamas interval throws exception
*/
- @Test(expected = IllegalArgumentException.class)
- public void yamasElementInvalid() {
- Element servicesYamasIllegalInterval = XML.getDocument(
- "<admin version=\"2.0\">" +
- " <adminserver hostalias=\"mockhost\"/>" +
- " <monitoring interval=\"5\"/>" +
- "</admin>").getDocumentElement();
- Admin admin = buildAdmin(servicesYamasIllegalInterval);
+ @Test
+ void yamasElementInvalid() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Element servicesYamasIllegalInterval = XML.getDocument(
+ "<admin version=\"2.0\">" +
+ " <adminserver hostalias=\"mockhost\"/>" +
+ " <monitoring interval=\"5\"/>" +
+ "</admin>").getDocumentElement();
+ Admin admin = buildAdmin(servicesYamasIllegalInterval);
+ });
}
@Test
- public void configOverridesCanBeUsedInAdmin() {
+ void configOverridesCanBeUsedInAdmin() {
Admin admin = buildAdmin(servicesOverride());
assertEquals(1, admin.getUserConfigs().size());
LogdConfig.Builder logdBuilder = new LogdConfig.Builder();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java
index 307cbf292db..ed3073a0ef4 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java
@@ -5,11 +5,11 @@ import com.yahoo.component.ComponentId;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.vespa.model.container.component.Component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.collections.CollectionUtil.first;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author gjoranv
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull;
public class DomComponentBuilderTest extends DomBuilderTest {
@Test
- public void ensureCorrectModel() {
+ void ensureCorrectModel() {
Component<?, ?> handler = new DomComponentBuilder().doBuild(root.getDeployState(), root, parse(
"<handler id='theId' class='theClass' bundle='theBundle' />"));
@@ -29,7 +29,7 @@ public class DomComponentBuilderTest extends DomBuilderTest {
@Test
@SuppressWarnings("unchecked")
- public void components_can_be_nested() {
+ void components_can_be_nested() {
Component<Component<?, ?>, ?> parent = new DomComponentBuilder().doBuild(root.getDeployState(), root, parse(
"<component id='parent'>",
" <component id='child' />",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java
index c0db0ac9e09..88af584de90 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.config.ConfigDefinitionBuilder;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.ConfigPayloadBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.ByteArrayOutputStream;
@@ -19,8 +19,7 @@ import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for the {@link com.yahoo.vespa.model.builder.xml.dom.DomConfigPayloadBuilder} class.
@@ -31,7 +30,7 @@ import static org.junit.Assert.fail;
public class DomConfigPayloadBuilderTest {
@Test
- public void testFunctionTest_DefaultValues() throws FileNotFoundException {
+ void testFunctionTest_DefaultValues() throws FileNotFoundException {
Element configRoot = getDocument(new FileReader("src/test/cfg/admin/userconfigs/functiontest-defaultvalues.xml"));
String expected = ""
+ "{"
@@ -57,13 +56,13 @@ public class DomConfigPayloadBuilderTest {
// Multi line strings are not tested in 'DefaultValues', so here it is.
@Test
- public void verifyThatWhitespaceIsPreservedForStrings() throws Exception {
+ void verifyThatWhitespaceIsPreservedForStrings() throws Exception {
Element configRoot = getDocument(new FileReader("src/test/cfg/admin/userconfigs/whitespace-test.xml"));
assertPayload("{\"stringVal\":\" This is a string\\n that contains different kinds of whitespace \"}", configRoot);
}
@Test
- public void put_to_leaf_map() {
+ void put_to_leaf_map() {
Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<config name=\"test.foobar\">" +
" <intmap>" +
@@ -75,7 +74,7 @@ public class DomConfigPayloadBuilderTest {
}
@Test
- public void put_to_inner_map() {
+ void put_to_inner_map() {
Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<config name=\"test.foobar\">" +
" <innermap>" +
@@ -91,7 +90,7 @@ public class DomConfigPayloadBuilderTest {
}
@Test
- public void put_to_nested_map() {
+ void put_to_nested_map() {
Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<config name=\"test.foobar\">" +
" <nestedmap>" +
@@ -115,7 +114,7 @@ public class DomConfigPayloadBuilderTest {
}
@Test
- public void camel_case_via_dashes() {
+ void camel_case_via_dashes() {
Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<config name=\"test.function-test\">" +
" <some-struct> <any-value>17</any-value> </some-struct>" +
@@ -125,7 +124,7 @@ public class DomConfigPayloadBuilderTest {
// Verifies that an exception is thrown when the root element is not 'config'.
@Test
- public void testFailWrongTagName() {
+ void testFailWrongTagName() {
Element configRoot = getDocument(new StringReader("<configs name=\"foo\"/>"));
try {
new DomConfigPayloadBuilder(null).build(configRoot);
@@ -137,7 +136,7 @@ public class DomConfigPayloadBuilderTest {
// Verifies that an exception is thrown when the root element is not 'config'.
@Test
- public void testFailNoNameAttribute() {
+ void testFailNoNameAttribute() {
Element configRoot = getDocument(new StringReader("<config/>"));
try {
new DomConfigPayloadBuilder(null).build(configRoot);
@@ -148,7 +147,7 @@ public class DomConfigPayloadBuilderTest {
}
@Test
- public void testNameParsing() {
+ void testNameParsing() {
Element configRoot = getDocument(new StringReader("<config name=\"test.function-test\" version=\"1\">" +
"<int_val>1</int_val> +" +
"</config>"));
@@ -157,38 +156,42 @@ public class DomConfigPayloadBuilderTest {
assertEquals("test", key.getNamespace());
}
- @Test(expected = ConfigurationRuntimeException.class)
- public void testNameParsingInvalidName() {
- Element configRoot = getDocument(new StringReader("<config name=\" function-test\" version=\"1\">" +
- "<int_val>1</int_val> +" +
- "</config>"));
- DomConfigPayloadBuilder.parseConfigName(configRoot);
+ @Test
+ void testNameParsingInvalidName() {
+ assertThrows(ConfigurationRuntimeException.class, () -> {
+ Element configRoot = getDocument(new StringReader("<config name=\" function-test\" version=\"1\">" +
+ "<int_val>1</int_val> +" +
+ "</config>"));
+ DomConfigPayloadBuilder.parseConfigName(configRoot);
+ });
}
- @Test(expected = ConfigurationRuntimeException.class)
- public void testNameParsingInvalidNamespace() {
- Element configRoot = getDocument(new StringReader("<config name=\"_foo.function-test\" version=\"1\">" +
- "<int_val>1</int_val> +" +
- "</config>"));
- DomConfigPayloadBuilder.parseConfigName(configRoot);
+ @Test
+ void testNameParsingInvalidNamespace() {
+ assertThrows(ConfigurationRuntimeException.class, () -> {
+ Element configRoot = getDocument(new StringReader("<config name=\"_foo.function-test\" version=\"1\">" +
+ "<int_val>1</int_val> +" +
+ "</config>"));
+ DomConfigPayloadBuilder.parseConfigName(configRoot);
+ });
}
@Test
- public void require_that_item_syntax_works_with_leaf() {
+ void require_that_item_syntax_works_with_leaf() {
Element configRoot = getDocument(
"<config name=\"test.arraytypes\" version=\"1\">" +
- " <intarr>" +
- " <item>13</item>" +
- " <item>10</item>" +
- " <item>1337</item>" +
- " </intarr>" +
- "</config>");
+ " <intarr>" +
+ " <item>13</item>" +
+ " <item>10</item>" +
+ " <item>1337</item>" +
+ " </intarr>" +
+ "</config>");
assertPayload("{\"intarr\":[\"13\",\"10\",\"1337\"]}", configRoot);
}
@Test
- public void require_that_item_syntax_works_with_struct() {
+ void require_that_item_syntax_works_with_struct() {
Element configRoot = getDocument(
"<config name=\"test.arraytypes\" version=\"1\">" +
" <lolarray>" +
@@ -199,42 +202,46 @@ public class DomConfigPayloadBuilderTest {
"</config>");
assertPayload("{\"lolarray\":[{\"foo\":\"hei\",\"bar\":\"hei2\"},{\"foo\":\"hoo\",\"bar\":\"hoo2\"},{\"foo\":\"happ\",\"bar\":\"happ2\"}]}",
- configRoot);
+ configRoot);
}
@Test
- public void require_that_item_syntax_works_with_struct_array() {
+ void require_that_item_syntax_works_with_struct_array() {
Element configRoot = getDocument(
"<config name=\"test.arraytypes\" version=\"1\">" +
- " <lolarray>" +
- " <item><fooarray><item>13</item></fooarray></item>" +
- " <item><fooarray><item>10</item></fooarray></item>" +
- " <item><fooarray><item>1337</item></fooarray></item>" +
- " </lolarray>" +
- "</config>");
+ " <lolarray>" +
+ " <item><fooarray><item>13</item></fooarray></item>" +
+ " <item><fooarray><item>10</item></fooarray></item>" +
+ " <item><fooarray><item>1337</item></fooarray></item>" +
+ " </lolarray>" +
+ "</config>");
assertPayload("{\"lolarray\":[{\"fooarray\":[\"13\"]},{\"fooarray\":[\"10\"]},{\"fooarray\":[\"1337\"]}]}", configRoot);
}
- @Test(expected = ConfigurationRuntimeException.class)
- public void require_that_item_is_reserved_in_root() {
- Element configRoot = getDocument(
- "<config name=\"test.arraytypes\" version=\"1\">" +
- " <item>13</item>" +
- "</config>");
- new DomConfigPayloadBuilder(null).build(configRoot);
+ @Test
+ void require_that_item_is_reserved_in_root() {
+ assertThrows(ConfigurationRuntimeException.class, () -> {
+ Element configRoot = getDocument(
+ "<config name=\"test.arraytypes\" version=\"1\">" +
+ " <item>13</item>" +
+ "</config>");
+ new DomConfigPayloadBuilder(null).build(configRoot);
+ });
}
- @Test(expected=ConfigurationRuntimeException.class)
- public void require_that_exceptions_are_issued() throws FileNotFoundException {
- Element configRoot = getDocument(
- "<config name=\"test.simpletypes\">" +
- "<longval>invalid</longval>" +
- "</config>");
- DefParser defParser = new DefParser("simpletypes",
- new FileReader("src/test/resources/configdefinitions/test.simpletypes.def"));
- ConfigDefinition def = ConfigDefinitionBuilder.createConfigDefinition(defParser.getTree());
- ConfigPayloadBuilder unused = new DomConfigPayloadBuilder(def).build(configRoot);
+ @Test
+ void require_that_exceptions_are_issued() throws FileNotFoundException {
+ assertThrows(ConfigurationRuntimeException.class, () -> {
+ Element configRoot = getDocument(
+ "<config name=\"test.simpletypes\">" +
+ "<longval>invalid</longval>" +
+ "</config>");
+ DefParser defParser = new DefParser("simpletypes",
+ new FileReader("src/test/resources/configdefinitions/test.simpletypes.def"));
+ ConfigDefinition def = ConfigDefinitionBuilder.createConfigDefinition(defParser.getTree());
+ ConfigPayloadBuilder unused = new DomConfigPayloadBuilder(def).build(configRoot);
+ });
}
private void assertPayload(String expected, Element configRoot) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java
index 4ed355a7dca..41cef783b68 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java
@@ -5,15 +5,12 @@ import com.yahoo.collections.CollectionUtil;
import com.yahoo.vespa.config.search.core.ProtonConfig;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.vespa.model.search.Tuning;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
@@ -46,7 +43,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseRequestThreadsTag() {
+ void requireThatWeCanParseRequestThreadsTag() {
Tuning t = createTuning(parseXml("<requestthreads>",
"<search>123</search>",
"<persearch>34</persearch>",
@@ -58,11 +55,11 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
assertEquals(cfg.numsearcherthreads(), 123);
assertEquals(cfg.numthreadspersearch(), 34);
assertEquals(cfg.numsummarythreads(), 456);
- }
+ }
@Test
- public void requireThatWeCanParseFlushStrategyTag() {
- Tuning t = createTuning(parseXml("<flushstrategy>","<native>",
+ void requireThatWeCanParseFlushStrategyTag() {
+ Tuning t = createTuning(parseXml("<flushstrategy>", "<native>",
"<total>",
"<maxmemorygain>900</maxmemorygain>",
"<diskbloatfactor>8.7</diskbloatfactor>",
@@ -79,7 +76,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
"<memory-limit-factor>0.6</memory-limit-factor>",
"<disk-limit-factor>0.7</disk-limit-factor>",
"</conservative>",
- "</native>","</flushstrategy>"));
+ "</native>", "</flushstrategy>"));
assertEquals(900, t.searchNode.strategy.totalMaxMemoryGain.longValue());
assertEquals(8.7, t.searchNode.strategy.totalDiskBloatFactor, DELTA);
assertEquals(600, t.searchNode.strategy.componentMaxMemoryGain.longValue());
@@ -100,7 +97,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseResizingTag() {
+ void requireThatWeCanParseResizingTag() {
Tuning t = createTuning(parseXml("<resizing>",
"<initialdocumentcount>128</initialdocumentcount>",
"<amortize-count>13</amortize-count>",
@@ -110,14 +107,14 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseIndexTag() {
+ void requireThatWeCanParseIndexTag() {
Tuning t = createTuning(parseXml("<index>", "<io>",
"<write>directio</write>",
"<read>normal</read>",
"<search>mmap</search>",
"</io>",
"<warmup>" +
- "<time>178</time>",
+ "<time>178</time>",
"<unpack>true</unpack>",
"</warmup>",
"</index>"));
@@ -134,7 +131,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanPopulateIndex() {
+ void requireThatWeCanPopulateIndex() {
Tuning t = createTuning(parseXml("<index>", "<io>",
"<search>populate</search>",
"</io>",
@@ -150,7 +147,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
@Test
- public void requireThatWeCanParseRemovedDBTag() {
+ void requireThatWeCanParseRemovedDBTag() {
Tuning t = createTuning(parseXml("<removed-db>", "<prune>",
"<age>19388</age>",
"<interval>193</interval>",
@@ -163,7 +160,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseAttributeTag() {
+ void requireThatWeCanParseAttributeTag() {
Tuning t = createTuning(parseXml("<attribute>", "<io>",
"<write>directio</write>",
"</io>", "</attribute>"));
@@ -173,7 +170,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseSummaryTag() {
+ void requireThatWeCanParseSummaryTag() {
Tuning t = createTuning(parseXml("<summary>",
"<io>",
"<write>directio</write>",
@@ -232,7 +229,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanGiveSummaryCacheSizeInPercentage() {
+ void requireThatWeCanGiveSummaryCacheSizeInPercentage() {
Tuning t = createTuning(parseXml("<summary>",
"<store>",
"<cache>",
@@ -242,14 +239,14 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
"</summary>"));
assertNull(t.searchNode.summary.store.cache.maxSize);
- assertEquals(30.7, t.searchNode.summary.store.cache.maxSizePercent,DELTA);
+ assertEquals(30.7, t.searchNode.summary.store.cache.maxSizePercent, DELTA);
ProtonConfig cfg = getProtonCfg(t);
assertEquals(cfg.summary().cache().maxbytes(), -30);
}
@Test
- public void requireThatWeCanPopulateSummary() {
+ void requireThatWeCanPopulateSummary() {
Tuning t = createTuning(parseXml("<summary>",
"<io>",
"<read>populate</read>",
@@ -265,7 +262,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
@Test
- public void requireThatWeCanParseInitializeTag() {
+ void requireThatWeCanParseInitializeTag() {
Tuning t = createTuning(parseXml("<initialize>",
"<threads>7</threads>",
"</initialize>"));
@@ -275,7 +272,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest {
}
@Test
- public void requireThatWeCanParseFeedingTag() {
+ void requireThatWeCanParseFeedingTag() {
Tuning t = createTuning(parseXml("<feeding>",
"<concurrency>0.7</concurrency>",
"</feeding>"));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java
index 2bcb1a7459b..1f9cddef028 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java
@@ -8,14 +8,13 @@ import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.text.XML;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -23,11 +22,11 @@ import static org.junit.Assert.assertThat;
public class LegacyConfigModelBuilderTest {
@Test
- public void testThatProducerIsInserted() {
+ void testThatProducerIsInserted() {
String services = "<foo><config name=\"bar.foo\"><key>value</key></config></foo>";
ModelBuilder builder = new ModelBuilder();
Model model = builder.build(DeployState.createTestState(new MockApplicationPackage.Builder().withServices(services).build()),
- null, null, new MockRoot(), XML.getDocument(services).getDocumentElement());
+ null, null, new MockRoot(), XML.getDocument(services).getDocumentElement());
assertEquals(1, model.getContext().getParentProducer().getUserConfigs().size());
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java
index 1a5a7bbe544..97951ab5a20 100755
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java
@@ -10,13 +10,13 @@ import com.yahoo.vespa.model.HostResource;
import com.yahoo.vespa.model.HostSystem;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.io.StringReader;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author gjoranv
@@ -45,7 +45,7 @@ public class VespaDomBuilderTest {
" <container version=\"1.0\">" +
" <config name=\"a.standard\">" +
" <basicStruct>" +
- " <stringVal>qrservers</stringVal>" +
+ " <stringVal>foo</stringVal>" +
" </basicStruct>" +
" </config> " +
" <nodes>\n" +
@@ -68,21 +68,21 @@ public class VespaDomBuilderTest {
@Test
- public void testUserConfigsWithNamespace() {
+ void testUserConfigsWithNamespace() {
VespaModel model = createModel(hosts, servicesWithNamespace);
- GenericConfig.GenericConfigBuilder builder =
+ GenericConfig.GenericConfigBuilder builder =
new GenericConfig.GenericConfigBuilder(new ConfigDefinitionKey("testnamespace", "foo"), new ConfigPayloadBuilder());
model.getConfig(builder, "admin");
assertEquals("{\n" +
- " \"basicStruct\": {\n" +
- " \"stringVal\": \"default\"\n" +
- " }\n" +
- "}\n", builder.getPayload().toString());
+ " \"basicStruct\": {\n" +
+ " \"stringVal\": \"default\"\n" +
+ " }\n" +
+ "}\n", builder.getPayload().toString());
}
@Test
- public void testGetElement() {
+ void testGetElement() {
Element e = Xml.getElement(new StringReader("<chain><foo>sdf</foo></chain>"));
assertEquals(e.getTagName(), "chain");
assertEquals(XML.getChild(e, "foo").getTagName(), "foo");
@@ -90,7 +90,7 @@ public class VespaDomBuilderTest {
}
@Test
- public void testHostSystem() {
+ void testHostSystem() {
VespaModel model = createModel(hosts, services);
HostSystem hostSystem = model.hostSystem();
assertEquals(1, hostSystem.getHosts().size());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java
index bc0df8196b8..7e87ebf782e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.model.builder.xml.dom.chains;
import com.yahoo.component.chain.dependencies.Dependencies;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Basic tests of DependencyBuilder
@@ -24,7 +24,7 @@ public class DependenciesBuilderTest extends DomBuilderTest {
}
@Test
- public void testBuildDependencies() {
+ void testBuildDependencies() {
DependenciesBuilder dependenciesBuilder = new DependenciesBuilder(parse(
"<searcher provides='symbol1 symbol2 ' before='p1' after=' s1' >",
" <provides> symbol3 </provides>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java
index d68f306c043..38488947db8 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java
@@ -6,14 +6,12 @@ import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.search.federation.FederationConfig;
import com.yahoo.search.searchchain.model.federation.FederationSearcherModel;
import com.yahoo.vespa.model.container.search.searchchain.FederationSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test of DomFederationSearcherBuilder.
@@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class DomFederationSearcherBuilderTest extends DomBuilderTest {
@Test
- public void ensureCorrectModel() {
+ void ensureCorrectModel() {
FederationSearcher searcher = new DomFederationSearcherBuilder().doBuild(root.getDeployState(), root, parse(
"<federation id='theId'>",
" <provides>p2</provides>",
@@ -41,7 +39,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest {
model.bundleInstantiationSpec.classId.stringValue());
assertEquals(2, model.targets.size());
- assertTrue("source-set option was ignored", model.inheritDefaultSources);
+ assertTrue(model.inheritDefaultSources, "source-set option was ignored");
assertTrue(targetNames(model.targets).containsAll(List.of("source1", "source2")));
}
@@ -55,7 +53,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest {
}
@Test
- public void require_that_target_selector_can_be_configured() {
+ void require_that_target_selector_can_be_configured() {
FederationSearcher searcher = new DomFederationSearcherBuilder().doBuild(root.getDeployState(), root, parse(
"<federation id='federation-id'>",
" <target-selector id='my-id' class='my-class' />",
@@ -64,7 +62,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest {
String targetSelectorId = "my-id@federation-id";
AbstractConfigProducer<?> targetSelector = searcher.getChildren().get(targetSelectorId);
- assertNotNull("No target selector child found", targetSelector);
+ assertNotNull(targetSelector, "No target selector child found");
FederationConfig.Builder builder = new FederationConfig.Builder();
searcher.getConfig(builder);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java
index 9fb7b58a43c..d470f184340 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java
@@ -16,8 +16,8 @@ import com.yahoo.vespa.model.container.search.searchchain.Source;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Arrays;
@@ -28,10 +28,7 @@ import static com.yahoo.container.core.ChainsConfig.Chains;
import static com.yahoo.container.core.ChainsConfig.Components;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test of Search chains builder.
@@ -70,13 +67,13 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
"</search>");
- @Before
+ @BeforeEach
public void createSearchChains() {
searchChains = new DomSearchChainsBuilder().build(root.getDeployState(), root, element);
}
@Test
- public void referToFederationAsSearcher() {
+ void referToFederationAsSearcher() {
final Element element = parse(
"<search>",
" <federation id='federationSearcher'>",
@@ -100,14 +97,14 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
}
@Test
- public void ensureSearchChainsExists() {
+ void ensureSearchChainsExists() {
for (String id : Arrays.asList("provider:1", "source:1@provider:1", "default")) {
- assertNotNull("Missing search chain " + id, getSearchChain(id));
+ assertNotNull(getSearchChain(id), "Missing search chain " + id);
}
}
@Test
- public void ensureSearcherExists() {
+ void ensureSearcherExists() {
assertThat(searchChains.allComponents(), hasItem(searcherWithId("searcher:1")));
}
@@ -127,7 +124,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
}
@Test
- public void checkProviderFederationOptions() {
+ void checkProviderFederationOptions() {
FederationOptions options = getProvider().federationOptions();
assertTrue(options.getOptional());
@@ -135,7 +132,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
}
@Test
- public void checkSourceFederationOptions() {
+ void checkSourceFederationOptions() {
FederationOptions options = getSource().federationOptions();
assertTrue(options.getOptional()); //inherited
@@ -143,7 +140,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
}
@Test
- public void checkDefaultTargets() {
+ void checkDefaultTargets() {
Collection<? extends GenericTarget> defaultTargets =
getProvider().defaultFederationTargets();
@@ -152,7 +149,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest {
}
@Test
- public void checkInnerSearcherIdIsNestedInSearchChainId() {
+ void checkInnerSearcherIdIsNestedInSearchChainId() {
ChainsConfig.Builder builder = new ChainsConfig.Builder();
searchChains.getConfig(builder);
ChainsConfig config = new ChainsConfig(builder);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java
index af3b4027b1c..933f57c76cd 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java
@@ -5,9 +5,9 @@ import com.yahoo.component.chain.model.ChainedComponentModel;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.vespa.model.container.component.chain.ChainedComponent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Tony Vaagenes
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals;
public class DomSearcherBuilderTest extends DomBuilderTest {
@Test
- public void ensureCorrectModel() {
+ void ensureCorrectModel() {
ChainedComponent<ChainedComponentModel> searcher = new DomSearcherBuilder().doBuild(root.getDeployState(), root, parse(
"<searcher id='theId' class='theclassid' bundle='thebundle' provides='p1'>",
" <provides>p2</provides>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java
index 198b5713876..dbc7d475c27 100755
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java
@@ -30,8 +30,10 @@ import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.docproc.ContainerDocproc;
import com.yahoo.vespa.model.container.search.ContainerSearch;
import com.yahoo.vespa.model.container.search.searchchain.SearchChains;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
@@ -48,9 +50,7 @@ import static com.yahoo.config.model.api.ApplicationClusterEndpoint.Scope.applic
import static com.yahoo.config.model.api.ApplicationClusterEndpoint.Scope.global;
import static com.yahoo.config.provision.SystemName.cd;
import static com.yahoo.config.provision.SystemName.main;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -58,7 +58,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerClusterTest {
@Test
- public void requireThatClusterInfoIsPopulated() {
+ void requireThatClusterInfoIsPopulated() {
ApplicationContainerCluster cluster = newContainerCluster();
ClusterInfoConfig config = getClusterInfoConfig(cluster);
assertEquals("name", config.clusterId());
@@ -79,10 +79,30 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatWeCanGetTheZoneConfig() {
+ void search_and_docproc_bundles_are_not_installed_for_plain_application_clusters() {
+ ApplicationContainerCluster cluster = newContainerCluster();
+
+ var bundleBuilder = new PlatformBundlesConfig.Builder();
+ cluster.getConfig(bundleBuilder);
+ List<Path> installedBundles = bundleBuilder.build().bundlePaths().stream().map(Paths::get).toList();
+ installedBundles.forEach(bundle -> assertFalse(PlatformBundles.SEARCH_AND_DOCPROC_BUNDLES.contains(bundle)));
+ }
+
+ @Test
+ void search_and_docproc_bundles_are_installed_for_application_clusters_with_search() {
+ ApplicationContainerCluster cluster = newClusterWithSearch(createRoot(false), false, null);
+
+ var bundleBuilder = new PlatformBundlesConfig.Builder();
+ cluster.getConfig(bundleBuilder);
+ List<Path> installedBundles = bundleBuilder.build().bundlePaths().stream().map(Paths::get).toList();
+ PlatformBundles.SEARCH_AND_DOCPROC_BUNDLES.forEach(bundle -> assertTrue(installedBundles.contains(bundle)));
+ }
+
+ @Test
+ void requireThatWeCanGetTheZoneConfig() {
DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true))
- .zone(new Zone(SystemName.cd, Environment.test, RegionName.from("some-region")))
- .build();
+ .zone(new Zone(SystemName.cd, Environment.test, RegionName.from("some-region")))
+ .build();
MockRoot root = new MockRoot("foo", state);
ContainerCluster<?> cluster = new ApplicationContainerCluster(root, "container0", "container1", state);
ConfigserverConfig.Builder builder = new ConfigserverConfig.Builder();
@@ -93,33 +113,11 @@ public class ContainerClusterTest {
assertEquals("cd", config.system());
}
- private ApplicationContainerCluster createContainerCluster(MockRoot root) {
- return createContainerCluster(root, false, null);
- }
- private ApplicationContainerCluster createContainerCluster(MockRoot root, boolean isCombinedCluster, Integer memoryPercentage) {
- ApplicationContainerCluster cluster = new ApplicationContainerCluster(root, "container0", "container1", root.getDeployState());
- if (isCombinedCluster)
- cluster.setHostClusterId("test-content-cluster");
- cluster.setMemoryPercentage(memoryPercentage);
- cluster.setSearch(new ContainerSearch(cluster, new SearchChains(cluster, "search-chain"), new ContainerSearch.Options()));
- return cluster;
- }
- private ClusterControllerContainerCluster createClusterControllerCluster(MockRoot root) {
- return new ClusterControllerContainerCluster(root, "container0", "container1", root.getDeployState());
- }
- private MockRoot createRoot(boolean isHosted) {
- DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(isHosted)).build();
- return createRoot(state);
- }
- private MockRoot createRoot(DeployState deployState) {
- return new MockRoot("foo", deployState);
- }
-
private void verifyHeapSizeAsPercentageOfPhysicalMemory(boolean isHosted,
boolean isCombinedCluster,
Integer explicitMemoryPercentage,
int expectedMemoryPercentage) {
- ContainerCluster<?> cluster = createContainerCluster(createRoot(isHosted), isCombinedCluster, explicitMemoryPercentage);
+ ApplicationContainerCluster cluster = newClusterWithSearch(createRoot(isHosted), isCombinedCluster, explicitMemoryPercentage);
QrStartConfig.Builder qsB = new QrStartConfig.Builder();
cluster.getConfig(qsB);
QrStartConfig qsC= new QrStartConfig(qsB);
@@ -128,17 +126,17 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatHeapSizeAsPercentageOfPhysicalMemoryForHostedAndNot() {
+ void requireThatHeapSizeAsPercentageOfPhysicalMemoryForHostedAndNot() {
boolean hosted = true;
boolean combined = true; // a cluster running on content nodes (only relevant with hosted)
- verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, ! combined, null, 70);
+ verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, !combined, null, 70);
verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, combined, null, 18);
- verifyHeapSizeAsPercentageOfPhysicalMemory(! hosted, ! combined, null, 0);
-
+ verifyHeapSizeAsPercentageOfPhysicalMemory(!hosted, !combined, null, 0);
+
// Explicit value overrides all defaults
- verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, ! combined, 67, 67);
+ verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, !combined, 67, 67);
verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, combined, 68, 68);
- verifyHeapSizeAsPercentageOfPhysicalMemory(! hosted, ! combined, 69, 69);
+ verifyHeapSizeAsPercentageOfPhysicalMemory(!hosted, !combined, 69, 69);
}
private void verifyJvmArgs(boolean isHosted, boolean hasDocproc, String expectedArgs, String jvmArgs) {
@@ -155,26 +153,26 @@ public class ContainerClusterTest {
private void verifyJvmArgs(boolean isHosted, boolean hasDocProc) {
MockRoot root = createRoot(isHosted);
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
if (hasDocProc) {
cluster.setDocproc(new ContainerDocproc(cluster, null));
}
addContainer(root, cluster, "c1", "host-c1");
assertEquals(1, cluster.getContainers().size());
ApplicationContainer container = cluster.getContainers().get(0);
- verifyJvmArgs(isHosted, hasDocProc, "", container.getJvmOptions());
+ verifyJvmArgs(isHosted, hasDocProc, expectedJvmArgs(isHosted, ""), container.getJvmOptions());
container.setJvmOptions("initial");
- verifyJvmArgs(isHosted, hasDocProc, "initial", container.getJvmOptions());
+ verifyJvmArgs(isHosted, hasDocProc, expectedJvmArgs(isHosted, "initial"), container.getJvmOptions());
container.prependJvmOptions("ignored");
- verifyJvmArgs(isHosted, hasDocProc, "ignored initial", container.getJvmOptions());
+ verifyJvmArgs(isHosted, hasDocProc, expectedJvmArgs(isHosted, "ignored initial"), container.getJvmOptions());
container.appendJvmOptions("override");
- verifyJvmArgs(isHosted, hasDocProc, "ignored initial override", container.getJvmOptions());
+ verifyJvmArgs(isHosted, hasDocProc, expectedJvmArgs(isHosted, "ignored initial override"), container.getJvmOptions());
container.setJvmOptions(null);
- verifyJvmArgs(isHosted, hasDocProc, "", container.getJvmOptions());
+ verifyJvmArgs(isHosted, hasDocProc, expectedJvmArgs(isHosted, ""), container.getJvmOptions());
}
@Test
- public void testClusterControllerResourceUsage() {
+ void testClusterControllerResourceUsage() {
MockRoot root = createRoot(false);
ClusterControllerContainerCluster cluster = createClusterControllerCluster(root);
addClusterController(cluster, "host-c1", root.getDeployState());
@@ -194,7 +192,18 @@ public class ContainerClusterTest {
}
@Test
- public void testThatLinguisticsIsExcludedForClusterControllerCluster() {
+ void search_and_docproc_bundles_are_not_installed_for_cluster_controllers() {
+ MockRoot root = createRoot(false);
+ ClusterControllerContainerCluster cluster = createClusterControllerCluster(root);
+
+ var bundleBuilder = new PlatformBundlesConfig.Builder();
+ cluster.getConfig(bundleBuilder);
+ List<Path> installedBundles = bundleBuilder.build().bundlePaths().stream().map(Paths::get).toList();
+ installedBundles.forEach(bundle -> assertFalse(PlatformBundles.SEARCH_AND_DOCPROC_BUNDLES.contains(bundle)));
+ }
+
+ @Test
+ void testThatLinguisticsIsExcludedForClusterControllerCluster() {
MockRoot root = createRoot(false);
ClusterControllerContainerCluster cluster = createClusterControllerCluster(root);
addClusterController(cluster, "host-c1", root.getDeployState());
@@ -209,7 +218,7 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatJvmArgsControlWorksForHostedAndNot() {
+ void requireThatJvmArgsControlWorksForHostedAndNot() {
verifyJvmArgs(true, false);
verifyJvmArgs(true, true);
verifyJvmArgs(false, false);
@@ -217,10 +226,10 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatJvmOmitStackTraceInFastThrowOptionWorks() {
+ void requireThatJvmOmitStackTraceInFastThrowOptionWorks() {
// Empty option if option not set in property
MockRoot root = createRoot(new DeployState.Builder().build());
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
ApplicationContainer container = cluster.getContainers().get(0);
assertEquals("", container.getJvmOptions());
@@ -228,16 +237,16 @@ public class ContainerClusterTest {
String jvmOption = "-XX:-foo";
DeployState deployState = new DeployState.Builder().properties(new TestProperties().setJvmOmitStackTraceInFastThrowOption(jvmOption)).build();
root = createRoot(deployState);
- cluster = createContainerCluster(root);
+ cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
container = cluster.getContainers().get(0);
assertEquals(jvmOption, container.getJvmOptions());
}
@Test
- public void requireThatWeCanHandleNull() {
+ void requireThatWeCanHandleNullJvmOptions() {
MockRoot root = createRoot(false);
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
Container container = cluster.getContainers().get(0);
container.setJvmOptions("");
@@ -247,9 +256,9 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatNonHostedUsesExpectedDefaultThreadpoolConfiguration() {
+ void requireThatNonHostedUsesExpectedDefaultThreadpoolConfiguration() {
MockRoot root = new MockRoot("foo");
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
root.freezeModelTopology();
@@ -259,9 +268,9 @@ public class ContainerClusterTest {
}
@Test
- public void container_cluster_has_default_threadpool_provider() {
+ void container_cluster_has_default_threadpool_provider() {
MockRoot root = new MockRoot("foo");
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
root.freezeModelTopology();
@@ -273,14 +282,14 @@ public class ContainerClusterTest {
}
@Test
- public void config_for_default_threadpool_provider_scales_with_node_resources_in_hosted() {
+ void config_for_default_threadpool_provider_scales_with_node_resources_in_hosted() {
MockRoot root = new MockRoot(
"foo",
new DeployState.Builder()
.properties(new TestProperties().setHostedVespa(true))
.applicationPackage(new MockApplicationPackage.Builder().build())
.build());
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
root.freezeModelTopology();
@@ -290,14 +299,14 @@ public class ContainerClusterTest {
}
@Test
- public void jetty_threadpool_scales_with_node_resources_in_hosted() {
+ void jetty_threadpool_scales_with_node_resources_in_hosted() {
MockRoot root = new MockRoot(
"foo",
new DeployState.Builder()
.properties(new TestProperties().setHostedVespa(true))
.applicationPackage(new MockApplicationPackage.Builder().build())
.build());
- ApplicationContainerCluster cluster = createContainerCluster(root);
+ ApplicationContainerCluster cluster = newClusterWithSearch(root);
addContainer(root, cluster, "c1", "host-c1");
root.freezeModelTopology();
@@ -307,22 +316,22 @@ public class ContainerClusterTest {
}
@Test
- public void requireThatBundlesForTesterApplicationAreInstalled() {
+ void requireThatBundlesForTesterApplicationAreInstalled() {
List<String> expectedOnpremBundles =
List.of("vespa-testrunner-components-jar-with-dependencies.jar",
"vespa-osgi-testrunner-jar-with-dependencies.jar",
"tenant-cd-api-jar-with-dependencies.jar");
verifyTesterApplicationInstalledBundles(Zone.defaultZone(), expectedOnpremBundles);
-
+
List<String> expectedPublicBundles = new ArrayList<>(expectedOnpremBundles);
expectedPublicBundles.add("cloud-tenant-cd-jar-with-dependencies.jar");
Zone publicZone = new Zone(SystemName.PublicCd, Environment.dev, RegionName.defaultName());
verifyTesterApplicationInstalledBundles(publicZone, expectedPublicBundles);
-
+
}
@Test
- public void requireCuratorConfig() {
+ void requireCuratorConfig() {
DeployState state = new DeployState.Builder().build();
MockRoot root = new MockRoot("foo", state);
var cluster = new ApplicationContainerCluster(root, "container", "search-cluster", state);
@@ -332,12 +341,12 @@ public class ContainerClusterTest {
cluster.getConfig(configBuilder);
CuratorConfig config = configBuilder.build();
assertEquals(List.of("host-c1", "host-c2"),
- config.server().stream().map(CuratorConfig.Server::hostname).collect(Collectors.toList()));
+ config.server().stream().map(CuratorConfig.Server::hostname).collect(Collectors.toList()));
assertTrue(config.zookeeperLocalhostAffinity());
}
@Test
- public void requireZooKeeperServerConfig() {
+ void requireZooKeeperServerConfig() {
DeployState state = new DeployState.Builder().build();
MockRoot root = new MockRoot("foo", state);
var cluster = new ApplicationContainerCluster(root, "container", "search-cluster", state);
@@ -354,67 +363,67 @@ public class ContainerClusterTest {
cluster.getConfig(configBuilder);
assertEquals(0, configBuilder.build().myid());
assertEquals(List.of("host-c1", "host-c2", "host-c3"),
- configBuilder.build().server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toList()));
+ configBuilder.build().server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toList()));
}
@Test
- public void generatesCorrectRoutingInfo() {
+ void generatesCorrectRoutingInfo() {
// main system:
assertNames(main,
- ApplicationId.from("t1", "a1", "i1"),
- Set.of(),
- List.of("search-cluster.i1.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "i1"),
+ Set.of(),
+ List.of("search-cluster.i1.a1.t1.endpoint.suffix"));
assertNames(main,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(),
- List.of("search-cluster.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(),
+ List.of("search-cluster.a1.t1.endpoint.suffix"));
assertNames(main,
- ApplicationId.from("t1", "default", "default"),
- Set.of(),
- List.of("search-cluster.default.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "default", "default"),
+ Set.of(),
+ List.of("search-cluster.default.t1.endpoint.suffix"));
assertNames(main,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))),
- List.of("search-cluster.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))),
+ List.of("search-cluster.a1.t1.endpoint.suffix"));
assertNames(main,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4),
- new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4)),
- List.of("search-cluster.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4),
+ new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4)),
+ List.of("search-cluster.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z"));
// cd system:
assertNames(cd,
- ApplicationId.from("t1", "a1", "i1"),
- Set.of(),
- List.of("search-cluster.cd.i1.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "i1"),
+ Set.of(),
+ List.of("search-cluster.cd.i1.a1.t1.endpoint.suffix"));
assertNames(cd,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(),
- List.of("search-cluster.cd.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(),
+ List.of("search-cluster.cd.a1.t1.endpoint.suffix"));
assertNames(cd,
- ApplicationId.from("t1", "default", "default"),
- Set.of(),
- List.of("search-cluster.cd.default.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "default", "default"),
+ Set.of(),
+ List.of("search-cluster.cd.default.t1.endpoint.suffix"));
assertNames(cd,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))),
- List.of("search-cluster.cd.a1.t1.endpoint.suffix"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))),
+ List.of("search-cluster.cd.a1.t1.endpoint.suffix"));
assertNames(cd,
- ApplicationId.from("t1", "a1", "default"),
- Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4),
- new ContainerEndpoint("search-cluster", global, List.of("a.b.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), shared),
- new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4),
- new ContainerEndpoint("not-supported", global, List.of("not.supported"), OptionalInt.empty(), exclusive)),
- List.of("search-cluster.cd.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z"));
+ ApplicationId.from("t1", "a1", "default"),
+ Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4),
+ new ContainerEndpoint("search-cluster", global, List.of("a.b.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), shared),
+ new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4),
+ new ContainerEndpoint("not-supported", global, List.of("not.supported"), OptionalInt.empty(), exclusive)),
+ List.of("search-cluster.cd.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z"));
}
@@ -446,7 +455,7 @@ public class ContainerClusterTest {
private void assertNames(List<String> expectedNames, List<ApplicationClusterEndpoint> endpoints) {
assertEquals(expectedNames.size(), endpoints.size());
- expectedNames.forEach(expected -> assertTrue("Endpoint not matched " + expected + " was: " + endpoints, endpoints.stream().anyMatch(e -> Objects.equals(e.dnsName().value(), expected))));
+ expectedNames.forEach(expected -> assertTrue(endpoints.stream().anyMatch(e -> Objects.equals(e.dnsName().value(), expected)), "Endpoint not matched " + expected + " was: " + endpoints));
}
private boolean endpointsMatch(ContainerEndpoint configuredEndpoint, List<ApplicationClusterEndpoint> clusterEndpoints) {
@@ -471,6 +480,31 @@ public class ContainerClusterTest {
expectedBundleNames.forEach(b -> assertTrue(installedBundles.stream().filter(p -> p.endsWith(b)).count() > 0));
}
+ private static ApplicationContainerCluster newClusterWithSearch(MockRoot root) {
+ return newClusterWithSearch(root, false, null);
+ }
+
+ private static ApplicationContainerCluster newClusterWithSearch(MockRoot root, boolean isCombinedCluster, Integer memoryPercentage) {
+ ApplicationContainerCluster cluster = new ApplicationContainerCluster(root, "container0", "container1", root.getDeployState());
+ if (isCombinedCluster)
+ cluster.setHostClusterId("test-content-cluster");
+ cluster.setMemoryPercentage(memoryPercentage);
+ cluster.setSearch(new ContainerSearch(cluster, new SearchChains(cluster, "search-chain"), new ContainerSearch.Options()));
+ return cluster;
+ }
+
+ private static ClusterControllerContainerCluster createClusterControllerCluster(MockRoot root) {
+ return new ClusterControllerContainerCluster(root, "container0", "container1", root.getDeployState());
+ }
+
+ private static MockRoot createRoot(boolean isHosted) {
+ DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(isHosted)).build();
+ return createRoot(state);
+ }
+
+ private static MockRoot createRoot(DeployState deployState) {
+ return new MockRoot("foo", deployState);
+ }
private static void addContainer(MockRoot root, ApplicationContainerCluster cluster, String name, String hostName) {
addContainerWithHostResource(root, cluster, name, new HostResource(new Host(null, hostName)));
@@ -510,4 +544,13 @@ public class ContainerClusterTest {
return new ClusterInfoConfig(builder);
}
+ private static String expectedJvmArgs(boolean isHosted, String extra) {
+ if (!isHosted) return extra;
+ return "-Djdk.tls.server.enableStatusRequestExtension=true " +
+ "-Djdk.tls.stapling.responseTimeout=2000 " +
+ "-Djdk.tls.stapling.cacheSize=256 " +
+ "-Djdk.tls.stapling.cacheLifetime=3600" +
+ (extra.isEmpty() ? "" : " " + extra);
+ }
+
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java
index cb1b84d272a..51c0dd5f898 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java
@@ -6,15 +6,12 @@ import com.yahoo.vespa.model.container.docproc.DocprocChain;
import com.yahoo.vespa.model.container.processing.ProcessingChain;
import com.yahoo.vespa.model.container.search.searchchain.SearchChain;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
@@ -23,7 +20,7 @@ import static org.junit.Assert.fail;
public class ContainerIncludeTest {
@Test
- public void include() {
+ void include() {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude/");
VespaModel model = creator.create();
@@ -85,43 +82,51 @@ public class ContainerIncludeTest {
assertEquals("com.yahoo.Processor2", processingChainMap.get("processingchain2").getInnerComponents().iterator().next().getComponentId().stringValue());
}
- @Test(expected = IllegalArgumentException.class)
- public void includeNonExistent() {
- VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude2/");
- creator.create();
+ @Test
+ void includeNonExistent() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude2/");
+ creator.create();
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void includeAbsolutePath() {
- VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude3/");
- creator.create();
+ @Test
+ void includeAbsolutePath() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude3/");
+ creator.create();
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void includeNonDirectory() {
- VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude4/");
- creator.create();
+ @Test
+ void includeNonDirectory() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude4/");
+ creator.create();
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void include_file_with_wrong_root_element_name() {
- VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude5/");
- creator.create();
+ @Test
+ void include_file_with_wrong_root_element_name() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude5/");
+ creator.create();
+ });
}
@Test
- public void include_empty_directory() {
+ void include_empty_directory() {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude6/");
creator.create();
}
@Test
- public void included_file_with_xml_schema_violation() {
+ void included_file_with_xml_schema_violation() {
try {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/include_xml_error/");
creator.create(true);
fail("Expected exception due to xml schema violation ('zearcer')");
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid XML according to XML schema"));
assertTrue(e.getMessage().contains("zearcer"));
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java
index ea4ee073915..2cf38e4bc7e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author bjorncs
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertFalse;
public class BindingPatternTest {
@Test
- public void parses_valid_bindings_correctly() {
+ void parses_valid_bindings_correctly() {
assertBindingParses("http://host:1234/path");
assertBindingParses("http://host/path");
assertBindingParses("http://host/");
@@ -25,7 +25,7 @@ public class BindingPatternTest {
}
@Test
- public void getters_returns_correct_components() {
+ void getters_returns_correct_components() {
{
BindingPattern pattern = SystemBindingPattern.fromPattern("http://host:1234/path/*");
assertEquals("http", pattern.scheme());
@@ -46,8 +46,7 @@ public class BindingPatternTest {
BindingPattern pattern = SystemBindingPattern.fromPattern(binding);
String stringRepresentation = pattern.patternString();
assertEquals(
- "Expected string representation of parsed binding to match original binding string",
- binding, stringRepresentation);
+ binding, stringRepresentation, "Expected string representation of parsed binding to match original binding string");
}
} \ No newline at end of file
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java
index ada8e2c210b..4bf4cc71890 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java
@@ -19,7 +19,7 @@ import com.yahoo.vespa.model.container.ContainerModel;
import com.yahoo.vespa.model.container.ContainerModelEvaluation;
import com.yahoo.vespa.model.container.configserver.option.CloudConfigOptions;
import com.yahoo.vespa.model.container.xml.ConfigServerContainerModelBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -28,9 +28,7 @@ import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -38,7 +36,7 @@ import static org.junit.Assert.assertTrue;
public class ConfigserverClusterTest {
@Test
- public void zookeeperConfig_default() {
+ void zookeeperConfig_default() {
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class);
assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "localhost");
assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, 0);
@@ -46,7 +44,7 @@ public class ConfigserverClusterTest {
}
@Test
- public void zookeeperConfig_only_config_servers_set_hosted() {
+ void zookeeperConfig_only_config_servers_set_hosted() {
TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.emptyList());
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions);
assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3");
@@ -56,7 +54,7 @@ public class ConfigserverClusterTest {
}
@Test
- public void zookeeperConfig_with_config_servers_and_zk_ids_hosted() {
+ void zookeeperConfig_with_config_servers_and_zk_ids_hosted() {
TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3));
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions);
assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3");
@@ -65,7 +63,7 @@ public class ConfigserverClusterTest {
}
@Test
- public void zookeeperConfig_self_hosted() {
+ void zookeeperConfig_self_hosted() {
final boolean hostedVespa = false;
TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3), hostedVespa);
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions);
@@ -75,26 +73,30 @@ public class ConfigserverClusterTest {
assertEquals("gz", config.snapshotMethod());
}
- @Test(expected = IllegalArgumentException.class)
- public void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() {
- TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.singletonList(1));
- getConfig(ZookeeperServerConfig.class, testOptions);
+ @Test
+ void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.singletonList(1));
+ getConfig(ZookeeperServerConfig.class, testOptions);
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void zookeeperConfig_negative_zk_id() {
- TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(1, 2, -1));
- getConfig(ZookeeperServerConfig.class, testOptions);
+ @Test
+ void zookeeperConfig_negative_zk_id() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(1, 2, -1));
+ getConfig(ZookeeperServerConfig.class, testOptions);
+ });
}
@Test
- public void testHealthMonitorConfig() {
+ void testHealthMonitorConfig() {
HealthMonitorConfig config = getConfig(HealthMonitorConfig.class);
assertEquals(60, (int) config.snapshot_interval());
}
@Test
- public void testConfigserverConfig() {
+ void testConfigserverConfig() {
ConfigserverConfig config = getConfig(ConfigserverConfig.class);
assertEquals(1, config.configModelPluginDir().size());
assertEquals(Defaults.getDefaults().underVespaHome("lib/jars/config-models"), config.configModelPluginDir().get(0));
@@ -110,7 +112,7 @@ public class ConfigserverClusterTest {
}
@Test
- public void testCuratorConfig() {
+ void testCuratorConfig() {
CuratorConfig config = getConfig(CuratorConfig.class);
assertEquals(1, config.server().size());
assertEquals("localhost", config.server().get(0).hostname());
@@ -119,7 +121,7 @@ public class ConfigserverClusterTest {
}
@Test
- public void model_evaluation_bundles_are_not_installed_via_config() {
+ void model_evaluation_bundles_are_not_installed_via_config() {
// These bundles must be pre-installed because they are used by config-model.
PlatformBundlesConfig config = getConfig(PlatformBundlesConfig.class);
assertFalse(config.bundlePaths().contains(ContainerModelEvaluation.MODEL_INTEGRATION_BUNDLE_FILE.toString()));
@@ -177,7 +179,7 @@ public class ConfigserverClusterTest {
// Simulate the behaviour of StandaloneContainer
List<? extends Container> containers = containerModel.getCluster().getContainers();
- assertEquals("Standalone container", 1, containers.size());
+ assertEquals(1, containers.size(), "Standalone container");
HostResource hostResource = root.hostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC);
containers.get(0).setHostResource(hostResource);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/docproc/StandaloneDocprocContainerTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/docproc/StandaloneDocprocContainerTest.java
deleted file mode 100644
index 5bb93255a8f..00000000000
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/docproc/StandaloneDocprocContainerTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.vespa.model.container.docproc;
-
-import com.yahoo.component.ComponentId;
-import com.yahoo.config.model.deploy.DeployState;
-import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
-import com.yahoo.vespa.model.container.ContainerCluster;
-import com.yahoo.vespa.model.container.ContainerModel;
-import com.yahoo.vespa.model.container.component.Component;
-import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
-import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking;
-import org.junit.Test;
-import org.w3c.dom.Element;
-
-import java.util.Map;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Einar M R Rosenvinge
- */
-public class StandaloneDocprocContainerTest extends DomBuilderTest {
-
- public ContainerCluster setupCluster(boolean standalone) {
- ContainerModelBuilder builder = new ContainerModelBuilder(standalone, Networking.disable);
- ContainerModel model = builder.build(DeployState.createTestState(), null, null, root, servicesXml());
-
- if (!standalone)
- model.getCluster().getDocproc().getChains().addServersAndClientsForChains();
-
- root.freezeModelTopology();
- return model.getCluster();
- }
-
- private Element servicesXml() {
- return parse("" +
- "<container version=\"1.0\">\n" +
- " <document-processing>\n" +
- " <chain id=\"foo\">\n" +
- " <documentprocessor id=\"MyDocproc\"/>\n" +
- " </chain>\n" +
- " </document-processing>\n" +
- " <nodes>\n" +
- " <node hostalias=\"node01\"/>\n" +
- " </nodes>\n" +
- "</container>\n");
- }
-
- @Test
- public void requireMbusProvidersWhenNonStandalone() {
- ContainerCluster containerCluster = setupCluster(false);
- Map<ComponentId, Component<?, ?>> components = containerCluster.getComponentsMap();
-
- boolean foundAtLeastOneClient = false;
- boolean foundAtLeastOneServer = false;
-
- for (ComponentId componentId : components.keySet()) {
- if (componentId.stringValue().contains("MbusClient")) foundAtLeastOneClient = true;
- if (componentId.stringValue().contains("MbusServer")) foundAtLeastOneServer = true;
- }
- assertTrue(foundAtLeastOneClient);
- assertTrue(foundAtLeastOneServer);
-
- }
-
- @Test
- public void requireNoMbusProvidersWhenStandalone() {
- ContainerCluster containerCluster = setupCluster(true);
- Map<ComponentId, Component<?, ?>> components = containerCluster.getComponentsMap();
-
- boolean foundAtLeastOneClient = false;
- boolean foundAtLeastOneServer = false;
-
- for (ComponentId componentId : components.keySet()) {
- if (componentId.stringValue().contains("MbusClient")) foundAtLeastOneClient = true;
- if (componentId.stringValue().contains("MbusServer")) foundAtLeastOneServer = true;
- }
- assertFalse(foundAtLeastOneClient);
- assertFalse(foundAtLeastOneServer);
- }
-}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java
index 1691868ee65..78d28897bb8 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java
@@ -4,21 +4,20 @@ package com.yahoo.vespa.model.container.http;
import com.yahoo.config.model.api.ApplicationClusterEndpoint;
import com.yahoo.config.model.api.ContainerEndpoint;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig;
-import org.junit.Test;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class BlockFeedGlobalEndpointsFilterTest {
@Test
- public void setup_blocking_rule_when_endpoints_is_non_empty() {
+ void setup_blocking_rule_when_endpoints_is_non_empty() {
var endpoints = Set.of(new ContainerEndpoint("default", ApplicationClusterEndpoint.Scope.global, List.of("foo", "bar")));
var filter = new BlockFeedGlobalEndpointsFilter(endpoints, true);
var config = getConfig(filter);
@@ -29,7 +28,7 @@ public class BlockFeedGlobalEndpointsFilterTest {
}
@Test
- public void does_not_setup_blocking_rule_when_endpoints_empty() {
+ void does_not_setup_blocking_rule_when_endpoints_empty() {
var filter = new BlockFeedGlobalEndpointsFilter(Collections.emptySet(), true);
var config = getConfig(filter);
assertEquals(0, config.rule().size());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java
index 1624a4754c7..3e80b319e88 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java
@@ -8,7 +8,7 @@ import com.yahoo.jdisc.http.ServerConfig;
import com.yahoo.vespa.model.container.component.BindingPattern;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Set;
@@ -27,7 +27,7 @@ public class DefaultFilterTest extends DomBuilderTest {
}
@Test
- public void default_request_and_response_filters_in_services_xml_are_listen_in_server_config() {
+ void default_request_and_response_filters_in_services_xml_are_listen_in_server_config() {
BindingPattern binding = UserBindingPattern.fromHttpPath("/my-chain-binding");
Element xml = parse(
"<container version='1.0'>",
@@ -40,7 +40,7 @@ public class DefaultFilterTest extends DomBuilderTest {
" <binding>" + binding.patternString() + "</binding>",
" </response-chain>",
" <request-chain id='my-default-request-chain'/>" +
- " <response-chain id='my-default-response-chain'/>",
+ " <response-chain id='my-default-response-chain'/>",
" </filtering>",
" <server id='server1' port='8000' default-request-chain=\"my-default-request-chain\" default-response-chain=\"my-default-response-chain\"/>",
" <server id='server2' port='9000' />",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java
index 7634a5928e5..787a8255628 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java
@@ -11,12 +11,12 @@ import com.yahoo.vespa.model.container.component.chain.Chain;
import com.yahoo.vespa.model.container.http.xml.HttpBuilder;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import static com.yahoo.collections.CollectionUtil.first;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author gjoranv
@@ -39,7 +39,7 @@ public class FilterBindingsTest extends DomBuilderTest {
}
@Test
- public void request_chain_binding_is_added_to_http() throws Exception {
+ void request_chain_binding_is_added_to_http() throws Exception {
Element xml = parse(
"<http>",
" <filtering>",
@@ -55,11 +55,11 @@ public class FilterBindingsTest extends DomBuilderTest {
assertEquals(MY_CHAIN_BINDING, binding.binding());
Chain<Filter> myChain = http.getFilterChains().allChains().getComponent("my-request-chain");
- assertNotNull("Missing chain", myChain);
+ assertNotNull(myChain, "Missing chain");
}
@Test
- public void response_chain_binding_is_added_to_http() throws Exception {
+ void response_chain_binding_is_added_to_http() throws Exception {
Element xml = parse(
"<http>",
" <filtering>",
@@ -75,11 +75,11 @@ public class FilterBindingsTest extends DomBuilderTest {
assertEquals(MY_CHAIN_BINDING, binding.binding());
Chain<Filter> myChain = http.getFilterChains().allChains().getComponent("my-response-chain");
- assertNotNull("Missing chain", myChain);
+ assertNotNull(myChain, "Missing chain");
}
@Test
- public void bindings_are_added_to_config_for_all_http_servers_with_jetty() {
+ void bindings_are_added_to_config_for_all_http_servers_with_jetty() {
final Element xml = parse(
"<container version='1.0'>",
" <http>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java
index 6f223afd536..990896acb01 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java
@@ -5,13 +5,13 @@ import com.yahoo.component.ComponentSpecification;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.vespa.model.container.component.chain.Chain;
import com.yahoo.vespa.model.container.http.xml.HttpBuilder;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import static com.yahoo.collections.CollectionUtil.first;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author gjoranv
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull;
public class FilterChainsTest extends DomBuilderTest {
private Http http;
- @Before
+ @BeforeEach
public void setupFilterChains() {
http = new HttpBuilder().build(root.getDeployState(), root, servicesXml());
root.freezeModelTopology();
@@ -40,18 +40,18 @@ public class FilterChainsTest extends DomBuilderTest {
}
@Test
- public void chains_are_built() {
+ void chains_are_built() {
assertNotNull(getChain("myChain"));
}
@Test
- public void filters_outside_chains_are_built() {
- Filter outerFilter = (Filter)http.getFilterChains().componentsRegistry().getComponent("outer");
+ void filters_outside_chains_are_built() {
+ Filter outerFilter = (Filter) http.getFilterChains().componentsRegistry().getComponent("outer");
assertNotNull(outerFilter);
}
@Test
- public void filters_in_chains_are_built() {
+ void filters_in_chains_are_built() {
Filter filter = first(getChain("myChain").getInnerComponents());
assertNotNull(filter);
assertEquals("inner", filter.getComponentId().getName());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java
index e17c5eed242..76a3dcb2788 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java
@@ -4,15 +4,13 @@ package com.yahoo.vespa.model.container.http;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.container.core.http.HttpFilterConfig;
import com.yahoo.vespa.model.container.http.xml.HttpBuilder;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import static com.yahoo.collections.CollectionUtil.first;
import static com.yahoo.vespa.model.container.http.FilterConfigProvider.configProviderId;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -22,7 +20,7 @@ public class FilterConfigTest extends DomBuilderTest {
private Http http;
- @Before
+ @BeforeEach
public void setupFilterChains() {
http = new HttpBuilder().build(root.getDeployState(), root, servicesXml());
root.freezeModelTopology();
@@ -54,14 +52,14 @@ public class FilterConfigTest extends DomBuilderTest {
}
@Test
- public void filter_without_config_does_not_have_FilterConfigProvider() {
+ void filter_without_config_does_not_have_FilterConfigProvider() {
Filter noConfigFilter = getOuterFilter("no-config");
assertNull(getProvider(noConfigFilter));
}
@Test
- public void filterName_is_id_from_component_spec() {
+ void filterName_is_id_from_component_spec() {
Filter emptyConfigFilter = getOuterFilter("empty-config");
HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter);
@@ -69,7 +67,7 @@ public class FilterConfigTest extends DomBuilderTest {
}
@Test
- public void filterClass_is_class_from_component_spec() {
+ void filterClass_is_class_from_component_spec() {
Filter emptyConfigFilter = getOuterFilter("empty-config");
HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter);
@@ -77,7 +75,7 @@ public class FilterConfigTest extends DomBuilderTest {
}
@Test
- public void filter_with_empty_config_has_FilterConfigProvider_with_empty_map() {
+ void filter_with_empty_config_has_FilterConfigProvider_with_empty_map() {
Filter emptyConfigFilter = getOuterFilter("empty-config");
HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter);
@@ -85,7 +83,7 @@ public class FilterConfigTest extends DomBuilderTest {
}
@Test
- public void config_params_are_set_correctly_in_FilterConfigProvider() {
+ void config_params_are_set_correctly_in_FilterConfigProvider() {
Filter configWithParamsFilter = getOuterFilter("config-with-params");
HttpFilterConfig config = getHttpFilterConfig(configWithParamsFilter);
@@ -95,7 +93,7 @@ public class FilterConfigTest extends DomBuilderTest {
}
@Test
- public void inner_filter_can_have_filter_config() {
+ void inner_filter_can_have_filter_config() {
Filter innerFilter =
first(http.getFilterChains().allChains().getComponent("myChain").getInnerComponents());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java
index ad81c9a5a4d..effbb4d6fe1 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java
@@ -5,10 +5,10 @@ import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.jdisc.http.ServerConfig;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class StrictFilteringTest extends DomBuilderTest {
@Test
- public void strict_filtering_enabled_if_specified_in_services() {
+ void strict_filtering_enabled_if_specified_in_services() {
Element xml = parse(
"<container version='1.0'>",
" <http>",
@@ -33,7 +33,7 @@ public class StrictFilteringTest extends DomBuilderTest {
}
@Test
- public void strict_filtering_enabled_by_default_if_filter_present() {
+ void strict_filtering_enabled_by_default_if_filter_present() {
Element xml = parse(
"<container version='1.0'>",
" <http>",
@@ -49,7 +49,7 @@ public class StrictFilteringTest extends DomBuilderTest {
}
@Test
- public void strict_filtering_disabled_if_no_filter() {
+ void strict_filtering_disabled_if_no_filter() {
Element xml = parse(
"<container version='1.0'>",
" <http>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java
index 3deeef7f2a2..063f8f3109e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java
@@ -5,10 +5,10 @@ import ai.vespa.modelintegration.evaluator.OnnxEvaluator;
import ai.vespa.models.evaluation.FunctionEvaluator;
import ai.vespa.models.evaluation.ModelsEvaluator;
import com.yahoo.tensor.Tensor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Tests the ModelsEvaluatorTester.
@@ -18,7 +18,7 @@ import static org.junit.Assume.assumeTrue;
public class ModelsEvaluatorTest {
@Test
- public void testModelsEvaluator() {
+ void testModelsEvaluator() {
// Assumption fails but test passes on Intel macs
// Assumption fails and test fails on ARM64
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java
index 4ac6129c6ee..bd6400d81e0 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java
@@ -7,13 +7,13 @@ import com.yahoo.vespa.model.container.component.chain.ChainedComponent;
import com.yahoo.vespa.model.container.component.chain.Chains;
import com.yahoo.vespa.model.container.processing.ProcessingChain;
import com.yahoo.vespa.model.container.processing.Processor;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -23,7 +23,7 @@ public class ProcessingChainsTest extends DomBuilderTest {
private Chains<ProcessingChain> processingChains;
- @Before
+ @BeforeEach
public void setupProcessingChains() {
DomProcessingBuilder processingBuilder = new DomProcessingBuilder(null);
processingBuilder.build(root.getDeployState(), root, servicesXml());
@@ -43,7 +43,7 @@ public class ProcessingChainsTest extends DomBuilderTest {
}
@Test
- public void testProcessingChainConfiguration() {
+ void testProcessingChainConfiguration() {
ProcessingChain defaultChain = processingChains.allChains().getComponent("default");
assertEquals("default", defaultChain.getId().stringValue());
assertEquals(1, defaultChain.getInnerComponents().size());
@@ -57,7 +57,7 @@ public class ProcessingChainsTest extends DomBuilderTest {
}
@Test
- public void require_that_processors_have_correct_class() {
+ void require_that_processors_have_correct_class() {
ChainedComponent<?> processor1 = processingChains.getComponentGroup().getComponents().iterator().next();
assertEquals("com.yahoo.test.Processor1", processor1.model.bundleInstantiationSpec.classId.stringValue());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java
index d48c397b1f0..1441975110e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java
@@ -10,9 +10,9 @@ import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Tony Vaagenes
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull;
public class ImplicitIndexingClusterTest {
@Test
- public void existing_jdisc_is_used_as_indexing_cluster_when_multitenant() {
+ void existing_jdisc_is_used_as_indexing_cluster_when_multitenant() {
final String servicesXml = "<services version=\"1.0\">\n" + //
" <container version=\"1.0\" id=\"jdisc\">\n" + //
" <search />\n" + //
@@ -42,8 +42,8 @@ public class ImplicitIndexingClusterTest {
VespaModel vespaModel = buildMultiTenantVespaModel(servicesXml);
ContainerCluster jdisc = vespaModel.getContainerClusters().get("jdisc");
- assertNotNull("Docproc not added to jdisc", jdisc.getDocproc());
- assertNotNull("Indexing chain not added to jdisc", jdisc.getDocprocChains().allChains().getComponent("indexing"));
+ assertNotNull(jdisc.getDocproc(), "Docproc not added to jdisc");
+ assertNotNull(jdisc.getDocprocChains().allChains().getComponent("indexing"), "Indexing chain not added to jdisc");
}
private static VespaModel buildMultiTenantVespaModel(String servicesXml) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java
index 8d83ec4cc5f..d9e2ae59ef6 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java
@@ -7,10 +7,9 @@ import com.yahoo.prelude.semantics.RuleBase;
import com.yahoo.prelude.semantics.RuleImporter;
import com.yahoo.prelude.semantics.SemanticRulesConfig;
import com.yahoo.prelude.semantics.parser.ParseException;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.io.IOException;
@@ -25,7 +24,7 @@ public class SemanticRulesTest {
private final static String root = "src/test/java/com/yahoo/vespa/model/container/search/semanticrules";
@Test
- public void semanticRulesTest() throws ParseException, IOException {
+ void semanticRulesTest() throws ParseException, IOException {
SemanticRuleBuilder ruleBuilder = new SemanticRuleBuilder();
SemanticRules rules = ruleBuilder.build(FilesApplicationPackage.fromFile(new File(root)));
SemanticRulesConfig.Builder configBuilder = new SemanticRulesConfig.Builder();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java
index ac272301445..22ad6b79a74 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.model.container.search.searchchain;
import com.yahoo.test.SimpletypesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -55,15 +55,15 @@ public class Federation2Test extends SchemaChainsTestBase {
@Test
- public void testProviderConfigs() {
+ void testProviderConfigs() {
//SimpletypesConfig testConfig = root.getConfig(SimpletypesConfig.class, "test/searchchains/chain/chain1/component/com.yahoo.example.TestSearcher");
//assertEquals("testSearcher",testConfig.stringval());
SimpletypesConfig configA = root.getConfig(SimpletypesConfig.class, "searchchains/chain/providerA/source/commonSource/component/com.yahoo.example.AddHitSearcher");
- assertEquals("providerA",configA.stringval());
+ assertEquals("providerA", configA.stringval());
SimpletypesConfig configB = root.getConfig(SimpletypesConfig.class, "searchchains/chain/providerB/source/commonSource/component/com.yahoo.example.AddHitSearcher");
- assertEquals("providerB",configB.stringval());
+ assertEquals("providerB", configB.stringval());
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java
index 3f95fb99087..98f5bdbcd52 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java
@@ -12,22 +12,18 @@ import com.yahoo.search.searchchain.model.federation.FederationSearcherModel;
import com.yahoo.search.searchchain.model.federation.FederationSearcherModel.TargetSpec;
import com.yahoo.vespa.model.ConfigProducer;
import com.yahoo.vespa.model.container.search.searchchain.Source.GroupOption;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
-import static java.util.Collections.emptyList;
-import static java.util.Collections.emptySet;
-import static java.util.Collections.singletonList;
-import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -36,9 +32,9 @@ import static org.junit.Assert.assertTrue;
public class FederationSearcherTest {
private static class FederationFixture {
- FederationSearcher federationSearchWithDefaultSources = newFederationSearcher(true, emptyList());
- private ComponentRegistry<SearchChain> searchChainRegistry = new ComponentRegistry<>();
- private SourceGroupRegistry sourceGroupRegistry = new SourceGroupRegistry();
+ FederationSearcher federationSearchWithDefaultSources = newFederationSearcher(true, List.of());
+ private final ComponentRegistry<SearchChain> searchChainRegistry = new ComponentRegistry<>();
+ private final SourceGroupRegistry sourceGroupRegistry = new SourceGroupRegistry();
void initializeFederationSearcher(FederationSearcher searcher) {
searcher.initialize(searchChainRegistry, sourceGroupRegistry);
@@ -71,7 +67,7 @@ public class FederationSearcherTest {
}
@Test
- public void default_providers_are_inherited_when_inheritDefaultSources_is_true() throws Exception {
+ void default_providers_are_inherited_when_inheritDefaultSources_is_true() throws Exception {
FederationFixture f = new FederationFixture();
final String providerId = "providerId";
@@ -83,30 +79,30 @@ public class FederationSearcherTest {
FederationConfig.Target target = federationConfig.target(0);
assertSame(providerId, target.id()); // by identity
- assertTrue("Not used by default", target.searchChain(0).useByDefault());
+ assertTrue(target.searchChain(0).useByDefault(), "Not used by default");
}
@Test
- public void source_groups_are_inherited_when_inheritDefaultSources_is_true() throws Exception {
+ void source_groups_are_inherited_when_inheritDefaultSources_is_true() throws Exception {
FederationFixture f = new ProvidersWithSourceFixture();
FederationConfig federationConfig = getConfig(f.federationSearchWithDefaultSources);
- Assert.assertEquals(1, federationConfig.target().size());
+ assertEquals(1, federationConfig.target().size());
FederationConfig.Target target = federationConfig.target(0);
assertEquals(target.id(), "source");
- assertTrue("Not used by default", target.useByDefault());
+ assertTrue(target.useByDefault(), "Not used by default");
assertEquals(2, target.searchChain().size());
assertTrue(target.searchChain().stream()
- .map(FederationConfig.Target.SearchChain::providerId)
- .collect(toList()).containsAll(List.of("provider1", "provider2")));
+ .map(FederationConfig.Target.SearchChain::providerId)
+ .toList().containsAll(List.of("provider1", "provider2")));
}
@Test
- public void source_groups_are_not_inherited_when_inheritDefaultSources_is_false() throws Exception {
+ void source_groups_are_not_inherited_when_inheritDefaultSources_is_false() throws Exception {
FederationFixture f = new ProvidersWithSourceFixture();
- FederationSearcher federationSearcherWithoutDefaultSources = newFederationSearcher(false, emptyList());
+ FederationSearcher federationSearcherWithoutDefaultSources = newFederationSearcher(false, List.of());
f.initializeFederationSearcher(federationSearcherWithoutDefaultSources);
FederationConfig federationConfig = getConfig(federationSearcherWithoutDefaultSources);
@@ -114,7 +110,7 @@ public class FederationSearcherTest {
}
@Test
- public void leaders_must_be_the_first_search_chain_in_a_target() throws Exception {
+ void leaders_must_be_the_first_search_chain_in_a_target() throws Exception {
FederationFixture f = new ProvidersWithSourceFixture();
FederationConfig federationConfig = getConfig(f.federationSearchWithDefaultSources);
@@ -125,12 +121,12 @@ public class FederationSearcherTest {
}
@Test
- public void manually_specified_targets_overrides_inherited_targets() throws Exception {
+ void manually_specified_targets_overrides_inherited_targets() throws Exception {
FederationFixture f = new FederationFixture();
f.registerProviderWithSources(createProvider(ComponentId.fromString("provider1")));
FederationSearcher federation = newFederationSearcher(true,
- singletonList(new TargetSpec(ComponentSpecification.fromString("provider1"),
+ List.of(new TargetSpec(ComponentSpecification.fromString("provider1"),
new FederationOptions().setTimeoutInMilliseconds(12345))));
f.initializeFederationSearcher(federation);
@@ -150,7 +146,7 @@ public class FederationSearcherTest {
}
private static ChainSpecification searchChainSpecification(ComponentId id) {
- return new ChainSpecification(id, new ChainSpecification.Inheritance(null, null), emptyList(), emptySet());
+ return new ChainSpecification(id, new ChainSpecification.Inheritance(null, null), List.of(), Set.of());
}
private static Provider createProvider(ComponentId id) {
@@ -164,7 +160,7 @@ public class FederationSearcherTest {
private static FederationConfig getConfig(ConfigProducer configProducer) throws Exception {
Optional<Class<?>> builderClassOpt = Arrays.stream(FederationConfig.class.getDeclaredClasses())
.filter(c -> c.getSimpleName().equals("Builder")).findFirst();
- if (builderClassOpt.isPresent() == false) {
+ if ( builderClassOpt.isEmpty()) {
throw new RuntimeException("No Builder class in ConfigInstance.");
}
Class<?> builderClass = builderClassOpt.get();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java
index 3945a74cf15..ff884d6072f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java
@@ -2,15 +2,13 @@
package com.yahoo.vespa.model.container.search.searchchain;
import com.yahoo.search.federation.FederationConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.List;
import static org.assertj.core.api.Fail.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test generated config for federation.
@@ -52,7 +50,7 @@ public class FederationTest extends SchemaChainsTestBase {
@Test
- public void validateNativeDefaultTargets() {
+ void validateNativeDefaultTargets() {
FederationConfig.Builder fb = new FederationConfig.Builder();
root.getConfig(fb, "searchchains/chain/native/component/federation");
FederationConfig config = new FederationConfig(fb);
@@ -61,9 +59,9 @@ public class FederationTest extends SchemaChainsTestBase {
String failMessage = "Failed for target " + target.id();
if (target.id().startsWith("source")) {
- assertTrue(failMessage, target.useByDefault());
+ assertTrue(target.useByDefault(), failMessage);
} else {
- assertFalse(failMessage, target.useByDefault());
+ assertFalse(target.useByDefault(), failMessage);
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java
index 20345615753..5588787119c 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java
@@ -5,12 +5,17 @@ import com.yahoo.component.ComponentId;
import com.yahoo.container.core.ChainsConfig;
import com.yahoo.prelude.cluster.ClusterSearcher;
import com.yahoo.search.config.ClusterConfig;
+import com.yahoo.search.searchchain.PhaseNames;
import com.yahoo.vespa.defaults.Defaults;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static org.junit.Assert.assertEquals;
+import java.util.Collection;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -21,10 +26,15 @@ import static org.junit.Assert.assertEquals;
*/
public class SchemaChainsTest extends SchemaChainsTestBase {
+ private ChainsConfig chainsConfig;
private ClusterConfig clusterConfig;
- @Before
+ @BeforeEach
public void subscribe() {
+ ChainsConfig.Builder chainsBuilder = new ChainsConfig.Builder();
+ chainsBuilder = (ChainsConfig.Builder)root.getConfig(chainsBuilder, "searchchains");
+ chainsConfig = new ChainsConfig(chainsBuilder);
+
ClusterConfig.Builder clusterBuilder = new ClusterConfig.Builder();
clusterBuilder = (ClusterConfig.Builder)root.getConfig(clusterBuilder, "searchchains/chain/cluster2/component/" + ClusterSearcher.class.getName());
clusterConfig = new ClusterConfig(clusterBuilder);
@@ -70,15 +80,90 @@ public class SchemaChainsTest extends SchemaChainsTestBase {
}
@Test
- public void require_that_source_chain_spec_id_is_namespaced_in_provider_id() {
+ void require_that_source_chain_spec_id_is_namespaced_in_provider_id() {
Source source = (Source) getSearchChains().allChains().getComponent("source:1@provider:1");
assertEquals(ComponentId.fromString("provider:1"), source.getChainSpecification().componentId.getNamespace());
}
@Test
- public void validateLocalProviderConfig() {
+ void validateLocalProviderConfig() {
assertEquals(2, clusterConfig.clusterId());
assertEquals("cluster2", clusterConfig.clusterName());
}
+ private ChainsConfig.Chains findChain(String name) {
+ for (ChainsConfig.Chains chain : chainsConfig.chains()) {
+ if (name.equals(chain.id())) {
+ return chain;
+ }
+ }
+ return null;
+ }
+
+ private static boolean contains(Collection<ChainsConfig.Chains.Phases> phases, String name) {
+ for (var phase : phases) {
+ if (name.equals(phase.id())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void validateVespaPhasesChain(ChainsConfig.Chains chain) {
+ assertNotNull(chain);
+ assertEquals("vespaPhases", chain.id());
+ assertEquals(5, chain.phases().size());
+ assertTrue(contains(chain.phases(), PhaseNames.BACKEND));
+ assertTrue(contains(chain.phases(), PhaseNames.BLENDED_RESULT));
+ assertTrue(contains(chain.phases(), PhaseNames.RAW_QUERY));
+ assertTrue(contains(chain.phases(), PhaseNames.TRANSFORMED_QUERY));
+ assertTrue(contains(chain.phases(), PhaseNames.UNBLENDED_RESULT));
+ assertTrue(chain.inherits().isEmpty());
+ assertTrue(chain.components().isEmpty());
+ assertTrue(chain.excludes().isEmpty());
+ assertEquals(ChainsConfig.Chains.Type.SEARCH, chain.type());
+ }
+
+ private static void validateNativeChain(ChainsConfig.Chains chain) {
+ assertNotNull(chain);
+ assertEquals("native", chain.id());
+ assertTrue(chain.phases().isEmpty());
+ assertEquals(1, chain.inherits().size());
+ assertEquals("vespaPhases", chain.inherits(0));
+ assertEquals(2, chain.components().size());
+ assertEquals("federation@native", chain.components(0));
+ assertEquals("com.yahoo.prelude.statistics.StatisticsSearcher@native", chain.components(1));
+ assertTrue(chain.excludes().isEmpty());
+ assertEquals(ChainsConfig.Chains.Type.SEARCH, chain.type());
+ }
+
+ private static void validateVespaChain(ChainsConfig.Chains chain) {
+ assertNotNull(chain);
+ assertEquals("vespa", chain.id());
+ assertTrue(chain.phases().isEmpty());
+ assertEquals(1, chain.inherits().size());
+ assertEquals("native", chain.inherits(0));
+ assertEquals(10, chain.components().size());
+ assertEquals("com.yahoo.prelude.querytransform.PhrasingSearcher@vespa", chain.components(0));
+ assertEquals("com.yahoo.prelude.searcher.FieldCollapsingSearcher@vespa", chain.components(1));
+ assertEquals("com.yahoo.search.yql.MinimalQueryInserter@vespa", chain.components(2));
+ assertEquals("com.yahoo.search.yql.FieldFilter@vespa", chain.components(3));
+ assertEquals("com.yahoo.prelude.searcher.JuniperSearcher@vespa", chain.components(4));
+ assertEquals("com.yahoo.prelude.searcher.BlendingSearcher@vespa", chain.components(5));
+ assertEquals("com.yahoo.prelude.searcher.PosSearcher@vespa", chain.components(6));
+ assertEquals("com.yahoo.prelude.semantics.SemanticSearcher@vespa", chain.components(7));
+ assertEquals("com.yahoo.search.grouping.GroupingQueryParser@vespa", chain.components(8));
+ assertEquals("com.yahoo.search.querytransform.WeakAndReplacementSearcher@vespa", chain.components(9));
+ assertTrue(chain.excludes().isEmpty());
+ assertEquals(ChainsConfig.Chains.Type.SEARCH, chain.type());
+ }
+
+ @Test
+ public void require_all_default_chains_are_correct() {
+ assertEquals(61, chainsConfig.components().size());
+ assertEquals(10, chainsConfig.chains().size());
+ validateVespaPhasesChain(findChain("vespaPhases"));
+ validateNativeChain(findChain("native"));
+ validateVespaChain(findChain("vespa"));
+ }
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java
index 04bda0bce21..661d10b945d 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java
@@ -5,12 +5,12 @@ import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.vespa.model.builder.xml.dom.chains.search.DomSearchChainsBuilder;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilderTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author gjoranv
@@ -19,13 +19,13 @@ public class SchemaChainsTest2 {
private MockRoot root;
- @Before
+ @BeforeEach
public void prepareTest() {
root = new MockRoot("root");
}
@Test
- public void fail_upon_unresolved_inheritance() {
+ void fail_upon_unresolved_inheritance() {
final Element searchElem = DomBuilderTest.parse(
"<search>",
" <chain id='default' inherits='nonexistent' />",
@@ -37,12 +37,12 @@ public class SchemaChainsTest2 {
fail("Expected exception when inheriting a nonexistent search chain.");
} catch (Exception e) {
assertEquals("Missing chain 'nonexistent'.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void fail_upon_two_user_declared_chains_with_same_name() {
+ void fail_upon_two_user_declared_chains_with_same_name() {
final Element clusterElem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
ContainerModelBuilderTest.nodesXml,
@@ -56,12 +56,12 @@ public class SchemaChainsTest2 {
fail("Expected exception when declaring chains with duplicate id.");
} catch (Exception e) {
assertEquals("Both search chain 'same' and search chain 'same' are configured with the id 'same'. All components must have a unique id.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void fail_upon_user_declared_chain_with_same_id_as_builtin_chain() {
+ void fail_upon_user_declared_chain_with_same_id_as_builtin_chain() {
final Element clusterElem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
ContainerModelBuilderTest.nodesXml,
@@ -74,7 +74,7 @@ public class SchemaChainsTest2 {
fail("Expected exception when taking the id from a builtin chain.");
} catch (Exception e) {
assertEquals("Both search chain 'vespa' and search chain 'vespa' are configured with the id 'vespa'. All components must have a unique id.",
- e.getMessage());
+ e.getMessage());
}
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java
index e654f8deee1..a003a91a624 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.model.container.search.searchchain;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.vespa.model.builder.xml.dom.chains.search.DomSearchChainsBuilder;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
import org.w3c.dom.Element;
/** Creates SearchChains model from xml input.
@@ -11,7 +11,7 @@ import org.w3c.dom.Element;
*/
public abstract class SchemaChainsTestBase extends DomBuilderTest {
- @Before
+ @BeforeEach
public void setupSearchChains() {
SearchChains searchChains = new DomSearchChainsBuilder().build(root.getDeployState(), root, servicesXml());
searchChains.initialize(MockSearchClusters.twoMockClusterSpecsByName(root));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java
index 2cb0e8f0ab1..8c564f5cd6f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java
@@ -5,15 +5,13 @@ import com.yahoo.component.ComponentId;
import com.yahoo.component.chain.model.ChainSpecification;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -22,14 +20,14 @@ public class SourceGroupTest {
private MockRoot root;
private SearchChains searchChains;
- @Before
+ @BeforeEach
public void setUp() {
root = new MockRoot();
searchChains = new SearchChains(root, "searchchains");
}
@Test
- public void report_error_when_no_leader() {
+ void report_error_when_no_leader() {
try {
Provider provider = createProvider("p1");
Source source = createSource("s1", Source.GroupOption.participant);
@@ -65,7 +63,7 @@ public class SourceGroupTest {
}
@Test
- public void require_that_source_and_provider_id_is_not_allowed_to_be_equal() {
+ void require_that_source_and_provider_id_is_not_allowed_to_be_equal() {
Provider provider = createProvider("sameId");
Provider provider2 = createProvider("ignoredId");
@@ -82,7 +80,7 @@ public class SourceGroupTest {
fail("Expected exception");
} catch (Exception e) {
assertEquals("Id 'sameId' is used both for a source and another search chain/provider",
- e.getMessage());
+ e.getMessage());
}
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java
index 4afdecc3cde..d1c1b357dbd 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.io.IOUtils;
import com.yahoo.io.reader.NamedReader;
import com.yahoo.text.StringUtilities;
import com.yahoo.vespa.model.container.search.PageTemplates;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -23,8 +23,8 @@ public class PageTemplatesTestCase {
private final static String root="src/test/java/com/yahoo/vespa/model/container/search/test/pages";
@Test
- public void testExport() throws IOException {
- List<NamedReader> pageFiles=new ArrayList<>(2);
+ void testExport() throws IOException {
+ List<NamedReader> pageFiles = new ArrayList<>(2);
pageFiles.add(new NamedReader(root + "/slottingSerp.xml", IOUtils.createReader(root + "/slottingSerp.xml")));
pageFiles.add(new NamedReader(root + "/richSerp.xml", IOUtils.createReader(root + "/richSerp.xml")));
pageFiles.add(new NamedReader(root + "/footer.xml", IOUtils.createReader(root + "/footer.xml")));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java
index 4bdb130178f..0098cc921f2 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java
@@ -6,13 +6,13 @@ import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.vespa.model.container.search.QueryProfiles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.logging.Level;
import static helpers.CompareConfigTestHelper.assertSerializedConfigFileEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -22,45 +22,45 @@ public class QueryProfileVariantsTestCase {
private final String root = "src/test/java/com/yahoo/vespa/model/container/search/test/";
@Test
- public void testConfigCreation() throws IOException {
+ void testConfigCreation() throws IOException {
QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "queryprofilevariants");
QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger());
assertSerializedConfigFileEquals(root + "query-profile-variants-configuration.cfg", profiles.getConfig().toString());
}
@Test
- public void testConfigCreation2() throws IOException {
+ void testConfigCreation2() throws IOException {
QueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/vespa/model/container/search/test/queryprofilevariants2");
QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger());
assertSerializedConfigFileEquals(root + "query-profile-variants2-configuration.cfg", profiles.getConfig().toString());
}
@Test
- public void testConfigCreationNewsBESimple() throws IOException {
+ void testConfigCreationNewsBESimple() throws IOException {
QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "newsbesimple");
QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger());
assertSerializedConfigFileEquals(root + "newsbe-query-profiles-simple.cfg", profiles.getConfig().toString());
}
@Test
- public void testConfigCreationNewsFESimple() throws IOException {
+ void testConfigCreationNewsFESimple() throws IOException {
QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "newsfesimple");
QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger());
assertSerializedConfigFileEquals(root + "newsfe-query-profiles-simple.cfg", profiles.getConfig().toString());
}
@Test
- public void testVariantsOfExplicitCompound() throws IOException {
+ void testVariantsOfExplicitCompound() throws IOException {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile a1 = new QueryProfile("a1");
a1.set("b", "a1.b", registry);
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a", a1, registry);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, registry);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, registry);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, registry);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, registry);
registry.register(a1);
registry.register(profile);
@@ -70,7 +70,7 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsOfExplicitCompoundWithVariantReference() throws IOException {
+ void testVariantsOfExplicitCompoundWithVariantReference() throws IOException {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile a1 = new QueryProfile("a1");
@@ -80,11 +80,11 @@ public class QueryProfileVariantsTestCase {
a2.set("b", "a2.b", registry);
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a", a1, registry);
- profile.set("a", a2, new String[] {"x1"}, registry);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, registry);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, registry);
+ profile.set("a", a2, new String[]{"x1"}, registry);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, registry);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, registry);
registry.register(a1);
registry.register(a2);
@@ -96,7 +96,7 @@ public class QueryProfileVariantsTestCase {
/** For comparison with the above */
@Test
- public void testExplicitReferenceOverride() throws IOException {
+ void testExplicitReferenceOverride() throws IOException {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile a1 = new QueryProfile("a1");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java
index 03641e95f84..9c2c830c36f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java
@@ -17,15 +17,13 @@ import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
import com.yahoo.schema.derived.TestableDeployLogger;
import com.yahoo.vespa.model.container.search.QueryProfiles;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.logging.Level;
import static helpers.CompareConfigTestHelper.assertSerializedConfigFileEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests generation of config from query profiles (XML reading is tested elsewhere)
@@ -37,7 +35,7 @@ public class QueryProfilesTestCase {
private final static String root = "src/test/java/com/yahoo/vespa/model/container/search/test/";
@Test
- public void testVariantReference() {
+ void testVariantReference() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile parent = new QueryProfile("parent");
@@ -46,31 +44,31 @@ public class QueryProfilesTestCase {
QueryProfile referenced = new QueryProfile("referenced");
referenced.addInherited(parent);
- referenced.setDimensions(new String[] { "d2", "d3" });
+ referenced.setDimensions(new String[]{"d2", "d3"});
registry.register(referenced);
QueryProfile base = new QueryProfile("base");
- base.setDimensions(new String[] { "d1", "d2", "d3" });
- base.set("a", referenced, new String[] { null, null, "d3-val" }, registry);
- base.set("a.b", 1, new String[] { null, null, "d3-val" }, registry);
+ base.setDimensions(new String[]{"d1", "d2", "d3"});
+ base.set("a", referenced, new String[]{ null, null, "d3-val"}, registry);
+ base.set("a.b", 1, new String[]{ null, null, "d3-val"}, registry);
QueryProfileVariant aVariants = base.getVariants().getVariants().get(0);
- QueryProfile a = (QueryProfile)aVariants.values().get("a");
+ QueryProfile a = (QueryProfile) aVariants.values().get("a");
assertEquals("[d1, d2, d3]", a.getDimensions().toString());
registry.register(base);
QueryProfiles profiles = new QueryProfiles(registry, new TestableDeployLogger());
QueryProfileRegistry registryFromConfig = QueryProfileConfigurer.createFromConfig(profiles.getConfig());
var directValue = registry.findQueryProfile("base")
- .get("a.b",
- new String[] { "default", null, "d3-val"});
+ .get("a.b",
+ new String[]{"default", null, "d3-val"});
var throughConfigValue = registryFromConfig.findQueryProfile("base")
- .get("a.b",
- new String[] { "default", null, "d3-val"});
+ .get("a.b",
+ new String[]{"default", null, "d3-val"});
assertEquals(directValue.toString(), throughConfigValue.toString());
}
@Test
- public void testVariants() {
+ void testVariants() {
QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "variants");
QueryProfiles profiles = new QueryProfiles(registry, new TestableDeployLogger());
QueryProfileRegistry registryFromConfig = QueryProfileConfigurer.createFromConfig(profiles.getConfig());
@@ -84,13 +82,13 @@ public class QueryProfilesTestCase {
}
@Test
- public void testEmpty() throws IOException {
+ void testEmpty() throws IOException {
QueryProfileRegistry reg = new QueryProfileRegistry();
assertConfig("empty.cfg", reg);
}
@Test
- public void testQueryProfiles() throws IOException {
+ void testQueryProfiles() throws IOException {
final boolean mandatory = true;
final boolean overridable = true;
QueryProfileRegistry registry = new QueryProfileRegistry();
@@ -118,13 +116,13 @@ public class QueryProfilesTestCase {
typeRegistry.register(marketType);
QueryProfile defaultProfile = new QueryProfile("default");
- defaultProfile.set("ranking","production23", registry);
+ defaultProfile.set("ranking", "production23", registry);
defaultProfile.set("representation.defaultIndex", "title", registry);
defaultProfile.setOverridable("representation.defaultIndex", false, DimensionValues.empty);
registry.register(defaultProfile);
QueryProfile test = new QueryProfile("test");
- test.set("tracelevel",2, registry);
+ test.set("tracelevel", 2, registry);
registry.register(test);
QueryProfile genericUser = new QueryProfile("genericUser");
@@ -147,8 +145,8 @@ public class QueryProfilesTestCase {
QueryProfile marketUser = new QueryProfile("marketUser");
marketUser.setType(userType);
marketUser.addInherited(genericUser);
- marketUser.set("ads","none", registry);
- marketUser.set("age",25, registry);
+ marketUser.set("ads", "none", registry);
+ marketUser.set("age", 25, registry);
registry.register(marketUser);
QueryProfile market = new QueryProfile("root/market");
@@ -173,7 +171,7 @@ public class QueryProfilesTestCase {
}
@Test
- public void testValidation() {
+ void testValidation() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileTypeRegistry typeRegistry = registry.getTypeRegistry();
@@ -184,13 +182,13 @@ public class QueryProfilesTestCase {
new QueryProfiles(registry, logger);
assertEquals(1, logger.entries.size());
assertEquals("This application define query profile types, but has no query profiles referencing them " +
- "so they have no effect. " +
- "See https://docs.vespa.ai/en/query-profiles.html",
- logger.entries.get(0).message);
+ "so they have no effect. " +
+ "See https://docs.vespa.ai/en/query-profiles.html",
+ logger.entries.get(0).message);
}
@Test
- public void testValidationWithTensorFields() {
+ void testValidationWithTensorFields() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileTypeRegistry typeRegistry = registry.getTypeRegistry();
@@ -203,10 +201,10 @@ public class QueryProfilesTestCase {
new QueryProfiles(registry, logger);
assertEquals(1, logger.entries.size());
assertEquals("This application define query profile types, but has no query profiles referencing them " +
- "so they have no effect. " +
- "In particular, the tensors (vector, matrix) will be interpreted as strings, not tensors if sent in requests. " +
- "See https://docs.vespa.ai/en/query-profiles.html",
- logger.entries.get(0).message);
+ "so they have no effect. " +
+ "In particular, the tensors (vector, matrix) will be interpreted as strings, not tensors if sent in requests. " +
+ "See https://docs.vespa.ai/en/query-profiles.html",
+ logger.entries.get(0).message);
}
protected void assertConfig(String correctFileName, QueryProfileRegistry check) throws IOException {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
index d676dc29c94..faeac12f508 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java
@@ -2,10 +2,20 @@
package com.yahoo.vespa.model.container.xml;
import com.yahoo.component.ComponentId;
+import com.yahoo.config.model.api.EndpointCertificateSecrets;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
+import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.AthenzDomain;
+import com.yahoo.config.provision.Environment;
+import com.yahoo.config.provision.RegionName;
+import com.yahoo.config.provision.SystemName;
+import com.yahoo.config.provision.Zone;
+import com.yahoo.jdisc.http.ConnectorConfig;
+import com.yahoo.path.Path;
+import com.yahoo.security.X509CertificateUtils;
+import com.yahoo.security.tls.TlsContext;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.model.container.ApplicationContainer;
import com.yahoo.vespa.model.container.http.AccessControl;
@@ -13,8 +23,14 @@ import com.yahoo.vespa.model.container.http.ConnectorFactory;
import com.yahoo.vespa.model.container.http.FilterChains;
import com.yahoo.vespa.model.container.http.Http;
import com.yahoo.vespa.model.container.http.ssl.HostedSslConnectorFactory;
-import org.junit.Test;
-
+import org.hamcrest.Matchers;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.w3c.dom.Element;
+
+import java.io.File;
+import java.io.StringReader;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -22,19 +38,22 @@ import java.util.Set;
import java.util.stream.Collectors;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
* @author bjorncs
+ * @author mortent
*/
public class AccessControlTest extends ContainerModelBuilderTestBase {
+ @TempDir
+ public File applicationFolder;
+
@Test
- public void access_control_filter_chains_are_set_up() {
+ void access_control_filter_chains_are_set_up() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -49,7 +68,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void properties_are_set_from_xml() {
+ void properties_are_set_from_xml() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -59,12 +78,12 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
AccessControl accessControl = http.getAccessControl().get();
- assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain);
+ assertEquals("my-tenant-domain", accessControl.domain, "Wrong domain.");
}
@Test
- public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
+ void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -86,7 +105,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() {
+ void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -104,7 +123,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
@Test
- public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
+ void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
Http http = createModelAndGetHttp(
" <http>",
" <handler id='custom.Handler'>",
@@ -125,7 +144,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void hosted_connector_for_port_4443_uses_access_control_filter_chain_as_default_request_filter_chain() {
+ void hosted_connector_for_port_4443_uses_access_control_filter_chain_as_default_request_filter_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -136,7 +155,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
assertTrue(actualBindings.isEmpty());
- HostedSslConnectorFactory hostedConnectorFactory = (HostedSslConnectorFactory)http.getHttpServer().get().getConnectorFactories().stream()
+ HostedSslConnectorFactory hostedConnectorFactory = (HostedSslConnectorFactory) http.getHttpServer().get().getConnectorFactories().stream()
.filter(connectorFactory -> connectorFactory instanceof HostedSslConnectorFactory)
.findAny()
.get();
@@ -146,7 +165,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_is_implicitly_added_for_hosted_apps() {
+ void access_control_is_implicitly_added_for_hosted_apps() {
Http http = createModelAndGetHttp("<container version='1.0'/>");
Optional<AccessControl> maybeAccessControl = http.getAccessControl();
assertTrue(maybeAccessControl.isPresent());
@@ -156,7 +175,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
+ void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
Http http = createModelAndGetHttp(
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
@@ -173,7 +192,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_chain_exclude_chain_does_not_contain_duplicate_bindings_to_user_request_filter_chain() {
+ void access_control_chain_exclude_chain_does_not_contain_duplicate_bindings_to_user_request_filter_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <handler id='custom.Handler'>",
@@ -206,7 +225,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_excludes_are_not_affected_by_user_response_filter_chain() {
+ void access_control_excludes_are_not_affected_by_user_response_filter_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <handler id='custom.Handler'>",
@@ -243,7 +262,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_client_auth_defaults_to_need() {
+ void access_control_client_auth_defaults_to_need() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -255,7 +274,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_control_client_auth_can_be_overridden() {
+ void access_control_client_auth_can_be_overridden() {
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
@@ -264,17 +283,17 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
.allowDisableMtls(true))
.build();
Http http = createModelAndGetHttp(state,
- " <http>",
- " <filtering>",
- " <access-control tls-handshake-client-auth=\"want\"/>",
- " </filtering>",
- " </http>");
+ " <http>",
+ " <filtering>",
+ " <access-control tls-handshake-client-auth=\"want\"/>",
+ " </filtering>",
+ " </http>");
assertTrue(http.getAccessControl().isPresent());
assertEquals(AccessControl.ClientAuthentication.want, http.getAccessControl().get().clientAuthentication);
}
@Test
- public void access_control_client_auth_cannot_be_overridden_when_disabled() {
+ void access_control_client_auth_cannot_be_overridden_when_disabled() {
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
@@ -285,11 +304,11 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
try {
Http http = createModelAndGetHttp(state,
- " <http>",
- " <filtering>",
- " <access-control tls-handshake-client-auth=\"want\"/>",
- " </filtering>",
- " </http>");
+ " <http>",
+ " <filtering>",
+ " <access-control tls-handshake-client-auth=\"want\"/>",
+ " </filtering>",
+ " </http>");
fail("Overriding tls-handshake-client-auth allowed, but should have failed");
} catch (IllegalArgumentException e) {
assertEquals("Overriding 'tls-handshake-client-auth' for application is not allowed.", e.getMessage());
@@ -297,7 +316,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
}
@Test
- public void local_connector_has_default_chain() {
+ void local_connector_has_default_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
@@ -318,6 +337,182 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
assertEquals(AccessControl.DEFAULT_CONNECTOR_HOSTED_REQUEST_CHAIN_ID, defaultChain.get());
}
+ @Test
+ void client_authentication_is_enforced() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ nodesXml,
+ " <http><filtering>" +
+ " <access-control domain=\"vespa\" tls-handshake-client-auth=\"need\"/>" +
+ " </filtering></http>" +
+ "</container>");
+
+ DeployState state = new DeployState.Builder().properties(
+ new TestProperties()
+ .setHostedVespa(true)
+ .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
+ .build();
+ createModel(root, state, null, clusterElem);
+ ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0");
+
+ List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
+ ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
+
+ ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
+ tlsPort.getConfig(builder);
+
+ ConnectorConfig connectorConfig = new ConnectorConfig(builder);
+ assertTrue(connectorConfig.ssl().enabled());
+ assertEquals(ConnectorConfig.Ssl.ClientAuth.Enum.NEED_AUTH, connectorConfig.ssl().clientAuth());
+ assertEquals("CERT", connectorConfig.ssl().certificate());
+ assertEquals("KEY", connectorConfig.ssl().privateKey());
+ assertEquals(4443, connectorConfig.listenPort());
+
+ assertEquals("/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem",
+ connectorConfig.ssl().caCertificateFile(),
+ "Connector must use Athenz truststore in a non-public system.");
+ assertTrue(connectorConfig.ssl().caCertificate().isEmpty());
+ }
+
+ @Test
+ void missing_security_clients_pem_fails_in_public() {
+ Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
+
+ try {
+ DeployState state = new DeployState.Builder()
+ .properties(
+ new TestProperties()
+ .setHostedVespa(true)
+ .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
+ .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
+ .build();
+ createModel(root, state, null, clusterElem);
+ } catch (RuntimeException e) {
+ assertEquals("Client certificate authority security/clients.pem is missing - see: https://cloud.vespa.ai/en/security-model#data-plane",
+ e.getMessage());
+ return;
+ }
+ fail();
+ }
+
+ @Test
+ void security_clients_pem_is_picked_up() {
+ var applicationPackage = new MockApplicationPackage.Builder()
+ .withRoot(applicationFolder)
+ .build();
+
+ applicationPackage.getFile(Path.fromString("security")).createDirectory();
+ applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader("I am a very nice certificate"));
+
+ var deployState = DeployState.createTestState(applicationPackage);
+
+ Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
+
+ createModel(root, deployState, null, clusterElem);
+ assertEquals(Optional.of("I am a very nice certificate"), getContainerCluster("container").getTlsClientAuthority());
+ }
+
+ @Test
+ void operator_certificates_are_joined_with_clients_pem() {
+ var applicationPackage = new MockApplicationPackage.Builder()
+ .withRoot(applicationFolder)
+ .build();
+
+ var applicationTrustCert = X509CertificateUtils.toPem(
+ X509CertificateUtils.createSelfSigned("CN=application", Duration.ofDays(1)).certificate());
+ var operatorCert = X509CertificateUtils.createSelfSigned("CN=operator", Duration.ofDays(1)).certificate();
+
+ applicationPackage.getFile(Path.fromString("security")).createDirectory();
+ applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader(applicationTrustCert));
+
+ var deployState = new DeployState.Builder().properties(
+ new TestProperties()
+ .setOperatorCertificates(List.of(operatorCert))
+ .setHostedVespa(true)
+ .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
+ .zone(new Zone(SystemName.PublicCd, Environment.dev, RegionName.defaultName()))
+ .applicationPackage(applicationPackage)
+ .build();
+
+ Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
+
+ createModel(root, deployState, null, clusterElem);
+
+ ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0");
+ List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
+ ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
+
+ ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
+ tlsPort.getConfig(builder);
+
+ ConnectorConfig connectorConfig = new ConnectorConfig(builder);
+ var caCerts = X509CertificateUtils.certificateListFromPem(connectorConfig.ssl().caCertificate());
+ assertEquals(2, caCerts.size());
+ List<String> certnames = caCerts.stream()
+ .map(cert -> cert.getSubjectX500Principal().getName())
+ .collect(Collectors.toList());
+ assertThat(certnames, containsInAnyOrder("CN=operator", "CN=application"));
+ }
+
+ @Test
+ void require_allowed_ciphers() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ nodesXml,
+ "</container>");
+
+ DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build();
+ createModel(root, state, null, clusterElem);
+ ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0");
+
+ List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
+ ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
+ ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
+ tlsPort.getConfig(builder);
+
+ ConnectorConfig connectorConfig = new ConnectorConfig(builder);
+
+ assertThat(connectorConfig.ssl().enabledCipherSuites(), containsInAnyOrder(TlsContext.ALLOWED_CIPHER_SUITES.toArray()));
+ }
+
+ @Test
+ void providing_endpoint_certificate_secrets_opens_port_4443() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ nodesXml,
+ "</container>");
+
+ DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build();
+ createModel(root, state, null, clusterElem);
+ ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0");
+
+ // Verify that there are two connectors
+ List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
+ assertEquals(2, connectorFactories.size());
+ List<Integer> ports = connectorFactories.stream()
+ .map(ConnectorFactory::getListenPort)
+ .collect(Collectors.toList());
+ assertThat(ports, Matchers.containsInAnyOrder(8080, 4443));
+
+ ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
+
+ ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
+ tlsPort.getConfig(builder);
+
+
+ ConnectorConfig connectorConfig = new ConnectorConfig(builder);
+ assertTrue(connectorConfig.ssl().enabled());
+ assertEquals(ConnectorConfig.Ssl.ClientAuth.Enum.WANT_AUTH, connectorConfig.ssl().clientAuth());
+ assertEquals("CERT", connectorConfig.ssl().certificate());
+ assertEquals("KEY", connectorConfig.ssl().privateKey());
+ assertEquals(4443, connectorConfig.listenPort());
+
+ assertEquals("/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem",
+ connectorConfig.ssl().caCertificateFile(),
+ "Connector must use Athenz truststore in a non-public system.");
+ assertTrue(connectorConfig.ssl().caCertificate().isEmpty());
+ }
+
private Http createModelAndGetHttp(String... httpElement) {
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
@@ -327,6 +522,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase {
.build();
return createModelAndGetHttp(state, httpElement);
}
+
private Http createModelAndGetHttp(DeployState state, String... httpElement) {
List<String> servicesXml = new ArrayList<>();
servicesXml.add("<container version='1.0'>");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java
index 0486d463279..05e83de9157 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java
@@ -2,7 +2,14 @@
package com.yahoo.vespa.model.container.xml;
import com.yahoo.component.ComponentId;
+import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
+import com.yahoo.config.model.deploy.DeployState;
+import com.yahoo.config.model.deploy.TestProperties;
+import com.yahoo.config.model.test.MockApplicationPackage;
+import com.yahoo.config.provision.Environment;
+import com.yahoo.config.provision.RegionName;
+import com.yahoo.config.provision.Zone;
import com.yahoo.container.core.AccessLogConfig;
import com.yahoo.container.logging.ConnectionLogConfig;
import com.yahoo.container.logging.FileConnectionLog;
@@ -10,13 +17,14 @@ import com.yahoo.container.logging.JSONAccessLog;
import com.yahoo.container.logging.VespaAccessLog;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.component.Component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
+import java.util.logging.Level;
+
+import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.text.StringUtilities.quote;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -24,13 +32,13 @@ import static org.junit.Assert.assertNull;
public class AccessLogTest extends ContainerModelBuilderTestBase {
@Test
- public void default_access_log_is_added_by_default() {
+ void default_access_log_is_added_by_default() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
" <nodes>",
" <node hostalias='mockhost' baseport='1234' />",
" </nodes>",
- "</container>" );
+ "</container>");
createModel(root, cluster1Elem);
@@ -39,14 +47,14 @@ public class AccessLogTest extends ContainerModelBuilderTestBase {
}
@Test
- public void default_search_access_log_can_be_disabled() {
+ void default_search_access_log_can_be_disabled() {
final String jdiscClusterId = "jdisc-cluster";
Element clusterElem = DomBuilderTest.parse(
"<container id=" + quote(jdiscClusterId) + " version='1.0'>" +
" <search />" +
" <accesslog type='disabled' />" +
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
assertNull(getVespaAccessLog(jdiscClusterId));
@@ -63,7 +71,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase {
}
@Test
- public void access_log_can_be_configured() {
+ void access_log_can_be_configured() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <accesslog type='vespa' ",
@@ -71,28 +79,28 @@ public class AccessLogTest extends ContainerModelBuilderTestBase {
" <accesslog type='json' ",
" fileNamePattern='pattern' rotationInterval='interval' queueSize='17' bufferSize='65536'/>",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
assertNotNull(getJsonAccessLog("default"));
assertNotNull(getVespaAccessLog("default"));
{ // vespa
- Component<?, ?> accessLogComponent = getContainerComponent("default", VespaAccessLog.class.getName());
+ Component<?, ?> accessLogComponent = getComponent("default", VespaAccessLog.class.getName());
assertNotNull(accessLogComponent);
- assertEquals(VespaAccessLog.class.getName(), accessLogComponent.getClassId().getName(), VespaAccessLog.class.getName());
+ assertEquals(accessLogComponent.getClassId().getName(), VespaAccessLog.class.getName(), VespaAccessLog.class.getName());
AccessLogConfig config = root.getConfig(AccessLogConfig.class, "default/component/com.yahoo.container.logging.VespaAccessLog");
AccessLogConfig.FileHandler fileHandlerConfig = config.fileHandler();
assertEquals("pattern", fileHandlerConfig.pattern());
assertEquals("interval", fileHandlerConfig.rotation());
assertEquals(256, fileHandlerConfig.queueSize());
- assertEquals(256*1024, fileHandlerConfig.bufferSize());
+ assertEquals(256 * 1024, fileHandlerConfig.bufferSize());
}
{ // json
- Component<?, ?> accessLogComponent = getContainerComponent("default", JSONAccessLog.class.getName());
+ Component<?, ?> accessLogComponent = getComponent("default", JSONAccessLog.class.getName());
assertNotNull(accessLogComponent);
- assertEquals(JSONAccessLog.class.getName(), accessLogComponent.getClassId().getName(), JSONAccessLog.class.getName());
+ assertEquals(accessLogComponent.getClassId().getName(), JSONAccessLog.class.getName(), JSONAccessLog.class.getName());
AccessLogConfig config = root.getConfig(AccessLogConfig.class, "default/component/com.yahoo.container.logging.JSONAccessLog");
AccessLogConfig.FileHandler fileHandlerConfig = config.fileHandler();
assertEquals("pattern", fileHandlerConfig.pattern());
@@ -103,7 +111,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase {
}
@Test
- public void connection_log_configured_when_access_log_not_disabled() {
+ void connection_log_configured_when_access_log_not_disabled() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <accesslog type='vespa' ",
@@ -111,25 +119,59 @@ public class AccessLogTest extends ContainerModelBuilderTestBase {
" <accesslog type='json' ",
" fileNamePattern='pattern' rotationInterval='interval' />",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
- Component<?, ?> connectionLogComponent = getContainerComponent("default", FileConnectionLog.class.getName());
+ Component<?, ?> connectionLogComponent = getComponent("default", FileConnectionLog.class.getName());
assertNotNull(connectionLogComponent);
ConnectionLogConfig config = root.getConfig(ConnectionLogConfig.class, "default/component/com.yahoo.container.logging.FileConnectionLog");
assertEquals("default", config.cluster());
assertEquals(-1, config.queueSize());
- assertEquals(256*1024, config.bufferSize());
+ assertEquals(256 * 1024, config.bufferSize());
}
@Test
- public void connection_log_disabled_when_access_log_disabled() {
+ void connection_log_disabled_when_access_log_disabled() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <accesslog type='disabled' />",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
- Component<?, ?> fileConnectionLogComponent = getContainerComponent("default", FileConnectionLog.class.getName());
+ Component<?, ?> fileConnectionLogComponent = getComponent("default", FileConnectionLog.class.getName());
assertNull(fileConnectionLogComponent);
}
+
+ @Test
+ void hosted_applications_get_a_log_warning_when_overriding_accesslog() {
+ String containerService = joinLines("<container id='foo' version='1.0'>",
+ " <accesslog type='json' fileNamePattern='logs/vespa/qrs/access.%Y%m%d%H%M%S' symlinkName='json_access' />",
+ " <nodes count=\"2\">",
+ " </nodes>",
+ "</container>");
+
+ String deploymentXml = joinLines("<deployment version='1.0'>",
+ " <prod>",
+ " <region>us-east-1</region>",
+ " </prod>",
+ "</deployment>");
+
+ ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
+ .withServices(containerService)
+ .withDeploymentSpec(deploymentXml)
+ .build();
+
+ TestLogger logger = new TestLogger();
+ DeployState deployState = new DeployState.Builder()
+ .applicationPackage(applicationPackage)
+ .zone(new Zone(Environment.prod, RegionName.from("us-east-1")))
+ .properties(new TestProperties().setHostedVespa(true))
+ .deployLogger(logger)
+ .build();
+ createModel(root, deployState, null, DomBuilderTest.parse(containerService));
+ assertFalse(logger.msgs.isEmpty());
+ assertEquals(Level.WARNING, logger.msgs.get(0).getFirst());
+ assertEquals("Applications are not allowed to override the 'accesslog' element",
+ logger.msgs.get(0).getSecond());
+ }
+
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java
index 686f7bbd1f1..afcb9caa805 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java
@@ -6,12 +6,12 @@ import com.yahoo.config.model.builder.xml.XmlHelper;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.search.grouping.GroupingValidator;
import com.yahoo.vespa.model.container.PlatformBundles;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.io.StringReader;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -21,19 +21,19 @@ import static org.junit.Assert.assertEquals;
public class BundleInstantiationSpecificationBuilderTest {
@Test
- public void bundle_is_not_replaced_for_user_defined_class() {
+ void bundle_is_not_replaced_for_user_defined_class() {
final String userDefinedClass = "my own class that will also be set as bundle";
verifyExpectedBundle(userDefinedClass, null, userDefinedClass);
}
@Test
- public void bundle_is_replaced_for_internal_class() {
+ void bundle_is_replaced_for_internal_class() {
String internalClass = GroupingValidator.class.getName();
- verifyExpectedBundle(internalClass, null, PlatformBundles.searchAndDocprocBundle);
+ verifyExpectedBundle(internalClass, null, PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE);
}
@Test
- public void bundle_is_not_replaced_for_internal_class_with_explicitly_set_bundle() {
+ void bundle_is_not_replaced_for_internal_class_with_explicitly_set_bundle() {
String internalClass = GroupingValidator.class.getName();
String explicitBundle = "my-own-implementation";
verifyExpectedBundle(internalClass, explicitBundle, explicitBundle);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java
index b4242336c5c..3c68a77f2ad 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java
@@ -5,11 +5,13 @@ import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.model.test.MockRoot;
import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
+import com.yahoo.document.config.DocumentmanagerConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.ContainerModel;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
import com.yahoo.vespa.model.container.component.UserBindingPattern;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.Collection;
@@ -17,10 +19,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
@@ -28,11 +27,11 @@ import static org.junit.Assert.assertTrue;
*/
public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBase {
- private Map<String, Handler<?>> getHandlers(String clusterName) {
+ private Map<String, Handler> getHandlers(String clusterName) {
ContainerCluster<?> cluster = (ContainerCluster<?>) root.getChildren().get(clusterName);
- Map<String, Handler<?>> handlerMap = new HashMap<>();
- Collection<Handler<?>> handlers = cluster.getHandlers();
- for (Handler<?> handler : handlers) {
+ Map<String, Handler> handlerMap = new HashMap<>();
+ Collection<Handler> handlers = cluster.getHandlers();
+ for (Handler handler : handlers) {
assertFalse(handlerMap.containsKey(handler.getComponentId().toString())); //die on overwrites
handlerMap.put(handler.getComponentId().toString(), handler);
}
@@ -40,7 +39,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
}
@Test
- public void custom_bindings_are_allowed() {
+ void custom_bindings_are_allowed() {
Element elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
" <document-api>",
@@ -54,7 +53,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
}
private void verifyCustomBindings(String id) {
- Handler<?> handler = getHandlers("cluster1").get(id);
+ Handler handler = getHandlers("cluster1").get(id);
assertTrue(handler.getServerBindings().contains(UserBindingPattern.fromHttpPath("/document-api/reserved-for-internal-use/feedapi")));
assertTrue(handler.getServerBindings().contains(UserBindingPattern.fromHttpPath("/document-api/reserved-for-internal-use/feedapi/")));
@@ -63,7 +62,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
}
@Test
- public void requireThatHandlersAreSetup() {
+ void test_handler_setup() {
Element elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
" <document-api />",
@@ -71,7 +70,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
"</container>");
createModel(root, elem);
- Map<String, Handler<?>> handlerMap = getHandlers("cluster1");
+ Map<String, Handler> handlerMap = getHandlers("cluster1");
assertNotNull(handlerMap.get("com.yahoo.container.handler.VipStatusHandler"));
assertNotNull(handlerMap.get("com.yahoo.container.handler.observability.ApplicationStatusHandler"));
@@ -86,7 +85,23 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
}
@Test
- public void feeding_api_have_separate_threadpools() {
+ void nonexisting_fields_can_be_ignored() {
+ Element elem = DomBuilderTest.parse(
+ "<container id='cluster1' version='1.0'>",
+ " <document-api>" +
+ " <ignore-undefined-fields>true</ignore-undefined-fields>" +
+ nodesXml,
+ " </document-api>" +
+ "</container>");
+ ContainerModel model = createModel(root, elem).get(0);
+
+ var documentManager = new DocumentmanagerConfig.Builder();
+ model.getCluster().getConfig(documentManager);
+ assertTrue(documentManager.build().ignoreundefinedfields());
+ }
+
+ @Test
+ void feeding_api_have_separate_threadpools() {
Element elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
" <document-api />",
@@ -94,8 +109,8 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
"</container>");
root = new MockRoot("root", new MockApplicationPackage.Builder().build());
createModel(root, elem);
- Map<String, Handler<?>> handlers = getHandlers("cluster1");
- Handler<?> feedApiHandler = handlers.get("com.yahoo.vespa.http.server.FeedHandler");
+ Map<String, Handler> handlers = getHandlers("cluster1");
+ Handler feedApiHandler = handlers.get("com.yahoo.vespa.http.server.FeedHandler");
Set<String> injectedComponentIds = feedApiHandler.getInjectedComponentIds();
assertTrue(injectedComponentIds.contains("threadpool@feedapi-handler"));
@@ -106,7 +121,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa
}
@Test
- public void threadpools_configuration_can_be_overridden() {
+ void threadpools_configuration_can_be_overridden() {
Element elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
" <document-api>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java
index d91dba0572f..4d9bd978883 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java
@@ -7,9 +7,7 @@ import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.api.ApplicationClusterEndpoint;
import com.yahoo.config.model.api.ContainerEndpoint;
-import com.yahoo.config.model.api.EndpointCertificateSecrets;
import com.yahoo.config.model.api.ModelContext;
-import com.yahoo.config.model.api.TenantSecretStore;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
@@ -21,7 +19,6 @@ import com.yahoo.config.model.test.MockRoot;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.RegionName;
-import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.config.provisioning.FlavorsConfig;
import com.yahoo.container.ComponentsConfig;
@@ -33,15 +30,10 @@ import com.yahoo.container.handler.VipStatusHandler;
import com.yahoo.container.handler.metrics.MetricsV2Handler;
import com.yahoo.container.handler.observability.ApplicationStatusHandler;
import com.yahoo.container.jdisc.JdiscBindingsConfig;
-import com.yahoo.container.jdisc.secretstore.SecretStoreConfig;
import com.yahoo.container.usability.BindingsOverviewHandler;
-import com.yahoo.jdisc.http.ConnectorConfig;
import com.yahoo.net.HostName;
-import com.yahoo.path.Path;
import com.yahoo.prelude.cluster.QrMonitorConfig;
import com.yahoo.search.config.QrStartConfig;
-import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.tls.TlsContext;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.model.AbstractService;
import com.yahoo.vespa.model.VespaModel;
@@ -49,25 +41,18 @@ import com.yahoo.vespa.model.container.ApplicationContainer;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.ContainerModelEvaluation;
-import com.yahoo.vespa.model.container.SecretStore;
import com.yahoo.vespa.model.container.component.Component;
-import com.yahoo.vespa.model.container.http.ConnectorFactory;
+import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
import com.yahoo.vespa.model.test.VespaModelTester;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.hamcrest.Matchers;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
-import java.io.StringReader;
-import java.time.Duration;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
@@ -76,22 +61,12 @@ import java.util.stream.Collectors;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.test.LinePatternMatcher.containsLineWithPattern;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import static com.yahoo.vespa.model.container.ContainerCluster.ROOT_HANDLER_BINDING;
-import static com.yahoo.vespa.model.container.ContainerCluster.STATE_HANDLER_BINDING_1;
-import static org.hamcrest.CoreMatchers.is;
+import static com.yahoo.vespa.model.container.component.chain.ProcessingHandler.PROCESSING_HANDLER_CLASS;
import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.hasItem;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for "core functionality" of the container model, e.g. ports, or the 'components' and 'bundles' configs.
@@ -103,11 +78,8 @@ import static org.junit.Assert.fail;
*/
public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
- @Rule
- public TemporaryFolder applicationFolder = new TemporaryFolder();
-
@Test
- public void model_evaluation_bundles_are_deployed() {
+ void model_evaluation_bundles_are_deployed() {
createBasicContainerModel();
PlatformBundlesConfig config = root.getConfig(PlatformBundlesConfig.class, "default");
assertTrue(config.bundlePaths().contains(ContainerModelEvaluation.MODEL_EVALUATION_BUNDLE_FILE.toString()));
@@ -115,79 +87,79 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void default_port_is_4080() {
+ void default_port_is_4080() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
- nodesXml,
- "</container>" );
+ nodesXml,
+ "</container>");
createModel(root, clusterElem);
- AbstractService container = (AbstractService)root.getProducer("container/container.0");
+ AbstractService container = (AbstractService) root.getProducer("container/container.0");
assertEquals(getDefaults().vespaWebServicePort(), container.getRelativePort(0));
}
@Test
- public void http_server_port_is_configurable_and_does_not_affect_other_ports() {
+ void http_server_port_is_configurable_and_does_not_affect_other_ports() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <http>",
" <server port='9000' id='foo' />",
" </http>",
- nodesXml,
- "</container>" );
+ nodesXml,
+ "</container>");
createModel(root, clusterElem);
- AbstractService container = (AbstractService)root.getProducer("container/container.0");
+ AbstractService container = (AbstractService) root.getProducer("container/container.0");
assertEquals(9000, container.getRelativePort(0));
assertNotEquals(9001, container.getRelativePort(1));
}
@Test
- public void omitting_http_server_port_gives_default() {
+ void omitting_http_server_port_gives_default() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <http>",
" <server id='foo'/>",
" </http>",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
- AbstractService container = (AbstractService)root.getProducer("container/container.0");
+ AbstractService container = (AbstractService) root.getProducer("container/container.0");
assertEquals(Defaults.getDefaults().vespaWebServicePort(), container.getRelativePort(0));
}
@Test
- public void fail_if_http_port_is_not_default_in_hosted_vespa() throws Exception {
+ void fail_if_http_port_is_not_default_in_hosted_vespa() throws Exception {
try {
String servicesXml =
"<services>" +
- "<admin version='3.0'>" +
- " <nodes count='1'/>" +
- "</admin>" +
- "<container version='1.0'>" +
- " <http>" +
- " <server port='9000' id='foo' />" +
- " </http>" +
- nodesXml +
- "</container>" +
- "</services>";
+ "<admin version='3.0'>" +
+ " <nodes count='1'/>" +
+ "</admin>" +
+ "<container version='1.0'>" +
+ " <http>" +
+ " <server port='9000' id='foo' />" +
+ " </http>" +
+ nodesXml +
+ "</container>" +
+ "</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
TestLogger logger = new TestLogger();
new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
- .applicationPackage(applicationPackage)
- .deployLogger(logger)
- .properties(new TestProperties().setHostedVespa(true))
- .build());
+ .applicationPackage(applicationPackage)
+ .deployLogger(logger)
+ .properties(new TestProperties().setHostedVespa(true))
+ .build());
fail("Expected exception");
}
catch (IllegalArgumentException e) {
// Success
assertEquals("Illegal port 9000 in http server 'foo': Port must be set to " + Defaults.getDefaults().vespaWebServicePort(),
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void one_cluster_with_explicit_port_and_one_without_is_ok() {
+ void one_cluster_with_explicit_port_and_one_without_is_ok() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0' />");
Element cluster2Elem = DomBuilderTest.parse(
@@ -200,15 +172,15 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void two_clusters_without_explicit_port_throws_exception() {
+ void two_clusters_without_explicit_port_throws_exception() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
- nodesXml,
- "</container>" );
+ nodesXml,
+ "</container>");
Element cluster2Elem = DomBuilderTest.parse(
"<container id='cluster2' version='1.0'>",
- nodesXml,
- "</container>" );
+ nodesXml,
+ "</container>");
try {
createModel(root, cluster1Elem, cluster2Elem);
fail("Expected exception");
@@ -218,7 +190,18 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void verify_bindings_for_builtin_handlers() {
+ void builtin_handlers_get_default_threadpool() {
+ createBasicContainerModel();
+
+ Handler h1 = getHandler("default", ApplicationStatusHandler.class.getName());
+ assertTrue(h1.getInjectedComponentIds().contains("threadpool@default-handler-common"));
+
+ Handler h2 = getHandler("default", BindingsOverviewHandler.class.getName());
+ assertTrue(h2.getInjectedComponentIds().contains("threadpool@default-handler-common"));
+ }
+
+ @Test
+ void verify_bindings_for_builtin_handlers() {
createBasicContainerModel();
JdiscBindingsConfig config = root.getConfig(JdiscBindingsConfig.class, "default/container.0");
@@ -236,69 +219,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void default_root_handler_binding_can_be_stolen_by_user_configured_handler() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>" +
- " <handler id='userRootHandler'>" +
- " <binding>" + ROOT_HANDLER_BINDING.patternString() + "</binding>" +
- " </handler>" +
- "</container>");
- createModel(root, clusterElem);
-
- // The handler is still set up.
- ComponentsConfig.Components userRootHandler = getComponent(componentsConfig(), BindingsOverviewHandler.class.getName());
- assertNotNull(userRootHandler);
-
- // .. but it has no bindings
- var discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default");
- assertNull(discBindingsConfig.handlers(BindingsOverviewHandler.class.getName()));
- }
-
- @Test
- public void reserved_binding_cannot_be_stolen_by_user_configured_handler() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>" +
- " <handler id='userHandler'>" +
- " <binding>" + STATE_HANDLER_BINDING_1.patternString() + "</binding>" +
- " </handler>" +
- "</container>");
- try {
- createModel(root, clusterElem);
- fail("Expected exception when stealing a reserved binding.");
- } catch (IllegalArgumentException e) {
- assertThat(e.getMessage(), is("Binding 'http://*/state/v1' is a reserved Vespa binding " +
- "and cannot be used by handler: userHandler"));
- }
- }
-
- @Test
- public void handler_bindings_are_included_in_discBindings_config() {
- createClusterWithJDiscHandler();
- String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
- assertThat(discBindingsConfig, containsString(".serverBindings[0] \"http://*/binding0\""));
- assertThat(discBindingsConfig, containsString(".serverBindings[1] \"http://*/binding1\""));
- }
-
- @Test
- public void handlers_are_included_in_components_config() {
- createClusterWithJDiscHandler();
- assertThat(componentsConfig().toString(), containsString(".id \"discHandler\""));
- }
-
- private void createClusterWithJDiscHandler() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>",
- " <handler id='discHandler'>",
- " <binding>http://*/binding0</binding>",
- " <binding>http://*/binding1</binding>",
- " </handler>",
- "</container>");
-
- createModel(root, clusterElem);
- }
-
- @Test
- public void processing_handler_bindings_can_be_overridden() {
+ void processing_handler_bindings_can_be_overridden() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <processing>",
@@ -316,11 +237,11 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void serverProviders_are_included_in_components_config() {
+ void serverProviders_are_included_in_components_config() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
- " <server id='discServer' />" +
- "</container>" );
+ " <server id='discServer' />" +
+ "</container>");
createModel(root, clusterElem);
@@ -333,7 +254,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void searchHandler_gets_only_search_chains_in_chains_config() {
+ void searchHandler_gets_only_search_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
String searchHandlerConfigId = "default/component/com.yahoo.search.handler.SearchHandler";
String chainsConfig = getChainsConfig(searchHandlerConfigId);
@@ -342,14 +263,21 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void processingHandler_gets_only_processing_chains_in_chains_config() {
+ void processingHandler_gets_only_processing_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
- String processingHandlerConfigId = "default/component/com.yahoo.processing.handler.ProcessingHandler";
+ String processingHandlerConfigId = "default/component/" + PROCESSING_HANDLER_CLASS;
String chainsConfig = getChainsConfig(processingHandlerConfigId);
assertThat(chainsConfig, containsLineWithPattern(".*\\.id \"testProcessor@default\"$"));
assertThat(chainsConfig, not(containsLineWithPattern(".*\\.id \"testSearcher@default\"$")));
}
+ @Test
+ void processingHandler_is_instantiated_from_the_default_bundle() {
+ createClusterWithProcessingAndSearchChains();
+ ComponentsConfig.Components config = getComponentInConfig(componentsConfig(), PROCESSING_HANDLER_CLASS);
+ assertEquals(PROCESSING_HANDLER_CLASS, config.bundle());
+ }
+
private void createClusterWithProcessingAndSearchChains() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
@@ -370,13 +298,13 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void user_config_can_be_overridden_on_node() {
+ void user_config_can_be_overridden_on_node() {
Element containerElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <config name=\"prelude.cluster.qr-monitor\">" +
- " <requesttimeout>111</requesttimeout>",
+ " <requesttimeout>111</requesttimeout>",
" </config> " +
- " <nodes>",
+ " <nodes>",
" <node hostalias='host1' />",
" <node hostalias='host2'>",
" <config name=\"prelude.cluster.qr-monitor\">",
@@ -388,39 +316,25 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
root = ContentClusterUtils.createMockRoot(new String[]{"host1", "host2"});
createModel(root, containerElem);
- ContainerCluster cluster = (ContainerCluster)root.getChildren().get("default");
+ ContainerCluster cluster = (ContainerCluster) root.getChildren().get("default");
assertEquals(2, cluster.getContainers().size());
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.0").requesttimeout(), 111);
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.1").requesttimeout(), 222);
}
@Test
- public void nested_components_are_injected_to_handlers() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>",
- " <handler id='myHandler'>",
- " <component id='injected' />",
- " </handler>",
- "</container>");
-
- createModel(root, clusterElem);
- Component<?,?> handler = getContainerComponent("default", "myHandler");
- assertThat(handler.getInjectedComponentIds(), hasItem("injected@myHandler"));
- }
-
- @Test
- public void component_includes_are_added() {
+ void component_includes_are_added() {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/application/include_dirs");
VespaModel model = creator.create(true);
ContainerCluster cluster = model.getContainerClusters().get("default");
Map<ComponentId, Component<?, ?>> componentsMap = cluster.getComponentsMap();
- Component<?,?> example = componentsMap.get(
+ Component<?, ?> example = componentsMap.get(
ComponentId.fromString("test.Exampledocproc"));
assertEquals("test.Exampledocproc", example.getComponentId().getName());
}
@Test
- public void affinity_is_set() {
+ void affinity_is_set() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
@@ -429,14 +343,14 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
" <nodes cpu-socket-affinity='true'>",
" <node hostalias='node1' />",
" </nodes>" +
- "</container>");
+ "</container>");
createModel(root, clusterElem);
assertTrue(getContainerCluster("default").getContainers().get(0).getAffinity().isPresent());
assertEquals(0, getContainerCluster("default").getContainers().get(0).getAffinity().get().cpuSocket());
}
@Test
- public void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException {
+ void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
String hostsXml = "<hosts>\n" +
" <host name=\"test1.yahoo.com\">\n" +
@@ -452,7 +366,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void endpoints_are_added_to_containers() throws IOException, SAXException {
+ void endpoints_are_added_to_containers() throws IOException, SAXException {
final var servicesXml = joinLines("",
"<container id='comics-search' version='1.0'>",
" <nodes>",
@@ -484,7 +398,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
.flatMap(cluster -> cluster.getContainers().stream())
.collect(Collectors.toList());
- assertFalse("Missing container objects based on configuration", containers.isEmpty());
+ assertFalse(containers.isEmpty(), "Missing container objects based on configuration");
containers.forEach(container -> {
final var rotations = container.getServicePropertyString("rotations").split(",");
@@ -494,7 +408,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException {
+ void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
@@ -507,23 +421,27 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
assertEquals(2, model.hostSystem().getHosts().size());
}
- @Test(expected = IllegalArgumentException.class)
- public void renderers_named_JsonRenderer_are_not_allowed() {
- createModel(root, generateContainerElementWithRenderer("JsonRenderer"));
+ @Test
+ void renderers_named_JsonRenderer_are_not_allowed() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ createModel(root, generateContainerElementWithRenderer("JsonRenderer"));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void renderers_named_DefaultRenderer_are_not_allowed() {
- createModel(root, generateContainerElementWithRenderer("XmlRenderer"));
+ @Test
+ void renderers_named_DefaultRenderer_are_not_allowed() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ createModel(root, generateContainerElementWithRenderer("XmlRenderer"));
+ });
}
@Test
- public void renderers_named_something_else_are_allowed() {
+ void renderers_named_something_else_are_allowed() {
createModel(root, generateContainerElementWithRenderer("my-little-renderer"));
}
@Test
- public void vip_status_handler_uses_file_for_hosted_vespa() throws Exception {
+ void vip_status_handler_uses_file_for_hosted_vespa() throws Exception {
String servicesXml = "<services>" +
"<container version='1.0'>" +
nodesXml +
@@ -543,7 +461,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void qrconfig_is_produced() throws IOException, SAXException {
+ void qrconfig_is_produced() throws IOException, SAXException {
QrConfig qr = getQrConfig(new TestProperties());
String hostname = HostName.getLocalhost(); // Using the same way of getting hostname as filedistribution model
assertEquals("default.container.0", qr.discriminator());
@@ -556,6 +474,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
assertEquals(50.0, qr.shutdown().timeout(), 0.00000000000001);
assertFalse(qr.shutdown().dumpHeapOnTimeout());
}
+
private QrConfig getQrConfig(ModelContext.Properties properties) throws IOException, SAXException {
String servicesXml =
"<services>" +
@@ -581,192 +500,14 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void control_container_shutdown() throws IOException, SAXException {
+ void control_container_shutdown() throws IOException, SAXException {
QrConfig qr = getQrConfig(new TestProperties().containerShutdownTimeout(133).containerDumpHeapOnShutdownTimeout(true));
assertEquals(133.0, qr.shutdown().timeout(), 0.00000000000001);
assertTrue(qr.shutdown().dumpHeapOnTimeout());
}
@Test
- public void secret_store_can_be_set_up() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- " <secret-store type='oath-ckms'>",
- " <group name='group1' environment='env1'/>",
- " </secret-store>",
- "</container>");
- createModel(root, clusterElem);
- SecretStore secretStore = getContainerCluster("container").getSecretStore().get();
- assertEquals("group1", secretStore.getGroups().get(0).name);
- assertEquals("env1", secretStore.getGroups().get(0).environment);
- }
-
- @Test
- public void cloud_secret_store_requires_configured_secret_store() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- " <secret-store type='cloud'>",
- " <store id='store'>",
- " <aws-parameter-store account='store1' region='eu-north-1'/>",
- " </store>",
- " </secret-store>",
- "</container>");
- try {
- DeployState state = new DeployState.Builder()
- .properties(new TestProperties().setHostedVespa(true))
- .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
- .build();
- createModel(root, state, null, clusterElem);
- fail("secret store not defined");
- } catch (RuntimeException e) {
- assertEquals("No configured secret store named store1", e.getMessage());
- }
- }
-
-
- @Test
- public void cloud_secret_store_can_be_set_up() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- " <secret-store type='cloud'>",
- " <store id='store'>",
- " <aws-parameter-store account='store1' region='eu-north-1'/>",
- " </store>",
- " </secret-store>",
- "</container>");
-
- DeployState state = new DeployState.Builder()
- .properties(
- new TestProperties()
- .setHostedVespa(true)
- .setTenantSecretStores(List.of(new TenantSecretStore("store1", "1234", "role", Optional.of("externalid")))))
- .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
- .build();
- createModel(root, state, null, clusterElem);
-
- ApplicationContainerCluster container = getContainerCluster("container");
- assertComponentConfigured(container, "com.yahoo.jdisc.cloud.aws.AwsParameterStore");
- CloudSecretStore secretStore = (CloudSecretStore) container.getComponentsMap().get(ComponentId.fromString("com.yahoo.jdisc.cloud.aws.AwsParameterStore"));
-
-
- SecretStoreConfig.Builder configBuilder = new SecretStoreConfig.Builder();
- secretStore.getConfig(configBuilder);
- SecretStoreConfig secretStoreConfig = configBuilder.build();
-
- assertEquals(1, secretStoreConfig.awsParameterStores().size());
- assertEquals("store1", secretStoreConfig.awsParameterStores().get(0).name());
- }
-
- @Test
- public void cloud_secret_store_fails_to_set_up_in_non_public_zone() {
- try {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- " <secret-store type='cloud'>",
- " <store id='store'>",
- " <aws-parameter-store account='store1' region='eu-north-1'/>",
- " </store>",
- " </secret-store>",
- "</container>");
-
- DeployState state = new DeployState.Builder()
- .properties(
- new TestProperties()
- .setHostedVespa(true)
- .setTenantSecretStores(List.of(new TenantSecretStore("store1", "1234", "role", Optional.of("externalid")))))
- .zone(new Zone(SystemName.main, Environment.prod, RegionName.defaultName()))
- .build();
- createModel(root, state, null, clusterElem);
- } catch (RuntimeException e) {
- assertEquals("Cloud secret store is not supported in non-public system, see the documentation",
- e.getMessage());
- return;
- }
- fail();
- }
-
- @Test
- public void missing_security_clients_pem_fails_in_public() {
- Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
-
- try {
- DeployState state = new DeployState.Builder()
- .properties(
- new TestProperties()
- .setHostedVespa(true)
- .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
- .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
- .build();
- createModel(root, state, null, clusterElem);
- } catch (RuntimeException e) {
- assertEquals("Client certificate authority security/clients.pem is missing - see: https://cloud.vespa.ai/en/security-model#data-plane",
- e.getMessage());
- return;
- }
- fail();
- }
-
- @Test
- public void security_clients_pem_is_picked_up() {
- var applicationPackage = new MockApplicationPackage.Builder()
- .withRoot(applicationFolder.getRoot())
- .build();
-
- applicationPackage.getFile(Path.fromString("security")).createDirectory();
- applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader("I am a very nice certificate"));
-
- var deployState = DeployState.createTestState(applicationPackage);
-
- Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
-
- createModel(root, deployState, null, clusterElem);
- assertEquals(Optional.of("I am a very nice certificate"), getContainerCluster("container").getTlsClientAuthority());
- }
-
- @Test
- public void operator_certificates_are_joined_with_clients_pem() {
- var applicationPackage = new MockApplicationPackage.Builder()
- .withRoot(applicationFolder.getRoot())
- .build();
-
- var applicationTrustCert = X509CertificateUtils.toPem(
- X509CertificateUtils.createSelfSigned("CN=application", Duration.ofDays(1)).certificate());
- var operatorCert = X509CertificateUtils.createSelfSigned("CN=operator", Duration.ofDays(1)).certificate();
-
- applicationPackage.getFile(Path.fromString("security")).createDirectory();
- applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader(applicationTrustCert));
-
- var deployState = new DeployState.Builder().properties(
- new TestProperties()
- .setOperatorCertificates(List.of(operatorCert))
- .setHostedVespa(true)
- .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
- .zone(new Zone(SystemName.PublicCd, Environment.dev, RegionName.defaultName()))
- .applicationPackage(applicationPackage)
- .build();
-
- Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
-
- createModel(root, deployState, null, clusterElem);
-
- ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
- List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
- ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
-
- ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
- tlsPort.getConfig(builder);
-
- ConnectorConfig connectorConfig = new ConnectorConfig(builder);
- var caCerts = X509CertificateUtils.certificateListFromPem(connectorConfig.ssl().caCertificate());
- assertEquals(2, caCerts.size());
- List<String> certnames = caCerts.stream()
- .map(cert -> cert.getSubjectX500Principal().getName())
- .collect(Collectors.toList());
- assertThat(certnames, containsInAnyOrder("CN=operator", "CN=application"));
- }
-
- @Test
- public void environment_vars_are_honoured() {
+ void environment_vars_are_honoured() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <nodes>",
@@ -776,7 +517,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
" </environment-variables>",
" <node hostalias='mockhost'/>",
" </nodes>",
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
@@ -808,122 +549,26 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatAvailableProcessorsFollowFlavor() {
- verifyAvailableprocessors(false, null,0);
- verifyAvailableprocessors(true, null,0);
+ void requireThatAvailableProcessorsFollowFlavor() {
+ verifyAvailableprocessors(false, null, 0);
+ verifyAvailableprocessors(true, null, 0);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build()), 9);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(1).build()), 2);
}
@Test
- public void requireThatProvidingEndpointCertificateSecretsOpensPort4443() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- nodesXml,
- "</container>" );
-
- DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build();
- createModel(root, state, null, clusterElem);
- ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
-
- // Verify that there are two connectors
- List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
- assertEquals(2, connectorFactories.size());
- List<Integer> ports = connectorFactories.stream()
- .map(ConnectorFactory::getListenPort)
- .collect(Collectors.toList());
- assertThat(ports, Matchers.containsInAnyOrder(8080, 4443));
-
- ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
-
- ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
- tlsPort.getConfig(builder);
-
-
- ConnectorConfig connectorConfig = new ConnectorConfig(builder);
- assertTrue(connectorConfig.ssl().enabled());
- assertEquals(ConnectorConfig.Ssl.ClientAuth.Enum.WANT_AUTH, connectorConfig.ssl().clientAuth());
- assertEquals("CERT", connectorConfig.ssl().certificate());
- assertEquals("KEY", connectorConfig.ssl().privateKey());
- assertEquals(4443, connectorConfig.listenPort());
-
- assertEquals("Connector must use Athenz truststore in a non-public system.",
- "/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem",
- connectorConfig.ssl().caCertificateFile());
- assertTrue(connectorConfig.ssl().caCertificate().isEmpty());
- }
-
- @Test
- public void requireThatClientAuthenticationIsEnforced() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- nodesXml,
- " <http><filtering>" +
- " <access-control domain=\"vespa\" tls-handshake-client-auth=\"need\"/>" +
- " </filtering></http>" +
- "</container>" );
-
- DeployState state = new DeployState.Builder().properties(
- new TestProperties()
- .setHostedVespa(true)
- .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY"))))
- .build();
- createModel(root, state, null, clusterElem);
- ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
-
- List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
- ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
-
- ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
- tlsPort.getConfig(builder);
-
- ConnectorConfig connectorConfig = new ConnectorConfig(builder);
- assertTrue(connectorConfig.ssl().enabled());
- assertEquals(ConnectorConfig.Ssl.ClientAuth.Enum.NEED_AUTH, connectorConfig.ssl().clientAuth());
- assertEquals("CERT", connectorConfig.ssl().certificate());
- assertEquals("KEY", connectorConfig.ssl().privateKey());
- assertEquals(4443, connectorConfig.listenPort());
-
- assertEquals("Connector must use Athenz truststore in a non-public system.",
- "/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem",
- connectorConfig.ssl().caCertificateFile());
- assertTrue(connectorConfig.ssl().caCertificate().isEmpty());
- }
-
- @Test
- public void require_allowed_ciphers() {
- Element clusterElem = DomBuilderTest.parse(
- "<container version='1.0'>",
- nodesXml,
- "</container>" );
-
- DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build();
- createModel(root, state, null, clusterElem);
- ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
-
- List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories();
- ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
- ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
- tlsPort.getConfig(builder);
-
- ConnectorConfig connectorConfig = new ConnectorConfig(builder);
-
- assertThat(connectorConfig.ssl().enabledCipherSuites(), containsInAnyOrder(TlsContext.ALLOWED_CIPHER_SUITES.toArray()));
- }
-
- @Test
- public void cluster_with_zookeeper() {
+ void cluster_with_zookeeper() {
Function<Integer, String> servicesXml = (nodeCount) -> "<container version='1.0' id='default'>" +
- "<nodes count='" + nodeCount + "'/>" +
- "<zookeeper/>" +
- "</container>";
+ "<nodes count='" + nodeCount + "'/>" +
+ "<zookeeper/>" +
+ "</container>";
VespaModelTester tester = new VespaModelTester();
tester.addHosts(3);
{
VespaModel model = tester.createModel(servicesXml.apply(3), true);
ApplicationContainerCluster cluster = model.getContainerClusters().get("default");
assertNotNull(cluster);
- assertComponentConfigured(cluster,"com.yahoo.vespa.curator.Curator");
+ assertComponentConfigured(cluster, "com.yahoo.vespa.curator.Curator");
cluster.getContainers().forEach(container -> {
assertComponentConfigured(container, "com.yahoo.vespa.zookeeper.ReconfigurableVespaZooKeeperServer");
assertComponentConfigured(container, "com.yahoo.vespa.zookeeper.Reconfigurer");
@@ -938,75 +583,39 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
try {
tester.createModel(servicesXml.apply(2), true);
fail("Expected exception");
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
}
{
String xmlWithNodes =
"<?xml version='1.0' encoding='utf-8' ?>" +
- "<services>" +
- " <container version='1.0' id='container1'>" +
- " <zookeeper/>" +
- " <nodes of='content1'/>" +
- " </container>" +
- " <content version='1.0' id='content1'>" +
- " <nodes count='3'/>" +
- " </content>" +
- "</services>";
+ "<services>" +
+ " <container version='1.0' id='container1'>" +
+ " <zookeeper/>" +
+ " <nodes of='content1'/>" +
+ " </container>" +
+ " <content version='1.0' id='content1'>" +
+ " <nodes count='3'/>" +
+ " </content>" +
+ "</services>";
try {
tester.createModel(xmlWithNodes, true);
fail("Expected exception");
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
}
}
@Test
- public void logs_deployment_spec_deprecations() throws Exception {
- String containerService = joinLines("<container id='foo' version='1.0'>",
- " <nodes>",
- " <node hostalias='host1' />",
- " </nodes>",
- "</container>");
- String deploymentXml = joinLines("<deployment version='1.0'>",
- " <prod global-service-id='foo'>",
- " <region active='true'>us-east-1</region>",
- " </prod>",
- "</deployment>");
-
- ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
- .withServices(containerService)
- .withDeploymentSpec(deploymentXml)
- .build();
-
- TestLogger logger = new TestLogger();
- DeployState deployState = new DeployState.Builder()
- .applicationPackage(applicationPackage)
- .zone(new Zone(Environment.prod, RegionName.from("us-east-1")))
- .properties(new TestProperties().setHostedVespa(true))
- .deployLogger(logger)
- .build();
-
- createModel(root, deployState, null, DomBuilderTest.parse(containerService));
- assertFalse(logger.msgs.isEmpty());
- System.out.println(logger.msgs);
- assertEquals(Level.WARNING, logger.msgs.get(0).getFirst());
- assertEquals(Level.WARNING, logger.msgs.get(1).getFirst());
- assertEquals("Element 'prod' contains attribute 'global-service-id' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax",
- logger.msgs.get(0).getSecond());
- assertEquals("Element 'region' contains attribute 'active' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax",
- logger.msgs.get(1).getSecond());
- }
-
- @Test
- public void logs_accesslog_not_overidable_in_hosted() {
+ void logs_deployment_spec_deprecations() throws Exception {
String containerService = joinLines("<container id='foo' version='1.0'>",
- " <accesslog type='json' fileNamePattern='logs/vespa/qrs/access.%Y%m%d%H%M%S' symlinkName='json_access' />",
- " <nodes count=\"2\">",
+ " <nodes>",
+ " <node hostalias='host1' />",
" </nodes>",
"</container>");
-
String deploymentXml = joinLines("<deployment version='1.0'>",
- " <prod>",
- " <region>us-east-1</region>",
+ " <prod global-service-id='foo'>",
+ " <region active='true'>us-east-1</region>",
" </prod>",
"</deployment>");
@@ -1022,16 +631,15 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
.properties(new TestProperties().setHostedVespa(true))
.deployLogger(logger)
.build();
+
createModel(root, deployState, null, DomBuilderTest.parse(containerService));
assertFalse(logger.msgs.isEmpty());
assertEquals(Level.WARNING, logger.msgs.get(0).getFirst());
- assertEquals("Applications are not allowed to override the 'accesslog' element",
+ assertEquals(Level.WARNING, logger.msgs.get(1).getFirst());
+ assertEquals("Element 'prod' contains attribute 'global-service-id' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax",
logger.msgs.get(0).getSecond());
- }
-
- private void assertComponentConfigured(ApplicationContainerCluster cluster, String componentId) {
- Component<?, ?> component = cluster.getComponentsMap().get(ComponentId.fromString(componentId));
- assertNotNull(component);
+ assertEquals("Element 'region' contains attribute 'active' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax",
+ logger.msgs.get(1).getSecond());
}
private void assertComponentConfigured(ApplicationContainer container, String id) {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java
index cfe4b72f37d..9dee99f8f17 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java
@@ -13,8 +13,9 @@ import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.ContainerModel;
import com.yahoo.vespa.model.container.component.Component;
+import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.search.ContainerSearch;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
import org.w3c.dom.Element;
import java.util.ArrayList;
@@ -22,6 +23,8 @@ import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
/**
* Utility functions for testing the ContainerModelBuilder. Note that XML validation will
* not be done when using this class
@@ -51,23 +54,31 @@ public abstract class ContainerModelBuilderTestBase {
protected MockRoot root;
+ @BeforeEach
+ public void prepareTest() {
+ root = new MockRoot("root");
+ }
+
protected void createBasicContainerModel() {
Element clusterElem = DomBuilderTest.parse("<container id='default' version='1.0' />");
createModel(root, clusterElem);
}
- public static void createModel(MockRoot root, DeployState deployState, VespaModel vespaModel, Element... containerElems) {
+ public static List<ContainerModel> createModel(MockRoot root, DeployState deployState, VespaModel vespaModel, Element... containerElems) {
+ List<ContainerModel> containerModels = new ArrayList<>();
for (Element containerElem : containerElems) {
ContainerModel model = new ContainerModelBuilder(false, ContainerModelBuilder.Networking.enable)
.build(deployState, vespaModel, null, root, containerElem);
ContainerCluster<?> cluster = model.getCluster();
generateDefaultSearchChains(cluster);
+ containerModels.add(model);
}
root.freezeModelTopology();
+ return containerModels;
}
- public static void createModel(MockRoot root, Element... containerElems) {
- createModel(root, DeployState.createTestState(), null, containerElems);
+ public static List<ContainerModel> createModel(MockRoot root, Element... containerElems) {
+ return createModel(root, DeployState.createTestState(), null, containerElems);
}
public static void createModel(MockRoot root, DeployLogger testLogger, Element... containerElems) {
@@ -80,16 +91,11 @@ public abstract class ContainerModelBuilderTestBase {
search.initializeSearchChains(Collections.emptyMap());
}
- @Before
- public void prepareTest() {
- root = new MockRoot("root");
- }
-
protected ComponentsConfig componentsConfig() {
return root.getConfig(ComponentsConfig.class, "default");
}
- protected ComponentsConfig.Components getComponent(ComponentsConfig componentsConfig, String id) {
+ protected ComponentsConfig.Components getComponentInConfig(ComponentsConfig componentsConfig, String id) {
for (ComponentsConfig.Components component : componentsConfig.components()) {
if (component.id().equals(id))
return component;
@@ -101,9 +107,21 @@ public abstract class ContainerModelBuilderTestBase {
return (ApplicationContainerCluster) root.getChildren().get(clusterId);
}
- public Component<?, ?> getContainerComponent(String clusterId, String componentId) {
+ public Component<?, ?> getComponent(String clusterId, String componentId) {
return getContainerCluster(clusterId).getComponentsMap().get(
ComponentId.fromString(componentId));
}
+ public Handler getHandler(String clusterId, String componentId) {
+ Component<?,?> component = getComponent(clusterId, componentId);
+ if (! (component instanceof Handler))
+ throw new RuntimeException("Component is not a handler: " + componentId);
+ return (Handler) component;
+ }
+
+ void assertComponentConfigured(ApplicationContainerCluster cluster, String componentId) {
+ Component<?, ?> component = cluster.getComponentsMap().get(ComponentId.fromString(componentId));
+ assertNotNull(component);
+ }
+
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java
index 77681489dac..e8703f57fe3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java
@@ -1,14 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
-import com.yahoo.config.docproc.DocprocConfig;
import com.yahoo.config.docproc.SchemamappingConfig;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.container.ComponentsConfig;
import com.yahoo.container.core.ChainsConfig;
import com.yahoo.container.jdisc.ContainerMbusConfig;
-import com.yahoo.document.config.DocumentmanagerConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.HostPorts;
import com.yahoo.vespa.model.container.ApplicationContainer;
@@ -17,36 +15,30 @@ import com.yahoo.vespa.model.container.ContainerModel;
import com.yahoo.vespa.model.container.docproc.DocprocChain;
import com.yahoo.vespa.model.container.docproc.DocumentProcessor;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
+import static org.junit.jupiter.api.Assertions.*;
/**
- * @author einarmr
+ * @author Einar M R Rosenvinge
* @author gjoranv
- * @since 5.1.9
*/
public class DocprocBuilderTest extends DomBuilderTest {
private ApplicationContainerCluster cluster;
- private DocumentmanagerConfig documentmanagerConfig;
private ContainerMbusConfig containerMbusConfig;
private ComponentsConfig componentsConfig;
private ChainsConfig chainsConfig;
private SchemamappingConfig schemamappingConfig;
- private DocprocConfig docprocConfig;
private QrStartConfig qrStartConfig;
- @Before
+ @BeforeEach
public void setupCluster() {
ContainerModel model = new ContainerModelBuilder(false, Networking.disable).build(DeployState.createTestState(), null, null, root, servicesXml());
cluster = (ApplicationContainerCluster) model.getCluster();
@@ -58,10 +50,8 @@ public class DocprocBuilderTest extends DomBuilderTest {
chainsConfig = root.getConfig(ChainsConfig.class,
cluster.getConfigId() + "/component/com.yahoo.docproc.jdisc.DocumentProcessingHandler");
- documentmanagerConfig = root.getConfig(DocumentmanagerConfig.class, cluster.getConfigId());
schemamappingConfig = root.getConfig(SchemamappingConfig.class, cluster.getContainers().get(0).getConfigId());
qrStartConfig = root.getConfig(QrStartConfig.class, cluster.getConfigId());
- docprocConfig = root.getConfig(DocprocConfig.class, cluster.getConfigId());
}
private Element servicesXml() {
@@ -70,7 +60,7 @@ public class DocprocBuilderTest extends DomBuilderTest {
" <nodes>",
" <node hostalias='mockhost' baseport='1500' />",
" </nodes>",
- " <document-processing compressdocuments='true' preferlocalnode='true' numnodesperclient='2' maxqueuebytesize='100m' maxmessagesinqueue='300' maxqueuewait='200'>",
+ " <document-processing maxmessagesinqueue='300' maxqueuewait='200'>",
" <documentprocessor id='docproc1' class='com.yahoo.Docproc1' bundle='docproc1bundle'/>",
" <chain id='chein'>",
" <documentprocessor id='docproc2'/>",
@@ -79,13 +69,9 @@ public class DocprocBuilderTest extends DomBuilderTest {
"</container>");
}
- // TODO: re-enable assertions when the appropriate attributes are handled by the builder
@Test
- public void testDocprocCluster() {
+ void testDocprocCluster() {
assertEquals("banan", cluster.getName());
- assertTrue(cluster.getDocproc().isCompressDocuments());
- //assertTrue(cluster.getContainerDocproc().isPreferLocalNode());
- //assertEquals(2, cluster.getContainerDocproc().getNumNodesPerClient());
List<ApplicationContainer> services = cluster.getContainers();
assertEquals(1, services.size());
ApplicationContainer service = services.get(0);
@@ -105,20 +91,13 @@ public class DocprocBuilderTest extends DomBuilderTest {
}
@Test
- public void testDocumentManagerConfig() {
- assertTrue(documentmanagerConfig.enablecompression());
- }
-
- @Test
- public void testContainerMbusConfig() {
- assertTrue(containerMbusConfig.enabled());
+ void testContainerMbusConfig() {
assertTrue(containerMbusConfig.port() >= HostPorts.BASE_PORT);
assertEquals(300, containerMbusConfig.maxpendingcount());
- assertEquals(100, containerMbusConfig.maxpendingsize());
}
@Test
- public void testComponentsConfig() {
+ void testComponentsConfig() {
Map<String, ComponentsConfig.Components> components = new HashMap<>();
for (ComponentsConfig.Components component : componentsConfig.components()) {
System.err.println(component.id());
@@ -142,12 +121,12 @@ public class DocprocBuilderTest extends DomBuilderTest {
assertEquals("banan/docprocchains/chain/chein/component/docproc2", docproc2.configId());
assertEquals("docproc2", docproc2.classId());
assertEquals("docproc2", docproc2.bundle());
-/*
- ComponentsConfig.Components health = components.get("com.yahoo.container.jdisc.state.StateHandler");
- assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.id()));
- assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.classId());
- assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.bundle()));
-*/
+ /*
+ ComponentsConfig.Components health = components.get("com.yahoo.container.jdisc.state.StateHandler");
+ assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.id()));
+ assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.classId());
+ assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.bundle()));
+ */
ComponentsConfig.Components sourceClient = components.get("source@MbusClient");
assertNotNull(sourceClient);
assertEquals("com.yahoo.container.jdisc.messagebus.MbusClientProvider", sourceClient.classId());
@@ -160,7 +139,7 @@ public class DocprocBuilderTest extends DomBuilderTest {
}
@Test
- public void testChainsConfig() {
+ void testChainsConfig() {
Map<String, ChainsConfig.Components> components = new HashMap<>();
for (ChainsConfig.Components component : chainsConfig.components()) {
components.put(component.id(), component);
@@ -195,12 +174,12 @@ public class DocprocBuilderTest extends DomBuilderTest {
}
@Test
- public void testSchemaMappingConfig() {
+ void testSchemaMappingConfig() {
assertTrue(schemamappingConfig.fieldmapping().isEmpty());
}
@Test
- public void testQrStartConfig() {
+ void testQrStartConfig() {
QrStartConfig.Jvm jvm = qrStartConfig.jvm();
assertTrue(jvm.server());
assertTrue(jvm.verbosegc());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java
index 0dae86473c8..fcccdcf8f23 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.xml.embedder.EmbedderConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
@@ -24,8 +24,8 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class EmbedderTestCase {
@@ -33,7 +33,7 @@ public class EmbedderTestCase {
private static final String PREDEFINED_EMBEDDER_CONFIG = "embedding.bert-base-embedder";
@Test
- public void testGenericEmbedConfig() throws IOException, SAXException {
+ void testGenericEmbedConfig() throws IOException, SAXException {
String embedder = "<embedder id=\"test\" class=\"ai.vespa.test\" bundle=\"bundle\" def=\"def.name\">" +
" <val>123</val>" +
"</embedder>";
@@ -46,7 +46,7 @@ public class EmbedderTestCase {
}
@Test
- public void testGenericEmbedConfigRequiresBundleAndDef() throws IOException, SAXException {
+ void testGenericEmbedConfigRequiresBundleAndDef() throws IOException, SAXException {
assertTransformThrows("<embedder id=\"test\" class=\"ai.vespa.test\"></embedder>",
"Embedder configuration requires a bundle name");
assertTransformThrows("<embedder id=\"test\" class=\"ai.vespa.test\" bundle=\"bundle\"></embedder>",
@@ -54,7 +54,7 @@ public class EmbedderTestCase {
}
@Test
- public void testPredefinedEmbedConfigSelfHosted() throws IOException, SAXException {
+ void testPredefinedEmbedConfigSelfHosted() throws IOException, SAXException {
assertTransformThrows("<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\"></embedder>",
"Embedder '" + PREDEFINED_EMBEDDER_CLASS + "' requires options for [vocab, model]");
assertTransformThrows("<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\">" +
@@ -99,7 +99,7 @@ public class EmbedderTestCase {
}
@Test
- public void testPredefinedEmbedConfigCloud() throws IOException, SAXException {
+ void testPredefinedEmbedConfigCloud() throws IOException, SAXException {
String embedder = "<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\" />";
String component = "<component id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\" bundle=\"model-integration\">" +
" <config name=\"" + PREDEFINED_EMBEDDER_CONFIG + "\">" +
@@ -133,7 +133,7 @@ public class EmbedderTestCase {
}
@Test
- public void testEmbedConfig() throws Exception {
+ void testEmbedConfig() throws Exception {
final String emptyPathFileName = "services.xml";
Path applicationDir = Path.fromString("src/test/cfg/application/embed/");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java
new file mode 100644
index 00000000000..291a5f21305
--- /dev/null
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java
@@ -0,0 +1,115 @@
+package com.yahoo.vespa.model.container.xml;
+
+import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
+import com.yahoo.container.ComponentsConfig;
+import com.yahoo.container.jdisc.JdiscBindingsConfig;
+import com.yahoo.container.usability.BindingsOverviewHandler;
+import com.yahoo.vespa.model.container.ApplicationContainerCluster;
+import com.yahoo.vespa.model.container.component.Component;
+import com.yahoo.vespa.model.container.component.Handler;
+import org.junit.jupiter.api.Test;
+import org.w3c.dom.Element;
+
+import static com.yahoo.vespa.model.container.ContainerCluster.ROOT_HANDLER_BINDING;
+import static com.yahoo.vespa.model.container.ContainerCluster.STATE_HANDLER_BINDING_1;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.hasItem;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests for container model building with custom handlers.
+ *
+ * @author gjoranv
+ */
+public class HandlerBuilderTest extends ContainerModelBuilderTestBase {
+
+ @Test
+ void handlers_are_included_in_components_config() {
+ createClusterWithJDiscHandler();
+ assertThat(componentsConfig().toString(), containsString(".id \"discHandler\""));
+ }
+
+ @Test
+ void handler_bindings_are_included_in_discBindings_config() {
+ createClusterWithJDiscHandler();
+ String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
+ assertThat(discBindingsConfig, containsString(".serverBindings[0] \"http://*/binding0\""));
+ assertThat(discBindingsConfig, containsString(".serverBindings[1] \"http://*/binding1\""));
+ }
+
+ @Test
+ void nested_components_are_injected_to_handlers() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container id='default' version='1.0'>",
+ " <handler id='myHandler'>",
+ " <component id='injected' />",
+ " </handler>",
+ "</container>");
+
+ createModel(root, clusterElem);
+ Component<?, ?> handler = getComponent("default", "myHandler");
+ assertThat(handler.getInjectedComponentIds(), hasItem("injected@myHandler"));
+ }
+
+ @Test
+ void default_root_handler_binding_can_be_stolen_by_user_configured_handler() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container id='default' version='1.0'>" +
+ " <handler id='userRootHandler'>" +
+ " <binding>" + ROOT_HANDLER_BINDING.patternString() + "</binding>" +
+ " </handler>" +
+ "</container>");
+ createModel(root, clusterElem);
+
+ // The handler is still set up.
+ ComponentsConfig.Components userRootHandler = getComponentInConfig(componentsConfig(), BindingsOverviewHandler.class.getName());
+ assertNotNull(userRootHandler);
+
+ // .. but it has no bindings
+ var discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default");
+ assertNull(discBindingsConfig.handlers(BindingsOverviewHandler.class.getName()));
+ }
+
+ @Test
+ void reserved_binding_cannot_be_stolen_by_user_configured_handler() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container id='default' version='1.0'>" +
+ " <handler id='userHandler'>" +
+ " <binding>" + STATE_HANDLER_BINDING_1.patternString() + "</binding>" +
+ " </handler>" +
+ "</container>");
+ try {
+ createModel(root, clusterElem);
+ fail("Expected exception when stealing a reserved binding.");
+ } catch (IllegalArgumentException e) {
+ assertThat(e.getMessage(), is("Binding 'http://*/state/v1' is a reserved Vespa binding " +
+ "and cannot be used by handler: userHandler"));
+ }
+ }
+
+ @Test
+ void custom_handler_gets_default_threadpool() {
+ createClusterWithJDiscHandler();
+ ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default");
+ Handler handler = cluster.getHandlers().stream()
+ .filter(h -> h.getComponentId().toString().equals("discHandler"))
+ .findAny().orElseThrow();
+
+ assertTrue(handler.getInjectedComponentIds().contains("threadpool@default-handler-common"));
+ }
+
+ private void createClusterWithJDiscHandler() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container id='default' version='1.0'>",
+ " <handler id='discHandler'>",
+ " <binding>http://*/binding0</binding>",
+ " <binding>http://*/binding1</binding>",
+ " </handler>",
+ "</container>");
+
+ createModel(root, clusterElem);
+ }
+
+}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java
index 73bef70910d..78269d00cf3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java
@@ -8,36 +8,36 @@ import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.container.core.identity.IdentityConfig;
import com.yahoo.vespa.model.container.IdentityProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
*/
public class IdentityBuilderTest extends ContainerModelBuilderTestBase {
@Test
- public void identity_config_produced_from_deployment_spec() {
+ void identity_config_produced_from_deployment_spec() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'><search /></container>");
String deploymentXml = "<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" +
- " <test/>\n" +
- " <prod>\n" +
- " <region active='true'>default</region>\n" +
- " </prod>\n" +
- "</deployment>\n";
+ " <test/>\n" +
+ " <prod>\n" +
+ " <region active='true'>default</region>\n" +
+ " </prod>\n" +
+ "</deployment>\n";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withDeploymentSpec(deploymentXml)
.build();
createModel(root, new DeployState.Builder()
- .properties(new TestProperties().setHostedVespa(true))
- .applicationPackage(applicationPackage)
- .build(),
- null,
- clusterElem);
+ .properties(new TestProperties().setHostedVespa(true))
+ .applicationPackage(applicationPackage)
+ .build(),
+ null,
+ clusterElem);
IdentityConfig identityConfig = root.getConfig(IdentityConfig.class, "default/component/" + IdentityProvider.CLASS);
assertEquals("domain", identityConfig.domain());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java
index 6cd0fa18c3d..8b1217758ab 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java
@@ -16,16 +16,14 @@ import com.yahoo.vespa.model.container.component.SimpleComponent;
import com.yahoo.vespa.model.container.http.ConnectorFactory;
import com.yahoo.vespa.model.container.http.JettyHttpServer;
import com.yahoo.vespa.model.container.http.ssl.ConfiguredFilebasedSslProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.io.StringReader;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author einarmr
@@ -34,19 +32,19 @@ import static org.junit.Assert.assertTrue;
public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBase {
@Test
- public void verify_that_overriding_connector_options_works() {
+ void verify_that_overriding_connector_options_works() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>\n" +
- " <http>\n" +
- " <server id='bananarama' port='4321'>\n" +
- " <config name='jdisc.http.connector'>\n" +
- " <requestHeaderSize>300000</requestHeaderSize>\n" +
- " <headerCacheSize>300000</headerCacheSize>\n" +
- " </config>\n" +
- " </server>\n" +
- " </http>\n" +
- nodesXml +
- "</container>\n"
+ " <http>\n" +
+ " <server id='bananarama' port='4321'>\n" +
+ " <config name='jdisc.http.connector'>\n" +
+ " <requestHeaderSize>300000</requestHeaderSize>\n" +
+ " <headerCacheSize>300000</headerCacheSize>\n" +
+ " </config>\n" +
+ " </server>\n" +
+ " </http>\n" +
+ nodesXml +
+ "</container>\n"
);
createModel(root, clusterElem);
ConnectorConfig cfg = root.getConfig(ConnectorConfig.class, "default/http/jdisc-jetty/bananarama");
@@ -55,7 +53,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verify_that_enabling_jetty_works() {
+ void verify_that_enabling_jetty_works() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
nodesXml +
@@ -66,24 +64,24 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verify_that_enabling_jetty_works_for_custom_http_servers() {
+ void verify_that_enabling_jetty_works_for_custom_http_servers() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
" <server port='9000' id='foo' />",
" </http>",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
assertJettyServerInConfig();
}
@Test
- public void verifyThatJettyHttpServerHasFilterBindingsProvider() {
+ void verifyThatJettyHttpServerHasFilterBindingsProvider() {
final Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
final ComponentsConfig.Components jettyHttpServerComponent = extractComponentByClassName(
@@ -100,14 +98,14 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verifyThatJettyHttpServerHasFilterBindingsProviderForCustomHttpServers() {
+ void verifyThatJettyHttpServerHasFilterBindingsProviderForCustomHttpServers() {
final Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
" <server port='9000' id='foo' />",
" </http>",
nodesXml,
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
final ComponentsConfig.Components jettyHttpServerComponent = extractComponentByClassName(
@@ -124,7 +122,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void ssl_element_generates_connector_config_and_injects_provider_component() {
+ void ssl_element_generates_connector_config_and_injects_provider_component() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
@@ -196,7 +194,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verify_tht_ssl_provider_configuration_configures_correct_config() {
+ void verify_tht_ssl_provider_configuration_configures_correct_config() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
@@ -220,7 +218,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verify_that_container_factory_sees_same_config(){
+ void verify_that_container_factory_sees_same_config() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
@@ -241,7 +239,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
}
@Test
- public void verify_that_container_setup_additional_tls4443(){
+ void verify_that_container_setup_additional_tls4443() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
@@ -257,14 +255,14 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas
"</container>");
String hostsxml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<hosts>\n" +
- " <host name=\"mockhost-1\">\n" +
- " <alias>mockhost1</alias>\n" +
- " </host>\n" +
- " <host name=\"mockhost-2\">\n" +
- " <alias>mockhost2</alias>\n" +
- " </host>\n" +
- "</hosts>\n";
+ "<hosts>\n" +
+ " <host name=\"mockhost-1\">\n" +
+ " <alias>mockhost1</alias>\n" +
+ " </host>\n" +
+ " <host name=\"mockhost-2\">\n" +
+ " <alias>mockhost2</alias>\n" +
+ " </host>\n" +
+ "</hosts>\n";
DeployState deployState = new DeployState.Builder()
.properties(
new TestProperties()
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java
index 146e383078e..3515bb7409e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java
@@ -12,7 +12,7 @@ import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ContainerCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
@@ -21,9 +21,7 @@ import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -32,7 +30,7 @@ import static org.junit.Assert.fail;
public class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
- public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
+ void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
@@ -57,14 +55,14 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void honours_jvm_gc_options() {
+ void honours_jvm_gc_options() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <search/>",
" <nodes jvm-gc-options='-XX:+UseG1GC'>",
" <node hostalias='mockhost'/>",
" </nodes>",
- "</container>" );
+ "</container>");
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
@@ -94,7 +92,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void ignores_jvmgcoptions_on_conflicting_jvmoptions() throws IOException, SAXException {
+ void ignores_jvmgcoptions_on_conflicting_jvmoptions() throws IOException, SAXException {
verifyIgnoreJvmGCOptions(false);
verifyIgnoreJvmGCOptions(true);
}
@@ -121,7 +119,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException {
+ void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException {
verifyJvmGCOptions(false, null, null, ContainerCluster.G1GC);
verifyJvmGCOptions(true, null, null, ContainerCluster.PARALLEL_GC);
verifyJvmGCOptions(true, "", null, ContainerCluster.PARALLEL_GC);
@@ -133,7 +131,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatValidJvmGcOptionsAreNotLogged() throws IOException, SAXException {
+ void requireThatValidJvmGcOptionsAreNotLogged() throws IOException, SAXException {
// Valid options, should not log anything
verifyLoggingOfJvmGcOptions(true, "-XX:+ParallelGCThreads=8");
verifyLoggingOfJvmGcOptions(true, "-XX:MaxTenuringThreshold=15"); // No + or - after colon
@@ -141,7 +139,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException {
+ void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true),
new TestLogger(),
@@ -164,11 +162,11 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
List<String> strings = Arrays.asList(invalidOptions.clone());
// Verify that nothing is logged if there are no invalid options
if (strings.isEmpty()) {
- assertEquals(logger.msgs.size() > 0 ? logger.msgs.get(0).getSecond() : "", 0, logger.msgs.size());
+ assertEquals(0, logger.msgs.size(), logger.msgs.size() > 0 ? logger.msgs.get(0).getSecond() : "");
return;
}
- assertTrue("Expected 1 or more log messages for invalid JM options, got none", logger.msgs.size() > 0);
+ assertTrue(logger.msgs.size() > 0, "Expected 1 or more log messages for invalid JM options, got none");
Pair<Level, String> firstOption = logger.msgs.get(0);
assertEquals(Level.WARNING, firstOption.getFirst());
@@ -200,7 +198,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatValidJvmOptionsAreNotLogged() throws IOException, SAXException {
+ void requireThatValidJvmOptionsAreNotLogged() throws IOException, SAXException {
// Valid options, should not log anything
verifyLoggingOfJvmOptions(true, "options", "-Xms2G");
verifyLoggingOfJvmOptions(true, "options", "-Xlog:gc");
@@ -210,12 +208,12 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase {
}
@Test
- public void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException {
+ void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true),
- new TestLogger(),
- "options",
- "-Xms2G foo bar");
+ new TestLogger(),
+ "options",
+ "-Xms2G foo bar");
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid or misplaced JVM options in services.xml: bar,foo"));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java
index c78c4d617ea..58b9462978f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java
@@ -12,14 +12,14 @@ import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
import com.yahoo.vespa.model.container.ApplicationContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -27,20 +27,20 @@ import static org.junit.Assert.assertEquals;
public class RoutingBuilderTest extends ContainerModelBuilderTestBase {
@Test
- public void setsRotationActiveAccordingToDeploymentSpec() throws IOException, SAXException {
+ void setsRotationActiveAccordingToDeploymentSpec() throws IOException, SAXException {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'><search /></container>");
String deploymentSpec = "<deployment>\n" +
- " <prod> \n" +
- " <region active='true'>us-north-1</region>\n" +
- " <parallel>\n" +
- " <region active='false'>us-north-2</region>\n" +
- " <region active='true'>us-north-3</region>\n" +
- " </parallel>\n" +
- " <region active='false'>us-north-4</region>\n" +
- " </prod>\n" +
- "</deployment>";
+ " <prod> \n" +
+ " <region active='true'>us-north-1</region>\n" +
+ " <parallel>\n" +
+ " <region active='false'>us-north-2</region>\n" +
+ " <region active='true'>us-north-3</region>\n" +
+ " </parallel>\n" +
+ " <region active='false'>us-north-4</region>\n" +
+ " </prod>\n" +
+ "</deployment>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withDeploymentSpec(deploymentSpec)
@@ -49,18 +49,21 @@ public class RoutingBuilderTest extends ContainerModelBuilderTestBase {
for (String region : Arrays.asList("us-north-1", "us-north-3")) {
ApplicationContainer container = getContainer(applicationPackage, region, clusterElem);
- assertEquals("Region " + region + " is active", "true",
- container.getServicePropertyString("activeRotation"));
+ assertEquals("true",
+ container.getServicePropertyString("activeRotation"),
+ "Region " + region + " is active");
}
for (String region : Arrays.asList("us-north-2", "us-north-4")) {
ApplicationContainer container = getContainer(applicationPackage, region, clusterElem);
- assertEquals("Region " + region + " is inactive", "false",
- container.getServicePropertyString("activeRotation"));
+ assertEquals("false",
+ container.getServicePropertyString("activeRotation"),
+ "Region " + region + " is inactive");
}
ApplicationContainer container = getContainer(applicationPackage, "unknown", clusterElem);
- assertEquals("Unknown region is inactive", "false",
- container.getServicePropertyString("activeRotation"));
+ assertEquals("false",
+ container.getServicePropertyString("activeRotation"),
+ "Unknown region is inactive");
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ApplicationBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java
index ca59e053a89..bd067fa3e63 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ApplicationBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java
@@ -8,52 +8,44 @@ import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.container.jdisc.JdiscBindingsConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
-import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.search.GUIHandler;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
-import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER;
import static com.yahoo.test.Matchers.hasItemWithMethod;
import static com.yahoo.vespa.model.container.search.ContainerSearch.QUERY_PROFILE_REGISTRY_CLASS;
import static org.hamcrest.MatcherAssert.assertThat;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author gjoranv
*/
-public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
+public class SearchBuilderTest extends ContainerModelBuilderTestBase {
private ChainsConfig chainsConfig() {
return root.getConfig(ChainsConfig.class, "default/component/com.yahoo.search.handler.SearchHandler");
}
@Test
- public void gui_search_handler_is_always_included_when_search_is_specified() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>",
- " <search />",
- nodesXml,
- "</container>");
-
- createModel(root, clusterElem);
+ void gui_search_handler_is_always_included_when_search_is_specified() {
+ createBasicSearchModel();
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertTrue(discBindingsConfig.contains(GUIHandler.BINDING_PATH));
- ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default");
+ ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default");
GUIHandler guiHandler = null;
- for (Handler<?> handler : cluster.getHandlers()) {
+ for (Handler handler : cluster.getHandlers()) {
if (handler instanceof GUIHandler) {
guiHandler = (GUIHandler) handler;
}
@@ -62,7 +54,7 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void search_handler_bindings_can_be_overridden() {
+ void search_handler_bindings_can_be_overridden() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <search>",
@@ -81,7 +73,7 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void search_handler_bindings_can_be_disabled() {
+ void search_handler_bindings_can_be_disabled() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <search>",
@@ -97,7 +89,7 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void search_handler_binding_can_be_stolen_by_user_configured_handler() {
+ void search_handler_binding_can_be_stolen_by_user_configured_handler() {
var myHandler = "replaces_search_handler";
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
@@ -115,16 +107,8 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
assertNull(discBindingsConfig.handlers(SearchHandler.HANDLER_CLASS));
}
- // TODO: remove test when all containers are named 'container'
@Test
- public void cluster_with_only_search_gets_qrserver_as_service_name() {
- createClusterWithOnlyDefaultChains();
- ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default");
- assertEquals(CONTAINER.serviceName, cluster.getContainers().get(0).getServiceName());
- }
-
- @Test
- public void empty_search_element_gives_default_chains() {
+ void empty_search_element_gives_default_chains() {
createClusterWithOnlyDefaultChains();
assertThat(chainsConfig().chains(), hasItemWithMethod("vespaPhases", "id"));
assertThat(chainsConfig().chains(), hasItemWithMethod("native", "id"));
@@ -132,9 +116,9 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void query_profiles_registry_component_is_added() {
+ void query_profiles_registry_component_is_added() {
createClusterWithOnlyDefaultChains();
- ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default");
+ ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default");
var queryProfileRegistryId = ComponentId.fromString(QUERY_PROFILE_REGISTRY_CLASS);
assertTrue(cluster.getComponentsMap().containsKey(queryProfileRegistryId));
}
@@ -152,7 +136,7 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void manually_setting_up_search_handler_is_forbidden() {
+ void manually_setting_up_search_handler_is_forbidden() {
try {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
@@ -169,73 +153,62 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void cluster_is_connected_to_content_clusters() {
+ void cluster_is_connected_to_content_clusters() {
String hosts = hostsXml();
String services = "" +
- "<services>"+
+ "<services>" +
" <admin version='2.0'>" +
" <adminserver hostalias='mockhost'/>" +
" </admin>" +
- " <container version='1.0' id='container'>"+
+ " <container version='1.0' id='container'>" +
" <search>" +
" <chain id='mychain' inherits='vespa'/>" +
" </search>" +
- " <nodes>"+
- " <node hostalias=\"mockhost\" />"+
- " </nodes>"+
- " </container>"+
+ " <nodes>" +
+ " <node hostalias=\"mockhost\" />" +
+ " </nodes>" +
+ " </container>" +
contentXml() +
"</services>";
VespaModel model = getVespaModelWithMusic(hosts, services);
- ContainerCluster cluster = model.getContainerClusters().get("container");
+ ApplicationContainerCluster cluster = model.getContainerClusters().get("container");
assertFalse(cluster.getSearchChains().localProviders().isEmpty());
}
@Test
- public void cluster_is_connected_to_search_clusters() {
+ void cluster_is_connected_to_search_clusters() {
String hosts = hostsXml();
String services = "" +
- "<services>"+
+ "<services>" +
" <admin version='2.0'>" +
" <adminserver hostalias='mockhost'/>" +
" </admin>" +
- " <container version='1.0' id='container'>"+
+ " <container version='1.0' id='container'>" +
" <search>" +
" <chain id='mychain' inherits='vespa'/>" +
" </search>" +
- " <nodes>"+
- " <node hostalias=\"mockhost\" />"+
- " </nodes>"+
- " </container>"+
+ " <nodes>" +
+ " <node hostalias=\"mockhost\" />" +
+ " </nodes>" +
+ " </container>" +
contentXml() +
"</services>";
VespaModel model = getVespaModelWithMusic(hosts, services);
- ContainerCluster cluster = model.getContainerClusters().get("container");
+ ApplicationContainerCluster cluster = model.getContainerClusters().get("container");
assertFalse(cluster.getSearchChains().localProviders().isEmpty());
}
@Test
- public void search_handler_has_dedicated_threadpool() {
- Element clusterElem = DomBuilderTest.parse(
- "<container id='default' version='1.0'>",
- " <search />",
- nodesXml,
- "</container>");
-
- createModel(root, clusterElem);
-
- ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default");
- Handler<?> searchHandler = cluster.getHandlers().stream()
- .filter(h -> h.getComponentId().toString().equals(SearchHandler.HANDLER_CLASS))
- .findAny()
- .get();
+ void search_handler_has_dedicated_threadpool() {
+ createBasicSearchModel();
+ Handler searchHandler = getHandler("default", SearchHandler.HANDLER_CLASS);
assertTrue(searchHandler.getInjectedComponentIds().contains("threadpool@search-handler"));
ContainerThreadpoolConfig config = root.getConfig(
@@ -246,7 +219,7 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
}
@Test
- public void threadpool_configuration_can_be_overridden() {
+ void threadpool_configuration_can_be_overridden() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <search>",
@@ -266,10 +239,30 @@ public class ApplicationBuilderTest extends ContainerModelBuilderTestBase {
assertEquals(10, config.queueSize());
}
+ @Test
+ void ExecutionFactory_gets_same_chains_config_as_SearchHandler() {
+ createBasicSearchModel();
+ Component<?, ?> executionFactory = ((SearchHandler) getComponent("default", SearchHandler.HANDLER_CLASS))
+ .getChildren().get(SearchHandler.EXECUTION_FACTORY_CLASS);
+
+ ChainsConfig executionFactoryChainsConfig = root.getConfig(ChainsConfig.class, executionFactory.getConfigId());
+ assertEquals(chainsConfig(), executionFactoryChainsConfig);
+ }
+
private VespaModel getVespaModelWithMusic(String hosts, String services) {
return new VespaModelCreatorWithMockPkg(hosts, services, ApplicationPackageUtils.generateSchemas("music")).create();
}
+ private void createBasicSearchModel() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container id='default' version='1.0'>",
+ " <search />",
+ nodesXml,
+ "</container>");
+
+ createModel(root, clusterElem);
+ }
+
private String hostsXml() {
return "" +
"<hosts> " +
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java
new file mode 100644
index 00000000000..80d95752c5e
--- /dev/null
+++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java
@@ -0,0 +1,127 @@
+package com.yahoo.vespa.model.container.xml;
+
+import com.yahoo.component.ComponentId;
+import com.yahoo.config.model.api.TenantSecretStore;
+import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
+import com.yahoo.config.model.deploy.DeployState;
+import com.yahoo.config.model.deploy.TestProperties;
+import com.yahoo.config.provision.Environment;
+import com.yahoo.config.provision.RegionName;
+import com.yahoo.config.provision.SystemName;
+import com.yahoo.config.provision.Zone;
+import com.yahoo.container.jdisc.secretstore.SecretStoreConfig;
+import com.yahoo.vespa.model.container.ApplicationContainerCluster;
+import com.yahoo.vespa.model.container.SecretStore;
+import org.junit.jupiter.api.Test;
+import org.w3c.dom.Element;
+
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * @author tokle
+ */
+public class SecretStoreTest extends ContainerModelBuilderTestBase {
+
+ @Test
+ void secret_store_can_be_set_up() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ " <secret-store type='oath-ckms'>",
+ " <group name='group1' environment='env1'/>",
+ " </secret-store>",
+ "</container>");
+ createModel(root, clusterElem);
+ SecretStore secretStore = getContainerCluster("container").getSecretStore().get();
+ assertEquals("group1", secretStore.getGroups().get(0).name);
+ assertEquals("env1", secretStore.getGroups().get(0).environment);
+ }
+
+ @Test
+ void cloud_secret_store_requires_configured_secret_store() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ " <secret-store type='cloud'>",
+ " <store id='store'>",
+ " <aws-parameter-store account='store1' region='eu-north-1'/>",
+ " </store>",
+ " </secret-store>",
+ "</container>");
+ try {
+ DeployState state = new DeployState.Builder()
+ .properties(new TestProperties().setHostedVespa(true))
+ .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
+ .build();
+ createModel(root, state, null, clusterElem);
+ fail("secret store not defined");
+ } catch (RuntimeException e) {
+ assertEquals("No configured secret store named store1", e.getMessage());
+ }
+ }
+
+
+ @Test
+ void cloud_secret_store_can_be_set_up() {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ " <secret-store type='cloud'>",
+ " <store id='store'>",
+ " <aws-parameter-store account='store1' region='eu-north-1'/>",
+ " </store>",
+ " </secret-store>",
+ "</container>");
+
+ DeployState state = new DeployState.Builder()
+ .properties(
+ new TestProperties()
+ .setHostedVespa(true)
+ .setTenantSecretStores(List.of(new TenantSecretStore("store1", "1234", "role", Optional.of("externalid")))))
+ .zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
+ .build();
+ createModel(root, state, null, clusterElem);
+
+ ApplicationContainerCluster container = getContainerCluster("container");
+ assertComponentConfigured(container, "com.yahoo.jdisc.cloud.aws.AwsParameterStore");
+ CloudSecretStore secretStore = (CloudSecretStore) container.getComponentsMap().get(ComponentId.fromString("com.yahoo.jdisc.cloud.aws.AwsParameterStore"));
+
+
+ SecretStoreConfig.Builder configBuilder = new SecretStoreConfig.Builder();
+ secretStore.getConfig(configBuilder);
+ SecretStoreConfig secretStoreConfig = configBuilder.build();
+
+ assertEquals(1, secretStoreConfig.awsParameterStores().size());
+ assertEquals("store1", secretStoreConfig.awsParameterStores().get(0).name());
+ }
+
+ @Test
+ void cloud_secret_store_fails_to_set_up_in_non_public_zone() {
+ try {
+ Element clusterElem = DomBuilderTest.parse(
+ "<container version='1.0'>",
+ " <secret-store type='cloud'>",
+ " <store id='store'>",
+ " <aws-parameter-store account='store1' region='eu-north-1'/>",
+ " </store>",
+ " </secret-store>",
+ "</container>");
+
+ DeployState state = new DeployState.Builder()
+ .properties(
+ new TestProperties()
+ .setHostedVespa(true)
+ .setTenantSecretStores(List.of(new TenantSecretStore("store1", "1234", "role", Optional.of("externalid")))))
+ .zone(new Zone(SystemName.main, Environment.prod, RegionName.defaultName()))
+ .build();
+ createModel(root, state, null, clusterElem);
+ } catch (RuntimeException e) {
+ assertEquals("Cloud secret store is not supported in non-public system, see the documentation",
+ e.getMessage());
+ return;
+ }
+ fail();
+ }
+
+}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java
index cf7cd07e440..14e6efe7dff 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java
@@ -5,15 +5,12 @@ import com.yahoo.config.model.api.ModelContext;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.text.XML;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author geirst
@@ -61,7 +58,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void content_node_limits_are_derived_from_cluster_controller_limits_if_not_set() {
+ void content_node_limits_are_derived_from_cluster_controller_limits_if_not_set() {
assertLimits(0.4, 0.7, 0.76, 0.85,
new Fixture().ctrlDisk(0.4).ctrlMemory(0.7));
assertLimits(0.4, 0.8, 0.76, 0.9,
@@ -71,7 +68,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void content_node_limits_can_be_set_explicit() {
+ void content_node_limits_can_be_set_explicit() {
assertLimits(0.4, 0.7, 0.9, 0.95,
new Fixture().ctrlDisk(0.4).ctrlMemory(0.7).nodeDisk(0.9).nodeMemory(0.95));
assertLimits(0.4, 0.8, 0.95, 0.9,
@@ -81,7 +78,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void cluster_controller_limits_are_equal_to_content_node_limits_minus_one_percent_if_not_set() {
+ void cluster_controller_limits_are_equal_to_content_node_limits_minus_one_percent_if_not_set() {
assertLimits(0.89, 0.94, 0.9, 0.95,
new Fixture().nodeDisk(0.9).nodeMemory(0.95));
assertLimits(0.89, 0.8, 0.9, 0.9,
@@ -93,7 +90,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void limits_are_derived_from_the_other_if_not_set() {
+ void limits_are_derived_from_the_other_if_not_set() {
assertLimits(0.6, 0.94, 0.84, 0.95,
new Fixture().ctrlDisk(0.6).nodeMemory(0.95));
assertLimits(0.89, 0.7, 0.9, 0.85,
@@ -101,13 +98,13 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void default_resource_limits_when_feed_block_is_enabled_in_distributor() {
+ void default_resource_limits_when_feed_block_is_enabled_in_distributor() {
assertLimits(0.75, 0.8, 0.9, 0.9,
new Fixture(true));
}
@Test
- public void hosted_exception_is_thrown_when_resource_limits_are_specified() {
+ void hosted_exception_is_thrown_when_resource_limits_are_specified() {
try {
hostedBuild();
fail();
@@ -117,7 +114,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void hosted_limits_from_feature_flag_are_used() {
+ void hosted_limits_from_feature_flag_are_used() {
TestProperties featureFlags = new TestProperties();
featureFlags.setResourceLimitDisk(0.85);
featureFlags.setResourceLimitMemory(0.90);
@@ -129,7 +126,7 @@ public class ClusterResourceLimitsTest {
}
@Test
- public void exception_is_thrown_when_resource_limits_are_out_of_range() {
+ void exception_is_thrown_when_resource_limits_are_out_of_range() {
TestProperties featureFlags = new TestProperties();
featureFlags.setResourceLimitDisk(1.1);
@@ -188,7 +185,7 @@ public class ClusterResourceLimitsTest {
if (expLimit == null) {
assertFalse(actLimit.isPresent());
} else {
- assertEquals(limitType + " limit not as expected", expLimit, actLimit.get(), 0.00001);
+ assertEquals(expLimit, actLimit.get(), 0.00001, limitType + " limit not as expected");
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java
index 03fcf8df213..ccff07109a7 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.model.content;
import com.yahoo.messagebus.routing.RouteSpec;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ContentBaseTest {
public static String getHosts() {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java
index 8c263e21a21..cfb2fceb60b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java
@@ -38,7 +38,7 @@ import com.yahoo.vespa.model.routing.DocumentProtocol;
import com.yahoo.vespa.model.routing.Routing;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -47,13 +47,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class ContentClusterTest extends ContentBaseTest {
@@ -66,41 +60,41 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testHierarchicRedundancy() {
+ void testHierarchicRedundancy() {
ContentCluster cc = parse("" +
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <engine>" +
- " <proton>" +
- " <searchable-copies>3</searchable-copies>" +
- " </proton>" +
- " </engine>" +
- " <redundancy>15</redundancy>\n" +
- " <group name='root' distribution-key='0'>" +
- " <distribution partitions='1|1|*'/>" +
- " <group name='g-1' distribution-key='0'>" +
- " <node hostalias='mockhost' distribution-key='0'/>" +
- " <node hostalias='mockhost' distribution-key='1'/>" +
- " <node hostalias='mockhost' distribution-key='2'/>" +
- " <node hostalias='mockhost' distribution-key='3'/>" +
- " <node hostalias='mockhost' distribution-key='4'/>" +
- " </group>" +
- " <group name='g-2' distribution-key='1'>" +
- " <node hostalias='mockhost' distribution-key='5'/>" +
- " <node hostalias='mockhost' distribution-key='6'/>" +
- " <node hostalias='mockhost' distribution-key='7'/>" +
- " <node hostalias='mockhost' distribution-key='8'/>" +
- " <node hostalias='mockhost' distribution-key='9'/>" +
- " </group>" +
- " <group name='g-3' distribution-key='1'>" +
- " <node hostalias='mockhost' distribution-key='10'/>" +
- " <node hostalias='mockhost' distribution-key='11'/>" +
- " <node hostalias='mockhost' distribution-key='12'/>" +
- " <node hostalias='mockhost' distribution-key='13'/>" +
- " <node hostalias='mockhost' distribution-key='14'/>" +
- " </group>" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <engine>" +
+ " <proton>" +
+ " <searchable-copies>3</searchable-copies>" +
+ " </proton>" +
+ " </engine>" +
+ " <redundancy>15</redundancy>\n" +
+ " <group name='root' distribution-key='0'>" +
+ " <distribution partitions='1|1|*'/>" +
+ " <group name='g-1' distribution-key='0'>" +
+ " <node hostalias='mockhost' distribution-key='0'/>" +
+ " <node hostalias='mockhost' distribution-key='1'/>" +
+ " <node hostalias='mockhost' distribution-key='2'/>" +
+ " <node hostalias='mockhost' distribution-key='3'/>" +
+ " <node hostalias='mockhost' distribution-key='4'/>" +
+ " </group>" +
+ " <group name='g-2' distribution-key='1'>" +
+ " <node hostalias='mockhost' distribution-key='5'/>" +
+ " <node hostalias='mockhost' distribution-key='6'/>" +
+ " <node hostalias='mockhost' distribution-key='7'/>" +
+ " <node hostalias='mockhost' distribution-key='8'/>" +
+ " <node hostalias='mockhost' distribution-key='9'/>" +
+ " </group>" +
+ " <group name='g-3' distribution-key='1'>" +
+ " <node hostalias='mockhost' distribution-key='10'/>" +
+ " <node hostalias='mockhost' distribution-key='11'/>" +
+ " <node hostalias='mockhost' distribution-key='12'/>" +
+ " <node hostalias='mockhost' distribution-key='13'/>" +
+ " <node hostalias='mockhost' distribution-key='14'/>" +
+ " </group>" +
+ " </group>" +
+ "</content>"
);
DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder();
cc.getConfig(distributionBuilder);
@@ -126,24 +120,24 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testRedundancy() {
+ void testRedundancy() {
ContentCluster cc = parse("" +
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <engine>" +
- " <proton>" +
- " <searchable-copies>3</searchable-copies>" +
- " </proton>" +
- " </engine>" +
- " <redundancy reply-after='4'>5</redundancy>\n" +
- " <group>" +
- " <node hostalias='mockhost' distribution-key='0'/>" +
- " <node hostalias='mockhost' distribution-key='1'/>" +
- " <node hostalias='mockhost' distribution-key='2'/>" +
- " <node hostalias='mockhost' distribution-key='3'/>" +
- " <node hostalias='mockhost' distribution-key='4'/>" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <engine>" +
+ " <proton>" +
+ " <searchable-copies>3</searchable-copies>" +
+ " </proton>" +
+ " </engine>" +
+ " <redundancy reply-after='4'>5</redundancy>\n" +
+ " <group>" +
+ " <node hostalias='mockhost' distribution-key='0'/>" +
+ " <node hostalias='mockhost' distribution-key='1'/>" +
+ " <node hostalias='mockhost' distribution-key='2'/>" +
+ " <node hostalias='mockhost' distribution-key='3'/>" +
+ " <node hostalias='mockhost' distribution-key='4'/>" +
+ " </group>" +
+ "</content>"
);
DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder();
cc.getConfig(distributionBuilder);
@@ -167,32 +161,32 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testNoId() {
+ void testNoId() {
ContentCluster c = parse(
- "<content version=\"1.0\">\n" +
- " <redundancy>1</redundancy>\n" +
- " <documents/>" +
- " <redundancy reply-after=\"4\">5</redundancy>\n" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\">\n" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents/>" +
+ " <redundancy reply-after=\"4\">5</redundancy>\n" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" +
+ " </group>" +
+ "</content>"
);
assertEquals("content", c.getName());
}
@Test
- public void testRedundancyDefaults() {
+ void testRedundancyDefaults() {
ContentCluster cc = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>" +
- " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" +
- " <node hostalias=\"mockhost\" distribution-key=\"1\"/>\"" +
- " <node hostalias=\"mockhost\" distribution-key=\"2\"/>\"" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>" +
+ " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" +
+ " <node hostalias=\"mockhost\" distribution-key=\"1\"/>\"" +
+ " <node hostalias=\"mockhost\" distribution-key=\"2\"/>\"" +
+ " </group>" +
+ "</content>"
);
DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder();
@@ -209,41 +203,41 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testEndToEnd() {
+ void testEndToEnd() {
String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<services>\n" +
- "\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"configserver\" />\n" +
- " <logserver hostalias=\"logserver\" />\n" +
- " <slobroks>\n" +
- " <slobrok hostalias=\"configserver\" />\n" +
- " <slobrok hostalias=\"logserver\" />\n" +
- " </slobroks>\n" +
- " <cluster-controllers>\n" +
- " <cluster-controller hostalias=\"configserver\"/>" +
- " <cluster-controller hostalias=\"configserver2\"/>" +
- " <cluster-controller hostalias=\"configserver3\"/>" +
- " </cluster-controllers>\n" +
- " </admin>\n" +
- " <content version='1.0' id='bar'>" +
- " <redundancy>1</redundancy>\n" +
- " <documents>" +
- " <document type=\"type1\" mode=\"index\"/>\n" +
- " <document type=\"type2\" mode=\"index\"/>\n" +
- " </documents>\n" +
- " <group>" +
- " <node hostalias='node0' distribution-key='0' />" +
- " </group>" +
- " <tuning>" +
- " <cluster-controller>\n" +
- " <init-progress-time>34567</init-progress-time>" +
- " </cluster-controller>" +
- " </tuning>" +
- " </content>" +
- "\n" +
- "</services>";
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
+ "<services>\n" +
+ "\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"configserver\" />\n" +
+ " <logserver hostalias=\"logserver\" />\n" +
+ " <slobroks>\n" +
+ " <slobrok hostalias=\"configserver\" />\n" +
+ " <slobrok hostalias=\"logserver\" />\n" +
+ " </slobroks>\n" +
+ " <cluster-controllers>\n" +
+ " <cluster-controller hostalias=\"configserver\"/>" +
+ " <cluster-controller hostalias=\"configserver2\"/>" +
+ " <cluster-controller hostalias=\"configserver3\"/>" +
+ " </cluster-controllers>\n" +
+ " </admin>\n" +
+ " <content version='1.0' id='bar'>" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>" +
+ " <document type=\"type1\" mode=\"index\"/>\n" +
+ " <document type=\"type2\" mode=\"index\"/>\n" +
+ " </documents>\n" +
+ " <group>" +
+ " <node hostalias='node0' distribution-key='0' />" +
+ " </group>" +
+ " <tuning>" +
+ " <cluster-controller>\n" +
+ " <init-progress-time>34567</init-progress-time>" +
+ " </cluster-controller>" +
+ " </tuning>" +
+ " </content>" +
+ "\n" +
+ "</services>";
List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2");
VespaModel model = new VespaModelCreatorWithMockPkg(null, xml, sds).create();
@@ -294,7 +288,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testEndToEndOneNode() {
+ void testEndToEndOneNode() {
VespaModel model = createEnd2EndOneNode(new TestProperties());
assertEquals(1, model.getContentClusters().get("storage").getDocumentDefinitions().size());
@@ -303,34 +297,34 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testSearchTuning() {
+ void testSearchTuning() {
String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<services>\n" +
- "\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"node0\" />\n" +
- " <cluster-controllers>\n" +
- " <cluster-controller hostalias=\"node0\"/>" +
- " </cluster-controllers>\n" +
- " </admin>\n" +
- " <content version='1.0' id='bar'>" +
- " <redundancy>1</redundancy>\n" +
- " <documents>" +
- " <document type=\"type1\" mode='index'/>\n" +
- " <document type=\"type2\" mode='index'/>\n" +
- " </documents>\n" +
- " <group>" +
- " <node hostalias='node0' distribution-key='0'/>" +
- " </group>" +
- " <tuning>\n" +
- " <cluster-controller>" +
- " <init-progress-time>34567</init-progress-time>" +
- " </cluster-controller>" +
- " </tuning>" +
- " </content>" +
- "\n" +
- "</services>";
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
+ "<services>\n" +
+ "\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"node0\" />\n" +
+ " <cluster-controllers>\n" +
+ " <cluster-controller hostalias=\"node0\"/>" +
+ " </cluster-controllers>\n" +
+ " </admin>\n" +
+ " <content version='1.0' id='bar'>" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>" +
+ " <document type=\"type1\" mode='index'/>\n" +
+ " <document type=\"type2\" mode='index'/>\n" +
+ " </documents>\n" +
+ " <group>" +
+ " <node hostalias='node0' distribution-key='0'/>" +
+ " </group>" +
+ " <tuning>\n" +
+ " <cluster-controller>" +
+ " <init-progress-time>34567</init-progress-time>" +
+ " </cluster-controller>" +
+ " </tuning>" +
+ " </content>" +
+ "\n" +
+ "</services>";
List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2");
VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), xml, sds).create();
@@ -353,66 +347,68 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testRedundancyRequired() {
+ void testRedundancyRequired() {
String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<services>\n" +
- "\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"node0\" />\n" +
- " </admin>\n" +
- " <content version='1.0' id='bar'>" +
- " <documents>" +
- " <document type=\"type1\" mode='index'/>\n" +
- " </documents>\n" +
- " <group>\n" +
- " <node hostalias='node0' distribution-key='0'/>\n" +
- " </group>\n" +
- " </content>\n" +
- "</services>\n";
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
+ "<services>\n" +
+ "\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"node0\" />\n" +
+ " </admin>\n" +
+ " <content version='1.0' id='bar'>" +
+ " <documents>" +
+ " <document type=\"type1\" mode='index'/>\n" +
+ " </documents>\n" +
+ " <group>\n" +
+ " <node hostalias='node0' distribution-key='0'/>\n" +
+ " </group>\n" +
+ " </content>\n" +
+ "</services>\n";
List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2");
- try{
+ try {
new VespaModelCreatorWithMockPkg(getHosts(), xml, sds).create();
fail("Deploying without redundancy should fail");
} catch (IllegalArgumentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("missing required element \"redundancy\""));
+ assertTrue(e.getMessage().contains("missing required element \"redundancy\""), e.getMessage());
}
}
@Test
- public void testRedundancyFinalLessThanInitial() {
+ void testRedundancyFinalLessThanInitial() {
try {
parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <redundancy reply-after=\"4\">2</redundancy>\n" +
- " <group>" +
- " <node hostalias='node0' distribution-key='0' />" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <redundancy reply-after=\"4\">2</redundancy>\n" +
+ " <group>" +
+ " <node hostalias='node0' distribution-key='0' />" +
+ " </group>" +
+ "</content>"
);
fail("no exception thrown");
- } catch (Exception e) { /* ignore */ }
+ } catch (Exception e) { /* ignore */
+ }
}
@Test
- public void testReadyTooHigh() {
+ void testReadyTooHigh() {
try {
parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <engine>" +
- " <proton>" +
- " <searchable-copies>3</searchable-copies>" +
- " </proton>" +
- " </engine>" +
- " <redundancy>2</redundancy>\n" +
- " <group>" +
- " <node hostalias='node0' distribution-key='0' />" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <engine>" +
+ " <proton>" +
+ " <searchable-copies>3</searchable-copies>" +
+ " </proton>" +
+ " </engine>" +
+ " <redundancy>2</redundancy>\n" +
+ " <group>" +
+ " <node hostalias='node0' distribution-key='0' />" +
+ " </group>" +
+ "</content>"
);
fail("no exception thrown");
- } catch (Exception e) { /* ignore */ }
+ } catch (Exception e) { /* ignore */
+ }
}
FleetcontrollerConfig getFleetControllerConfig(String xml) {
@@ -425,16 +421,16 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testFleetControllerOverride()
+ void testFleetControllerOverride()
{
{
FleetcontrollerConfig config = getFleetControllerConfig(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
assertEquals(0, config.min_storage_up_ratio(), 0.01);
@@ -445,17 +441,17 @@ public class ContentClusterTest extends ContentBaseTest {
{
FleetcontrollerConfig config = getFleetControllerConfig(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"2\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"3\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"4\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"5\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"2\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"3\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"4\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"5\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
assertNotSame(0, config.min_storage_up_ratio());
@@ -463,65 +459,65 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testImplicitDistributionBits()
+ void testImplicitDistributionBits()
{
ContentCluster cluster = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
assertDistributionBitsInConfig(cluster, 8);
cluster = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
assertDistributionBitsInConfig(cluster, 8);
}
@Test
- public void testExplicitDistributionBits()
+ void testExplicitDistributionBits()
{
ContentCluster cluster = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- " <tuning>\n" +
- " <distribution type=\"strict\"/>\n" +
- " </tuning>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ " <tuning>\n" +
+ " <distribution type=\"strict\"/>\n" +
+ " </tuning>\n" +
+ "</content>"
);
assertDistributionBitsInConfig(cluster, 8);
cluster = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- " <tuning>\n" +
- " <distribution type=\"loose\"/>\n" +
- " </tuning>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ " <tuning>\n" +
+ " <distribution type=\"loose\"/>\n" +
+ " </tuning>\n" +
+ "</content>"
);
assertDistributionBitsInConfig(cluster, 8);
}
@Test
- public void testZoneDependentDistributionBits() throws Exception {
+ void testZoneDependentDistributionBits() throws Exception {
String xml = new ContentClusterBuilder().docTypes("test").getXml();
ContentCluster prodWith16Bits = createWithZone(xml, new Zone(Environment.prod, RegionName.from("us-east-3")));
@@ -532,19 +528,19 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testGenerateSearchNodes()
+ void testGenerateSearchNodes()
{
ContentCluster cluster = parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <engine>" +
- " <proton/>" +
- " </engine>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <engine>" +
+ " <proton/>" +
+ " </engine>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
{
@@ -563,19 +559,19 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testAlternativeNodeSyntax()
+ void testAlternativeNodeSyntax()
{
ContentCluster cluster = parse(
- "<content version=\"1.0\" id=\"test\">\n" +
- " <documents/>" +
- " <engine>" +
- " <proton/>" +
- " </engine>" +
- " <nodes>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
- " </nodes>\n" +
- "</content>"
+ "<content version=\"1.0\" id=\"test\">\n" +
+ " <documents/>" +
+ " <engine>" +
+ " <proton/>" +
+ " </engine>" +
+ " <nodes>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
+ " </nodes>\n" +
+ "</content>"
);
DistributionConfig.Builder bob = new DistributionConfig.Builder();
@@ -597,16 +593,16 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testReadyWhenInitialOne() {
+ void testReadyWhenInitialOne() {
StorDistributionConfig.Builder builder = new StorDistributionConfig.Builder();
parse(
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <redundancy>1</redundancy>\n" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
- " </group>" +
- "</content>"
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <documents/>" +
+ " <redundancy>1</redundancy>\n" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
+ " </group>" +
+ "</content>"
).getConfig(builder);
StorDistributionConfig config = new StorDistributionConfig(builder);
@@ -651,21 +647,21 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testProviders() {
+ void testProviders() {
testProvider("proton", StorServerConfig.Persistence_provider.Type.RPC);
testProvider("dummy", StorServerConfig.Persistence_provider.Type.DUMMY);
}
@Test
- public void testMetrics() {
+ void testMetrics() {
MetricsmanagerConfig.Builder builder = new MetricsmanagerConfig.Builder();
ContentCluster cluster = parse("<content version=\"1.0\" id=\"storage\">\n" +
- " <documents/>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
- " </group>\n" +
- "</content>"
+ " <documents/>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
+ " </group>\n" +
+ "</content>"
);
cluster.getConfig(builder);
@@ -715,24 +711,24 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testConfiguredMetrics() {
+ void testConfiguredMetrics() {
String xml = "" +
- "<services>" +
- "<content version=\"1.0\" id=\"storage\">\n" +
- " <redundancy>1</redundancy>\n" +
- " <documents>" +
- " <document type=\"type1\" mode='index'/>\n" +
- " <document type=\"type2\" mode='index'/>\n" +
- " </documents>" +
- " <group>\n" +
- " <node distribution-key=\"0\" hostalias=\"node0\"/>\n" +
- " </group>\n" +
- "</content>" +
- "<admin version=\"2.0\">" +
- " <logserver hostalias=\"node0\"/>" +
- " <adminserver hostalias=\"node0\"/>" +
- "</admin>" +
- "</services>";
+ "<services>" +
+ "<content version=\"1.0\" id=\"storage\">\n" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>" +
+ " <document type=\"type1\" mode='index'/>\n" +
+ " <document type=\"type2\" mode='index'/>\n" +
+ " </documents>" +
+ " <group>\n" +
+ " <node distribution-key=\"0\" hostalias=\"node0\"/>\n" +
+ " </group>\n" +
+ "</content>" +
+ "<admin version=\"2.0\">" +
+ " <logserver hostalias=\"node0\"/>" +
+ " <adminserver hostalias=\"node0\"/>" +
+ "</admin>" +
+ "</services>";
List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2");
@@ -745,25 +741,25 @@ public class ContentClusterTest extends ContentBaseTest {
String expected =
"[vds.filestor.allthreads.put\n" +
- "vds.filestor.allthreads.get\n" +
- "vds.filestor.allthreads.remove\n" +
- "vds.filestor.allthreads.update\n" +
- "vds.datastored.alldisks.docs\n" +
- "vds.datastored.alldisks.bytes\n" +
- "vds.filestor.queuesize\n" +
- "vds.filestor.averagequeuewait\n" +
- "vds.visitor.cv_queuewaittime\n" +
- "vds.visitor.allthreads.averagequeuewait\n" +
- "vds.visitor.allthreads.averagevisitorlifetime\n" +
- "vds.visitor.allthreads.created]";
+ "vds.filestor.allthreads.get\n" +
+ "vds.filestor.allthreads.remove\n" +
+ "vds.filestor.allthreads.update\n" +
+ "vds.datastored.alldisks.docs\n" +
+ "vds.datastored.alldisks.bytes\n" +
+ "vds.filestor.queuesize\n" +
+ "vds.filestor.averagequeuewait\n" +
+ "vds.visitor.cv_queuewaittime\n" +
+ "vds.visitor.allthreads.averagequeuewait\n" +
+ "vds.visitor.allthreads.averagevisitorlifetime\n" +
+ "vds.visitor.allthreads.created]";
String actual = getConsumer("log", config).addedmetrics().toString().replaceAll(", ", "\n");
assertEquals(expected, actual);
assertEquals("[logdefault]", getConsumer("log", config).tags().toString());
expected =
"[vds.datastored.alldisks.docs\n" +
- "vds.datastored.alldisks.bytes\n" +
- "vds.datastored.alldisks.buckets\n" +
- "vds.datastored.bucket_space.buckets_total]";
+ "vds.datastored.alldisks.bytes\n" +
+ "vds.datastored.alldisks.buckets\n" +
+ "vds.datastored.bucket_space.buckets_total]";
actual = getConsumer("fleetcontroller", config).addedmetrics().toString().replaceAll(", ", "\n");
assertEquals(expected, actual);
}
@@ -778,22 +774,22 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void flush_on_shutdown_is_default_on_for_non_hosted() throws Exception {
+ void flush_on_shutdown_is_default_on_for_non_hosted() throws Exception {
assertPrepareRestartCommand(createOneNodeCluster(false));
}
@Test
- public void flush_on_shutdown_can_be_turned_off_for_non_hosted() throws Exception {
+ void flush_on_shutdown_can_be_turned_off_for_non_hosted() throws Exception {
assertNoPreShutdownCommand(createClusterWithFlushOnShutdownOverride(false, false));
}
@Test
- public void flush_on_shutdown_is_default_on_for_hosted() throws Exception {
+ void flush_on_shutdown_is_default_on_for_hosted() throws Exception {
assertPrepareRestartCommand(createOneNodeCluster(true));
}
@Test
- public void flush_on_shutdown_can_be_turned_on_for_hosted() throws Exception {
+ void flush_on_shutdown_can_be_turned_on_for_hosted() throws Exception {
assertPrepareRestartCommand(createClusterWithFlushOnShutdownOverride(true, true));
}
@@ -861,16 +857,16 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void reserved_document_name_throws_exception() {
+ void reserved_document_name_throws_exception() {
String xml = "<content version=\"1.0\" id=\"storage\">" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document type=\"true\" mode=\"index\"/>" +
- " </documents>" +
- " <group>" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
- " </group>" +
- "</content>";
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document type=\"true\" mode=\"index\"/>" +
+ " </documents>" +
+ " <group>" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
+ " </group>" +
+ "</content>";
List<String> sds = ApplicationPackageUtils.generateSchemas("true");
try {
@@ -929,7 +925,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void all_clusters_bucket_spaces_config_contains_mappings_across_all_clusters() {
+ void all_clusters_bucket_spaces_config_contains_mappings_across_all_clusters() {
VespaModel model = createDualContentCluster();
AllClustersBucketSpacesConfig.Builder builder = new AllClustersBucketSpacesConfig.Builder();
model.getConfig(builder, "client");
@@ -940,8 +936,9 @@ public class ContentClusterTest extends ContentBaseTest {
assertClusterHasBucketSpaceMappings(config, "foo_c", Arrays.asList("bunnies", "hares"), Collections.emptyList());
assertClusterHasBucketSpaceMappings(config, "bar_c", Collections.emptyList(), Collections.singletonList("rabbits"));
}
+
@Test
- public void test_routing_with_multiple_clusters() {
+ void test_routing_with_multiple_clusters() {
VespaModel model = createDualContentCluster();
Routing routing = model.getRouting();
assertNotNull(routing);
@@ -1004,7 +1001,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void default_topKprobability_controlled_by_properties() {
+ void default_topKprobability_controlled_by_properties() {
verifyTopKProbabilityPropertiesControl();
}
@@ -1019,7 +1016,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void default_distributor_three_phase_update_config_controlled_by_properties() {
+ void default_distributor_three_phase_update_config_controlled_by_properties() {
assertFalse(resolveThreePhaseUpdateConfigWithFeatureFlag(false));
assertTrue(resolveThreePhaseUpdateConfigWithFeatureFlag(true));
}
@@ -1039,7 +1036,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void default_max_compact_buffers_config_controlled_by_properties() {
+ void default_max_compact_buffers_config_controlled_by_properties() {
assertEquals(1, resolveMaxCompactBuffers(OptionalInt.empty()));
assertEquals(2, resolveMaxCompactBuffers(OptionalInt.of(2)));
assertEquals(7, resolveMaxCompactBuffers(OptionalInt.of(7)));
@@ -1054,8 +1051,9 @@ public class ContentClusterTest extends ContentBaseTest {
ProtonConfig protonConfig = new ProtonConfig(protonBuilder);
return protonConfig.flush().memory().maxtlssize();
}
+
@Test
- public void verifyt_max_tls_size() throws Exception {
+ void verifyt_max_tls_size() throws Exception {
var flavor = new Flavor(new FlavorsConfig.Flavor(new FlavorsConfig.Flavor.Builder().name("test").minDiskAvailableGb(100)));
assertEquals(21474836480L, resolveMaxTLSSize(Optional.empty()));
assertEquals(2147483648L, resolveMaxTLSSize(Optional.of(flavor)));
@@ -1087,7 +1085,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void default_distributor_max_inhibited_group_activation_config_controlled_by_properties() throws Exception {
+ void default_distributor_max_inhibited_group_activation_config_controlled_by_properties() throws Exception {
assertEquals(0, resolveMaxInhibitedGroupsConfigWithFeatureFlag(0));
assertEquals(2, resolveMaxInhibitedGroupsConfigWithFeatureFlag(2));
}
@@ -1105,13 +1103,13 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void num_distributor_stripes_config_defaults_to_zero() throws Exception {
+ void num_distributor_stripes_config_defaults_to_zero() throws Exception {
// This triggers tuning when starting the distributor process, based on CPU core sampling on the node.
assertEquals(0, resolveNumDistributorStripesConfig(Optional.empty()));
}
@Test
- public void num_distributor_stripes_config_tuned_by_flavor() throws Exception {
+ void num_distributor_stripes_config_tuned_by_flavor() throws Exception {
assertEquals(1, resolveTunedNumDistributorStripesConfig(1));
assertEquals(1, resolveTunedNumDistributorStripesConfig(16));
assertEquals(2, resolveTunedNumDistributorStripesConfig(17));
@@ -1120,7 +1118,7 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void unordered_merge_chaining_config_controlled_by_properties() throws Exception {
+ void unordered_merge_chaining_config_controlled_by_properties() throws Exception {
assertFalse(resolveUnorderedMergeChainingConfig(Optional.of(false)));
assertTrue(resolveUnorderedMergeChainingConfig(Optional.empty()));
}
@@ -1137,60 +1135,60 @@ public class ContentClusterTest extends ContentBaseTest {
}
@Test
- public void testDedicatedClusterControllers() {
+ void testDedicatedClusterControllers() {
VespaModel noContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true)
- .setMultitenant(true),
- "<?xml version='1.0' encoding='UTF-8' ?>" +
- "<services version='1.0'>" +
- " <container id='default' version='1.0' />" +
- " </services>");
+ .setMultitenant(true),
+ "<?xml version='1.0' encoding='UTF-8' ?>" +
+ "<services version='1.0'>" +
+ " <container id='default' version='1.0' />" +
+ " </services>");
assertEquals(Map.of(), noContentModel.getContentClusters());
- assertNull("No cluster controller without content", noContentModel.getAdmin().getClusterControllers());
+ assertNull(noContentModel.getAdmin().getClusterControllers(), "No cluster controller without content");
VespaModel oneContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true)
- .setMultitenant(true),
- "<?xml version='1.0' encoding='UTF-8' ?>" +
- "<services version='1.0'>" +
- " <container id='default' version='1.0' />" +
- " <content id='storage' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1' />" +
- " </documents>" +
- " </content>" +
- " </services>");
- assertNotNull("Shared cluster controller with content", oneContentModel.getAdmin().getClusterControllers());
+ .setMultitenant(true),
+ "<?xml version='1.0' encoding='UTF-8' ?>" +
+ "<services version='1.0'>" +
+ " <container id='default' version='1.0' />" +
+ " <content id='storage' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1' />" +
+ " </documents>" +
+ " </content>" +
+ " </services>");
+ assertNotNull(oneContentModel.getAdmin().getClusterControllers(), "Shared cluster controller with content");
String twoContentServices = "<?xml version='1.0' encoding='UTF-8' ?>" +
- "<services version='1.0'>" +
- " <container id='default' version='1.0' />" +
- " <content id='storage' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1' />" +
- " </documents>" +
- " <tuning>" +
- " <cluster-controller>" +
- " <min-distributor-up-ratio>0.618</min-distributor-up-ratio>" +
- " </cluster-controller>" +
- " </tuning>" +
- " </content>" +
- " <content id='dev-null' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1' />" +
- " </documents>" +
- " <tuning>" +
- " <cluster-controller>" +
- " <min-distributor-up-ratio>0.418</min-distributor-up-ratio>" +
- " </cluster-controller>" +
- " </tuning>" +
- " </content>" +
- " </services>";
+ "<services version='1.0'>" +
+ " <container id='default' version='1.0' />" +
+ " <content id='storage' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1' />" +
+ " </documents>" +
+ " <tuning>" +
+ " <cluster-controller>" +
+ " <min-distributor-up-ratio>0.618</min-distributor-up-ratio>" +
+ " </cluster-controller>" +
+ " </tuning>" +
+ " </content>" +
+ " <content id='dev-null' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1' />" +
+ " </documents>" +
+ " <tuning>" +
+ " <cluster-controller>" +
+ " <min-distributor-up-ratio>0.418</min-distributor-up-ratio>" +
+ " </cluster-controller>" +
+ " </tuning>" +
+ " </content>" +
+ " </services>";
VespaModel twoContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true)
- .setMultitenant(true),
- twoContentServices);
- assertNotNull("Shared cluster controller with content", twoContentModel.getAdmin().getClusterControllers());
+ .setMultitenant(true),
+ twoContentServices);
+ assertNotNull(twoContentModel.getAdmin().getClusterControllers(), "Shared cluster controller with content");
ClusterControllerContainerCluster clusterControllers = twoContentModel.getAdmin().getClusterControllers();
@@ -1204,11 +1202,11 @@ public class ContentClusterTest extends ContentBaseTest {
assertEquals(0.418, devNullBuilder.build().min_distributor_up_ratio(), 1e-9);
assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.ReconfigurableVespaZooKeeperServer",
- clusterControllers);
+ clusterControllers);
assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.Reconfigurer",
- clusterControllers);
+ clusterControllers);
assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.VespaZooKeeperAdminImpl",
- clusterControllers);
+ clusterControllers);
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java
index 67260ce1f9d..da892934070 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java
@@ -12,7 +12,7 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterBuilder;
import com.yahoo.vespa.model.content.utils.DocType;
import com.yahoo.vespa.model.content.utils.SchemaBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -21,10 +21,7 @@ import java.util.List;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster;
import static com.yahoo.vespa.model.content.utils.SchemaBuilder.createSchemas;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for content search cluster.
@@ -99,51 +96,51 @@ public class ContentSchemaClusterTest {
}
@Test
- public void requireThatProtonInitializeThreadsIsSet() throws Exception {
+ void requireThatProtonInitializeThreadsIsSet() throws Exception {
assertEquals(2, getProtonConfig(createClusterWithOneDocumentType()).initialize().threads());
assertEquals(3, getProtonConfig(createClusterWithTwoDocumentType()).initialize().threads());
}
@Test
- public void requireThatProtonResourceLimitsCanBeSet() throws Exception {
+ void requireThatProtonResourceLimitsCanBeSet() throws Exception {
assertProtonResourceLimits(0.88, 0.77,
new ContentClusterBuilder().protonDiskLimit(0.88).protonMemoryLimit(0.77).getXml());
}
@Test
- public void requireThatOnlyDiskLimitCanBeSet() throws Exception {
+ void requireThatOnlyDiskLimitCanBeSet() throws Exception {
assertProtonResourceLimits(0.88, 0.9,
new ContentClusterBuilder().protonDiskLimit(0.88).getXml());
}
@Test
- public void requireThatOnlyMemoryLimitCanBeSet() throws Exception {
+ void requireThatOnlyMemoryLimitCanBeSet() throws Exception {
assertProtonResourceLimits(0.9, 0.77,
new ContentClusterBuilder().protonMemoryLimit(0.77).getXml());
}
@Test
- public void cluster_controller_resource_limits_can_be_set() throws Exception {
+ void cluster_controller_resource_limits_can_be_set() throws Exception {
assertClusterControllerResourceLimits(0.92, 0.93,
new ContentClusterBuilder().clusterControllerDiskLimit(0.92).clusterControllerMemoryLimit(0.93).getXml());
}
@Test
- public void resource_limits_are_derived_from_the_other_if_not_specified() throws Exception {
+ void resource_limits_are_derived_from_the_other_if_not_specified() throws Exception {
var cluster = createCluster(new ContentClusterBuilder().clusterControllerDiskLimit(0.5).protonMemoryLimit(0.95).getXml());
assertProtonResourceLimits(0.8, 0.95, cluster);
assertClusterControllerResourceLimits(0.5, 0.94, cluster);
}
@Test
- public void default_resource_limits_with_feed_block_in_distributor() throws Exception {
+ void default_resource_limits_with_feed_block_in_distributor() throws Exception {
var cluster = createCluster(new ContentClusterBuilder().getXml());
assertProtonResourceLimits(0.9, 0.9, cluster);
assertClusterControllerResourceLimits(0.75, 0.8, cluster);
}
@Test
- public void requireThatGloballyDistributedDocumentTypeIsTaggedAsSuch() throws Exception {
+ void requireThatGloballyDistributedDocumentTypeIsTaggedAsSuch() throws Exception {
ProtonConfig cfg = getProtonConfig(createClusterWithGlobalType());
assertEquals(2, cfg.documentdb().size());
assertDocumentDb("global", true, cfg.documentdb(0));
@@ -156,7 +153,7 @@ public class ContentSchemaClusterTest {
}
@Test
- public void require_that_document_types_with_references_are_topologically_sorted() throws Exception {
+ void require_that_document_types_with_references_are_topologically_sorted() throws Exception {
ProtonConfig cfg = getProtonConfig(createClusterWithThreeDocumentTypes());
assertEquals(3, cfg.documentdb().size());
assertDocumentDb("c", true, cfg.documentdb(0));
@@ -202,7 +199,7 @@ public class ContentSchemaClusterTest {
}
@Test
- public void require_that_document_types_belong_to_correct_bucket_spaces() throws Exception {
+ void require_that_document_types_belong_to_correct_bucket_spaces() throws Exception {
BucketspacesConfig config = getBucketspacesConfig(createClusterWithGlobalType());
assertEquals(2, config.documenttype().size());
assertDocumentType("global", "global", config.documenttype(0));
@@ -210,7 +207,7 @@ public class ContentSchemaClusterTest {
}
@Test
- public void bucket_space_config_builder_returns_correct_mappings() throws Exception {
+ void bucket_space_config_builder_returns_correct_mappings() throws Exception {
ContentCluster cluster = createClusterWithGlobalType();
BucketspacesConfig expected = getBucketspacesConfig(cluster);
AllClustersBucketSpacesConfig.Cluster actual = cluster.clusterBucketSpaceConfigBuilder().build();
@@ -223,13 +220,13 @@ public class ContentSchemaClusterTest {
}
@Test
- public void cluster_with_global_document_types_sets_cluster_controller_global_docs_config_option() throws Exception {
+ void cluster_with_global_document_types_sets_cluster_controller_global_docs_config_option() throws Exception {
ContentCluster cluster = createClusterWithGlobalType();
assertTrue(getFleetcontrollerConfig(cluster).cluster_has_global_document_types());
}
@Test
- public void cluster_without_global_document_types_unsets_cluster_controller_global_docs_config_option() throws Exception {
+ void cluster_without_global_document_types_unsets_cluster_controller_global_docs_config_option() throws Exception {
ContentCluster cluster = createClusterWithoutGlobalType();
assertFalse(getFleetcontrollerConfig(cluster).cluster_has_global_document_types());
}
@@ -241,21 +238,21 @@ public class ContentSchemaClusterTest {
}
@Test
- public void fsync_is_controllable() throws Exception {
+ void fsync_is_controllable() throws Exception {
assertTrue(getTlsConfig(createCluster(new ContentClusterBuilder().getXml())).usefsync());
assertTrue(getTlsConfig(createCluster(new ContentClusterBuilder().syncTransactionLog(true).getXml())).usefsync());
assertFalse(getTlsConfig(createCluster(new ContentClusterBuilder().syncTransactionLog(false).getXml())).usefsync());
}
@Test
- public void verifyDefaultDocStoreCompression() throws Exception {
+ void verifyDefaultDocStoreCompression() throws Exception {
ProtonConfig cfg = getProtonConfig(createCluster(new ContentClusterBuilder().getXml()));
assertEquals(3, cfg.summary().log().chunk().compression().level());
assertEquals(3, cfg.summary().log().compact().compression().level());
}
@Test
- public void verifyDefaultDiskBloatFactor() throws Exception {
+ void verifyDefaultDiskBloatFactor() throws Exception {
var defaultCfg = getProtonConfig(createCluster(new ContentClusterBuilder().getXml()));
assertEquals(0.25, defaultCfg.flush().memory().diskbloatfactor(), EPSILON);
assertEquals(0.25, defaultCfg.flush().memory().each().diskbloatfactor(), EPSILON);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java
index 952a0b945dd..ad17d6f385b 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Simon Thoresen Hult
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertNull;
public class ContentSchemaTest {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
ContentSearch search = new ContentSearch.Builder()
.setQueryTimeout(1.0)
.setVisibilityDelay(2.0)
@@ -22,7 +22,7 @@ public class ContentSchemaTest {
}
@Test
- public void requireThatDefaultsAreNull() {
+ void requireThatDefaultsAreNull() {
ContentSearch search = new ContentSearch.Builder().build();
assertNull(search.getQueryTimeout());
assertNull(search.getVisibilityDelay());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java
index c3a40946c06..cddbe267628 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java
@@ -1,11 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -13,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class DispatchTuningTest {
@Test
- public void requireThatAccessorWork() {
+ void requireThatAccessorWork() {
DispatchTuning dispatch = new DispatchTuning.Builder()
.setMaxHitsPerPartition(69)
.setDispatchPolicy("round-robin")
@@ -22,29 +21,30 @@ public class DispatchTuningTest {
.build();
assertEquals(69, dispatch.getMaxHitsPerPartition().intValue());
assertEquals(12.5, dispatch.getMinActiveDocsCoverage().doubleValue(), 0.0);
- assertTrue(DispatchTuning.DispatchPolicy.ROUNDROBIN == dispatch.getDispatchPolicy());
+ assertEquals(DispatchTuning.DispatchPolicy.ROUNDROBIN, dispatch.getDispatchPolicy());
assertEquals(18.3, dispatch.getTopkProbability(), 0.0);
}
+
@Test
- public void requireThatRandomDispatchWork() {
+ void requireThatRandomDispatchWork() {
DispatchTuning dispatch = new DispatchTuning.Builder()
.setDispatchPolicy("random")
.build();
- assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy());
+ assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy());
assertNull(dispatch.getMinActiveDocsCoverage());
}
@Test
- public void requireThatWeightedDispatchWork() {
+ void requireThatWeightedDispatchWork() {
DispatchTuning dispatch = new DispatchTuning.Builder()
.setDispatchPolicy("adaptive")
.build();
- assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy());
+ assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy());
assertNull(dispatch.getMinActiveDocsCoverage());
}
@Test
- public void requireThatDefaultsAreNull() {
+ void requireThatDefaultsAreNull() {
DispatchTuning dispatch = new DispatchTuning.Builder().build();
assertNull(dispatch.getMaxHitsPerPartition());
assertNull(dispatch.getDispatchPolicy());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java
index 635f799411b..06f78a1c68d 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java
@@ -9,13 +9,11 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
import com.yahoo.vespa.model.content.utils.DocType;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for content DistributorCluster.
@@ -37,14 +35,14 @@ public class DistributorTest {
}
@Test
- public void testBasics() {
+ void testBasics() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("<content id=\"foofighters\"><documents/>\n" +
- " <group>" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
- " </group>" +
- "</content>\n").
+ " <group>" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
+ " </group>" +
+ "</content>\n").
getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
@@ -53,7 +51,7 @@ public class DistributorTest {
}
@Test
- public void testRevertDefaultOffForSearch() {
+ void testRevertDefaultOffForSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
@@ -66,7 +64,7 @@ public class DistributorTest {
}
@Test
- public void testSplitAndJoin() {
+ void testSplitAndJoin() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
@@ -89,7 +87,7 @@ public class DistributorTest {
}
@Test
- public void testThatGroupsAreCountedInWhenComputingSplitBits() {
+ void testThatGroupsAreCountedInWhenComputingSplitBits() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
ContentCluster cluster = parseCluster("<cluster id=\"storage\">\n" +
" <documents/>" +
@@ -145,7 +143,7 @@ public class DistributorTest {
}
@Test
- public void testMaxMergesPerNode() {
+ void testMaxMergesPerNode() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
DistributorCluster dcluster = parse("<content id=\"storage\">\n" +
" <documents/>" +
@@ -159,30 +157,30 @@ public class DistributorTest {
builder = new StorDistributormanagerConfig.Builder();
dcluster = parse("<content id=\"storage\">\n" +
- " <documents/>" +
- " <tuning>\n" +
- " <merges max-nodes-per-merge=\"4\"/>\n" +
- " </tuning>\n" +
- " <group>" +
- " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
- " </group>" +
- "</content>");
+ " <documents/>" +
+ " <tuning>\n" +
+ " <merges max-nodes-per-merge=\"4\"/>\n" +
+ " </tuning>\n" +
+ " <group>" +
+ " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
+ " </group>" +
+ "</content>");
((ContentCluster) dcluster.getParent()).getConfig(builder);
conf = new StorDistributormanagerConfig(builder);
assertEquals(4, conf.maximum_nodes_per_merge());
}
@Test
- public void testGarbageCollectionSetExplicitly() {
+ void testGarbageCollectionSetExplicitly() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
- " <documents garbage-collection=\"true\">\n" +
- " <document type=\"music\"/>\n" +
- " </documents>\n" +
+ " <documents garbage-collection=\"true\">\n" +
+ " <document type=\"music\"/>\n" +
+ " </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
- "</cluster>").getConfig(builder);
+ "</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(3600, conf.garbagecollection().interval());
@@ -190,7 +188,7 @@ public class DistributorTest {
}
@Test
- public void testGarbageCollectionInterval() {
+ void testGarbageCollectionInterval() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents garbage-collection=\"true\" garbage-collection-interval=\"30\">\n" +
@@ -206,7 +204,7 @@ public class DistributorTest {
}
@Test
- public void testGarbageCollectionOffByDefault() {
+ void testGarbageCollectionOffByDefault() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents>\n" +
@@ -223,7 +221,7 @@ public class DistributorTest {
}
@Test
- public void testComplexGarbageCollectionSelectionForIndexedSearch() {
+ void testComplexGarbageCollectionSelectionForIndexedSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents garbage-collection=\"true\" selection=\"true\">" +
@@ -243,7 +241,7 @@ public class DistributorTest {
}
@Test
- public void testGarbageCollectionDisabledIfForced() {
+ void testGarbageCollectionDisabledIfForced() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents selection=\"true\" garbage-collection=\"false\" garbage-collection-interval=\"30\">\n" +
@@ -261,7 +259,7 @@ public class DistributorTest {
}
@Test
- public void testPortOverride() {
+ void testPortOverride() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" +
@@ -273,12 +271,11 @@ public class DistributorTest {
cluster.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
- assertTrue(config.mbus().dispatch_on_encode());
assertEquals(14066, config.rpcport());
}
@Test
- public void testCommunicationManagerDefaults() {
+ void testCommunicationManagerDefaults() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\">" +
@@ -290,13 +287,7 @@ public class DistributorTest {
cluster.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
- assertTrue(config.mbus().dispatch_on_encode());
- assertTrue(config.mbus().dispatch_on_decode());
- assertEquals(4, config.mbus().num_threads());
- assertEquals(StorCommunicationmanagerConfig.Mbus.Optimize_for.LATENCY, config.mbus().optimize_for());
- assertFalse(config.skip_thread());
- assertFalse(config.mbus().skip_request_thread());
- assertFalse(config.mbus().skip_reply_thread());
+ assertEquals(1, config.mbus().num_network_threads());
}
private StorDistributormanagerConfig clusterXmlToConfig(String xml) {
@@ -312,38 +303,38 @@ public class DistributorTest {
}
@Test
- public void bucket_activation_disabled_if_no_documents_in_indexed_mode() {
+ void bucket_activation_disabled_if_no_documents_in_indexed_mode() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music")));
assertTrue(config.disable_bucket_activation());
}
@Test
- public void bucket_activation_enabled_with_single_indexed_document() {
+ void bucket_activation_enabled_with_single_indexed_document() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music")));
assertFalse(config.disable_bucket_activation());
}
@Test
- public void bucket_activation_enabled_with_multiple_indexed_documents() {
+ void bucket_activation_enabled_with_multiple_indexed_documents() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music"),
- DocType.index("movies")));
+ DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
- public void bucket_activation_enabled_if_at_least_one_document_indexed() {
+ void bucket_activation_enabled_if_at_least_one_document_indexed() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music"),
- DocType.streaming("bunnies"),
- DocType.index("movies")));
+ DocType.streaming("bunnies"),
+ DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
- public void bucket_activation_disabled_for_single_streaming_type() {
+ void bucket_activation_disabled_for_single_streaming_type() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.streaming("music")));
assertTrue(config.disable_bucket_activation());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java
index f9fcb777408..1e6847a47be 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java
@@ -8,11 +8,11 @@ import com.yahoo.config.model.test.MockRoot;
import com.yahoo.text.XML;
import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class FleetControllerClusterTest {
@@ -36,7 +36,7 @@ public class FleetControllerClusterTest {
}
@Test
- public void testParameters() {
+ void testParameters() {
FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
@@ -65,7 +65,7 @@ public class FleetControllerClusterTest {
}
@Test
- public void testDurationParameters() {
+ void testDurationParameters() {
FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
@@ -82,7 +82,7 @@ public class FleetControllerClusterTest {
}
@Test
- public void min_node_ratio_per_group_tuning_config_is_propagated() {
+ void min_node_ratio_per_group_tuning_config_is_propagated() {
FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>\n" +
@@ -97,18 +97,18 @@ public class FleetControllerClusterTest {
}
@Test
- public void min_node_ratio_per_group_is_implicitly_zero_when_omitted() {
+ void min_node_ratio_per_group_is_implicitly_zero_when_omitted() {
var config = getConfigForBasicCluster();
assertEquals(0.0, config.min_node_ratio_per_group(), 0.01);
}
@Test
- public void default_cluster_feed_block_limits_are_set() {
+ void default_cluster_feed_block_limits_are_set() {
assertLimits(0.75, 0.8, getConfigForBasicCluster());
}
@Test
- public void resource_limits_can_be_set_in_tuning() {
+ void resource_limits_can_be_set_in_tuning() {
assertLimits(0.6, 0.7, getConfigForResourceLimitsTuning(0.6, 0.7));
assertLimits(0.6, 0.8, getConfigForResourceLimitsTuning(0.6, null));
assertLimits(0.75, 0.7, getConfigForResourceLimitsTuning(null, 0.7));
@@ -140,7 +140,7 @@ public class FleetControllerClusterTest {
}
@Test
- public void feature_flag_controls_min_node_ratio_per_group() {
+ void feature_flag_controls_min_node_ratio_per_group() {
verifyFeatureFlagControlsMinNodeRatioPerGroup(0.0, new TestProperties());
verifyFeatureFlagControlsMinNodeRatioPerGroup(0.3,
new TestProperties().setMinNodeRatioPerGroup(0.3));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java
index e6e8a02e951..9fcf426e2e8 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java
@@ -7,10 +7,10 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.storagecluster.StorageCluster;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -47,13 +47,13 @@ public class GenericConfigTest {
"</services>";
}
- @Before
+ @BeforeEach
public void getVespaModel() {
model = (new VespaModelCreatorWithMockPkg(ContentBaseTest.getHosts(), servicesXml(), ApplicationPackageUtils.generateSchemas("type1"))).create();
}
@Test
- public void config_override_on_root_is_visible_on_storage_cluster() {
+ void config_override_on_root_is_visible_on_storage_cluster() {
StorageCluster cluster = model.getContentClusters().get("storage").getStorageCluster();
StorFilestorConfig config = model.getConfig(StorFilestorConfig.class, cluster.getConfigId());
@@ -61,7 +61,7 @@ public class GenericConfigTest {
}
@Test
- public void config_override_on_root_is_visible_on_content_cluster() {
+ void config_override_on_root_is_visible_on_content_cluster() {
ContentCluster cluster = model.getContentClusters().get("storage");
StorFilestorConfig config = model.getConfig(StorFilestorConfig.class, cluster.getConfigId());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java
index a47d25ab391..4def4e0c10f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.model.content;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.HashSet;
@@ -14,8 +14,8 @@ import java.util.stream.Stream;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bjorncs
@@ -23,20 +23,20 @@ import static org.junit.Assert.fail;
public class GlobalDistributionValidatorTest {
@Test
- public void validation_succeeds_on_no_documents() {
+ void validation_succeeds_on_no_documents() {
new GlobalDistributionValidator()
.validate(emptyMap(), emptySet());
}
@Test
- public void validation_succeeds_on_no_global_documents() {
+ void validation_succeeds_on_no_global_documents() {
Fixture fixture = new Fixture()
.addNonGlobalDocument(createDocumentType("foo"));
validate(fixture);
}
@Test
- public void throws_exception_if_referenced_document_not_global() {
+ void throws_exception_if_referenced_document_not_global() {
NewDocumentType parent = createDocumentType("parent");
Fixture fixture = new Fixture()
.addNonGlobalDocument(parent)
@@ -51,7 +51,7 @@ public class GlobalDistributionValidatorTest {
}
@Test
- public void validation_succeeds_if_referenced_document_is_global() {
+ void validation_succeeds_if_referenced_document_is_global() {
NewDocumentType parent = createDocumentType("parent");
Fixture fixture = new Fixture()
.addGlobalDocument(parent)
@@ -60,7 +60,7 @@ public class GlobalDistributionValidatorTest {
}
@Test
- public void throws_exception_on_unknown_document() {
+ void throws_exception_on_unknown_document() {
NewDocumentType unknown = new NewDocumentType(new NewDocumentType.Name("unknown"));
NewDocumentType child = createDocumentType("child", unknown);
Fixture fixture = new Fixture()
@@ -76,7 +76,7 @@ public class GlobalDistributionValidatorTest {
}
@Test
- public void throws_exception_if_referenced_document_not_global_end_to_end() {
+ void throws_exception_if_referenced_document_not_global_end_to_end() {
try {
new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/global_distribution_validation/").create();
fail();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java
index 7d7ba7994aa..07c032a52a5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.search.DispatchGroup;
import com.yahoo.vespa.model.search.SearchInterface;
import com.yahoo.vespa.model.search.SearchNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -15,10 +15,7 @@ import java.util.Optional;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster;
import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createClusterXml;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for hierarchic distribution in an indexed content cluster.
@@ -73,7 +70,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatSearchNodesAreCorrectWithOneGroup() throws Exception {
+ void requireThatSearchNodesAreCorrectWithOneGroup() throws Exception {
ContentCluster c = getOneGroupCluster();
List<SearchNode> searchNodes = c.getSearch().getSearchNodes();
@@ -84,13 +81,13 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatActivePerLeafGroupIsDefaultWithOneGroup() throws Exception {
+ void requireThatActivePerLeafGroupIsDefaultWithOneGroup() throws Exception {
ContentCluster c = getOneGroupCluster();
assertFalse(getStorDistributionConfig(c).active_per_leaf_group());
}
@Test
- public void requireThatSearchNodesAreCorrectWithTwoGroups() throws Exception {
+ void requireThatSearchNodesAreCorrectWithTwoGroups() throws Exception {
ContentCluster c = getTwoGroupsCluster();
List<SearchNode> searchNodes = c.getSearch().getSearchNodes();
@@ -104,7 +101,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatActivePerLeafGroupIsSetWithTwoGroups() throws Exception {
+ void requireThatActivePerLeafGroupIsSetWithTwoGroups() throws Exception {
ContentCluster c = getTwoGroupsCluster();
assertTrue(getStorDistributionConfig(c).active_per_leaf_group());
}
@@ -174,7 +171,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatWeMustHaveOnlyOneGroupLevel() {
+ void requireThatWeMustHaveOnlyOneGroupLevel() {
try {
getIllegalMultipleGroupsLevelCluster();
fail("Did not get expected Exception");
@@ -184,7 +181,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatLeafGroupsMustHaveEqualNumberOfNodes() {
+ void requireThatLeafGroupsMustHaveEqualNumberOfNodes() {
try {
getIllegalGroupsCluster();
fail("Did not get expected Exception");
@@ -194,14 +191,14 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatLeafGroupsCanHaveUnequalNumberOfNodesIfRandomPolicy() throws Exception {
+ void requireThatLeafGroupsCanHaveUnequalNumberOfNodesIfRandomPolicy() throws Exception {
ContentCluster c = getOddGroupsCluster();
DispatchGroup dg = c.getSearch().getIndexed().getRootDispatch();
assertEquals(8, dg.getRowBits());
assertEquals(3, dg.getNumPartitions());
assertTrue(dg.useFixedRowInDispatch());
ArrayList<SearchInterface> list = new ArrayList<>();
- for(SearchInterface si : dg.getSearchersIterable()) {
+ for (SearchInterface si : dg.getSearchersIterable()) {
list.add(si);
}
assertEquals(5, list.size());
@@ -218,7 +215,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatLeafGroupsCountMustBeAFactorOfRedundancy() {
+ void requireThatLeafGroupsCountMustBeAFactorOfRedundancy() {
try {
getTwoGroupsCluster(3, 3, "2|*");
fail("Did not get expected Exception");
@@ -228,7 +225,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatRedundancyPerGroupMustBeIsEqual() {
+ void requireThatRedundancyPerGroupMustBeIsEqual() {
try {
getTwoGroupsCluster(4, 4, "1|*");
fail("Did not get expected Exception");
@@ -238,7 +235,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void requireThatReadyCopiesMustBeEqualToRedundancy() {
+ void requireThatReadyCopiesMustBeEqualToRedundancy() {
try {
getTwoGroupsCluster(4, 3, "2|*");
fail("Did not get expected Exception");
@@ -248,7 +245,7 @@ public class IndexedHierarchicDistributionTest {
}
@Test
- public void allowLessReadyCopiesThanRedundancy() throws Exception {
+ void allowLessReadyCopiesThanRedundancy() throws Exception {
getTwoGroupsCluster(4, 2, "2|*");
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java
index 17e295c1c2a..d2de9d6c23a 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java
@@ -5,14 +5,14 @@ import com.yahoo.vespa.config.search.core.ProtonConfig;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.search.SearchNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.config.model.test.TestUtil.joinLines;
import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster;
import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createClusterXml;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit tests for the naming of search nodes base dir and config ids in an indexed content cluster.
@@ -69,14 +69,14 @@ public class IndexedSchemaNodeNamingTest {
}
@Test
- public void requireThatSingleNodeIsNamedAfterDistributionKey() throws Exception {
+ void requireThatSingleNodeIsNamedAfterDistributionKey() throws Exception {
ContentCluster cluster = getSingleNodeCluster();
List<SearchNode> nodes = cluster.getSearch().getSearchNodes();
assertSearchNode("n3", "3", nodes.get(0));
}
@Test
- public void requireThatMultipleNodesAreNamedAfterDistributionKey() throws Exception {
+ void requireThatMultipleNodesAreNamedAfterDistributionKey() throws Exception {
ContentCluster cluster = getMultiNodeCluster();
List<SearchNode> nodes = cluster.getSearch().getSearchNodes();
assertEquals(3, nodes.size());
@@ -86,7 +86,7 @@ public class IndexedSchemaNodeNamingTest {
}
@Test
- public void requireThatNodesInHierarchicGroupsAreNamedAfterDistributionKey() throws Exception {
+ void requireThatNodesInHierarchicGroupsAreNamedAfterDistributionKey() throws Exception {
ContentCluster cluster = getMultiGroupCluster();
List<SearchNode> nodes = cluster.getSearch().getSearchNodes();
assertEquals(4, nodes.size());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java
index a39cbc60a89..96aa88303bf 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java
@@ -15,13 +15,11 @@ import com.yahoo.vespa.model.routing.Routing;
import com.yahoo.vespa.model.search.IndexedSearchCluster;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for using the content model to create indexed search clusters.
@@ -111,7 +109,7 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void requireMultipleDocumentTypes() {
+ void requireMultipleDocumentTypes() {
VespaModelCreatorWithMockPkg creator = getIndexedVespaModelCreator();
VespaModel model = creator.create();
DeployState deployState = creator.deployState;
@@ -126,13 +124,13 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void requireIndexedOnlyServices() {
+ void requireIndexedOnlyServices() {
VespaModel model = getIndexedVespaModel();
// TODO
// HostResource h = model.getHostSystem().getHosts().get(0);
// String [] expectedServices = {"logserver", "configserver", "adminserver", "slobrok",
// "logd", "configproxy","config-sentinel",
- // "qrserver", "fleetcontroller",
+ // "container", "fleetcontroller",
// "storagenode", "searchnode", "distributor", "transactionlogserver"};
// DomContentBuilderTest.assertServices(h, expectedServices);
Routing routing = model.getRouting();
@@ -155,13 +153,13 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void requireProtonStreamingOnly() {
+ void requireProtonStreamingOnly() {
VespaModel model = getStreamingVespaModel();
// TODO
// HostResource h = model.getHostSystem().getHosts().get(0);
// String [] expectedServices = {"logserver", "configserver", "adminserver", "slobrok",
// "logd", "configproxy","config-sentinel",
- // "qrserver", "storagenode", "searchnode", "distributor",
+ // "container", "storagenode", "searchnode", "distributor",
// "transactionlogserver"};
// DomContentBuilderTest.assertServices(h, expectedServices);
ContentCluster s = model.getContentClusters().get("test");
@@ -173,7 +171,7 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void requireCorrectClusterList() {
+ void requireCorrectClusterList() {
VespaModel model = getStreamingVespaModel();
ContentCluster s = model.getContentClusters().get("test");
assertNotNull(s);
@@ -185,38 +183,38 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void testContentSummaryStore() {
- String services=
+ void testContentSummaryStore() {
+ String services =
"<services version='1.0'>" +
- "<admin version='2.0'><adminserver hostalias='node0' /></admin>" +
- "<content id='docstore' version='1.0'>\n" +
- " <redundancy>1</redundancy>\n" +
- " <documents>\n" +
- " <document mode='index' type='docstorebench'/>\n" +
- " </documents>\n" +
- " <group>\n" +
- " <node distribution-key='0' hostalias='node0'/>\n" +
- " </group>\n" +
- " <engine>\n" +
- " <proton>\n" +
- " <searchable-copies>1</searchable-copies>\n" +
- " <tuning>\n" +
- " <searchnode>\n" +
- " <summary>\n" +
- " <store>\n" +
- " <logstore>\n" +
- " <chunk>\n" +
- " <maxsize>2048</maxsize>\n" +
- " </chunk>\n" +
- " </logstore>\n" +
- " </store>\n" +
- " </summary>\n" +
- " </searchnode>\n" +
- " </tuning>\n" +
- " </proton>\n" +
- " </engine>\n" +
- " </content>\n" +
- " </services>";
+ "<admin version='2.0'><adminserver hostalias='node0' /></admin>" +
+ "<content id='docstore' version='1.0'>\n" +
+ " <redundancy>1</redundancy>\n" +
+ " <documents>\n" +
+ " <document mode='index' type='docstorebench'/>\n" +
+ " </documents>\n" +
+ " <group>\n" +
+ " <node distribution-key='0' hostalias='node0'/>\n" +
+ " </group>\n" +
+ " <engine>\n" +
+ " <proton>\n" +
+ " <searchable-copies>1</searchable-copies>\n" +
+ " <tuning>\n" +
+ " <searchnode>\n" +
+ " <summary>\n" +
+ " <store>\n" +
+ " <logstore>\n" +
+ " <chunk>\n" +
+ " <maxsize>2048</maxsize>\n" +
+ " </chunk>\n" +
+ " </logstore>\n" +
+ " </store>\n" +
+ " </summary>\n" +
+ " </searchnode>\n" +
+ " </tuning>\n" +
+ " </proton>\n" +
+ " </engine>\n" +
+ " </content>\n" +
+ " </services>";
List<String> sds = ApplicationPackageUtils.generateSchemas("docstorebench");
VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), services, sds).create();
@@ -225,21 +223,21 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void testMixedIndexAndStoreOnly() {
- String services=
+ void testMixedIndexAndStoreOnly() {
+ String services =
"<services version='1.0'>" +
- " <admin version='2.0'><adminserver hostalias='node0' /></admin>" +
- " <content id='docstore' version=\"1.0\">" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document type=\"index_me\" mode=\"index\"/>" +
- " <document type=\"store_me\" mode=\"store-only\"/>" +
- " </documents>" +
- " <group>" +
- " <node distribution-key=\"0\" hostalias=\"node0\"/>" +
- " </group>" +
- " </content>" +
- "</services>";
+ " <admin version='2.0'><adminserver hostalias='node0' /></admin>" +
+ " <content id='docstore' version=\"1.0\">" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document type=\"index_me\" mode=\"index\"/>" +
+ " <document type=\"store_me\" mode=\"store-only\"/>" +
+ " </documents>" +
+ " <group>" +
+ " <node distribution-key=\"0\" hostalias=\"node0\"/>" +
+ " </group>" +
+ " </content>" +
+ "</services>";
List<String> sds = ApplicationPackageUtils.generateSchemas("index_me", "store_me");
VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), services, sds).create();
@@ -254,7 +252,7 @@ public class IndexedTest extends ContentBaseTest {
}
@Test
- public void requireThatIndexingDocprocGetsConfigIdBasedOnDistributionKey() {
+ void requireThatIndexingDocprocGetsConfigIdBasedOnDistributionKey() {
VespaModel model = getIndexedVespaModel();
ApplicationContainerCluster cluster = model.getContainerClusters().get("container");
assertEquals("container/container.0", cluster.getContainers().get(0).getConfigId());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java
index 0b7dbf2eb21..430628238d9 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.model.routing.Protocol;
import com.yahoo.vespa.model.routing.Routing;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -23,10 +23,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
@@ -34,7 +31,7 @@ import static org.junit.Assert.fail;
public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
@Test
- public void oneContentOneDoctypeImplicitIndexingClusterImplicitIndexingChain() {
+ void oneContentOneDoctypeImplicitIndexingClusterImplicitIndexingChain() {
final String CLUSTERNAME = "musiccluster";
SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, null, null);
searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -44,7 +41,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void oneContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() {
+ void oneContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() {
final String CLUSTERNAME = "musicandbookscluster";
SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, null, null);
searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -55,7 +52,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void twoContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() {
+ void twoContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() {
final String MUSIC = "musiccluster";
SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, null, null);
musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -67,7 +64,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
VespaModel model = getIndexedContentVespaModel(List.of(), List.of(musicCluster, booksCluster));
assertIndexing(model,
- new DocprocClusterSpec("container", new DocprocChainSpec("container/chain.indexing")));
+ new DocprocClusterSpec("container", new DocprocChainSpec("container/chain.indexing")));
assertFeedingRoute(model, MUSIC, "container/chain.indexing");
assertFeedingRoute(model, BOOKS, "container/chain.indexing");
@@ -75,7 +72,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
@Test
- public void oneContentOneDoctypeExplicitIndexingClusterImplicitIndexingChain() {
+ void oneContentOneDoctypeExplicitIndexingClusterImplicitIndexingChain() {
final String CLUSTERNAME = "musiccluster";
SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, "dpcluster", null);
searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -85,45 +82,45 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void oneSearchOneDoctypeExplicitIndexingClusterExplicitIndexingChain() {
+ void oneSearchOneDoctypeExplicitIndexingClusterExplicitIndexingChain() {
String xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<services version=\"1.0\">\n" +
- " <admin version=\"2.0\">\n" +
- " <adminserver hostalias=\"node0\"/> \n" +
- " </admin>\n" +
- "\n" +
- " <content id=\"searchcluster\" version=\"1.0\">\n" +
- " <redundancy>2</redundancy>\n" +
- " <documents>\n" +
- " <document-processing cluster='dpcluster' chain='fooindexing'/>\n" +
- " <document type=\"music\" mode=\"index\"/>\n" +
- " </documents>\n" +
- " <nodes>\n" +
- " <node hostalias=\"node0\" distribution-key=\"0\"/>\n" +
- " </nodes>\n" +
- " </content>\n" +
- " \n" +
- " <container version='1.0' id='dpcluster'>\n" +
- " <document-processing>\n" +
- " <chain id='fooindexing' inherits='indexing '/>\n" +
- " </document-processing>\n" +
- " <nodes>\n" +
- " <node hostalias='node0'/>\n" +
- " </nodes>\n" +
- " <http>\n" +
- " <server id='dpcluster' port='8000'/>\n" +
- " </http>\n" +
- " </container>\n" +
- "</services>\n";
+ "<services version=\"1.0\">\n" +
+ " <admin version=\"2.0\">\n" +
+ " <adminserver hostalias=\"node0\"/> \n" +
+ " </admin>\n" +
+ "\n" +
+ " <content id=\"searchcluster\" version=\"1.0\">\n" +
+ " <redundancy>2</redundancy>\n" +
+ " <documents>\n" +
+ " <document-processing cluster='dpcluster' chain='fooindexing'/>\n" +
+ " <document type=\"music\" mode=\"index\"/>\n" +
+ " </documents>\n" +
+ " <nodes>\n" +
+ " <node hostalias=\"node0\" distribution-key=\"0\"/>\n" +
+ " </nodes>\n" +
+ " </content>\n" +
+ " \n" +
+ " <container version='1.0' id='dpcluster'>\n" +
+ " <document-processing>\n" +
+ " <chain id='fooindexing' inherits='indexing '/>\n" +
+ " </document-processing>\n" +
+ " <nodes>\n" +
+ " <node hostalias='node0'/>\n" +
+ " </nodes>\n" +
+ " <http>\n" +
+ " <server id='dpcluster' port='8000'/>\n" +
+ " </http>\n" +
+ " </container>\n" +
+ "</services>\n";
VespaModel model = getIndexedSearchVespaModel(xml);
assertIndexing(model, new DocprocClusterSpec("dpcluster", new DocprocChainSpec("dpcluster/chain.fooindexing", "indexing"),
- new DocprocChainSpec("dpcluster/chain.indexing")));
+ new DocprocChainSpec("dpcluster/chain.indexing")));
assertFeedingRouteIndexed(model, "searchcluster", "dpcluster/chain.fooindexing");
}
@Test
- public void twoContentTwoDoctypesExplicitIndexingInSameIndexingCluster() {
+ void twoContentTwoDoctypesExplicitIndexingInSameIndexingCluster() {
final String MUSIC = "musiccluster";
SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, "dpcluster", null);
musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -133,7 +130,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
booksCluster.searchDefs.add(new SearchDefSpec("book", "author", "title"));
VespaModel model = getIndexedContentVespaModel(List.of(new DocprocClusterSpec("dpcluster")),
- List.of(musicCluster, booksCluster));
+ List.of(musicCluster, booksCluster));
assertIndexing(model, new DocprocClusterSpec("dpcluster", new DocprocChainSpec("dpcluster/chain.indexing")));
assertFeedingRoute(model, MUSIC, "dpcluster/chain.indexing");
@@ -141,7 +138,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void noContentClustersOneDocprocCluster() {
+ void noContentClustersOneDocprocCluster() {
String services =
"<?xml version='1.0' encoding='utf-8' ?>\n" +
"<services version='1.0'>\n" +
@@ -162,7 +159,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void twoContentTwoDoctypesExplicitIndexingInDifferentIndexingClustersExplicitChain() {
+ void twoContentTwoDoctypesExplicitIndexingInDifferentIndexingClustersExplicitChain() {
final String MUSIC = "musiccluster";
SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, "dpmusiccluster", "dpmusicchain");
musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
@@ -174,7 +171,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("dpmusicchain", "indexing"));
DocprocClusterSpec dpBooksCluster = new DocprocClusterSpec("dpbookscluster", new DocprocChainSpec("dpbookschain", "indexing"));
VespaModel model = getIndexedContentVespaModel(List.of(dpMusicCluster, dpBooksCluster),
- List.of(musicCluster, booksCluster));
+ List.of(musicCluster, booksCluster));
//after we generated model, add indexing chains for validation:
dpMusicCluster.chains.clear();
@@ -191,11 +188,11 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void requiresIndexingInheritance() {
+ void requiresIndexingInheritance() {
try {
SearchClusterSpec musicCluster = new SearchClusterSpec("musiccluster",
- "dpmusiccluster",
- "dpmusicchain");
+ "dpmusiccluster",
+ "dpmusicchain");
musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("dpmusicchain"));
@@ -208,11 +205,11 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest {
}
@Test
- public void indexingChainShouldNotBeTheDefaultChain() {
+ void indexingChainShouldNotBeTheDefaultChain() {
try {
SearchClusterSpec musicCluster = new SearchClusterSpec("musiccluster",
- "dpmusiccluster",
- "default");
+ "dpmusiccluster",
+ "default");
musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album"));
DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("default", "indexing"));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java
index d1ce16bfe73..95ab1b46401 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java
@@ -4,9 +4,10 @@ package com.yahoo.vespa.model.content;
import com.yahoo.config.model.test.TestDriver;
import com.yahoo.config.model.test.TestRoot;
import com.yahoo.metrics.MetricsmanagerConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
@@ -44,7 +45,7 @@ public class MonitoringConfigSnoopTest {
}
@Test
- public void correct_config_is_snooped() {
+ void correct_config_is_snooped() {
initRoot(60);
assertEquals(2, getConfig().snapshot().periods().size());
assertEquals(60, getConfig().snapshot().periods(0));
@@ -52,7 +53,7 @@ public class MonitoringConfigSnoopTest {
}
@Test
- public void correct_config_is_snooped_default_interval() {
+ void correct_config_is_snooped_default_interval() {
String getAdminXmlIntervalNotSpecified = "<admin version='2.0'>"
+ " <adminserver hostalias='mockhost' />"
+ "</admin>";
@@ -64,8 +65,10 @@ public class MonitoringConfigSnoopTest {
assertEquals(300, getConfig().snapshot().periods(1));
}
- @Test(expected = Exception.class)
- public void invalid_model_1() {
- initRoot(120);
+ @Test
+ void invalid_model_1() {
+ assertThrows(Exception.class, () -> {
+ initRoot(120);
+ });
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java
index 437af50e3ef..c7e9b09d77d 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class RedundancyTest {
@Test
- public void effectively_globally_distributed_is_correct() {
+ void effectively_globally_distributed_is_correct() {
assertFalse(createRedundancy(4, 2, 10).isEffectivelyGloballyDistributed());
assertFalse(createRedundancy(5, 1, 10).isEffectivelyGloballyDistributed());
assertFalse(createRedundancy(5, 2, 12).isEffectivelyGloballyDistributed());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java
index 684f07d99f0..96ddf6ea215 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.model.content;
import com.yahoo.documentmodel.NewDocumentType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -12,9 +12,7 @@ import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class ReservedDocumentTypeNameValidatorTest {
@@ -23,7 +21,7 @@ public class ReservedDocumentTypeNameValidatorTest {
}
@Test
- public void exception_thrown_on_reserved_names() {
+ void exception_thrown_on_reserved_names() {
// Ensure ordering is consistent for testing
Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(ReservedDocumentTypeNameValidator.ORDERED_RESERVED_NAMES));
@@ -40,13 +38,13 @@ public class ReservedDocumentTypeNameValidatorTest {
}
@Test
- public void exception_is_not_thrown_on_unreserved_name() {
+ void exception_is_not_thrown_on_unreserved_name() {
ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator();
validator.validate(asDocTypeMapping(Collections.singletonList("foo")));
}
@Test
- public void validation_is_case_insensitive() {
+ void validation_is_case_insensitive() {
ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator();
Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(Arrays.asList("NULL", "True", "anD")));
try {
@@ -54,7 +52,7 @@ public class ReservedDocumentTypeNameValidatorTest {
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("The following document types conflict with reserved keyword names: " +
- "'NULL', 'True', 'anD'."));
+ "'NULL', 'True', 'anD'."));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java
index 66184d74251..7a331538291 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.fail;
public class SchemaCoverageTest {
@Test
- public void requireThatAccessorWork() {
+ void requireThatAccessorWork() {
SearchCoverage coverage = new SearchCoverage.Builder()
.setMinimum(0.1)
.setMinWaitAfterCoverageFactor(0.2)
@@ -25,7 +23,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatDefaultsAreNull() {
+ void requireThatDefaultsAreNull() {
SearchCoverage search = new SearchCoverage.Builder().build();
assertNull(search.getMinimum());
assertNull(search.getMinWaitAfterCoverageFactor());
@@ -33,7 +31,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatInvalidMinimumCanNotBeSet() {
+ void requireThatInvalidMinimumCanNotBeSet() {
SearchCoverage.Builder coverage = new SearchCoverage.Builder();
coverage.setMinimum(0.5);
assertEquals(0.5, coverage.build().getMinimum(), 1E-6);
@@ -54,7 +52,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatInvalidMinWaitAfterCoverageFactorCanNotBeSet() {
+ void requireThatInvalidMinWaitAfterCoverageFactorCanNotBeSet() {
SearchCoverage.Builder coverage = new SearchCoverage.Builder();
coverage.setMinWaitAfterCoverageFactor(0.5);
assertEquals(0.5, coverage.build().getMinWaitAfterCoverageFactor(), 1E-6);
@@ -75,7 +73,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatInvalidMaxWaitAfterCoverageFactorCanNotBeSet() {
+ void requireThatInvalidMaxWaitAfterCoverageFactorCanNotBeSet() {
SearchCoverage.Builder coverage = new SearchCoverage.Builder();
coverage.setMaxWaitAfterCoverageFactor(0.5);
assertEquals(0.5, coverage.build().getMaxWaitAfterCoverageFactor(), 1E-6);
@@ -96,7 +94,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatMinWaitCanNotBeSetLargerThanMaxWait() {
+ void requireThatMinWaitCanNotBeSetLargerThanMaxWait() {
SearchCoverage.Builder coverage = new SearchCoverage.Builder();
coverage.setMaxWaitAfterCoverageFactor(0.5);
coverage.setMinWaitAfterCoverageFactor(0.4);
@@ -113,7 +111,7 @@ public class SchemaCoverageTest {
}
@Test
- public void requireThatMaxWaitCanNotBeSetSmallerThanMaxWait() {
+ void requireThatMaxWaitCanNotBeSetSmallerThanMaxWait() {
SearchCoverage.Builder coverage = new SearchCoverage.Builder();
coverage.setMinWaitAfterCoverageFactor(0.5);
coverage.setMaxWaitAfterCoverageFactor(0.6);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java
index c03ffba1c34..f7afcc281f9 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java
@@ -21,13 +21,10 @@ import static com.yahoo.config.model.test.TestUtil.joinLines;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.storagecluster.StorageCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class StorageClusterTest {
@@ -83,8 +80,9 @@ public class StorageClusterTest {
group(),
"</content>");
}
+
@Test
- public void testBasics() {
+ void testBasics() {
StorageCluster storage = parse(cluster("foofighters", ""));
assertEquals(1, storage.getChildren().size());
@@ -95,23 +93,18 @@ public class StorageClusterTest {
assertEquals("foofighters", config.cluster_name());
assertEquals(4, config.content_node_bucket_db_stripe_bits());
}
+
@Test
- public void testCommunicationManagerDefaults() {
+ void testCommunicationManagerDefaults() {
StorageCluster storage = parse(cluster("foofighters", ""));
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
storage.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
- assertTrue(config.mbus().dispatch_on_encode());
- assertTrue(config.mbus().dispatch_on_decode());
- assertEquals(4, config.mbus().num_threads());
- assertEquals(StorCommunicationmanagerConfig.Mbus.Optimize_for.LATENCY, config.mbus().optimize_for());
- assertFalse(config.skip_thread());
- assertFalse(config.mbus().skip_request_thread());
- assertFalse(config.mbus().skip_reply_thread());
+ assertEquals(1, config.mbus().num_network_threads());
}
@Test
- public void testMergeDefaults() {
+ void testMergeDefaults() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse(cluster("foofighters", "")).getConfig(builder);
@@ -122,7 +115,7 @@ public class StorageClusterTest {
}
@Test
- public void testMerges() {
+ void testMerges() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse(cluster("foofighters", joinLines(
"<tuning>",
@@ -133,7 +126,7 @@ public class StorageClusterTest {
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1024, config.max_merges_per_node());
- assertEquals(1024*10, config.max_merge_queue_size());
+ assertEquals(1024 * 10, config.max_merge_queue_size());
}
private StorServerConfig configFromProperties(TestProperties properties) {
@@ -142,31 +135,58 @@ public class StorageClusterTest {
return new StorServerConfig(builder);
}
+ private StorCommunicationmanagerConfig communicationmanagerConfigFromProperties(TestProperties properties) {
+ StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
+ parse(cluster("foofighters", ""), properties).getChildren().values().iterator().next().getConfig(builder);
+ return new StorCommunicationmanagerConfig(builder);
+ }
+
private StorFilestorConfig filestorConfigFromProducer(StorFilestorConfig.Producer producer) {
var builder = new StorFilestorConfig.Builder();
producer.getConfig(builder);
return new StorFilestorConfig(builder);
}
- private StorFilestorConfig filestorConfigFromProperties(TestProperties properties) {
- return filestorConfigFromProducer(parse(cluster("foo", ""), properties));
+ @Test
+ void verifyDefaultMbusConfig() {
+ var confg = communicationmanagerConfigFromProperties(new TestProperties());
+ assertEquals(1, confg.mbus().num_network_threads());
+ assertEquals(1, confg.mbus().num_rpc_targets());
+ assertEquals(1, confg.mbus().events_before_wakeup());
+ assertEquals(1, confg.rpc().num_targets_per_node());
+ assertEquals(1, confg.rpc().events_before_wakeup());
}
@Test
- public void testMergeFeatureFlags() {
+ void verifyDefaultMbusConfigControl() {
+ var confg = communicationmanagerConfigFromProperties(new TestProperties()
+ .setMbusNetworkThreads(7)
+ .setRpcNumTargets(11)
+ .setRpcEventsBeforeWakeup(12)
+ .setMbusCppRpcNumTargets(8)
+ .setMbusCppEventsBeforeWakeup(9));
+ assertEquals(7, confg.mbus().num_network_threads());
+ assertEquals(8, confg.mbus().num_rpc_targets());
+ assertEquals(9, confg.mbus().events_before_wakeup());
+ assertEquals(11, confg.rpc().num_targets_per_node());
+ assertEquals(12, confg.rpc().events_before_wakeup());
+ }
+
+ @Test
+ void testMergeFeatureFlags() {
var config = configFromProperties(new TestProperties().setMaxMergeQueueSize(1919).setMaxConcurrentMergesPerNode(37));
assertEquals(37, config.max_merges_per_node());
assertEquals(1919, config.max_merge_queue_size());
}
@Test
- public void merge_throttling_policy_config_defaults_to_static() {
+ void merge_throttling_policy_config_defaults_to_static() {
var config = configFromProperties(new TestProperties());
assertEquals(StorServerConfig.Merge_throttling_policy.Type.STATIC, config.merge_throttling_policy().type());
}
@Test
- public void merge_throttling_policy_config_is_derived_from_flag() {
+ void merge_throttling_policy_config_is_derived_from_flag() {
var config = configFromProperties(new TestProperties().setMergeThrottlingPolicy("STATIC"));
assertEquals(StorServerConfig.Merge_throttling_policy.Type.STATIC, config.merge_throttling_policy().type());
@@ -179,15 +199,15 @@ public class StorageClusterTest {
}
@Test
- public void testVisitors() {
+ void testVisitors() {
StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder();
parse(cluster("bees",
joinLines(
- "<tuning>",
- " <visitors thread-count=\"7\" max-queue-size=\"1000\">",
- " <max-concurrent fixed=\"42\" variable=\"100\"/>",
- " </visitors>",
- "</tuning>"))
+ "<tuning>",
+ " <visitors thread-count=\"7\" max-queue-size=\"1000\">",
+ " <max-concurrent fixed=\"42\" variable=\"100\"/>",
+ " </visitors>",
+ "</tuning>"))
).getConfig(builder);
StorVisitorConfig config = new StorVisitorConfig(builder);
@@ -198,9 +218,9 @@ public class StorageClusterTest {
}
@Test
- public void testPersistenceThreads() {
+ void testPersistenceThreads() {
- StorageCluster stc = parse(cluster("bees",joinLines(
+ StorageCluster stc = parse(cluster("bees", joinLines(
"<tuning>",
" <persistence-threads count=\"7\"/>",
"</tuning>")),
@@ -223,9 +243,9 @@ public class StorageClusterTest {
}
@Test
- public void testResponseThreads() {
+ void testResponseThreads() {
- StorageCluster stc = parse(cluster("bees",joinLines(
+ StorageCluster stc = parse(cluster("bees", joinLines(
"<tuning>",
" <persistence-threads count=\"7\"/>",
"</tuning>")),
@@ -238,7 +258,7 @@ public class StorageClusterTest {
}
@Test
- public void testPersistenceThreadsOld() {
+ void testPersistenceThreadsOld() {
StorageCluster stc = parse(cluster("bees", joinLines(
"<tuning>",
@@ -266,7 +286,7 @@ public class StorageClusterTest {
}
@Test
- public void testNoPersistenceThreads() {
+ void testNoPersistenceThreads() {
StorageCluster stc = parse(cluster("bees", ""),
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
@@ -290,7 +310,7 @@ public class StorageClusterTest {
}
@Test
- public void testFeatureFlagControlOfResponseSequencer() {
+ void testFeatureFlagControlOfResponseSequencer() {
var config = filestorConfigFromProducer(simpleCluster(new TestProperties().setResponseNumThreads(13).setResponseSequencerType("THROUGHPUT")));
assertEquals(13, config.num_response_threads());
assertEquals(StorFilestorConfig.Response_sequencer_type.THROUGHPUT, config.response_sequencer_type());
@@ -300,14 +320,15 @@ public class StorageClusterTest {
var config = filestorConfigFromProducer(simpleCluster(new TestProperties().setAsyncMessageHandlingOnSchedule(value)));
assertEquals(expected, config.use_async_message_handling_on_schedule());
}
+
@Test
- public void testFeatureFlagControlOfAsyncMessageHandlingOnSchedule() {
+ void testFeatureFlagControlOfAsyncMessageHandlingOnSchedule() {
verifyAsyncMessageHandlingOnSchedule(false, false);
verifyAsyncMessageHandlingOnSchedule(true, true);
}
@Test
- public void persistence_dynamic_throttling_parameters_have_sane_defaults() {
+ void persistence_dynamic_throttling_parameters_have_sane_defaults() {
var config = filestorConfigFromProducer(simpleCluster(new TestProperties()));
assertEquals(StorFilestorConfig.Async_operation_throttler.Type.DYNAMIC, config.async_operation_throttler().type());
assertEquals(1.2, config.async_operation_throttler().window_size_decrement_factor(), 0.0001);
@@ -319,7 +340,7 @@ public class StorageClusterTest {
}
@Test
- public void persistence_dynamic_throttling_parameters_can_be_set_through_feature_flags() {
+ void persistence_dynamic_throttling_parameters_can_be_set_through_feature_flags() {
var config = filestorConfigFromProducer(simpleCluster(new TestProperties()
.setPersistenceThrottlingWsDecrementFactor(1.5)
.setPersistenceThrottlingWsBackoff(0.8)
@@ -336,7 +357,7 @@ public class StorageClusterTest {
}
@Test
- public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() {
+ void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() {
StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder();
parse(cluster("bees", "")).getConfig(builder);
StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder);
@@ -345,7 +366,7 @@ public class StorageClusterTest {
}
@Test
- public void testCapacity() {
+ void testCapacity() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <documents/>",
@@ -364,12 +385,12 @@ public class StorageClusterTest {
cluster.getStorageCluster().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
- assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001);
+ assertEquals(1.0 + (double) i * 0.5, config.node_capacity(), 0.001);
}
}
@Test
- public void testRootFolder() {
+ void testRootFolder() {
ContentCluster cluster = ContentClusterUtils.createCluster(cluster("storage", ""), new MockRoot());
StorageNode node = cluster.getStorageCluster().getChildren().get("0");
@@ -392,7 +413,7 @@ public class StorageClusterTest {
}
@Test
- public void testGenericPersistenceTuning() {
+ void testGenericPersistenceTuning() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <documents/>",
@@ -418,7 +439,7 @@ public class StorageClusterTest {
}
@Test
- public void requireThatUserDoesNotSpecifyBothGroupAndNodes() {
+ void requireThatUserDoesNotSpecifyBothGroupAndNodes() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <documents/>",
@@ -444,12 +465,12 @@ public class StorageClusterTest {
fail("Did not fail when having both group and nodes");
} catch (RuntimeException e) {
assertEquals("Both <group> and <nodes> is specified: Only one of these tags can be used in the same configuration",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatGroupNamesMustBeUniqueAmongstSiblings() {
+ void requireThatGroupNamesMustBeUniqueAmongstSiblings() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <redundancy>2</redundancy>",
@@ -470,12 +491,12 @@ public class StorageClusterTest {
fail("Did not get exception with duplicate group names");
} catch (RuntimeException e) {
assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " +
- "Group sibling names must be unique.", e.getMessage());
+ "Group sibling names must be unique.", e.getMessage());
}
}
@Test
- public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() {
+ void requireThatGroupNamesCanBeDuplicatedAcrossLevels() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <redundancy>2</redundancy>",
@@ -500,7 +521,7 @@ public class StorageClusterTest {
}
@Test
- public void requireThatNestedGroupsRequireDistribution() {
+ void requireThatNestedGroupsRequireDistribution() {
String xml = joinLines(
"<cluster id=\"storage\">",
" <documents/>",
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java
index bbfcc0ac4c4..a7ad376b483 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.model.routing.DocumentProtocol;
import com.yahoo.vespa.model.routing.Routing;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
@@ -17,10 +17,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class StorageContentTest extends ContentBaseTest {
// TODO: Test with document-definitions
@@ -105,7 +102,7 @@ public class StorageContentTest extends ContentBaseTest {
}
@Test
- public void testDocumentTypesRouting() throws Exception {
+ void testDocumentTypesRouting() throws Exception {
String cluster1docs = "<documents>\n" +
" <document type=\"type1\" mode=\"store-only\"/>\n" +
" <document type=\"type2\" mode=\"store-only\"/>\n" +
@@ -120,7 +117,7 @@ public class StorageContentTest extends ContentBaseTest {
}
@Test
- public void testDocumentTypesAndLocalSelectionRouting() throws Exception {
+ void testDocumentTypesAndLocalSelectionRouting() throws Exception {
String cluster1docs = "<documents>\n" +
" <document type=\"type1\" mode=\"store-only\" selection=\"1 != 2\"/>\n" +
" <document type=\"type2\" mode=\"store-only\" selection=\"now() &gt; 1000\"/>\n" +
@@ -135,7 +132,7 @@ public class StorageContentTest extends ContentBaseTest {
}
@Test
- public void testDocumentTypesAndGlobalSelection() throws Exception {
+ void testDocumentTypesAndGlobalSelection() throws Exception {
String cluster1docs = "<documents selection=\"5 != 6\">\n" +
" <document type=\"type1\" mode=\"store-only\" selection=\"type1.f1 == 'baz'\"/>\n" + // Can refer to own type
" <document type=\"type2\" mode=\"store-only\"/>\n" +
@@ -150,7 +147,7 @@ public class StorageContentTest extends ContentBaseTest {
}
@Test
- public void testIllegalDocumentTypesInSelection() throws Exception {
+ void testIllegalDocumentTypesInSelection() throws Exception {
String localDefs = "<documents>\n" +
" <document type=\"type1\" mode=\"store-only\"/>\n" +
" <document type=\"type2\" mode=\"store-only\" selection=\"type1.bar == 'baz'\"/>\n" + // Not own type
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java
index 7ea8420c162..5407298d0a5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java
@@ -6,10 +6,10 @@ import com.yahoo.vespa.config.content.DistributionConfig;
import com.yahoo.vespa.config.content.StorDistributionConfig;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.content.utils.ContentClusterUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test for storage groups.
@@ -21,7 +21,7 @@ public class StorageGroupTest {
}
@Test
- public void testSingleGroup() throws Exception {
+ void testSingleGroup() throws Exception {
ContentCluster cluster = parse(
"<content id=\"storage\">\n" +
" <documents/>" +
@@ -65,7 +65,7 @@ public class StorageGroupTest {
}
@Test
- public void testNestedGroupsNoDistribution() {
+ void testNestedGroupsNoDistribution() {
try {
parse(
"<content version=\"1.0\" id=\"storage\">\n" +
@@ -87,7 +87,7 @@ public class StorageGroupTest {
}
@Test
- public void testNestedGroups() throws Exception {
+ void testNestedGroups() throws Exception {
ContentCluster cluster = parse(
"<content version=\"1.0\" id=\"storage\">\n" +
" <redundancy>4</redundancy>" +
@@ -171,7 +171,7 @@ public class StorageGroupTest {
}
@Test
- public void testGroupCapacity() throws Exception {
+ void testGroupCapacity() throws Exception {
ContentCluster cluster = parse(
"<content version=\"1.0\" id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java
index b6e2e9e4eae..cad888168fe 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.model.content;
import com.yahoo.documentmodel.NewDocumentType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -11,7 +11,7 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -19,14 +19,14 @@ import static org.junit.Assert.assertEquals;
public class TopologicalDocumentTypeSorterTest {
@Test
- public void require_that_types_without_references_are_returned_in_input_order() {
+ void require_that_types_without_references_are_returned_in_input_order() {
assertOrder(Arrays.asList("a"), new DocumentTypesBuilder().add("a"));
assertOrder(Arrays.asList("a", "c", "b"),
new DocumentTypesBuilder().add("a").add("c").add("b"));
}
@Test
- public void require_that_types_with_references_are_sorted_in_topological_order() {
+ void require_that_types_with_references_are_sorted_in_topological_order() {
assertOrder(Arrays.asList("b", "a"), new DocumentTypesBuilder()
.add("a", Arrays.asList("b"))
.add("b"));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java
index aa68dad83cd..1104ac7477a 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.config.search.core.ProtonConfig;
import com.yahoo.vespa.model.content.Content;
import com.yahoo.vespa.model.search.IndexedSearchCluster;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.config.model.test.TestUtil.joinLines;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -25,7 +25,7 @@ public class ClusterTest {
private static final double DELTA = 1E-12;
@Test
- public void requireThatContentSearchIsApplied() {
+ void requireThatContentSearchIsApplied() {
ContentCluster cluster = newContentCluster(joinLines("<search>",
" <query-timeout>1.1</query-timeout>",
" <visibility-delay>2.3</visibility-delay>",
@@ -39,7 +39,7 @@ public class ClusterTest {
}
@Test
- public void requireThatVisibilityDelayIsZeroForGlobalDocumentType() {
+ void requireThatVisibilityDelayIsZeroForGlobalDocumentType() {
ContentCluster cluster = newContentCluster(joinLines("<search>",
" <visibility-delay>2.3</visibility-delay>",
"</search>"), true);
@@ -48,7 +48,7 @@ public class ClusterTest {
}
@Test
- public void requireThatSearchCoverageIsApplied() {
+ void requireThatSearchCoverageIsApplied() {
ContentCluster cluster = newContentCluster(joinLines("<search>",
" <coverage>",
" <minimum>0.11</minimum>",
@@ -67,15 +67,15 @@ public class ClusterTest {
}
@Test
- public void requireThatDispatchTuningIsApplied() {
+ void requireThatDispatchTuningIsApplied() {
ContentCluster cluster = newContentCluster(joinLines("<search>", "</search>"),
- "",
- joinLines(
- "<max-hits-per-partition>77</max-hits-per-partition>",
- "<dispatch-policy>round-robin</dispatch-policy>",
- "<min-active-docs-coverage>93</min-active-docs-coverage>",
- "<top-k-probability>0.777</top-k-probability>"),
- false);
+ "",
+ joinLines(
+ "<max-hits-per-partition>77</max-hits-per-partition>",
+ "<dispatch-policy>round-robin</dispatch-policy>",
+ "<min-active-docs-coverage>93</min-active-docs-coverage>",
+ "<top-k-probability>0.777</top-k-probability>"),
+ false);
DispatchConfig.Builder builder = new DispatchConfig.Builder();
cluster.getSearch().getConfig(builder);
DispatchConfig config = new DispatchConfig(builder);
@@ -87,9 +87,9 @@ public class ClusterTest {
}
@Test
- public void requireThatDefaultDispatchConfigIsCorrect() {
+ void requireThatDefaultDispatchConfigIsCorrect() {
ContentCluster cluster = newContentCluster(joinLines("<search>", "</search>"),
- joinLines("<tuning>", "</tuning>"));
+ joinLines("<tuning>", "</tuning>"));
DispatchConfig.Builder builder = new DispatchConfig.Builder();
cluster.getSearch().getConfig(builder);
DispatchConfig config = new DispatchConfig(builder);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java
index 11aeea5f90d..d73b7f78391 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.model.content.cluster;
import com.yahoo.vespa.model.content.ContentSearch;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertNull;
public class DomContentApplicationBuilderTest {
@Test
- public void requireThatDefaultsAreNull() throws Exception {
+ void requireThatDefaultsAreNull() throws Exception {
ContentSearch search = newContentSearch(
"<content/>");
assertNull(search.getVisibilityDelay());
@@ -26,24 +26,24 @@ public class DomContentApplicationBuilderTest {
}
@Test
- public void requireThatEmptySearchIsSafe() throws Exception {
+ void requireThatEmptySearchIsSafe() throws Exception {
ContentSearch search = newContentSearch(
"<content>" +
- " <search/>" +
- "</content>");
+ " <search/>" +
+ "</content>");
assertNull(search.getVisibilityDelay());
assertNull(search.getQueryTimeout());
}
@Test
- public void requireThatContentSearchCanBeBuilt() throws Exception {
+ void requireThatContentSearchCanBeBuilt() throws Exception {
ContentSearch search = newContentSearch(
"<content>" +
- " <search>" +
- " <query-timeout>1.1</query-timeout>" +
- " <visibility-delay>2.3</visibility-delay>" +
- " </search>" +
- "</content>");
+ " <search>" +
+ " <query-timeout>1.1</query-timeout>" +
+ " <visibility-delay>2.3</visibility-delay>" +
+ " </search>" +
+ "</content>");
assertEquals(1.1, search.getQueryTimeout(), 1E-6);
assertEquals(2.3, search.getVisibilityDelay(), 1E-6);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java
index a9a784668b3..564d6024acf 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java
@@ -4,15 +4,14 @@ package com.yahoo.vespa.model.content.cluster;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
import com.yahoo.vespa.model.content.DispatchTuning;
import com.yahoo.vespa.model.test.utils.DeployLoggerStub;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -20,29 +19,29 @@ import static org.junit.Assert.assertTrue;
public class DomDispatchTuningBuilderTest {
@Test
- public void requireThatDefaultsAreNull() throws Exception {
+ void requireThatDefaultsAreNull() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content/>");
assertNull(dispatch.getMaxHitsPerPartition());
}
@Test
- public void requireThatEmptyTuningIsSafe() throws Exception {
+ void requireThatEmptyTuningIsSafe() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content>" +
- " <tuning/>" +
- "</content>");
+ " <tuning/>" +
+ "</content>");
assertNull(dispatch.getMaxHitsPerPartition());
}
@Test
- public void requireThatEmptydispatchIsSafe() throws Exception {
+ void requireThatEmptydispatchIsSafe() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content>" +
- " <tuning>" +
- " <dispatch/>" +
- " </tuning>" +
- "</content>");
+ " <tuning>" +
+ " <dispatch/>" +
+ " </tuning>" +
+ "</content>");
assertNull(dispatch.getMaxHitsPerPartition());
assertNull(dispatch.getMinActiveDocsCoverage());
assertNull(dispatch.getDispatchPolicy());
@@ -50,23 +49,24 @@ public class DomDispatchTuningBuilderTest {
}
@Test
- public void requireThatTuningDispatchCanBeBuilt() throws Exception {
+ void requireThatTuningDispatchCanBeBuilt() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content>" +
- " <tuning>" +
- " <dispatch>" +
- " <max-hits-per-partition>69</max-hits-per-partition>" +
- " <min-active-docs-coverage>12.5</min-active-docs-coverage>" +
- " <top-k-probability>0.999</top-k-probability>" +
- " </dispatch>" +
- " </tuning>" +
- "</content>");
+ " <tuning>" +
+ " <dispatch>" +
+ " <max-hits-per-partition>69</max-hits-per-partition>" +
+ " <min-active-docs-coverage>12.5</min-active-docs-coverage>" +
+ " <top-k-probability>0.999</top-k-probability>" +
+ " </dispatch>" +
+ " </tuning>" +
+ "</content>");
assertEquals(69, dispatch.getMaxHitsPerPartition().intValue());
assertEquals(12.5, dispatch.getMinActiveDocsCoverage().doubleValue(), 0.0);
assertEquals(0.999, dispatch.getTopkProbability().doubleValue(), 0.0);
}
+
@Test
- public void requireThatTuningDispatchPolicyRoundRobin() throws Exception {
+ void requireThatTuningDispatchPolicyRoundRobin() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content>" +
" <tuning>" +
@@ -75,10 +75,11 @@ public class DomDispatchTuningBuilderTest {
" </dispatch>" +
" </tuning>" +
"</content>");
- assertTrue(DispatchTuning.DispatchPolicy.ROUNDROBIN == dispatch.getDispatchPolicy());
+ assertEquals(DispatchTuning.DispatchPolicy.ROUNDROBIN, dispatch.getDispatchPolicy());
}
+
@Test
- public void requireThatTuningDispatchPolicyRandom() throws Exception {
+ void requireThatTuningDispatchPolicyRandom() throws Exception {
DispatchTuning dispatch = newTuningDispatch(
"<content>" +
" <tuning>" +
@@ -87,7 +88,7 @@ public class DomDispatchTuningBuilderTest {
" </dispatch>" +
" </tuning>" +
"</content>");
- assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy());
+ assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy());
}
private static DispatchTuning newTuningDispatch(String xml) throws Exception {
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java
index 6c5456e73fc..8fae348f648 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.model.content.cluster;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
import com.yahoo.vespa.model.content.SearchCoverage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertNull;
public class DomSchemaCoverageBuilderTest {
@Test
- public void requireThatDefaultsAreNull() throws Exception {
+ void requireThatDefaultsAreNull() throws Exception {
SearchCoverage coverage = newSearchCoverage(
"<content/>");
assertNull(coverage.getMinimum());
@@ -27,41 +27,41 @@ public class DomSchemaCoverageBuilderTest {
}
@Test
- public void requireThatEmptySearchIsSafe() throws Exception {
+ void requireThatEmptySearchIsSafe() throws Exception {
SearchCoverage coverage = newSearchCoverage(
"<content>" +
- " <search/>" +
- "</content>");
+ " <search/>" +
+ "</content>");
assertNull(coverage.getMinimum());
assertNull(coverage.getMinWaitAfterCoverageFactor());
assertNull(coverage.getMaxWaitAfterCoverageFactor());
}
@Test
- public void requireThatEmptyCoverageIsSafe() throws Exception {
+ void requireThatEmptyCoverageIsSafe() throws Exception {
SearchCoverage coverage = newSearchCoverage(
"<content>" +
- " <search>" +
- " <coverage/>" +
- " </search>" +
- "</content>");
+ " <search>" +
+ " <coverage/>" +
+ " </search>" +
+ "</content>");
assertNull(coverage.getMinimum());
assertNull(coverage.getMinWaitAfterCoverageFactor());
assertNull(coverage.getMaxWaitAfterCoverageFactor());
}
@Test
- public void requireThatSearchCoverageCanBeBuilt() throws Exception {
+ void requireThatSearchCoverageCanBeBuilt() throws Exception {
SearchCoverage coverage = newSearchCoverage(
"<content>" +
- " <search>" +
- " <coverage>" +
- " <minimum>0.11</minimum>" +
- " <min-wait-after-coverage-factor>0.23</min-wait-after-coverage-factor>" +
- " <max-wait-after-coverage-factor>0.58</max-wait-after-coverage-factor>" +
- " </coverage>" +
- " </search>" +
- "</content>");
+ " <search>" +
+ " <coverage>" +
+ " <minimum>0.11</minimum>" +
+ " <min-wait-after-coverage-factor>0.23</min-wait-after-coverage-factor>" +
+ " <max-wait-after-coverage-factor>0.58</max-wait-after-coverage-factor>" +
+ " </coverage>" +
+ " </search>" +
+ "</content>");
assertEquals(0.11, coverage.getMinimum(), 1E-6);
assertEquals(0.23, coverage.getMinWaitAfterCoverageFactor(), 1E-6);
assertEquals(0.58, coverage.getMaxWaitAfterCoverageFactor(), 1E-6);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java
index 8f654a86fef..e1b33ddedd2 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.model.content.cluster;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.text.XML;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -12,7 +12,7 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -25,15 +25,15 @@ public class GlobalDistributionBuilderTest {
private static final NewDocumentType GLOBAL_2 = new NewDocumentType(new NewDocumentType.Name("global-2"));
@Test
- public void global_documents_are_identified() {
+ void global_documents_are_identified() {
GlobalDistributionBuilder builder = new GlobalDistributionBuilder(createDocumentDefinitions());
String documentsElement =
"<documents>" +
- " <document type=\"" + NON_GLOBAL_EXPLICIT.getName() + "\" global=\"false\"/>" +
- " <document type=\"" + GLOBAL_1.getName() + "\" global=\"true\"/>" +
- " <document type=\"" + NON_GLOBAL_IMPLICIT.getName() + "\"/>" +
- " <document type=\"" + GLOBAL_2.getName() + "\" global=\"true\"/>" +
- "</documents>";
+ " <document type=\"" + NON_GLOBAL_EXPLICIT.getName() + "\" global=\"false\"/>" +
+ " <document type=\"" + GLOBAL_1.getName() + "\" global=\"true\"/>" +
+ " <document type=\"" + NON_GLOBAL_IMPLICIT.getName() + "\"/>" +
+ " <document type=\"" + GLOBAL_2.getName() + "\" global=\"true\"/>" +
+ "</documents>";
Set<NewDocumentType> expectedResult = new HashSet<>(Arrays.asList(GLOBAL_1, GLOBAL_2));
Set<NewDocumentType> actualResult = builder.build(new ModelElement(XML.getDocument(documentsElement).getDocumentElement()));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java
index dd98beea091..628e87e24c5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.vespa.model.filedistribution;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.model.application.provider.MockFileRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull;
public class FileReferencesRepositoryTestCase {
@Test
- public void fileDistributor() {
+ void fileDistributor() {
FileRegistry fileRegistry = new MockFileRegistry();
FileReferencesRepository fileReferencesRepository = new FileReferencesRepository(fileRegistry);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java
index bd07513b704..598b6b103bf 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java
@@ -23,9 +23,7 @@ import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Helper for testing of imported models.
@@ -79,8 +77,8 @@ public class ImportedModelTester {
if (expectedSize.isPresent()) {
Path constantPath = applicationDir.append(constantApplicationPackagePath);
- assertTrue("Constant file '" + constantPath + "' has been written",
- constantPath.toFile().exists());
+ assertTrue(constantPath.toFile().exists(),
+ "Constant file '" + constantPath + "' has been written");
Tensor deserializedConstant = TypedBinaryFormat.decode(Optional.empty(),
GrowableByteBuffer.wrap(IOUtils.readFileBytes(constantPath.toFile())));
assertEquals(expectedSize.get().longValue(), deserializedConstant.size());
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java
index b1dc78b4bb7..485d45e6c66 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java
@@ -6,11 +6,11 @@ import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.search.RankProfilesConfig;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests rank profile imported model evaluation
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class MlModelsTest {
@Test
- public void testMl_serving() throws IOException {
+ void testMl_serving() throws IOException {
Path appDir = Path.fromString("src/test/cfg/application/ml_models");
Path storedAppDir = appDir.append("copy");
try {
@@ -31,9 +31,9 @@ public class MlModelsTest {
storedAppDir.toFile().mkdirs();
IOUtils.copy(appDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString());
IOUtils.copyDirectory(appDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(),
- storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
+ storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
IOUtils.copyDirectory(appDir.append(ApplicationPackage.SCHEMAS_DIR).toFile(),
- storedAppDir.append(ApplicationPackage.SCHEMAS_DIR).toFile());
+ storedAppDir.append(ApplicationPackage.SCHEMAS_DIR).toFile());
ImportedModelTester storedTester = new ImportedModelTester("ml_models", storedAppDir);
verify(storedTester.createVespaModel());
}
@@ -44,8 +44,7 @@ public class MlModelsTest {
}
private void verify(VespaModel model) {
- assertEquals("Global models are created (although not used directly here)",
- 3, model.rankProfileList().getRankProfiles().size());
+ assertEquals(3, model.rankProfileList().getRankProfiles().size(), "Global models are created (although not used directly here)");
RankProfilesConfig.Builder builder = new RankProfilesConfig.Builder();
model.getSearchClusters().get(0).getConfig(builder);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java
index 694b908478d..f4d37cc4b35 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java
@@ -18,7 +18,7 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig;
import com.yahoo.vespa.config.search.core.RankingExpressionsConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -27,11 +27,8 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Tests stateless model evaluation (turned on by the "model-evaluation" tag in "container")
@@ -42,7 +39,7 @@ public class ModelEvaluationTest {
/** Tests that we do not load models (which would waste memory) when not requested */
@Test
- public void testMl_serving_not_activated() {
+ void testMl_serving_not_activated() {
Path appDir = Path.fromString("src/test/cfg/application/ml_serving_not_activated");
try {
ImportedModelTester tester = new ImportedModelTester("ml_serving", appDir);
@@ -62,7 +59,7 @@ public class ModelEvaluationTest {
}
@Test
- public void testMl_serving() throws IOException {
+ void testMl_serving() throws IOException {
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
Path appDir = Path.fromString("src/test/cfg/application/ml_serving");
Path storedAppDir = appDir.append("copy");
@@ -74,7 +71,7 @@ public class ModelEvaluationTest {
storedAppDir.toFile().mkdirs();
IOUtils.copy(appDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString());
IOUtils.copyDirectory(appDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(),
- storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
+ storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile());
ImportedModelTester storedTester = new ImportedModelTester("ml_serving", storedAppDir);
assertHasMlModels(storedTester.createVespaModel(), appDir);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java
index b2d4953f8e2..804133fbc0a 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java
@@ -6,17 +6,17 @@ import com.yahoo.config.model.application.provider.FilesApplicationPackage;
import com.yahoo.io.IOUtils;
import com.yahoo.path.Path;
import com.yahoo.tensor.TensorType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class OnnxModelProbeTest {
@Test
- public void testProbedOutputTypes() throws IOException {
+ void testProbedOutputTypes() throws IOException {
Path appDir = Path.fromString("src/test/cfg/application/onnx_probe");
Path storedAppDir = appDir.append("copy");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java
index bad6fcc68c2..00e510ce0ff 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java
@@ -18,7 +18,7 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig;
import com.yahoo.vespa.config.search.core.RankingExpressionsConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -27,10 +27,8 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Tests stateless model evaluation (turned on by the "model-evaluation" tag in "container")
@@ -41,7 +39,7 @@ import static org.junit.Assume.assumeTrue;
public class StatelessOnnxEvaluationTest {
@Test
- public void testStatelessOnnxModelNameCollision() {
+ void testStatelessOnnxModelNameCollision() {
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
Path appDir = Path.fromString("src/test/cfg/application/onnx_name_collision");
try {
@@ -62,7 +60,7 @@ public class StatelessOnnxEvaluationTest {
}
@Test
- public void testStatelessOnnxModelEvaluation() throws IOException {
+ void testStatelessOnnxModelEvaluation() throws IOException {
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
Path appDir = Path.fromString("src/test/cfg/application/onnx");
Path storedAppDir = appDir.append("copy");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java
index 30678205e3a..f661d17bcf5 100755
--- a/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.messagebus.MessagebusConfig;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocolPoliciesConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -23,9 +23,7 @@ import java.util.List;
import java.util.Map;
import static helpers.CompareConfigTestHelper.assertSerializedConfigEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -35,13 +33,13 @@ public class RoutingTestCase {
private static final boolean WRITE_FILES = false;
@Test
- public void testRoutingContent() throws IOException {
+ void testRoutingContent() throws IOException {
assertApplication(new File("src/test/cfg/routing/contentsimpleconfig"));
assertApplication(new File("src/test/cfg/routing/content_two_clusters"));
}
@Test
- public void testRouting() throws IOException {
+ void testRouting() throws IOException {
assertApplication(new File("src/test/cfg/routing/unexpectedrecipient"));
assertApplication(new File("src/test/cfg/routing/servicenotfound"));
assertApplication(new File("src/test/cfg/routing/routenotfoundinroute"));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java
index 5571ead11ce..fece6ca47e3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java
@@ -6,13 +6,13 @@ import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provisioning.FlavorsConfig;
import com.yahoo.vespa.config.search.core.ProtonConfig;
import com.yahoo.vespa.model.container.ApplicationContainerCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static com.yahoo.vespa.model.search.NodeResourcesTuning.reservedMemoryGb;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.vespa.model.search.NodeResourcesTuning.MB;
import static com.yahoo.vespa.model.search.NodeResourcesTuning.GB;
@@ -26,19 +26,19 @@ public class NodeResourcesTuningTest {
private static final double DEFAULT_MEMORY_GAIN = 0.08;
@Test
- public void require_that_hwinfo_disk_size_is_set() {
+ void require_that_hwinfo_disk_size_is_set() {
ProtonConfig cfg = configFromDiskSetting(100);
assertEquals(100 * GB, cfg.hwinfo().disk().size());
}
@Test
- public void require_that_hwinfo_memory_size_is_set() {
+ void require_that_hwinfo_memory_size_is_set() {
assertEquals(24 * GB, configFromMemorySetting(24 + reservedMemoryGb, 0).hwinfo().memory().size());
- assertEquals(combinedFactor * 24 * GB, configFromMemorySetting(24 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).hwinfo().memory().size(), 1000);
+ assertEquals(combinedFactor * 24 * GB, configFromMemorySetting(24 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).hwinfo().memory().size(), 1000);
}
@Test
- public void reserved_memory_on_content_node_is_0_5_gb() {
+ void reserved_memory_on_content_node_is_0_5_gb() {
assertEquals(0.5, reservedMemoryGb, delta);
}
@@ -65,19 +65,19 @@ public class NodeResourcesTuningTest {
}
@Test
- public void require_that_initial_numdocs_is_dependent_of_mode_and_searchablecopies() {
+ void require_that_initial_numdocs_is_dependent_of_mode_and_searchablecopies() {
verify_that_initial_numdocs_is_dependent_of_mode();
}
@Test
- public void require_that_hwinfo_cpu_cores_is_set() {
+ void require_that_hwinfo_cpu_cores_is_set() {
ProtonConfig cfg = configFromNumCoresSetting(24);
assertEquals(24, cfg.hwinfo().cpu().cores());
}
@Test
- public void require_that_num_search_threads_and_summary_threads_follow_cores() {
+ void require_that_num_search_threads_and_summary_threads_follow_cores() {
ProtonConfig cfg = configFromNumCoresSetting(4.5);
assertEquals(5, cfg.numsearcherthreads());
assertEquals(5, cfg.numsummarythreads());
@@ -85,7 +85,7 @@ public class NodeResourcesTuningTest {
}
@Test
- public void require_that_num_search_threads_and_considers_explict_num_threads_per_search() {
+ void require_that_num_search_threads_and_considers_explict_num_threads_per_search() {
ProtonConfig cfg = configFromNumCoresSetting(4.5, 3);
assertEquals(15, cfg.numsearcherthreads());
assertEquals(5, cfg.numsummarythreads());
@@ -93,45 +93,45 @@ public class NodeResourcesTuningTest {
}
@Test
- public void require_that_fast_disk_is_reflected_in_proton_config() {
+ void require_that_fast_disk_is_reflected_in_proton_config() {
ProtonConfig cfg = configFromDiskSetting(true);
assertEquals(200, cfg.hwinfo().disk().writespeed(), delta);
assertEquals(100, cfg.hwinfo().disk().slowwritespeedlimit(), delta);
}
@Test
- public void require_that_slow_disk_is_reflected_in_proton_config() {
+ void require_that_slow_disk_is_reflected_in_proton_config() {
ProtonConfig cfg = configFromDiskSetting(false);
assertEquals(40, cfg.hwinfo().disk().writespeed(), delta);
assertEquals(100, cfg.hwinfo().disk().slowwritespeedlimit(), delta);
}
@Test
- public void require_that_document_store_maxfilesize_is_set_based_on_available_memory() {
+ void require_that_document_store_maxfilesize_is_set_based_on_available_memory() {
assertDocumentStoreMaxFileSize(256 * MB, 4);
assertDocumentStoreMaxFileSize(256 * MB, 6);
assertDocumentStoreMaxFileSize(256 * MB, 8);
assertDocumentStoreMaxFileSize(256 * MB, 12);
- assertDocumentStoreMaxFileSize((long)(16*GB*0.02), 16);
- assertDocumentStoreMaxFileSize((long)(24*GB*0.02), 24);
- assertDocumentStoreMaxFileSize((long)(32*GB*0.02), 32);
- assertDocumentStoreMaxFileSize((long)(48*GB*0.02), 48);
- assertDocumentStoreMaxFileSize((long)(64*GB*0.02), 64);
- assertDocumentStoreMaxFileSize((long)(128*GB*0.02), 128);
- assertDocumentStoreMaxFileSize((long)(256*GB*0.02), 256);
- assertDocumentStoreMaxFileSize((long)(512*GB*0.02), 512);
+ assertDocumentStoreMaxFileSize((long) (16 * GB * 0.02), 16);
+ assertDocumentStoreMaxFileSize((long) (24 * GB * 0.02), 24);
+ assertDocumentStoreMaxFileSize((long) (32 * GB * 0.02), 32);
+ assertDocumentStoreMaxFileSize((long) (48 * GB * 0.02), 48);
+ assertDocumentStoreMaxFileSize((long) (64 * GB * 0.02), 64);
+ assertDocumentStoreMaxFileSize((long) (128 * GB * 0.02), 128);
+ assertDocumentStoreMaxFileSize((long) (256 * GB * 0.02), 256);
+ assertDocumentStoreMaxFileSize((long) (512 * GB * 0.02), 512);
}
@Test
- public void require_that_flush_strategy_memory_limits_are_set_based_on_available_memory() {
- assertFlushStrategyMemory((long)(4 * GB * DEFAULT_MEMORY_GAIN), 4);
- assertFlushStrategyMemory((long)(8 * GB * DEFAULT_MEMORY_GAIN), 8);
- assertFlushStrategyMemory((long)(24 * GB * DEFAULT_MEMORY_GAIN), 24);
- assertFlushStrategyMemory((long)(64 * GB * DEFAULT_MEMORY_GAIN), 64);
+ void require_that_flush_strategy_memory_limits_are_set_based_on_available_memory() {
+ assertFlushStrategyMemory((long) (4 * GB * DEFAULT_MEMORY_GAIN), 4);
+ assertFlushStrategyMemory((long) (8 * GB * DEFAULT_MEMORY_GAIN), 8);
+ assertFlushStrategyMemory((long) (24 * GB * DEFAULT_MEMORY_GAIN), 24);
+ assertFlushStrategyMemory((long) (64 * GB * DEFAULT_MEMORY_GAIN), 64);
}
@Test
- public void require_that_flush_strategy_tls_size_is_set_based_on_available_disk() {
+ void require_that_flush_strategy_tls_size_is_set_based_on_available_disk() {
assertFlushStrategyTlsSize(2 * GB, 10);
assertFlushStrategyTlsSize(2 * GB, 100);
assertFlushStrategyTlsSize(10 * GB, 500);
@@ -140,31 +140,31 @@ public class NodeResourcesTuningTest {
}
@Test
- public void require_that_summary_read_io_is_set_based_on_disk() {
+ void require_that_summary_read_io_is_set_based_on_disk() {
assertSummaryReadIo(ProtonConfig.Summary.Read.Io.DIRECTIO, true);
assertSummaryReadIo(ProtonConfig.Summary.Read.Io.MMAP, false);
}
@Test
- public void require_that_search_read_mmap_advise_is_set_based_on_disk() {
+ void require_that_search_read_mmap_advise_is_set_based_on_disk() {
assertSearchReadAdvise(ProtonConfig.Search.Mmap.Advise.RANDOM, true);
assertSearchReadAdvise(ProtonConfig.Search.Mmap.Advise.NORMAL, false);
}
@Test
- public void require_that_summary_cache_max_bytes_is_set_based_on_memory() {
- assertEquals(1*GB / 25, configFromMemorySetting(1 + reservedMemoryGb, 0).summary().cache().maxbytes());
- assertEquals(256*GB / 25, configFromMemorySetting(256 + reservedMemoryGb, 0).summary().cache().maxbytes());
+ void require_that_summary_cache_max_bytes_is_set_based_on_memory() {
+ assertEquals(1 * GB / 25, configFromMemorySetting(1 + reservedMemoryGb, 0).summary().cache().maxbytes());
+ assertEquals(256 * GB / 25, configFromMemorySetting(256 + reservedMemoryGb, 0).summary().cache().maxbytes());
}
@Test
- public void require_that_summary_cache_memory_is_reduced_with_combined_cluster() {
- assertEquals(combinedFactor * 1*GB / 25, configFromMemorySetting(1 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).summary().cache().maxbytes(), 1000);
- assertEquals(combinedFactor * 256*GB / 25, configFromMemorySetting(256 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).summary().cache().maxbytes(), 1000);
+ void require_that_summary_cache_memory_is_reduced_with_combined_cluster() {
+ assertEquals(combinedFactor * 1 * GB / 25, configFromMemorySetting(1 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).summary().cache().maxbytes(), 1000);
+ assertEquals(combinedFactor * 256 * GB / 25, configFromMemorySetting(256 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).summary().cache().maxbytes(), 1000);
}
@Test
- public void require_that_docker_node_is_tagged_with_shared_disk() {
+ void require_that_docker_node_is_tagged_with_shared_disk() {
assertSharedDisk(true, true);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java
index a3c57dae2de..8830e5484b3 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java
@@ -17,7 +17,7 @@ import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.content.ContentSearchCluster;
import com.yahoo.vespa.model.content.utils.DocType;
import com.yahoo.vespa.model.search.IndexedSearchCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -25,7 +25,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -35,31 +35,31 @@ public class DocumentDatabaseTestCase {
private static final double SMALL = 0.00000000000001;
@Test
- public void requireThatWeCanHaveOneSDForIndexedMode() {
+ void requireThatWeCanHaveOneSDForIndexedMode() {
new SchemaTester().assertSingleSD("index");
}
@Test
- public void requireThatConcurrencyIsReflectedCorrectlyForDefault() {
+ void requireThatConcurrencyIsReflectedCorrectlyForDefault() {
verifyConcurrency("index", "", 0.50);
verifyConcurrency("streaming", "", 1.0);
verifyConcurrency("store-only", "", 1.0);
}
@Test
- public void requireThatFeatureFlagConcurrencyIsReflectedCorrectlyForDefault() {
+ void requireThatFeatureFlagConcurrencyIsReflectedCorrectlyForDefault() {
verifyConcurrency("index", "", 0.30, 0.3);
verifyConcurrency("streaming", "", 0.6, 0.3);
verifyConcurrency("store-only", "", 0.8, 0.4);
}
@Test
- public void requireThatMixedModeConcurrencyIsReflectedCorrectlyForDefault() {
+ void requireThatMixedModeConcurrencyIsReflectedCorrectlyForDefault() {
verifyConcurrency(Arrays.asList(DocType.create("a", "index"), DocType.create("b", "streaming")), "", 1.0);
}
@Test
- public void requireThatMixedModeConcurrencyIsReflected() {
+ void requireThatMixedModeConcurrencyIsReflected() {
String feedTuning = "<feeding>" +
" <concurrency>0.7</concurrency>" +
"</feeding>\n";
@@ -67,10 +67,10 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void requireThatConcurrencyIsReflected() {
+ void requireThatConcurrencyIsReflected() {
String feedTuning = "<feeding>" +
- " <concurrency>0.7</concurrency>" +
- "</feeding>\n";
+ " <concurrency>0.7</concurrency>" +
+ "</feeding>\n";
verifyConcurrency("index", feedTuning, 0.7);
verifyConcurrency("streaming", feedTuning, 0.7);
verifyConcurrency("store-only", feedTuning, 0.7);
@@ -113,17 +113,17 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void requireFeedNicenessIsReflected() {
+ void requireFeedNicenessIsReflected() {
verifyFeedNiceness(Arrays.asList(DocType.create("a", "index")), 0.0, null);
verifyFeedNiceness(Arrays.asList(DocType.create("a", "index")), 0.32, 0.32);
}
@Test
- public void requireThatModeIsSet() {
+ void requireThatModeIsSet() {
var tester = new SchemaTester();
VespaModel model = tester.createModel(Arrays.asList(DocType.create("a", "index"),
- DocType.create("b", "streaming"),
- DocType.create("c", "store-only")), "");
+ DocType.create("b", "streaming"),
+ DocType.create("c", "store-only")), "");
ContentSearchCluster contentSearchCluster = model.getContentClusters().get("test").getSearch();
ProtonConfig proton = tester.getProtonConfig(contentSearchCluster);
assertEquals(3, proton.documentdb().size());
@@ -148,13 +148,14 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void requireThatMixedModeInitialDocumentCountIsReflectedCorrectlyForDefault() {
+ void requireThatMixedModeInitialDocumentCountIsReflectedCorrectlyForDefault() {
final long DEFAULT = 1024L;
verifyInitialDocumentCount(Arrays.asList(DocType.create("a", "index"), DocType.create("b", "streaming")),
"", Arrays.asList(DEFAULT, DEFAULT));
}
+
@Test
- public void requireThatMixedModeInitialDocumentCountIsReflected() {
+ void requireThatMixedModeInitialDocumentCountIsReflected() {
final long INITIAL = 1000000000L;
String feedTuning = "<resizing>" +
" <initialdocumentcount>1000000000</initialdocumentcount>" +
@@ -176,11 +177,11 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void testMultipleSchemas() {
+ void testMultipleSchemas() {
List<String> sds = List.of("type1", "type2", "type3");
var tester = new SchemaTester();
var model = tester.createModel(sds);
- IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster)model.getSearchClusters().get(0);
+ IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster) model.getSearchClusters().get(0);
ContentSearchCluster contentSearchCluster = model.getContentClusters().get("test").getSearch();
String type1Id = "test/search/cluster.test/type1";
String type2Id = "test/search/cluster.test/type2";
@@ -226,26 +227,26 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void testRankingConstants() {
+ void testRankingConstants() {
List<String> schemas = List.of("type1");
var tester = new SchemaTester();
// Use lz4 endings to avoid having to provide file content to be validated
String schemaConstants =
" constant constant_1 {" +
- " file: constants/my_constant_1.json.lz4" +
- " type: tensor<float>(x{},y{})" +
- " }" +
- " constant constant_2 {" +
- " file: constants/my_constant_2.json.lz4" +
- " type: tensor(x[1000])" +
- " }";
+ " file: constants/my_constant_1.json.lz4" +
+ " type: tensor<float>(x{},y{})" +
+ " }" +
+ " constant constant_2 {" +
+ " file: constants/my_constant_2.json.lz4" +
+ " type: tensor(x[1000])" +
+ " }";
Map<Path, String> constants = new HashMap<>();
constants.put(Path.fromString("constants/my_constant_1.json.lz4"), "");
constants.put(Path.fromString("constants/my_constant_2.json.lz4"), "");
var model = tester.createModel(schemaConstants, "", schemas, constants);
- IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster)model.getSearchClusters().get(0);
+ IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster) model.getSearchClusters().get(0);
RankingConstantsConfig.Builder b = new RankingConstantsConfig.Builder();
indexedSearchCluster.getDocumentDbs().get(0).getConfig(b);
RankingConstantsConfig config = b.build();
@@ -263,14 +264,14 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void requireThatRelevantConfigIsAvailableForClusterSearcher() {
+ void requireThatRelevantConfigIsAvailableForClusterSearcher() {
String inputsProfile =
" rank-profile inputs {" +
- " inputs {" +
- " query(foo) tensor<float>(x[10])" +
- " query(bar) tensor(key{},x[1000])" +
- " }" +
- " }";
+ " inputs {" +
+ " query(foo) tensor<float>(x[10])" +
+ " query(bar) tensor(key{},x[1000])" +
+ " }" +
+ " }";
List<String> schemas = List.of("type1", "type2");
var tester = new SchemaTester();
VespaModel model = tester.createModelWithRankProfile(inputsProfile, schemas);
@@ -305,7 +306,7 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void requireThatDocumentDBConfigIsAvailableForStreaming() {
+ void requireThatDocumentDBConfigIsAvailableForStreaming() {
assertDocumentDBConfigAvailableForStreaming("streaming");
}
@@ -343,7 +344,7 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void testThatAttributesMaxUnCommittedMemoryIsControlledByFeatureFlag() {
+ void testThatAttributesMaxUnCommittedMemoryIsControlledByFeatureFlag() {
assertAttributesConfigIndependentOfMode("index", Arrays.asList("type1"),
Arrays.asList("test/search/cluster.test/type1"),
ImmutableMap.of("type1", Arrays.asList("f2", "f2_nfa")),
@@ -351,20 +352,21 @@ public class DocumentDatabaseTestCase {
}
@Test
- public void testThatAttributesConfigIsProducedForIndexed() {
+ void testThatAttributesConfigIsProducedForIndexed() {
assertAttributesConfigIndependentOfMode("index", Arrays.asList("type1"),
Arrays.asList("test/search/cluster.test/type1"),
ImmutableMap.of("type1", Arrays.asList("f2", "f2_nfa")));
}
@Test
- public void testThatAttributesConfigIsProducedForStreamingForFastAccessFields() {
+ void testThatAttributesConfigIsProducedForStreamingForFastAccessFields() {
assertAttributesConfigIndependentOfMode("streaming", Arrays.asList("type1"),
Arrays.asList("test/search/type1"),
ImmutableMap.of("type1", Arrays.asList("f2")));
}
+
@Test
- public void testThatAttributesConfigIsNotProducedForStoreOnlyEvenForFastAccessFields() {
+ void testThatAttributesConfigIsNotProducedForStoreOnlyEvenForFastAccessFields() {
assertAttributesConfigIndependentOfMode("store-only", Arrays.asList("type1"),
Arrays.asList("test/search"), Collections.emptyMap());
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java
index 9f14a78d8c5..5efe75bdca5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java
@@ -3,10 +3,10 @@ package com.yahoo.vespa.model.search.test;
import com.yahoo.document.select.parser.ParseException;
import com.yahoo.vespa.model.search.DocumentSelectionConverter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Unit tests for RemoveSelection.
@@ -14,19 +14,20 @@ import static org.junit.Assert.assertTrue;
*/
public class DocumentSelectionConverterTest {
@Test
- public void testQueryConversion() throws ParseException, IllegalArgumentException, UnsupportedOperationException {
+ void testQueryConversion() throws ParseException, IllegalArgumentException, UnsupportedOperationException {
DocumentSelectionConverter converter = new DocumentSelectionConverter("music.expire>now() - 3600 and video.expire > now() - 300");
assertEquals("expire:>now(3600)", converter.getQuery("music"));
assertEquals("expire:<now(3600)", converter.getInvertedQuery("music"));
assertEquals("expire:>now(300)", converter.getQuery("video"));
assertEquals("expire:<now(300)", converter.getInvertedQuery("video"));
- assertTrue(null == converter.getQuery("book"));
- assertTrue(null == converter.getInvertedQuery("book"));
+ assertNull(converter.getQuery("book"));
+ assertNull(converter.getInvertedQuery("book"));
}
+
@Test
- public void testSelection() throws ParseException, IllegalArgumentException, UnsupportedOperationException {
+ void testSelection() throws ParseException, IllegalArgumentException, UnsupportedOperationException {
DocumentSelectionConverter converter = new DocumentSelectionConverter("music.expire>music.expire.nowdate");
- assertTrue(converter.getQuery("music") == null);
- assertTrue(converter.getInvertedQuery("music") == null);
+ assertNull(converter.getQuery("music"));
+ assertNull(converter.getInvertedQuery("music"));
}
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java
index 1d15f973d21..3e5a473c1ca 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java
@@ -21,12 +21,9 @@ import com.yahoo.vespa.model.container.component.Component;
import com.yahoo.vespa.model.search.SearchCluster;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -38,7 +35,7 @@ import static org.junit.Assert.assertTrue;
public class SchemaClusterTest {
@Test
- public void testSdConfigLogical() {
+ void testSdConfigLogical() {
// sd1
SDDocumentType sdt1 = new SDDocumentType("s1");
Schema schema1 = new Schema("s1", MockApplicationPackage.createEmpty());
@@ -51,7 +48,7 @@ public class SchemaClusterTest {
// sd2
SDDocumentType sdt2 = new SDDocumentType("s2");
Schema schema2 = new Schema("s2", MockApplicationPackage.createEmpty());
- SDField f2=new SDField(sdt2, "f2", DataType.STRING);
+ SDField f2 = new SDField(sdt2, "f2", DataType.STRING);
f2.addAttribute(new Attribute("f2", DataType.STRING));
f2.setIndexingScript(new ScriptExpression(new StatementExpression(new AttributeExpression("f2"))));
sdt2.addField(f2);
@@ -64,76 +61,76 @@ public class SchemaClusterTest {
}
@Test
- public void search_model_is_connected_to_container_clusters_two_content_clusters() {
+ void search_model_is_connected_to_container_clusters_two_content_clusters() {
String vespaHosts = "<?xml version='1.0' encoding='utf-8' ?>" +
- "<hosts>" +
- " <host name='node0host'>" +
- " <alias>node0</alias>" +
- " </host>" +
- " <host name='node1host'>" +
- " <alias>node1</alias>" +
- " </host>" +
- " <host name='node2host'>" +
- " <alias>node2</alias>" +
- " </host>" +
- "</hosts>";
+ "<hosts>" +
+ " <host name='node0host'>" +
+ " <alias>node0</alias>" +
+ " </host>" +
+ " <host name='node1host'>" +
+ " <alias>node1</alias>" +
+ " </host>" +
+ " <host name='node2host'>" +
+ " <alias>node2</alias>" +
+ " </host>" +
+ "</hosts>";
String services =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
- "<services version=\"1.0\">" +
- " <admin version='2.0'>" +
- " <adminserver hostalias='node0' />" +
- " </admin>\n" +
- " <container version='1.0' id='j1'>\n" +
- " <search>" +
- " <chain id='s1Chain'>" +
- " <searcher id='S1ClusterSearcher'/>" +
- " </chain>" +
- " <provider cluster='normal' id='normal' type='local'/>\n" +
- " </search>" +
- " <nodes>" +
- " <node hostalias=\"node0\" />" +
- " </nodes>" +
- " </container>" +
-
- " <container version='1.0' id='j2'>" +
- " <search>" +
- " <chain id='s2Chain'>" +
- " <searcher id='S2ClusterSearcher'/>" +
- " </chain>" +
- " <provider cluster='xbulk' id='xbulk' type='local'/>" +
- " </search>" +
- " <nodes>" +
- " <node hostalias=\"node2\" />" +
- " </nodes>" +
- " </container>" +
-
- " <content id='xbulk' version=\"1.0\">" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document mode='index' type=\"music\" />" +
- " </documents>" +
- " <nodes>" +
- " <node hostalias=\"node0\" distribution-key=\"0\" />" +
- " </nodes>" +
- " </content>" +
- " <content id=\"normal\" version='1.0'>" +
- " <redundancy>2</redundancy>" +
- " <documents>" +
- " <document mode='index' type=\"music\" />" +
- " </documents>" +
- " <nodes>" +
- " <node hostalias=\"node2\" distribution-key=\"0\" />" +
- " </nodes>" +
- " </content>" +
- "</services>";
+ "<services version=\"1.0\">" +
+ " <admin version='2.0'>" +
+ " <adminserver hostalias='node0' />" +
+ " </admin>\n" +
+ " <container version='1.0' id='j1'>\n" +
+ " <search>" +
+ " <chain id='s1Chain'>" +
+ " <searcher id='S1ClusterSearcher'/>" +
+ " </chain>" +
+ " <provider cluster='normal' id='normal' type='local'/>\n" +
+ " </search>" +
+ " <nodes>" +
+ " <node hostalias=\"node0\" />" +
+ " </nodes>" +
+ " </container>" +
+
+ " <container version='1.0' id='j2'>" +
+ " <search>" +
+ " <chain id='s2Chain'>" +
+ " <searcher id='S2ClusterSearcher'/>" +
+ " </chain>" +
+ " <provider cluster='xbulk' id='xbulk' type='local'/>" +
+ " </search>" +
+ " <nodes>" +
+ " <node hostalias=\"node2\" />" +
+ " </nodes>" +
+ " </container>" +
+
+ " <content id='xbulk' version=\"1.0\">" +
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type=\"music\" />" +
+ " </documents>" +
+ " <nodes>" +
+ " <node hostalias=\"node0\" distribution-key=\"0\" />" +
+ " </nodes>" +
+ " </content>" +
+ " <content id=\"normal\" version='1.0'>" +
+ " <redundancy>2</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type=\"music\" />" +
+ " </documents>" +
+ " <nodes>" +
+ " <node hostalias=\"node2\" distribution-key=\"0\" />" +
+ " </nodes>" +
+ " </content>" +
+ "</services>";
VespaModel model = new VespaModelCreatorWithMockPkg(vespaHosts, services, ApplicationPackageUtils.generateSchemas("music")).create();
- ContainerCluster containerCluster1 = (ContainerCluster)model.getConfigProducer("j1").get();
+ ContainerCluster containerCluster1 = (ContainerCluster) model.getConfigProducer("j1").get();
assertFalse(containerCluster1.getSearch().getChains().localProviders().isEmpty());
- ContainerCluster containerCluster2 = (ContainerCluster)model.getConfigProducer("j2").get();
+ ContainerCluster containerCluster2 = (ContainerCluster) model.getConfigProducer("j2").get();
assertFalse(containerCluster2.getSearch().getChains().localProviders().isEmpty());
QrSearchersConfig.Builder builder = new QrSearchersConfig.Builder();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java
index b8a14bc763b..622fcfdf4fd 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java
@@ -4,34 +4,34 @@ package com.yahoo.vespa.model.search.test;
import com.yahoo.search.config.SchemaInfoConfig;
import com.yahoo.vespa.config.search.RankProfilesConfig;
import com.yahoo.vespa.model.VespaModel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class SchemaInfoTestCase {
/** Schema-info should contain all schemas, independent of clusters. */
@Test
- public void requireThatSchemaInfoIsAvailable() {
- List.of(1.0,2.0,3.0).toArray(new Double[3]);
+ void requireThatSchemaInfoIsAvailable() {
+ List.of(1.0, 2.0, 3.0).toArray(new Double[3]);
String inputs =
" rank-profile inputs {" +
- " inputs {" +
- " query(foo) tensor<float>(x[10])" +
- " query(bar) tensor(key{},x[1000])" +
- " query(myDouble1) double: 0.5" +
- " query(myDouble2) tensor()" +
- " query(myMap) tensor(key{}): { label1:1.0,\n \"label2\": 2.0, 'label3': 3.0 }" +
- " query(myVector1) tensor(x[3]):\n\n[1 ,2.0,3]" +
- " query(myVector2) tensor(x[3]):{{x:0}:1,{x: 1}: 2 , { x:2}:3.0 }" +
- " query(myMatrix) tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]" +
- " query(myMixed1) tensor(key{},x[2]): { key1:[-1.0, 1.1], key2: [1,2]}" +
- " query(myMixed2) tensor(k1{},k2{},x[2]): { {k1:l1,k2:l1}:[-1.0, 1.1], {k1:l1,k2:l2}: [1,2]}" +
- " }" +
- " }";
+ " inputs {" +
+ " query(foo) tensor<float>(x[10])" +
+ " query(bar) tensor(key{},x[1000])" +
+ " query(myDouble1) double: 0.5" +
+ " query(myDouble2) tensor()" +
+ " query(myMap) tensor(key{}): { label1:1.0,\n \"label2\": 2.0, 'label3': 3.0 }" +
+ " query(myVector1) tensor(x[3]):\n\n[1 ,2.0,3]" +
+ " query(myVector2) tensor(x[3]):{{x:0}:1,{x: 1}: 2 , { x:2}:3.0 }" +
+ " query(myMatrix) tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]" +
+ " query(myMixed1) tensor(key{},x[2]): { key1:[-1.0, 1.1], key2: [1,2]}" +
+ " query(myMixed2) tensor(k1{},k2{},x[2]): { {k1:l1,k2:l1}:[-1.0, 1.1], {k1:l1,k2:l2}: [1,2]}" +
+ " }" +
+ " }";
List<String> schemas = List.of("type1", "type2");
var tester = new SchemaTester();
var model = tester.createModelWithRankProfile(inputs, schemas);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java
index 9d1aece61d4..3deccbbb679 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java
@@ -16,7 +16,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java
index f8a68e4b4a5..7ed27018d5f 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java
@@ -13,13 +13,11 @@ import com.yahoo.vespa.model.HostResource;
import com.yahoo.vespa.model.search.NodeSpec;
import com.yahoo.vespa.model.search.SearchNode;
import com.yahoo.vespa.model.search.TransactionLogServer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for search node.
@@ -59,14 +57,14 @@ public class SearchNodeTest {
}
@Test
- public void requireThatSyncIsHonoured() {
+ void requireThatSyncIsHonoured() {
assertTrue(getTlsConfig(new TestProperties(), null).usefsync());
assertTrue(getTlsConfig(new TestProperties(), true).usefsync());
assertFalse(getTlsConfig(new TestProperties(), false).usefsync());
}
@Test
- public void requireThatBasedirIsCorrectForElasticMode() {
+ void requireThatBasedirIsCorrectForElasticMode() {
MockRoot root = new MockRoot("");
SearchNode node = createSearchNode(root, "mynode", 3, new NodeSpec(7, 5), false, root.getDeployState().isHosted(), new TestProperties());
prepare(root, node, true);
@@ -74,7 +72,7 @@ public class SearchNodeTest {
}
@Test
- public void requireThatPreShutdownCommandIsEmptyWhenNotActivated() {
+ void requireThatPreShutdownCommandIsEmptyWhenNotActivated() {
MockRoot root = new MockRoot("");
SearchNode node = createSearchNode(root, "mynode", 3, new NodeSpec(7, 5), false, root.getDeployState().isHosted(), new TestProperties());
node.setHostResource(new HostResource(new Host(node, "mynbode")));
@@ -83,7 +81,7 @@ public class SearchNodeTest {
}
@Test
- public void requireThatPreShutdownCommandUsesPrepareRestartWhenActivated() {
+ void requireThatPreShutdownCommandUsesPrepareRestartWhenActivated() {
MockRoot root = new MockRoot("");
SearchNode node = createSearchNode(root, "mynode2", 4, new NodeSpec(7, 5), true, root.getDeployState().isHosted(), new TestProperties());
node.setHostResource(new HostResource(new Host(node, "mynbode2")));
@@ -101,7 +99,7 @@ public class SearchNodeTest {
}
@Test
- public void requireThatCodePageTypeCanBeControlled() {
+ void requireThatCodePageTypeCanBeControlled() {
verifyCodePlacement(true);
verifyCodePlacement(false);
}
@@ -115,7 +113,7 @@ public class SearchNodeTest {
}
@Test
- public void requireThatSharedRepoReclaimCanBeControlled() {
+ void requireThatSharedRepoReclaimCanBeControlled() {
verifySharedStringRepoReclaim(true);
verifySharedStringRepoReclaim(false);
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java
index 356021cdd1d..e7bc3fa9867 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.model.storage;
import com.yahoo.vespa.model.content.DistributionBitCalculator;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class DistributionBitCalculatorTest {
@Test
- public void testBitCalculator() {
+ void testBitCalculator() {
ContentCluster.DistributionMode mode = ContentCluster.DistributionMode.STRICT;
assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode));
assertEquals(16, DistributionBitCalculator.getDistributionBits(10, mode));
@@ -19,15 +19,15 @@ public class DistributionBitCalculatorTest {
assertEquals(28, DistributionBitCalculator.getDistributionBits(1000, mode));
mode = ContentCluster.DistributionMode.LOOSE;
- assertEquals( 8, DistributionBitCalculator.getDistributionBits(1, mode));
- assertEquals( 8, DistributionBitCalculator.getDistributionBits(4, mode));
+ assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode));
+ assertEquals(8, DistributionBitCalculator.getDistributionBits(4, mode));
assertEquals(16, DistributionBitCalculator.getDistributionBits(5, mode));
assertEquals(16, DistributionBitCalculator.getDistributionBits(199, mode));
assertEquals(24, DistributionBitCalculator.getDistributionBits(200, mode));
assertEquals(24, DistributionBitCalculator.getDistributionBits(2500, mode));
mode = ContentCluster.DistributionMode.LEGACY;
- assertEquals( 8, DistributionBitCalculator.getDistributionBits(1, mode));
+ assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode));
assertEquals(14, DistributionBitCalculator.getDistributionBits(4, mode));
assertEquals(19, DistributionBitCalculator.getDistributionBits(16, mode));
assertEquals(23, DistributionBitCalculator.getDistributionBits(200, mode));
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java
index 72d6a80e711..f0b6157ba52 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java
@@ -6,10 +6,9 @@ import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests storage model
@@ -19,9 +18,11 @@ import static org.junit.Assert.assertNotNull;
*/
public class StorageModelTestCase {
- @Test(expected=RuntimeException.class)
- public void testTwoClustersSameName() {
- createModel("src/test/cfg/storage/twoclusterssamename");
+ @Test
+ void testTwoClustersSameName() {
+ assertThrows(RuntimeException.class, () -> {
+ createModel("src/test/cfg/storage/twoclusterssamename");
+ });
}
private VespaModel createModel(String filename) {
@@ -29,7 +30,7 @@ public class StorageModelTestCase {
}
@Test
- public void testIndexGreaterThanNumNodes() {
+ void testIndexGreaterThanNumNodes() {
VespaModel vespaModel = createModel("src/test/cfg/storage/app_index_higher_than_num_nodes");
// Test fleet controller config
@@ -41,7 +42,7 @@ public class StorageModelTestCase {
}
@Test
- public void testMetricsSnapshotIntervalYAMAS() {
+ void testMetricsSnapshotIntervalYAMAS() {
VespaModel vespaModel = createModel("src/test/cfg/storage/clustercontroller_advanced");
ContentCluster contentCluster = vespaModel.getContentClusters().values().iterator().next();
assertNotNull(contentCluster);
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java
index 2ae1399e9d1..9be3b15be07 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java
@@ -20,16 +20,14 @@ import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.ContainerModel;
import com.yahoo.vespa.model.container.xml.ContainerModelBuilder;
import com.yahoo.vespa.model.content.Content;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Demonstrates how a model can be added at build time to amend another model.
@@ -42,44 +40,44 @@ import static org.junit.Assert.assertNotNull;
public class ModelAmendingTestCase {
@Test
- public void testModelAmending() {
+ void testModelAmending() {
ConfigModelRegistry amendingModelRepo = MapConfigModelRegistry.createFromList(new AdminModelAmenderBuilder(),
- new ContainerModelAmenderBuilder(),
- new ContentModelAmenderBuilder());
+ new ContainerModelAmenderBuilder(),
+ new ContentModelAmenderBuilder());
String services =
"<services version='1.0'>" +
- " <admin version='4.0'/>" +
- " <container id='test1' version='1.0'>" +
- " <search/>" +
- " <nodes count='2'/>" +
- " </container>" +
- " <container id='test2' version='1.0'>" +
- " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" +
- " <document-api/>" +
- " <nodes count='2'/>" +
- " </container>" +
- " <content id='test3' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1'/>" +
- " </documents>" +
- " <nodes count='2'/>" +
- " </content>" +
- " <content id='test4' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1'/>" +
- " </documents>" +
- " <nodes count='3'/>" +
- " </content>" +
- "</services>";
+ " <admin version='4.0'/>" +
+ " <container id='test1' version='1.0'>" +
+ " <search/>" +
+ " <nodes count='2'/>" +
+ " </container>" +
+ " <container id='test2' version='1.0'>" +
+ " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" +
+ " <document-api/>" +
+ " <nodes count='2'/>" +
+ " </container>" +
+ " <content id='test3' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1'/>" +
+ " </documents>" +
+ " <nodes count='2'/>" +
+ " </content>" +
+ " <content id='test4' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1'/>" +
+ " </documents>" +
+ " <nodes count='3'/>" +
+ " </content>" +
+ "</services>";
VespaModelTester tester = new VespaModelTester(amendingModelRepo);
tester.addHosts(12);
VespaModel model = tester.createModel(services);
// Check that all hosts are amended
for (HostResource host : model.getAdmin().hostSystem().getHosts()) {
- assertFalse(host + " is amended", host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty());
+ assertFalse(host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty(), host + " is amended");
}
// Check that container clusters are amended
@@ -89,44 +87,44 @@ public class ModelAmendingTestCase {
}
@Test
- public void testModelAmendingWithDedicatedCC() {
+ void testModelAmendingWithDedicatedCC() {
ConfigModelRegistry amendingModelRepo = MapConfigModelRegistry.createFromList(new AdminModelAmenderBuilder(),
- new ContainerModelAmenderBuilder(),
- new ContentModelAmenderBuilder());
+ new ContainerModelAmenderBuilder(),
+ new ContentModelAmenderBuilder());
String services =
"<services version='1.0'>" +
- " <admin version='4.0'/>" +
- " <container id='test1' version='1.0'>" +
- " <search/>" +
- " <nodes count='2'/>" +
- " </container>" +
- " <container id='test2' version='1.0'>" +
- " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" +
- " <document-api/>" +
- " <nodes count='2'/>" +
- " </container>" +
- " <content id='test3' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1'/>" +
- " </documents>" +
- " <nodes count='2'/>" +
- " </content>" +
- " <content id='test4' version='1.0'>" +
- " <redundancy>1</redundancy>" +
- " <documents>" +
- " <document mode='index' type='type1'/>" +
- " </documents>" +
- " <nodes count='3'/>" +
- " </content>" +
- "</services>";
+ " <admin version='4.0'/>" +
+ " <container id='test1' version='1.0'>" +
+ " <search/>" +
+ " <nodes count='2'/>" +
+ " </container>" +
+ " <container id='test2' version='1.0'>" +
+ " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" +
+ " <document-api/>" +
+ " <nodes count='2'/>" +
+ " </container>" +
+ " <content id='test3' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1'/>" +
+ " </documents>" +
+ " <nodes count='2'/>" +
+ " </content>" +
+ " <content id='test4' version='1.0'>" +
+ " <redundancy>1</redundancy>" +
+ " <documents>" +
+ " <document mode='index' type='type1'/>" +
+ " </documents>" +
+ " <nodes count='3'/>" +
+ " </content>" +
+ "</services>";
VespaModelTester tester = new VespaModelTester(amendingModelRepo);
tester.addHosts(12);
VespaModel model = tester.createModel(services);
// Check that all hosts are amended
for (HostResource host : model.getAdmin().hostSystem().getHosts()) {
- assertFalse(host + " is amended", host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty());
+ assertFalse(host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty(), host + " is amended");
}
// Check that container clusters are amended
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java
index 4632c536e43..fba51c4c027 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java
@@ -4,9 +4,9 @@ package com.yahoo.vespa.model.test;
import com.yahoo.cloud.config.ModelConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test HostSystem
@@ -19,13 +19,13 @@ public class ModelConfigProviderTest {
* Get the config via ConfigInstance based API, by getting whole config
*/
@Test
- public void testGetModelConfig() {
+ void testGetModelConfig() {
VespaModel vespaModel = new VespaModelCreatorWithFilePkg("src/test/cfg/admin/adminconfig20").create();
ModelConfig config = vespaModel.getConfig(ModelConfig.class, "");
assertEquals(config.hosts().size(), 1);
ModelConfig.Hosts localhost = config.hosts(0); //Actually set to hostname.
- int numLogservers=0;
- int numSlobroks=0;
+ int numLogservers = 0;
+ int numSlobroks = 0;
for (ModelConfig.Hosts.Services service : localhost.services()) {
if ("logserver".equals(service.type())) {
numLogservers++;
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java
index a54897e7ae4..0a1506fab5d 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java
@@ -2,12 +2,9 @@
package com.yahoo.vespa.model.test;
import com.yahoo.vespa.model.PortsMeta;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests proper functioning of the PortsMeta.
@@ -17,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class PortsMetaTestCase {
@Test
- public void testRegister() {
+ void testRegister() {
PortsMeta pm = new PortsMeta();
pm.on(0).tag("foo");
pm.on(1).tag("bar");
@@ -31,7 +28,7 @@ public class PortsMetaTestCase {
}
@Test
- public void testAdminStatusApi() {
+ void testAdminStatusApi() {
PortsMeta pm = new PortsMeta()
.on(0).tag("rpc").tag("nc").tag("admin").tag("status")
.on(1).tag("rpc").tag("rtx").tag("admin").tag("status")
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java
index 7f8bca825d2..1aa010020f5 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java
@@ -31,8 +31,8 @@ import com.yahoo.vespa.model.application.validation.Validation;
import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg;
import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.File;
@@ -45,10 +45,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -82,7 +79,7 @@ public class VespaModelTestCase {
// Verify that common config from plugins is delivered from the root node for any configId, using the Builder based API
@Test
- public void testCommonConfig() {
+ void testCommonConfig() {
VespaModel model = getVespaModel(TESTDIR + "app_nohosts/");
LogdConfig.Builder b = new LogdConfig.Builder();
b = (LogdConfig.Builder) model.getConfig(b, "");
@@ -109,8 +106,8 @@ public class VespaModelTestCase {
}
@Test
- public void testHostsConfig() {
- VespaModel model = getVespaModel(TESTDIR + "app_qrserverandgw");
+ void testHostsConfig() {
+ VespaModel model = getVespaModel(TESTDIR + "app_nohosts");
LogdConfig config = getLogdConfig(model, "");
assertEquals(config.logserver().host(), HostName.getLocalhost());
assertNotNull(config);
@@ -128,7 +125,7 @@ public class VespaModelTestCase {
}
@Test
- public void testHostsOverrides() {
+ void testHostsOverrides() {
VespaModel model = new VespaModelCreatorWithMockPkg(
simpleHosts,
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
@@ -148,23 +145,25 @@ public class VespaModelTestCase {
assertEquals(config.logserver().host(), "foo");
}
- @Ignore
- @Test(expected = UnknownConfigIdException.class)
- public void testIllegalConfigIdWithBuilders() {
- VespaModel model = getVespaModel(TESTDIR + "app_nohosts/");
- DocumentmanagerConfig.Builder db = new DocumentmanagerConfig.Builder();
- model.getConfig(db, "bogus");
+ @Disabled
+ @Test
+ void testIllegalConfigIdWithBuilders() {
+ assertThrows(UnknownConfigIdException.class, () -> {
+ VespaModel model = getVespaModel(TESTDIR + "app_nohosts/");
+ DocumentmanagerConfig.Builder db = new DocumentmanagerConfig.Builder();
+ model.getConfig(db, "bogus");
+ });
}
@Test
- public void testConfigLists() {
+ void testConfigLists() {
VespaModel model = getVespaModel(TESTDIR + "app_nohosts/");
assertTrue(model.allConfigsProduced().size() > 0);
assertTrue(model.allConfigIds().size() > 0);
}
@Test
- public void testCreateFromReaders() {
+ void testCreateFromReaders() {
VespaModel model = new VespaModelCreatorWithMockPkg(
simpleHosts,
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
@@ -197,20 +196,22 @@ public class VespaModelTestCase {
assertEquals(mBus.routingtable().size(), 1);
}
- @Test(expected = IllegalArgumentException.class)
- public void testHostsWithoutAliases() {
- new TestDriver().buildModel(
- "<services version='1.0'>" +
- " <admin version='2.0'>" +
- " <adminserver hostalias='node0' />" +
- " </admin>" +
- "</services>",
- "<hosts>" +
- " <host name='localhost'>" +
- " <alias>node0</alias>" +
- " </host>" +
- " <host name='foo.yahoo.com' />" +
- "</hosts>");
+ @Test
+ void testHostsWithoutAliases() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TestDriver().buildModel(
+ "<services version='1.0'>" +
+ " <admin version='2.0'>" +
+ " <adminserver hostalias='node0' />" +
+ " </admin>" +
+ "</services>",
+ "<hosts>" +
+ " <host name='localhost'>" +
+ " <alias>node0</alias>" +
+ " </host>" +
+ " <host name='foo.yahoo.com' />" +
+ "</hosts>");
+ });
}
static class MyLogger implements DeployLogger {
@@ -220,9 +221,9 @@ public class VespaModelTestCase {
msgs.add(new Pair<>(level, message));
}
}
-
+
@Test
- public void testDeployLogger() throws IOException, SAXException {
+ void testDeployLogger() throws IOException, SAXException {
final String services = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<services version=\"1.0\">" +
"<config name=\"bar.unknsownfoo\">" +
@@ -247,7 +248,7 @@ public class VespaModelTestCase {
}
@Test
- public void testNoAdmin() {
+ void testNoAdmin() {
VespaModel model = new VespaModelCreatorWithMockPkg(
simpleHosts,
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
@@ -267,7 +268,7 @@ public class VespaModelTestCase {
}
@Test
- public void testNoMultitenantHostExported() throws IOException, SAXException {
+ void testNoMultitenantHostExported() throws IOException, SAXException {
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withServices("<services version='1.0'><admin version='3.0'><nodes count='1' /></admin></services>")
.build();
@@ -280,20 +281,20 @@ public class VespaModelTestCase {
.build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState);
AllocatedHosts info = model.allocatedHosts();
- assertEquals("Admin version 3 is ignored, and there are no other hosts to borrow for admin services", 0, info.getHosts().size());
+ assertEquals(0, info.getHosts().size(), "Admin version 3 is ignored, and there are no other hosts to borrow for admin services");
}
@Test
- public void testMinimalApp() throws IOException, SAXException {
+ void testMinimalApp() throws IOException, SAXException {
VespaModel model = new VespaModel(new MockApplicationPackage.Builder()
- .withServices("<services version='1.0'><container version='1.0'><search /></container></services>")
- .build());
+ .withServices("<services version='1.0'><container version='1.0'><search /></container></services>")
+ .build());
assertEquals(1, model.hostSystem().getHosts().size());
assertEquals(1, model.getContainerClusters().size());
}
@Test
- public void testPermanentServices() throws IOException, SAXException {
+ void testPermanentServices() throws IOException, SAXException {
ApplicationPackage app = MockApplicationPackage.createEmpty();
DeployState.Builder builder = new DeployState.Builder().applicationPackage(app);
VespaModel model = new VespaModel(new NullConfigModelRegistry(), builder.build());
@@ -303,7 +304,7 @@ public class VespaModelTestCase {
}
@Test
- public void testThatDeployLogContainsWarningWhenUsingSearchdefinitionsDir() throws IOException, SAXException {
+ void testThatDeployLogContainsWarningWhenUsingSearchdefinitionsDir() throws IOException, SAXException {
ApplicationPackage app = FilesApplicationPackage.fromFile(
new File("src/test/cfg/application/deprecated_features_app/"));
MyLogger logger = new MyLogger();
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java
index 533550b1d53..9e8174e858a 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.utils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
public class DurationTest {
@Test
- public void testDurationUnits() {
+ void testDurationUnits() {
assertEquals(1000, new Duration("1").getMilliSeconds());
assertEquals(2.0, new Duration("2").getSeconds(), 0.0001);
assertEquals(1, new Duration("1ms").getMilliSeconds());
@@ -30,7 +30,7 @@ public class DurationTest {
}
@Test
- public void testParseError() {
+ void testParseError() {
assertException("bjarne");
assertException("");
assertException("1 foo");
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java
index 96815646a88..c7358ff1d7e 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java
@@ -14,8 +14,8 @@ import com.yahoo.vespa.config.ConfigPayloadBuilder;
import com.yahoo.vespa.model.AbstractService;
import com.yahoo.vespa.model.PortAllocBridge;
import com.yahoo.vespa.model.SimpleConfigProducer;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -23,7 +23,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -64,7 +65,7 @@ public class FileSenderTest {
return new FileSender(serviceList, fileRegistry, new BaseDeployLogger());
}
- @Before
+ @BeforeEach
public void setup() {
MockRoot root = new MockRoot();
producer = new SimpleConfigProducer<>(root, "test");
@@ -81,7 +82,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_simple_file_fields_are_modified() {
+ void require_that_simple_file_fields_are_modified() {
def.addFileDef("fileVal");
def.addStringDef("stringVal");
builder.setField("fileVal", "foo.txt");
@@ -93,7 +94,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_simple_path_fields_are_modified() {
+ void require_that_simple_path_fields_are_modified() {
def.addPathDef("fileVal");
def.addStringDef("stringVal");
builder.setField("fileVal", "foo.txt");
@@ -105,7 +106,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_fields_in_inner_arrays_are_modified() {
+ void require_that_fields_in_inner_arrays_are_modified() {
def.innerArrayDef("inner").addFileDef("fileVal");
def.innerArrayDef("inner").addStringDef("stringVal");
ConfigPayloadBuilder inner = builder.getArray("inner").append();
@@ -118,7 +119,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_arrays_are_modified() {
+ void require_that_arrays_are_modified() {
def.arrayDef("fileArray").setTypeSpec(new ConfigDefinition.TypeSpec("fileArray", "file", null, null, null, null));
def.arrayDef("pathArray").setTypeSpec(new ConfigDefinition.TypeSpec("pathArray", "path", null, null, null, null));
def.arrayDef("stringArray").setTypeSpec(new ConfigDefinition.TypeSpec("stringArray", "string", null, null, null, null));
@@ -137,7 +138,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_structs_are_modified() {
+ void require_that_structs_are_modified() {
def.structDef("struct").addFileDef("fileVal");
def.structDef("struct").addStringDef("stringVal");
builder.getObject("struct").setField("fileVal", "foo.txt");
@@ -149,7 +150,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_leaf_maps_are_modified() {
+ void require_that_leaf_maps_are_modified() {
def.leafMapDef("fileMap").setTypeSpec(new ConfigDefinition.TypeSpec("fileMap", "file", null, null, null, null));
def.leafMapDef("pathMap").setTypeSpec(new ConfigDefinition.TypeSpec("pathMap", "path", null, null, null, null));
def.leafMapDef("stringMap").setTypeSpec(new ConfigDefinition.TypeSpec("stringMap", "string", null, null, null, null));
@@ -168,7 +169,7 @@ public class FileSenderTest {
}
@Test
- public void require_that_fields_in_inner_maps_are_modified() {
+ void require_that_fields_in_inner_maps_are_modified() {
def.structMapDef("inner").addFileDef("fileVal");
def.structMapDef("inner").addStringDef("stringVal");
ConfigPayloadBuilder inner = builder.getMap("inner").put("foo");
@@ -180,11 +181,13 @@ public class FileSenderTest {
assertEquals("bar.txt", builder.getMap("inner").get("foo").getObject("stringVal").getValue());
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_null_files_are_not_sent() {
- def.addFileDef("fileVal");
- fileRegistry.pathToRef.put("foo.txt", new FileNode("fooshash").value());
- fileSender().sendUserConfiguredFiles(producer);
+ @Test
+ void require_that_null_files_are_not_sent() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ def.addFileDef("fileVal");
+ fileRegistry.pathToRef.put("foo.txt", new FileNode("fooshash").value());
+ fileSender().sendUserConfiguredFiles(producer);
+ });
}
diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java
index fb1afb75e10..d8ea631ac96 100644
--- a/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java
+++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java
@@ -7,14 +7,12 @@ import com.yahoo.config.ChangesRequiringRestart;
import com.yahoo.config.ConfigInstance;
import com.yahoo.test.SimpletypesConfig;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import static com.yahoo.vespa.model.utils.internal.ReflectionUtil.getAllConfigsProduced;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Lilleengen
@@ -67,14 +65,14 @@ public class ReflectionUtilTest {
private static class NonRestartConfig extends ConfigInstance {}
@Test
- public void getAllConfigsProduced_includes_configs_produced_by_super_class() {
+ void getAllConfigsProduced_includes_configs_produced_by_super_class() {
Set<ConfigKey<?>> configs = getAllConfigsProduced(ConcreteProducer.class, "foo");
assertEquals(1, configs.size());
assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE)));
}
@Test
- public void getAllConfigsProduced_includes_configs_produced_by_implemented_interface() {
+ void getAllConfigsProduced_includes_configs_produced_by_implemented_interface() {
Set<ConfigKey<?>> configs = getAllConfigsProduced(InterfaceImplementingProducer.class, "foo");
assertEquals(2, configs.size());
assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE)));
@@ -82,27 +80,29 @@ public class ReflectionUtilTest {
}
@Test
- public void getAllConfigsProduced_includes_configs_directly_implemented_by_producer() {
+ void getAllConfigsProduced_includes_configs_directly_implemented_by_producer() {
Set<ConfigKey<?>> configs = getAllConfigsProduced(SimpleProducer.class, "foo");
assertEquals(1, configs.size());
assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE)));
}
@Test
- public void requireThatRestartMethodsAreDetectedProperly() {
+ void requireThatRestartMethodsAreDetectedProperly() {
assertFalse(ReflectionUtil.hasRestartMethods(NonRestartConfig.class));
assertTrue(ReflectionUtil.hasRestartMethods(RestartConfig.class));
}
@Test
- public void requireThatRestartMethodsAreProperlyInvoked() {
+ void requireThatRestartMethodsAreProperlyInvoked() {
assertTrue(ReflectionUtil.containsFieldsFlaggedWithRestart(RestartConfig.class));
assertEquals("testing", ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new RestartConfig()).getName());
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatGetChangesRequiringRestartValidatesParameterTypes() {
- ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new NonRestartConfig());
+ @Test
+ void requireThatGetChangesRequiringRestartValidatesParameterTypes() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new NonRestartConfig());
+ });
}
diff --git a/config-model/src/test/java/helpers/CompareConfigTestHelper.java b/config-model/src/test/java/helpers/CompareConfigTestHelper.java
index ba06ecc9397..4d8c46d0edb 100644
--- a/config-model/src/test/java/helpers/CompareConfigTestHelper.java
+++ b/config-model/src/test/java/helpers/CompareConfigTestHelper.java
@@ -11,7 +11,7 @@ import java.io.IOException;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vegard Sjonfjell
diff --git a/config-model/src/test/schema-test-files/hosts.xml b/config-model/src/test/schema-test-files/hosts.xml
index cbbab9c3fe2..0ca814c819d 100755
--- a/config-model/src/test/schema-test-files/hosts.xml
+++ b/config-model/src/test/schema-test-files/hosts.xml
@@ -6,13 +6,13 @@
<alias>host1</alias>
<alias>configserver</alias>
<alias>logserver</alias>
- <alias>qrserver</alias>
+ <alias>container</alias>
<alias>distributor</alias>
<alias>feeder</alias>
<alias>rtx</alias>
<alias>tld</alias>
- <alias>rtc-1</alias>
- <alias>rtc-2</alias>
+ <alias>searchnode-1</alias>
+ <alias>searchnode-2</alias>
</host>
<host name="example.yahoo.com">
diff --git a/config-model/src/test/schema-test-files/services.xml b/config-model/src/test/schema-test-files/services.xml
index 4fb81963152..b32849bb55f 100644
--- a/config-model/src/test/schema-test-files/services.xml
+++ b/config-model/src/test/schema-test-files/services.xml
@@ -11,8 +11,8 @@
<logserver hostalias="logserver" />
<slobroks>
<slobrok hostalias="configserver" />
- <slobrok hostalias="qrserver" />
- <slobrok hostalias="rtc-1" />
+ <slobrok hostalias="container" />
+ <slobrok hostalias="searchnode-1" />
</slobroks>
<metrics>
@@ -193,6 +193,9 @@
<handler id="jdisc-handler">
<binding>http://*:*/HelloWorld</binding>
<binding>http://*:*/Status</binding>
+ <component id="injected-to-handler">
+ <config name="foo"/>
+ </component>
</handler>
<server id="server-provider">
diff --git a/config-provisioning/pom.xml b/config-provisioning/pom.xml
index 119931465bf..b190bca06a5 100644
--- a/config-provisioning/pom.xml
+++ b/config-provisioning/pom.xml
@@ -61,10 +61,29 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/config-provisioning/src/main/java/com/yahoo/config/provision/zone/NodeSlice.java b/config-provisioning/src/main/java/com/yahoo/config/provision/zone/NodeSlice.java
new file mode 100644
index 00000000000..acb93139b27
--- /dev/null
+++ b/config-provisioning/src/main/java/com/yahoo/config/provision/zone/NodeSlice.java
@@ -0,0 +1,46 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.config.provision.zone;
+
+import java.util.Objects;
+import java.util.OptionalDouble;
+import java.util.OptionalLong;
+
+/**
+ * A slice of nodes, satisfied by either a minimum count or a fraction.
+ *
+ * @author mpolden
+ */
+public record NodeSlice(OptionalDouble fraction, OptionalLong minCount) {
+
+ public static final NodeSlice ALL = minCount(Long.MAX_VALUE);
+
+ public NodeSlice {
+ Objects.requireNonNull(fraction);
+ Objects.requireNonNull(minCount);
+ if (fraction.isEmpty() == minCount.isEmpty()) {
+ throw new IllegalArgumentException("Exactly one of 'fraction' or 'minCount' must be set");
+ }
+ if (fraction.isPresent() && fraction.getAsDouble() > 1.0D) {
+ throw new IllegalArgumentException("Fraction must be <= 1.0, got " + fraction.getAsDouble());
+ }
+ }
+
+ /** Returns whether this slice is satisfied by given node count, out of totalCount */
+ public boolean satisfiedBy(long count, long totalCount) {
+ if (fraction.isPresent()) {
+ return count + 1e-9 >= totalCount * fraction.getAsDouble();
+ }
+ return count >= Math.min(minCount.orElse(0), totalCount);
+ }
+
+ /** Returns a slice matching the given fraction of nodes */
+ public static NodeSlice fraction(double fraction) {
+ return new NodeSlice(OptionalDouble.of(fraction), OptionalLong.empty());
+ }
+
+ /** Returns a slice matching the given minimum number of nodes */
+ public static NodeSlice minCount(long count) {
+ return new NodeSlice(OptionalDouble.empty(), OptionalLong.of(count));
+ }
+
+}
diff --git a/config-provisioning/src/main/java/com/yahoo/config/provision/zone/UpgradePolicy.java b/config-provisioning/src/main/java/com/yahoo/config/provision/zone/UpgradePolicy.java
index 85cc384660d..1c5bfad4c47 100644
--- a/config-provisioning/src/main/java/com/yahoo/config/provision/zone/UpgradePolicy.java
+++ b/config-provisioning/src/main/java/com/yahoo/config/provision/zone/UpgradePolicy.java
@@ -4,6 +4,7 @@ package com.yahoo.config.provision.zone;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
/**
@@ -12,14 +13,13 @@ import java.util.Set;
*
* @author mpolden
*/
-public class UpgradePolicy {
+public record UpgradePolicy(List<Step> steps) {
- private final List<Set<ZoneApi>> steps;
-
- private UpgradePolicy(List<Set<ZoneApi>> steps) {
+ public UpgradePolicy(List<Step> steps) {
+ Objects.requireNonNull(steps);
for (int i = 0; i < steps.size(); i++) {
for (int j = 0; j < i; j++) {
- if (!Collections.disjoint(steps.get(i), steps.get(j))) {
+ if (!Collections.disjoint(steps.get(i).zones(), steps.get(j).zones())) {
throw new IllegalArgumentException("One or more zones are declared in multiple steps");
}
}
@@ -27,14 +27,9 @@ public class UpgradePolicy {
this.steps = List.copyOf(steps);
}
- /** Returns the steps in this */
- public List<Set<ZoneApi>> steps() {
- return steps;
- }
-
/** Returns a copy of this with the step order inverted */
public UpgradePolicy inverted() {
- List<Set<ZoneApi>> copy = new ArrayList<>(steps);
+ List<Step> copy = new ArrayList<>(steps);
Collections.reverse(copy);
return new UpgradePolicy(copy);
}
@@ -43,21 +38,23 @@ public class UpgradePolicy {
return new UpgradePolicy.Builder();
}
- public static class Builder {
+ public record Builder(List<Step> steps) {
- private final List<Set<ZoneApi>> steps = new ArrayList<>();
+ private Builder() {
+ this(new ArrayList<>());
+ }
- private Builder() {}
+ public Builder upgrade(Step step) {
+ this.steps.add(step);
+ return this;
+ }
- /** Upgrade given zone as the next step */
public Builder upgrade(ZoneApi zone) {
return upgradeInParallel(zone);
}
- /** Upgrade given zones in parallel as the next step */
public Builder upgradeInParallel(ZoneApi... zone) {
- this.steps.add(Set.of(zone));
- return this;
+ return upgrade(Step.of(zone));
}
public UpgradePolicy build() {
@@ -66,4 +63,28 @@ public class UpgradePolicy {
}
+ /**
+ * An upgrade step, consisting of one or more zones. If a step contains multiple zones, those will be upgraded in
+ * parallel.
+ */
+ public record Step(Set<ZoneApi> zones, NodeSlice nodeSlice) {
+
+ public Step(Set<ZoneApi> zones, NodeSlice nodeSlice) {
+ if (zones.isEmpty()) throw new IllegalArgumentException("A step must contain at least one zone");
+ this.zones = Set.copyOf(Objects.requireNonNull(zones));
+ this.nodeSlice = Objects.requireNonNull(nodeSlice);
+ }
+
+ /** Create a step for given zones, which requires all nodes to complete upgrade */
+ public static Step of(ZoneApi... zone) {
+ return new Step(Set.of(zone), NodeSlice.ALL);
+ }
+
+ /** Returns a copy of this step, requiring only the given slice of nodes for each zone in this step to upgrade */
+ public Step require(NodeSlice slice) {
+ return new Step(zones, slice);
+ }
+
+ }
+
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
index 622fc2527bf..0a60b868bde 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
@@ -3,7 +3,7 @@ package com.yahoo.config.provision;
import com.yahoo.cloud.config.ApplicationIdConfig;
import com.yahoo.test.TotalOrderTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -11,8 +11,9 @@ import java.util.Set;
import static com.yahoo.config.provision.ApplicationId.from;
import static com.yahoo.config.provision.ApplicationId.global;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -22,7 +23,7 @@ import static org.junit.Assert.assertNotEquals;
public class ApplicationIdTest {
@Test
- public void require_that_application_id_is_set() {
+ void require_that_application_id_is_set() {
ApplicationId app = applicationId("application");
assertEquals("application", app.application().value());
app = from("tenant", "application", "instance");
@@ -32,23 +33,23 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_equals_and_hashcode_behaves_correctly() {
+ void require_that_equals_and_hashcode_behaves_correctly() {
assertEquals(Set.of(from("tenant1", "name1", "instance1"),
- from("tenant2", "name1", "instance1"),
- from("tenant1", "name2", "instance1"),
- from("tenant1", "name1", "instance2"),
- applicationId("name1"),
- applicationId("name2")),
- new HashSet<>(List.of(from("tenant1", "name1", "instance1"),
- from("tenant2", "name1", "instance1"),
- from("tenant1", "name2", "instance1"),
- from("tenant1", "name1", "instance2"),
- applicationId("name1"),
- applicationId("name2"))));
+ from("tenant2", "name1", "instance1"),
+ from("tenant1", "name2", "instance1"),
+ from("tenant1", "name1", "instance2"),
+ applicationId("name1"),
+ applicationId("name2")),
+ new HashSet<>(List.of(from("tenant1", "name1", "instance1"),
+ from("tenant2", "name1", "instance1"),
+ from("tenant1", "name2", "instance1"),
+ from("tenant1", "name1", "instance2"),
+ applicationId("name1"),
+ applicationId("name2"))));
}
@Test
- public void require_that_value_format_is_correct() {
+ void require_that_value_format_is_correct() {
ApplicationId id1 = applicationId("foo");
ApplicationId id2 = applicationId("bar");
ApplicationId id3 = from("tenant", "baz", "bim");
@@ -58,7 +59,7 @@ public class ApplicationIdTest {
}
@Test
- public void require_string_formats_are_correct() {
+ void require_string_formats_are_correct() {
ApplicationId id1 = applicationId("foo");
ApplicationId id2 = from("bar", "baz", "default");
ApplicationId id3 = from("tenant", "baz", "bim");
@@ -71,38 +72,40 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_idstring_can_be_parsed() {
+ void require_that_idstring_can_be_parsed() {
ApplicationId id = ApplicationId.fromSerializedForm("ten:foo:bim");
assertEquals("ten", id.tenant().value());
assertEquals("foo", id.application().value());
assertEquals("bim", id.instance().value());
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_invalid_idstring_throws_exception() {
- ApplicationId.fromSerializedForm("foo:baz");
+ @Test
+ void require_that_invalid_idstring_throws_exception() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.fromSerializedForm("foo:baz");
+ });
}
@Test
- public void require_that_defaults_are_given() {
+ void require_that_defaults_are_given() {
ApplicationId id1 = applicationId("foo");
assertEquals("default", id1.tenant().value());
assertEquals("default", id1.instance().value());
}
@Test
- public void require_that_compare_to_is_correct() {
+ void require_that_compare_to_is_correct() {
new TotalOrderTester<ApplicationId>()
- .theseObjects(from("tenant1", "name1", "instance1"),
- from("tenant1", "name1", "instance1"))
- .areLessThan(from("tenant2", "name1", "instance1"))
- .areLessThan(from("tenant2", "name2", "instance1"))
- .areLessThan(from("tenant2", "name2", "instance2"))
- .testOrdering();
+ .theseObjects(from("tenant1", "name1", "instance1"),
+ from("tenant1", "name1", "instance1"))
+ .areLessThan(from("tenant2", "name1", "instance1"))
+ .areLessThan(from("tenant2", "name2", "instance1"))
+ .areLessThan(from("tenant2", "name2", "instance2"))
+ .testOrdering();
}
@Test
- public void require_that_instance_from_config_is_correct() {
+ void require_that_instance_from_config_is_correct() {
ApplicationIdConfig.Builder builder = new ApplicationIdConfig.Builder();
builder.tenant("a");
builder.application("b");
@@ -114,7 +117,7 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_global_is_special() {
+ void require_that_global_is_special() {
assertEquals(global(), global());
assertNotEquals(global(), from("hosted-vespa", "routing", "default"));
assertEquals(global().serializedForm(), from("hosted-vespa", "routing", "default").serializedForm());
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java
index 706addc4298..a6ddb401b2f 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -12,26 +12,26 @@ import static org.junit.Assert.fail;
public class CapacityTest {
@Test
- public void testCapacityValidation() {
+ void testCapacityValidation() {
// Equal min and max is allowed
- Capacity.from(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- false, true);
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(2, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 4, new NodeResources(1,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(2,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,3,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,4,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,5)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
+ Capacity.from(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ false, true);
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(2, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 4, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(2, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 3, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 4, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 5)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
// It's enough than one dimension is smaller also when the others are larger
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(8, 4, new NodeResources(2,1,6,8)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(8, 4, new NodeResources(2, 1, 6, 8)));
}
private void assertValidationFailure(ClusterResources min, ClusterResources max) {
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
index 986609357aa..b1195b6a54b 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
@@ -2,13 +2,13 @@
package com.yahoo.config.provision;
import com.yahoo.component.Vtag;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -16,13 +16,13 @@ import static org.junit.Assert.assertTrue;
public class ClusterMembershipTest {
@Test
- public void testContainerServiceInstance() {
+ void testContainerServiceInstance() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContainerService(ClusterMembership.from(cluster, 3));
}
@Test
- public void testSerializationWithOptionalParts() {
+ void testSerializationWithOptionalParts() {
{
ClusterMembership instance = ClusterMembership.from("container/id1/4/37/exclusive/retired", Vtag.currentVersion, Optional.empty());
ClusterMembership serialized = ClusterMembership.from(instance.stringValue(), Vtag.currentVersion, Optional.empty());
@@ -56,42 +56,42 @@ public class ClusterMembershipTest {
}
@Test
- public void testServiceInstance() {
+ void testServiceInstance() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContentService(ClusterMembership.from(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroup() {
+ void testServiceInstanceWithGroup() {
ClusterSpec cluster = ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("id1"))
- .group(ClusterSpec.Group.from(4))
- .vespaVersion("6.42")
- .build();
+ .group(ClusterSpec.Group.from(4))
+ .vespaVersion("6.42")
+ .build();
assertContentServiceWithGroup(ClusterMembership.from(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupFromString() {
+ void testServiceInstanceWithGroupFromString() {
assertContentServiceWithGroup(ClusterMembership.from("content/id1/4/37/stateful", Vtag.currentVersion, Optional.empty()));
}
@Test
- public void testServiceInstanceWithRetire() {
+ void testServiceInstanceWithRetire() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContentServiceWithRetire(ClusterMembership.retiredFrom(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupAndRetire() {
+ void testServiceInstanceWithGroupAndRetire() {
ClusterSpec cluster = ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("id1"))
- .group(ClusterSpec.Group.from(4))
- .vespaVersion("6.42")
- .build();
+ .group(ClusterSpec.Group.from(4))
+ .vespaVersion("6.42")
+ .build();
assertContentServiceWithGroupAndRetire(ClusterMembership.retiredFrom(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupAndRetireFromString() {
+ void testServiceInstanceWithGroupAndRetireFromString() {
assertContentServiceWithGroupAndRetire(ClusterMembership.from("content/id1/4/37/retired/stateful", Vtag.currentVersion, Optional.empty()));
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
index cbca931e4d0..06b5dd472d6 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class ClusterResourcesTest {
@Test
- public void testCost() {
+ void testCost() {
ClusterResources r1 = new ClusterResources(3, 1, new NodeResources(2, 8, 50, 1));
ClusterResources r2 = new ClusterResources(3, 1, new NodeResources(2, 16, 50, 1));
assertEquals(2.232, r1.cost() + r2.cost(), 0.01);
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
index dc228ee7fd2..21118266ce0 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
@@ -4,7 +4,7 @@ package com.yahoo.config.provision;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ClusterSpec.Group;
import com.yahoo.config.provision.ClusterSpec.Id;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -12,7 +12,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -20,32 +20,32 @@ import static org.junit.Assert.assertEquals;
public class ClusterSpecTest {
@Test
- public void testIdEquals() {
+ void testIdEquals() {
assertEquals(Set.of(Id.from("id1"), Id.from("id2"), Id.from("id3")),
- new HashSet<>(List.of(Id.from("id1"), Id.from("id1"), Id.from("id2"), Id.from("id3"))));
+ new HashSet<>(List.of(Id.from("id1"), Id.from("id1"), Id.from("id2"), Id.from("id3"))));
}
@Test
- public void testGroupEquals() {
+ void testGroupEquals() {
assertEquals(Set.of(Group.from(1), Group.from(2), Group.from(3)),
- new HashSet<>(List.of(Group.from(1), Group.from(1), Group.from(2), Group.from(3))));
+ new HashSet<>(List.of(Group.from(1), Group.from(1), Group.from(2), Group.from(3))));
}
@Test
- public void testSatisfies() {
+ void testSatisfies() {
var tests = Map.of(
- List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id2")), false,
- List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
- List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.content, "id1")), false,
- List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
- List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.content, "id1")), true,
- List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id1")), true
+ List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id2")), false,
+ List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
+ List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.content, "id1")), false,
+ List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
+ List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.content, "id1")), true,
+ List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id1")), true
);
tests.forEach((specs, satisfies) -> {
var s1 = specs.get(0);
var s2 = specs.get(1);
- assertEquals(s1 + (satisfies ? " satisfies " : " does not satisfy ") + s2, satisfies, s1.satisfies(s2));
- assertEquals(s2 + (satisfies ? " satisfies " : " does not satisfy ") + s1, satisfies, s2.satisfies(s1));
+ assertEquals(satisfies, s1.satisfies(s2), s1 + (satisfies ? " satisfies " : " does not satisfy ") + s2);
+ assertEquals(satisfies, s2.satisfies(s1), s2 + (satisfies ? " satisfies " : " does not satisfy ") + s1);
});
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java
index 2e0de192f03..36cc83f91b6 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -17,42 +17,42 @@ import static org.junit.Assert.fail;
public class DockerImageTest {
@Test
- public void parse() {
+ void parse() {
Map<String, DockerImage> tests = Map.of(
- "", DockerImage.EMPTY,
- "registry.example.com:9999/vespa/vespa:7.42", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.of("7.42")),
- "registry.example.com/vespa/vespa:7.42", new DockerImage("registry.example.com", "vespa/vespa", Optional.of("7.42")),
- "registry.example.com:9999/vespa/vespa", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.empty()),
- "registry.example.com/vespa/vespa", new DockerImage("registry.example.com", "vespa/vespa", Optional.empty()),
- "registry.example.com/project/repo/vespa/vespa", new DockerImage("registry.example.com/project/repo", "vespa/vespa", Optional.empty())
+ "", DockerImage.EMPTY,
+ "registry.example.com:9999/vespa/vespa:7.42", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.of("7.42")),
+ "registry.example.com/vespa/vespa:7.42", new DockerImage("registry.example.com", "vespa/vespa", Optional.of("7.42")),
+ "registry.example.com:9999/vespa/vespa", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.empty()),
+ "registry.example.com/vespa/vespa", new DockerImage("registry.example.com", "vespa/vespa", Optional.empty()),
+ "registry.example.com/project/repo/vespa/vespa", new DockerImage("registry.example.com/project/repo", "vespa/vespa", Optional.empty())
);
tests.forEach((value, expected) -> {
DockerImage parsed = DockerImage.fromString(value);
assertEquals(value, parsed.asString());
String untagged = expected.equals(DockerImage.EMPTY)
- ? ""
- : expected.registry() + "/" + expected.repository();
+ ? ""
+ : expected.registry() + "/" + expected.repository();
assertEquals(untagged, parsed.untagged());
});
}
@Test
- public void registry_cannot_contain_slash() {
+ void registry_cannot_contain_slash() {
DockerImage image = DockerImage.fromString("registry.example.com/vespa/vespa");
assertThrows(IllegalArgumentException.class, () -> image.withRegistry(""));
assertThrows(IllegalArgumentException.class, () -> image.withRegistry("my-registry/path/"));
}
@Test
- public void parse_invalid() {
+ void parse_invalid() {
List<String> tests = List.of(
- "registry.example.com",
- "registry.example.com/",
- "registry.example.com/repository",
- "registry.example.com/repository:",
- "foo",
- "foo:1.2.3"
+ "registry.example.com",
+ "registry.example.com/",
+ "registry.example.com/repository",
+ "registry.example.com/repository:",
+ "foo",
+ "foo:1.2.3"
);
for (var value : tests) {
try {
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
index b0ce1b3b8cb..e8ad99ff0d3 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
@@ -2,13 +2,13 @@
package com.yahoo.config.provision;
import com.yahoo.component.Vtag;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Optional;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue;
public class HostFilterTest {
@Test
- public void testSingleConditionFilter() {
+ void testSingleConditionFilter() {
HostFilter all = HostFilter.all();
HostFilter hostname = HostFilter.hostname("host1");
HostFilter type = HostFilter.clusterType(ClusterSpec.Type.content);
@@ -33,22 +33,22 @@ public class HostFilterTest {
assertFalse( id.matches("anyhost", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( all.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
- assertTrue( hostname.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
+ assertTrue(hostname.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( type.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertFalse( id.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( all.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
- assertTrue( hostname.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
+ assertTrue(hostname.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
assertTrue( type.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
assertTrue( id.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
}
@Test
- public void testMultiConditionFilter() {
+ void testMultiConditionFilter() {
HostFilter typeAndId = HostFilter.from(Collections.emptyList(),
- Collections.emptyList(),
- Collections.singletonList(ClusterSpec.Type.content),
- Collections.singletonList(ClusterSpec.Id.from("type1")));
+ Collections.emptyList(),
+ Collections.singletonList(ClusterSpec.Type.content),
+ Collections.singletonList(ClusterSpec.Id.from("type1")));
assertFalse(typeAndId.matches("anyhost", "flavor", membership("content/anyType/0/0/stateful")));
assertFalse(typeAndId.matches("anyhost", "flavor", membership("container/type1/0/0")));
@@ -56,7 +56,7 @@ public class HostFilterTest {
}
@Test
- public void testMultiConditionFilterFromStrings() {
+ void testMultiConditionFilterFromStrings() {
HostFilter typeAndId = HostFilter.from("host1 host2, host3,host4", " , ,flavor", null, "type1 ");
assertFalse(typeAndId.matches("anotherhost", "flavor", membership("content/type1/0/0/stateful")));
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
index da01920cc57..fe42e71682b 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author jonmv
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertThrows;
public class HostNameTest {
@Test
- public void testNames() {
+ void testNames() {
HostName.of("name-123.0.321-eman");
HostName.of(("." + "a".repeat(32)).repeat(2).substring(1, 65));
HostName.of("123");
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java b/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
index fd1a9401b81..1fd4c2e06ce 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Generic test for identifiers such as {@link Environment} and {@link RegionName}.
@@ -23,7 +23,7 @@ public abstract class IdentifierTestBase<ID_TYPE> {
protected abstract boolean isDefault(ID_TYPE instance);
@Test
- public void testDefault() {
+ void testDefault() {
ID_TYPE def = createDefaultInstance();
ID_TYPE def2 = createInstance("default");
ID_TYPE notdef = createInstance("default2");
@@ -35,9 +35,9 @@ public abstract class IdentifierTestBase<ID_TYPE> {
}
@Test
- public void testEquals() {
+ void testEquals() {
assertEquals(Set.of(createInstance("foo"), createInstance("bar"), createInstance("baz")),
- new HashSet<>(List.of(createInstance("foo"), createInstance("foo"), createInstance("bar"), createInstance("baz"))));
+ new HashSet<>(List.of(createInstance("foo"), createInstance("foo"), createInstance("bar"), createInstance("baz"))));
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
index 8c2a6b70cf5..5ab6aa64516 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
@@ -2,19 +2,19 @@
package com.yahoo.config.provision;
import com.yahoo.config.provisioning.FlavorsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NodeFlavorsTest {
private static final double delta = 0.00001;
@Test
- public void testConfigParsing() {
+ void testConfigParsing() {
FlavorsConfig.Builder builder = new FlavorsConfig.Builder();
List<FlavorsConfig.Flavor.Builder> flavorBuilderList = new ArrayList<>();
{
@@ -35,7 +35,7 @@ public class NodeFlavorsTest {
Flavor banana = nodeFlavors.getFlavor("banana").get();
assertEquals(3, banana.cost());
assertEquals(13, banana.resources().vcpu(), delta);
- assertEquals("10 * 1.3", 13, banana.resources().vcpu(), delta);
+ assertEquals(13, banana.resources().vcpu(), delta, "10 * 1.3");
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
index 564c53eeff0..35c7bfd35ec 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -14,17 +14,17 @@ import static org.junit.Assert.fail;
public class NodeResourcesTest {
@Test
- public void testToString() {
+ void testToString() {
assertEquals("[vcpu: 1.0, memory: 10.0 Gb, disk 100.0 Gb, architecture: x86_64]",
- new NodeResources(1., 10., 100., 0).toString());
+ new NodeResources(1., 10., 100., 0).toString());
assertEquals("[vcpu: 0.3, memory: 3.3 Gb, disk 33.3 Gb, bandwidth: 0.3 Gbps, architecture: x86_64]",
- new NodeResources(1/3., 10/3., 100/3., 0.3).toString());
+ new NodeResources(1 / 3., 10 / 3., 100 / 3., 0.3).toString());
assertEquals("[vcpu: 0.7, memory: 9.0 Gb, disk 66.7 Gb, bandwidth: 0.7 Gbps, architecture: x86_64]",
- new NodeResources(2/3., 8.97, 200/3., 0.67).toString());
+ new NodeResources(2 / 3., 8.97, 200 / 3., 0.67).toString());
}
@Test
- public void testInvalid() {
+ void testInvalid() {
assertInvalid("vcpu", () -> new NodeResources(Double.NaN, 1.0, 1.0, 1.0));
assertInvalid("memory", () -> new NodeResources(1.0, Double.NaN, 1.0, 1.0));
assertInvalid("disk", () -> new NodeResources(1.0, 1.0, Double.NaN, 1.0));
@@ -32,17 +32,17 @@ public class NodeResourcesTest {
}
@Test
- public void benchmark() {
+ void benchmark() {
NodeResources [] resouces = new NodeResources[100];
for (int i = 0; i < resouces.length; i++) {
- resouces[i] = new NodeResources(1/3., 10/3., 100/3., 0.3);
+ resouces[i] = new NodeResources(1 / 3., 10 / 3., 100 / 3., 0.3);
}
int NUM_ITER = 100; // Use at least 100000 for proper benchmarking
long warmup = runTest(resouces, NUM_ITER);
long start = System.nanoTime();
long benchmark = runTest(resouces, NUM_ITER);
long duration = System.nanoTime() - start;
- System.out.println("NodeResources.toString() took " + duration/1000000 + " ms");
+ System.out.println("NodeResources.toString() took " + duration / 1000000 + " ms");
assertEquals(warmup, benchmark);
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
index beb28241963..f0656f84a07 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
@@ -1,25 +1,25 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
*/
public class SystemNameTest {
@Test
- public void test() {
+ void test() {
for (SystemName name : SystemName.values()) {
assertEquals(name, SystemName.from(name.value()));
}
}
@Test
- public void allOf() {
+ void allOf() {
assertEquals(Set.of(SystemName.cd, SystemName.PublicCd), SystemName.allOf(SystemName::isCd));
assertEquals(Set.of(SystemName.PublicCd, SystemName.Public), SystemName.allOf(SystemName::isPublic));
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
index 2bfcd183c85..a68ea952475 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
@@ -2,9 +2,9 @@
package com.yahoo.config.provision;
import com.yahoo.test.TotalOrderTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -27,12 +27,12 @@ public class TenantTest extends IdentifierTestBase<TenantName> {
}
@Test
- public void testComparator() {
+ void testComparator() {
assertEquals(0, TenantName.defaultName().compareTo(TenantName.defaultName()));
new TotalOrderTester<TenantName>()
- .theseObjects(TenantName.from("a"), TenantName.from("a"))
- .areLessThan(TenantName.from("b"))
- .testOrdering();
+ .theseObjects(TenantName.from("a"), TenantName.from("a"))
+ .areLessThan(TenantName.from("b"))
+ .testOrdering();
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
index ae61be8f2e9..4fd1b1bbc26 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
@@ -2,10 +2,10 @@
package com.yahoo.config.provision;
import com.yahoo.config.provision.zone.ZoneId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author hmusum
@@ -16,14 +16,14 @@ public class ZoneIdTest {
private static final RegionName region = RegionName.from("moon-dark-side-1");
@Test
- public void testCreatingZoneId() {
+ void testCreatingZoneId() {
ZoneId zoneId = ZoneId.from(environment, region);
assertEquals(region, zoneId.region());
assertEquals(environment, zoneId.environment());
}
@Test
- public void testSerializingAndDeserializing() {
+ void testSerializingAndDeserializing() {
ZoneId zoneId = ZoneId.from(environment, region);
assertEquals(environment.value() + "." + region.value(), zoneId.value());
assertEquals(ZoneId.from(zoneId.value()), zoneId);
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
index ed87ff9f555..fec8be59c50 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NetworkPorts;
import com.yahoo.config.provision.NodeResources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.LinkedHashSet;
@@ -18,7 +18,7 @@ import java.util.Set;
import static com.yahoo.config.provision.serialization.AllocatedHostsSerializer.fromJson;
import static com.yahoo.config.provision.serialization.AllocatedHostsSerializer.toJson;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -31,7 +31,7 @@ public class AllocatedHostsSerializerTest {
private static final NodeResources arm64Node = new NodeResources(0.5, 3.1, 4, 1, NodeResources.DiskSpeed.any, NodeResources.StorageType.any, NodeResources.Architecture.arm64);
@Test
- public void testAllocatedHostsSerialization() throws IOException {
+ void testAllocatedHostsSerialization() throws IOException {
Set<HostSpec> hosts = new LinkedHashSet<>();
hosts.add(new HostSpec("empty", List.of(), Optional.empty()));
hosts.add(new HostSpec("with-aliases", List.of("alias1", "alias2"), Optional.empty()));
@@ -69,7 +69,7 @@ public class AllocatedHostsSerializerTest {
Optional.empty()),
Optional.empty(),
Optional.of(new NetworkPorts(List.of(new NetworkPorts.Allocation(1234, "service1", "configId1", "suffix1"),
- new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
+ new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
Optional.empty()));
hosts.add(new HostSpec("arm64",
arm64Node,
@@ -79,7 +79,7 @@ public class AllocatedHostsSerializerTest {
Optional.empty()),
Optional.empty(),
Optional.of(new NetworkPorts(List.of(new NetworkPorts.Allocation(1234, "service1", "configId1", "suffix1"),
- new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
+ new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
Optional.empty()));
assertAllocatedHosts(AllocatedHosts.withHosts(hosts));
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/zone/NodeSliceTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/zone/NodeSliceTest.java
new file mode 100644
index 00000000000..b13eba5fa32
--- /dev/null
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/zone/NodeSliceTest.java
@@ -0,0 +1,32 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.config.provision.zone;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * @author mpolden
+ */
+public class NodeSliceTest {
+
+ @Test
+ void node_slice() {
+ NodeSlice fraction = NodeSlice.fraction(0.6);
+ assertFalse(fraction.satisfiedBy(0, 4));
+ assertFalse(fraction.satisfiedBy(1, 4));
+ assertFalse(fraction.satisfiedBy(2, 4));
+ assertTrue(fraction.satisfiedBy(3, 4));
+ assertTrue(fraction.satisfiedBy(4, 4));
+ assertTrue(fraction.satisfiedBy(5, 4));
+
+ NodeSlice fixed = NodeSlice.minCount(5);
+ assertFalse(fixed.satisfiedBy(0, 5));
+ assertFalse(fixed.satisfiedBy(4, 5));
+ assertTrue(fixed.satisfiedBy(3, 3));
+ assertTrue(fixed.satisfiedBy(5, 5));
+ assertTrue(fixed.satisfiedBy(6, 5));
+ }
+
+}
diff --git a/config-proxy/pom.xml b/config-proxy/pom.xml
index 4272cf6617e..476f5f99b86 100644
--- a/config-proxy/pom.xml
+++ b/config-proxy/pom.xml
@@ -14,16 +14,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-lib</artifactId>
<version>${project.version}</version>
@@ -64,9 +54,19 @@
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>compile</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClient.java b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClient.java
index 02c5aeb33c7..994bdef5898 100644
--- a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClient.java
+++ b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClient.java
@@ -84,7 +84,7 @@ class RpcConfigSourceClient implements ConfigSourceClient, Runnable {
for (String configSource : configSourceSet.getSources()) {
Spec spec = new Spec(configSource);
Target target = supervisor.connect(spec);
- target.invokeSync(req, 30.0);
+ target.invokeSync(req, Duration.ofSeconds(30));
if (target.isValid())
return;
diff --git a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/FileDistributionAndUrlDownload.java b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/FileDistributionAndUrlDownload.java
index 68570722117..edd16c3d23d 100644
--- a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/FileDistributionAndUrlDownload.java
+++ b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/FileDistributionAndUrlDownload.java
@@ -6,11 +6,15 @@ import com.yahoo.config.subscription.ConfigSourceSet;
import com.yahoo.jrt.Supervisor;
import com.yahoo.vespa.filedistribution.FileDistributionConnectionPool;
import com.yahoo.vespa.filedistribution.FileDownloader;
-
import java.time.Duration;
+import java.util.Arrays;
+import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
/**
* Keeps track of file distribution and url download rpc servers.
@@ -45,9 +49,16 @@ public class FileDistributionAndUrlDownload {
}
private FileDownloader createDownloader(Supervisor supervisor, ConfigSourceSet source) {
+ Set<CompressionType> acceptedCompressionTypes = Set.of(CompressionType.gzip);
+ String env = System.getenv("VESPA_FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES");
+ if (env != null && ! env.isEmpty()) {
+ String[] types = env.split(",");
+ acceptedCompressionTypes = Arrays.stream(types).map(CompressionType::valueOf).collect(Collectors.toSet());
+ }
return new FileDownloader(new FileDistributionConnectionPool(source, supervisor),
supervisor,
- Duration.ofMinutes(5));
+ Duration.ofMinutes(5),
+ acceptedCompressionTypes);
}
}
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
index f743c0ed231..250f0705e5b 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
@@ -11,17 +11,17 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.Transport;
import com.yahoo.vespa.config.RawConfig;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.time.Duration;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author hmusum
@@ -34,16 +34,16 @@ public class ConfigProxyRpcServerTest {
private static TestServer server;
private static TestClient client;
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @BeforeClass
+ @BeforeAll
public static void setup() throws ListenFailedException {
server = new TestServer();
client = new TestClient(server.listenPort());
}
- @AfterClass
+ @AfterAll
public static void teardown() {
client.close();
server.close();
@@ -55,7 +55,7 @@ public class ConfigProxyRpcServerTest {
}
@Test
- public void basic() {
+ void basic() {
ProxyServer proxy = createTestServer(new MockConfigSource());
Spec spec = new Spec("localhost", 12345);
ConfigProxyRpcServer server = new ConfigProxyRpcServer(proxy, new Supervisor(new Transport()), spec);
@@ -66,11 +66,11 @@ public class ConfigProxyRpcServerTest {
* Tests ping RPC command
*/
@Test
- public void testRpcMethodPing() {
+ void testRpcMethodPing() {
Request req = new Request("ping");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals(0, req.returnValues().get(0).asInt32());
}
@@ -79,13 +79,13 @@ public class ConfigProxyRpcServerTest {
* Tests listCachedConfig RPC command
*/
@Test
- public void testRpcMethodListCachedConfig() throws ListenFailedException {
+ void testRpcMethodListCachedConfig() throws ListenFailedException {
reset();
Request req = new Request("listCachedConfig");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(1, req.returnValues().size());
assertEquals(0, ret.length);
@@ -94,24 +94,24 @@ public class ConfigProxyRpcServerTest {
server.proxyServer().memoryCache().update(config);
req = new Request("listCachedConfig");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
ret = req.returnValues().get(0).asStringArray();
assertEquals(1, ret.length);
assertEquals(config.getNamespace() + "." + config.getName() + "," + config.getConfigId() + "," +
- config.getGeneration() + "," + config.getPayloadChecksums(),
- ret[0]);
+ config.getGeneration() + "," + config.getPayloadChecksums(),
+ ret[0]);
}
/**
* Tests listCachedConfig RPC command
*/
@Test
- public void testRpcMethodListCachedConfigFull() {
+ void testRpcMethodListCachedConfigFull() {
Request req = new Request("listCachedConfigFull");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(0, ret.length);
@@ -120,25 +120,25 @@ public class ConfigProxyRpcServerTest {
server.proxyServer().memoryCache().update(config);
req = new Request("listCachedConfigFull");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
ret = req.returnValues().get(0).asStringArray();
assertEquals(1, ret.length);
assertEquals(config.getNamespace() + "." + config.getName() + "," + config.getConfigId() + "," +
- config.getGeneration() + "," + config.getPayloadChecksums() + "," + config.getPayload().getData(),
- ret[0]);
+ config.getGeneration() + "," + config.getPayloadChecksums() + "," + config.getPayload().getData(),
+ ret[0]);
}
/**
* Tests listSourceConnections RPC command
*/
@Test
- public void testRpcMethodListSourceConnections() throws ListenFailedException {
+ void testRpcMethodListSourceConnections() throws ListenFailedException {
reset();
Request req = new Request("listSourceConnections");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
final String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -150,11 +150,11 @@ public class ConfigProxyRpcServerTest {
* Tests invalidateCache RPC command
*/
@Test
- public void testRpcMethodInvalidateCache() {
+ void testRpcMethodInvalidateCache() {
Request req = new Request("invalidateCache");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
final String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -166,10 +166,10 @@ public class ConfigProxyRpcServerTest {
* Tests getMode and setMode RPC commands
*/
@Test
- public void testRpcMethodGetModeAndSetMode() {
+ void testRpcMethodGetModeAndSetMode() {
Request req = new Request("getMode");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("default", req.returnValues().get(0).asString());
@@ -177,7 +177,7 @@ public class ConfigProxyRpcServerTest {
String mode = "memorycache";
req.parameters().add(new StringValue(mode));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -187,7 +187,7 @@ public class ConfigProxyRpcServerTest {
req = new Request("getMode");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals(mode, req.returnValues().get(0).asString());
@@ -197,7 +197,7 @@ public class ConfigProxyRpcServerTest {
req.parameters().add(new StringValue(mode));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
assertEquals("1", ret[0]);
@@ -209,7 +209,7 @@ public class ConfigProxyRpcServerTest {
* Tests updateSources RPC command
*/
@Test
- public void testRpcMethodUpdateSources() throws ListenFailedException {
+ void testRpcMethodUpdateSources() throws ListenFailedException {
reset();
Request req = new Request("updateSources");
@@ -217,7 +217,7 @@ public class ConfigProxyRpcServerTest {
String spec2 = "tcp/b:19070";
req.parameters().add(new StringValue(spec1 + "," + spec2));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("Updated config sources to: " + spec1 + "," + spec2, req.returnValues().get(0).asString());
@@ -227,7 +227,7 @@ public class ConfigProxyRpcServerTest {
req = new Request("updateSources");
req.parameters().add(new StringValue(spec1 + "," + spec2));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("Cannot update sources when in '" + Mode.ModeName.MEMORYCACHE.name().toLowerCase() + "' mode", req.returnValues().get(0).asString());
@@ -246,12 +246,12 @@ public class ConfigProxyRpcServerTest {
* Tests dumpCache RPC command
*/
@Test
- public void testRpcMethodDumpCache() throws IOException {
+ void testRpcMethodDumpCache() throws IOException {
Request req = new Request("dumpCache");
- String path = temporaryFolder.newFolder().getAbsolutePath();
+ String path = temporaryFolder.getAbsolutePath();
req.parameters().add(new StringValue(path));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("success", req.returnValues().get(0).asString());
}
@@ -287,6 +287,15 @@ public class ConfigProxyRpcServerTest {
supervisor.transport().shutdown().join();
rpcServer.shutdown();
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
private static class TestClient implements AutoCloseable {
@@ -300,7 +309,7 @@ public class ConfigProxyRpcServerTest {
}
void invoke(Request request) {
- target.invokeSync(request, Duration.ofMinutes(10).getSeconds());
+ target.invokeSync(request, Duration.ofMinutes(10));
}
@Override
@@ -308,5 +317,23 @@ public class ConfigProxyRpcServerTest {
target.close();
supervisor.transport().shutdown().join();
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+ }
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
}
}
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
index 8a668b34fd0..7fbd6b2e68f 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
@@ -1,12 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
-import static org.junit.Assert.assertEquals;
+import java.io.File;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -15,17 +16,17 @@ public class DelayedResponseHandlerTest {
private final MockConfigSource source = new MockConfigSource();
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @Before
+ @BeforeEach
public void setup() {
source.clear();
source.put(ProxyServerTest.fooConfig.getKey(), ProxyServerTest.createConfigWithNextConfigGeneration(ProxyServerTest.fooConfig, 0));
}
@Test
- public void basic() {
+ void basic() {
ConfigTester tester = new ConfigTester();
DelayedResponses delayedResponses = new DelayedResponses();
MemoryCache memoryCache = new MemoryCache();
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
index d8c03961ddb..6bb9f74105c 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.config.proxy;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -20,7 +20,7 @@ public class DelayedResponseTest {
private static final String namespace = "bar";
@Test
- public void basic() {
+ void basic() {
ConfigTester tester = new ConfigTester();
final long returnTime = System.currentTimeMillis();
final long timeout = 1;
@@ -51,7 +51,7 @@ public class DelayedResponseTest {
}
@Test
- public void testDelayedResponse() {
+ void testDelayedResponse() {
ConfigTester tester = new ConfigTester();
final long timeout = 20000;
JRTServerConfigRequest request1 = tester.createRequest("baz", configId, namespace, timeout);
@@ -69,9 +69,9 @@ public class DelayedResponseTest {
// New request, should have larger delay than the first
JRTServerConfigRequest request2 = tester.createRequest("baz", configId, namespace, timeout);
DelayedResponse delayed2 = new DelayedResponse(request2);
- assertTrue("delayed1=" + delayed1.getReturnTime() + ", delayed2=" +
- delayed2.getReturnTime() + ": delayed2 should be greater than delayed1",
- delayed2.getReturnTime() > delayed1.getReturnTime());
+ assertTrue(delayed2.getReturnTime() > delayed1.getReturnTime(),
+ "delayed1=" + delayed1.getReturnTime() + ", delayed2=" +
+ delayed2.getReturnTime() + ": delayed2 should be greater than delayed1");
// Test compareTo() method
assertEquals(0, delayed1.compareTo(delayed1));
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
index c9e714a11a3..6d9fa668bf5 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class DelayedResponsesTest {
@Test
- public void basic() throws InterruptedException {
+ void basic() throws InterruptedException {
ConfigTester tester = new ConfigTester();
DelayedResponses responses = new DelayedResponses();
DelayedResponse delayedResponse = new DelayedResponse(tester.createRequest("foo", "id", "bar", 10));
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
index d243d9c6dff..ff30a5b2381 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class MemoryCacheConfigClientTest {
@Test
- public void basic() {
+ void basic() {
MemoryCacheConfigClient client = new MemoryCacheConfigClient(new MemoryCache());
client.memoryCache().update(ConfigTester.fooConfig);
assertEquals(ConfigTester.fooConfig, client.getConfig(ConfigTester.fooConfig, null).orElseThrow());
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
index b0cba728a0c..2732a84527e 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
@@ -8,14 +8,14 @@ import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.Payload;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -47,7 +47,7 @@ public class MemoryCacheTest {
private Payload payload2;
private Payload payloadDifferentMd5;
- @Before
+ @BeforeEach
public void setup() {
ArrayList<String> defContent = new ArrayList<>();
defContent.add("bar string");
@@ -74,7 +74,7 @@ public class MemoryCacheTest {
}
@Test
- public void basic() {
+ void basic() {
MemoryCache cache = new MemoryCache();
cache.update(config);
@@ -97,7 +97,7 @@ public class MemoryCacheTest {
}
@Test
- public void testSameConfigNameDifferentMd5() {
+ void testSameConfigNameDifferentMd5() {
MemoryCache cache = new MemoryCache();
cache.update(config);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
index 0e25e62b925..0277ea60b49 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
@@ -8,18 +8,18 @@ import com.yahoo.vespa.config.ErrorCode;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
import com.yahoo.vespa.config.protocol.Payload;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -38,10 +38,10 @@ public class ProxyServerTest {
fooConfig.getPayloadChecksums(), fooConfig.getGeneration(), false,
ErrorCode.UNKNOWN_DEFINITION, fooConfig.getDefContent(), Optional.empty());
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @Before
+ @BeforeEach
public void setup() {
source.clear();
source.put(fooConfig.getKey(), createConfigWithNextConfigGeneration(fooConfig, 0));
@@ -49,13 +49,13 @@ public class ProxyServerTest {
proxy = createTestServer(source, client);
}
- @After
+ @AfterEach
public void shutdown() {
proxy.stop();
}
@Test
- public void basic() {
+ void basic() {
assertTrue(proxy.getMode().isDefault());
assertEquals(0, proxy.memoryCache().size());
@@ -72,7 +72,7 @@ public class ProxyServerTest {
* Tests that the proxy server RPC commands for setting and getting mode works..
*/
@Test
- public void testModeSwitch() {
+ void testModeSwitch() {
ProxyServer proxy = createTestServer(source, client);
assertTrue(proxy.getMode().isDefault());
@@ -106,7 +106,7 @@ public class ProxyServerTest {
* when it is found there.
*/
@Test
- public void testGetConfigAndCaching() {
+ void testGetConfigAndCaching() {
ConfigTester tester = new ConfigTester();
MemoryCache memoryCache = proxy.memoryCache();
assertEquals(0, memoryCache.size());
@@ -127,7 +127,7 @@ public class ProxyServerTest {
* it must be updated in cache.
*/
@Test
- public void testNoCachingOfErrorRequests() {
+ void testNoCachingOfErrorRequests() {
ConfigTester tester = new ConfigTester();
// Simulate an error response
source.put(fooConfig.getKey(), createConfigWithNextConfigGeneration(fooConfig, ErrorCode.INTERNAL_ERROR));
@@ -163,7 +163,7 @@ public class ProxyServerTest {
* When the config has been successfully retrieved it must be updated in cache.
*/
@Test
- public void testNoCachingOfEmptyConfig() {
+ void testNoCachingOfEmptyConfig() {
ConfigTester tester = new ConfigTester();
MemoryCache cache = proxy.memoryCache();
@@ -175,8 +175,8 @@ public class ProxyServerTest {
// Simulate an empty response
RawConfig emptyConfig = new RawConfig(fooConfig.getKey(), fooConfig.getDefMd5(), Payload.from("{}"),
- fooConfig.getPayloadChecksums(), 0, false,
- 0, fooConfig.getDefContent(), Optional.empty());
+ fooConfig.getPayloadChecksums(), 0, false,
+ 0, fooConfig.getDefContent(), Optional.empty());
source.put(fooConfig.getKey(), emptyConfig);
res = proxy.resolveConfig(tester.createRequest(fooConfig)).orElseThrow();
@@ -195,7 +195,7 @@ public class ProxyServerTest {
}
@Test
- public void testReconfiguration() {
+ void testReconfiguration() {
ConfigTester tester = new ConfigTester();
RawConfig res = proxy.resolveConfig(tester.createRequest(fooConfig)).orElseThrow();
assertEquals(ConfigTester.fooPayload.toString(), res.getPayload().toString());
@@ -210,7 +210,7 @@ public class ProxyServerTest {
}
@Test
- public void testReadingSystemProperties() {
+ void testReadingSystemProperties() {
ProxyServer.Properties properties = ProxyServer.getSystemProperties();
assertEquals(1, properties.configSources.length);
assertEquals(ProxyServer.DEFAULT_PROXY_CONFIG_SOURCES, properties.configSources[0]);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
index ada98f4b30e..b55d6fb9e26 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
@@ -5,12 +5,13 @@ import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.JRTConfigRequestFactory;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
-import static org.junit.Assert.assertEquals;
+import java.io.File;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -20,18 +21,18 @@ public class RpcConfigSourceClientTest {
private ResponseHandler responseHandler;
private RpcConfigSourceClient rpcConfigSourceClient;
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
+ @TempDir
+ public File tempFolder;
- @Before
+ @BeforeEach
public void setup() {
responseHandler = new ResponseHandler(true);
rpcConfigSourceClient = new RpcConfigSourceClient(responseHandler, new MockConfigSource());
}
@Test
- public void basic() {
+ void basic() {
final RawConfig fooConfig = ProxyServerTest.fooConfig;
configUpdatedSendResponse(fooConfig);
// Nobody asked for the config, so no response sent
@@ -48,13 +49,13 @@ public class RpcConfigSourceClientTest {
}
@Test
- public void errorResponse() {
+ void errorResponse() {
configUpdatedSendResponse(ProxyServerTest.errorConfig);
assertSentResponses(0);
}
@Test
- public void it_does_not_send_old_config_in_response() {
+ void it_does_not_send_old_config_in_response() {
RawConfig fooConfigOldGeneration = ProxyServerTest.fooConfig;
RawConfig fooConfig = createConfigWithNextConfigGeneration(fooConfigOldGeneration);
@@ -74,7 +75,7 @@ public class RpcConfigSourceClientTest {
}
@Test
- public void it_does_send_config_with_generation_0_in_response() {
+ void it_does_send_config_with_generation_0_in_response() {
RawConfig fooConfigOldGeneration = ProxyServerTest.fooConfig;
RawConfig fooConfig = createConfigWithNextConfigGeneration(fooConfigOldGeneration, 1);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
index 3987ba176d7..a491a7b4fc4 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
@@ -2,18 +2,17 @@
package com.yahoo.vespa.config.proxy.filedistribution;
import com.yahoo.io.IOUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author hmusum
@@ -24,18 +23,18 @@ public class CachedFilesMaintainerTest {
private File cachedDownloads;
private CachedFilesMaintainer cachedFilesMaintainer;
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
+ @TempDir
+ public File tempFolder;
- @Before
+ @BeforeEach
public void setup() throws IOException {
- cachedFileReferences = tempFolder.newFolder();
- cachedDownloads = tempFolder.newFolder();
+ cachedFileReferences = newFolder(tempFolder, "cachedFileReferences");
+ cachedDownloads = newFolder(tempFolder, "cachedDownloads");
cachedFilesMaintainer = new CachedFilesMaintainer(cachedFileReferences, cachedDownloads, Duration.ofMinutes(1));
}
@Test
- public void require_old_files_to_be_deleted() throws IOException {
+ void require_old_files_to_be_deleted() throws IOException {
runMaintainerAndAssertFiles(0, 0);
File fileReference = writeFile(cachedFileReferences, "fileReference");
@@ -72,4 +71,13 @@ public class CachedFilesMaintainerTest {
return file;
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/config/pom.xml b/config/pom.xml
index f787a7b0b49..1f90d374d88 100755
--- a/config/pom.xml
+++ b/config/pom.xml
@@ -55,11 +55,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>defaults</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/config/src/main/java/com/yahoo/config/subscription/ConfigGetter.java b/config/src/main/java/com/yahoo/config/subscription/ConfigGetter.java
index aabfd211fac..316edda1ee8 100755
--- a/config/src/main/java/com/yahoo/config/subscription/ConfigGetter.java
+++ b/config/src/main/java/com/yahoo/config/subscription/ConfigGetter.java
@@ -1,7 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription;
-
import com.yahoo.config.ConfigInstance;
/**
@@ -13,7 +12,9 @@ import com.yahoo.config.ConfigInstance;
* command-line tools.
*
* @author gjoranv
+ * @deprecated Use config builders where possible
*/
+@Deprecated
public class ConfigGetter<T extends ConfigInstance> {
private final Class<T> clazz;
diff --git a/config/src/main/java/com/yahoo/config/subscription/impl/JRTConfigRequester.java b/config/src/main/java/com/yahoo/config/subscription/impl/JRTConfigRequester.java
index d77cfc17c92..858dc46f77a 100644
--- a/config/src/main/java/com/yahoo/config/subscription/impl/JRTConfigRequester.java
+++ b/config/src/main/java/com/yahoo/config/subscription/impl/JRTConfigRequester.java
@@ -45,7 +45,7 @@ public class JRTConfigRequester implements RequestWaiter {
private static final Duration delayBetweenWarnings = Duration.ofSeconds(60);
static final float randomFraction = 0.2f;
/* Time to be added to server timeout to create client timeout. This is the time allowed for the server to respond after serverTimeout has elapsed. */
- private static final Double additionalTimeForClientTimeout = 10.0;
+ private static final Duration additionalTimeForClientTimeout = Duration.ofSeconds(10);
private final TimingValues timingValues;
private final ScheduledThreadPoolExecutor scheduler;
@@ -100,7 +100,7 @@ public class JRTConfigRequester implements RequestWaiter {
request.setContext(new RequestContext(sub, req, connection));
if (!req.validateParameters()) throw new ConfigurationRuntimeException("Error in parameters for config request: " + req);
- double jrtClientTimeout = getClientTimeout(req);
+ Duration jrtClientTimeout = getClientTimeout(req);
log.log(FINE, () -> "Requesting config for " + sub + " on connection " + connection
+ " with client timeout " + jrtClientTimeout +
(log.isLoggable(FINEST) ? (",defcontent=" + req.getDefContent().asString()) : ""));
@@ -271,7 +271,7 @@ public class JRTConfigRequester implements RequestWaiter {
return connectionPool;
}
- private Double getClientTimeout(JRTClientConfigRequest request) {
- return (request.getTimeout() / 1000.0) + additionalTimeForClientTimeout;
+ private Duration getClientTimeout(JRTClientConfigRequest request) {
+ return Duration.ofMillis(request.getTimeout()).plus(additionalTimeForClientTimeout);
}
}
diff --git a/config/src/main/java/com/yahoo/config/subscription/impl/MockConnection.java b/config/src/main/java/com/yahoo/config/subscription/impl/MockConnection.java
index 24a080d5824..dc0372cea7f 100644
--- a/config/src/main/java/com/yahoo/config/subscription/impl/MockConnection.java
+++ b/config/src/main/java/com/yahoo/config/subscription/impl/MockConnection.java
@@ -10,6 +10,8 @@ import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
import com.yahoo.vespa.config.protocol.Payload;
+import java.time.Duration;
+
/**
* For unit testing
*
@@ -37,14 +39,14 @@ public class MockConnection implements ConnectionPool, Connection {
}
@Override
- public void invokeAsync(Request request, double jrtTimeout, RequestWaiter requestWaiter) {
+ public void invokeAsync(Request request, Duration jrtTimeout, RequestWaiter requestWaiter) {
numberOfRequests++;
lastRequest = request;
responseHandler.handle(request, requestWaiter);
}
@Override
- public void invokeSync(Request request, double jrtTimeout) {
+ public void invokeSync(Request request, Duration jrtTimeout) {
numberOfRequests++;
lastRequest = request;
}
diff --git a/config/src/main/java/com/yahoo/vespa/config/Connection.java b/config/src/main/java/com/yahoo/vespa/config/Connection.java
index ea6419c62e1..69e8fcf9963 100644
--- a/config/src/main/java/com/yahoo/vespa/config/Connection.java
+++ b/config/src/main/java/com/yahoo/vespa/config/Connection.java
@@ -4,14 +4,16 @@ package com.yahoo.vespa.config;
import com.yahoo.jrt.Request;
import com.yahoo.jrt.RequestWaiter;
+import java.time.Duration;
+
/**
* @author hmusum
*/
public interface Connection {
- void invokeAsync(Request request, double jrtTimeout, RequestWaiter requestWaiter);
+ void invokeAsync(Request request, Duration jrtTimeout, RequestWaiter requestWaiter);
- void invokeSync(Request request, double jrtTimeout);
+ void invokeSync(Request request, Duration jrtTimeout);
String getAddress();
diff --git a/config/src/main/java/com/yahoo/vespa/config/JRTConnection.java b/config/src/main/java/com/yahoo/vespa/config/JRTConnection.java
index 2d7c96febd6..f2a104696c1 100644
--- a/config/src/main/java/com/yahoo/vespa/config/JRTConnection.java
+++ b/config/src/main/java/com/yahoo/vespa/config/JRTConnection.java
@@ -7,6 +7,7 @@ import com.yahoo.jrt.Spec;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
+import java.time.Duration;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -30,12 +31,12 @@ public class JRTConnection implements Connection {
}
@Override
- public void invokeAsync(Request request, double jrtTimeout, RequestWaiter requestWaiter) {
+ public void invokeAsync(Request request, Duration jrtTimeout, RequestWaiter requestWaiter) {
getTarget().invokeAsync(request, jrtTimeout, requestWaiter);
}
@Override
- public void invokeSync(Request request, double jrtTimeout) {
+ public void invokeSync(Request request, Duration jrtTimeout) {
getTarget().invokeSync(request, jrtTimeout);
}
diff --git a/config/src/main/java/com/yahoo/vespa/config/UrlDownloader.java b/config/src/main/java/com/yahoo/vespa/config/UrlDownloader.java
index b3a4590fdb2..62308315c95 100644
--- a/config/src/main/java/com/yahoo/vespa/config/UrlDownloader.java
+++ b/config/src/main/java/com/yahoo/vespa/config/UrlDownloader.java
@@ -11,6 +11,7 @@ import com.yahoo.jrt.Transport;
import com.yahoo.vespa.defaults.Defaults;
import java.io.File;
+import java.time.Duration;
import java.util.logging.Logger;
import static java.util.logging.Level.FINE;
@@ -47,7 +48,7 @@ public class UrlDownloader {
target = supervisor.connect(spec);
// ping to check if connection is working
Request request = new Request("frt.rpc.ping");
- target.invokeSync(request, 5.0);
+ target.invokeSync(request, Duration.ofSeconds(5));
if (! request.isError()) {
log.log(FINE, () -> "Successfully connected to '" + spec + "', this = " + System.identityHashCode(this));
return;
diff --git a/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java b/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java
index 345118b5fd4..5b0f1351ff5 100644
--- a/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java
+++ b/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java
@@ -26,6 +26,7 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -239,7 +240,7 @@ public class LoadTester {
System.out.println("# Requesting: " + reqKey);
long start = System.nanoTime();
- target.invokeSync(request.getRequest(), 10.0);
+ target.invokeSync(request.getRequest(), Duration.ofSeconds(10));
long durationInMillis = (System.nanoTime() - start) / 1_000_000;
if (request.isError()) {
diff --git a/config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceDeserializer.java b/config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceDeserializer.java
index c5ce01f4e2a..6047c493505 100644
--- a/config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceDeserializer.java
+++ b/config/src/main/java/com/yahoo/vespa/config/protocol/SlimeTraceDeserializer.java
@@ -39,19 +39,13 @@ public class SlimeTraceDeserializer {
}
private static Object decodePayload(Inspector entry) {
- switch (entry.type()) {
- case STRING:
- return entry.asString();
- case LONG:
- return entry.asLong();
- case BOOL:
- return entry.asBool();
- case DOUBLE:
- return entry.asDouble();
- case DATA:
- return entry.asData();
- default:
- return null;
- }
+ return switch (entry.type()) {
+ case STRING -> entry.asString();
+ case LONG -> entry.asLong();
+ case BOOL -> entry.asBool();
+ case DOUBLE -> entry.asDouble();
+ case DATA -> entry.asData();
+ default -> null;
+ };
}
}
diff --git a/config/src/test/java/com/yahoo/config/subscription/ConfigGetterTest.java b/config/src/test/java/com/yahoo/config/subscription/ConfigGetterTest.java
index fb116729640..68b5d6a37d3 100644
--- a/config/src/test/java/com/yahoo/config/subscription/ConfigGetterTest.java
+++ b/config/src/test/java/com/yahoo/config/subscription/ConfigGetterTest.java
@@ -12,6 +12,7 @@ import static org.junit.Assert.assertTrue;
*
* @author gjoranv
*/
+@SuppressWarnings("deprecation")
public class ConfigGetterTest {
private final ConfigSourceSet sourceSet = new ConfigSourceSet("config-getter-test");
diff --git a/config/src/test/java/com/yahoo/config/subscription/FunctionTest.java b/config/src/test/java/com/yahoo/config/subscription/FunctionTest.java
index 42c2c599899..8656c0e945f 100644
--- a/config/src/test/java/com/yahoo/config/subscription/FunctionTest.java
+++ b/config/src/test/java/com/yahoo/config/subscription/FunctionTest.java
@@ -2,20 +2,16 @@
package com.yahoo.config.subscription;
import com.yahoo.foo.FunctionTestConfig;
-
import org.junit.Before;
import org.junit.Test;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -28,6 +24,7 @@ import static org.junit.Assert.fail;
*
* @author gjoranv
*/
+@SuppressWarnings("deprecation")
public class FunctionTest {
public static final String PATH = "src/test/resources/configs/function-test/";
diff --git a/config/src/test/java/com/yahoo/config/subscription/NamespaceTest.java b/config/src/test/java/com/yahoo/config/subscription/NamespaceTest.java
index 963f3de5e43..2e7beb0f0f4 100644
--- a/config/src/test/java/com/yahoo/config/subscription/NamespaceTest.java
+++ b/config/src/test/java/com/yahoo/config/subscription/NamespaceTest.java
@@ -12,6 +12,7 @@ import static org.junit.Assert.assertEquals;
public class NamespaceTest {
@Test
+ @SuppressWarnings("deprecation")
public void verifyConfigClassWithExplicitNamespace() {
NamespaceConfig config = new ConfigGetter<>(NamespaceConfig.class).getConfig("raw: a 0\n");
assertEquals(0, config.a());
diff --git a/config/src/test/java/com/yahoo/config/subscription/UnicodeTest.java b/config/src/test/java/com/yahoo/config/subscription/UnicodeTest.java
index 8864f114d87..c1d98ac7e3e 100644
--- a/config/src/test/java/com/yahoo/config/subscription/UnicodeTest.java
+++ b/config/src/test/java/com/yahoo/config/subscription/UnicodeTest.java
@@ -22,6 +22,7 @@ public class UnicodeTest {
* received correctly from the server
*/
@Test
+ @SuppressWarnings("deprecation")
public void testUnicodeConfigReading() {
ConfigGetter<UnicodeConfig> getter = new ConfigGetter<>(UnicodeConfig.class);
UnicodeConfig config = getter.getConfig("file:src/test/resources/configs/unicode/unicode.cfg");
diff --git a/container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/package-info.java b/configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java
index 7f9dc3d1cd9..9dcdc2504d1 100644
--- a/container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/package-info.java
+++ b/configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
-package com.yahoo.container.handler.observability;
+package com.yahoo.vespa.config.jdisc.http.filter;
import com.yahoo.osgi.annotation.ExportPackage;
diff --git a/configdefinitions/src/vespa/configserver.def b/configdefinitions/src/vespa/configserver.def
index da383ecb6f5..eaeea794a28 100644
--- a/configdefinitions/src/vespa/configserver.def
+++ b/configdefinitions/src/vespa/configserver.def
@@ -47,7 +47,7 @@ zoneDnsSuffixes[] string
# RPC protocol
maxgetconfigclients int default=1000000
maxoutputbuffersize int default=65536
-useVespaVersionInRequest bool default=false
+useVespaVersionInRequest bool default=true
payloadCompressionType enum { UNCOMPRESSED, LZ4 } default=LZ4
# Athenz config
@@ -55,9 +55,10 @@ loadBalancerAddress string default=""
athenzDnsSuffix string default=""
ztsUrl string default=""
-# Maintainers
+# Maintenance settings
maintainerIntervalMinutes int default=30
keepUnusedFileReferencesMinutes int default=300
+keepSessionsWithUnknownStatusHours int default=24
# Bootstrapping
# How long bootstrapping can take before giving up (in seconds)
diff --git a/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def b/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def
new file mode 100644
index 00000000000..3fe850908dc
--- /dev/null
+++ b/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def
@@ -0,0 +1,18 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package=com.yahoo.vespa.config.jdisc.http.filter
+
+dryrun bool default=false
+defaultRule.action enum { ALLOW, BLOCK }
+defaultRule.blockResponseCode int default=403
+defaultRule.blockResponseMessage string default=""
+defaultRule.blockResponseHeaders[].name string
+defaultRule.blockResponseHeaders[].value string
+rule[].name string
+rule[].action enum { ALLOW, BLOCK }
+rule[].hostNames[] string
+rule[].methods[] enum { GET, POST, PUT, PATCH, DELETE }
+rule[].pathExpressions[] string
+rule[].blockResponseCode int default=403
+rule[].blockResponseMessage string default=""
+rule[].blockResponseHeaders[].name string
+rule[].blockResponseHeaders[].value string
diff --git a/configgen/pom.xml b/configgen/pom.xml
index 11d6a195bc6..3c7032d684b 100644
--- a/configgen/pom.xml
+++ b/configgen/pom.xml
@@ -15,8 +15,13 @@
<description>Config java code generation from config definition files for Java Vespa components.</description>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/configgen/src/main/java/com/yahoo/config/codegen/CppClassBuilder.java b/configgen/src/main/java/com/yahoo/config/codegen/CppClassBuilder.java
index d3a0a79c737..ca38a8fda47 100644
--- a/configgen/src/main/java/com/yahoo/config/codegen/CppClassBuilder.java
+++ b/configgen/src/main/java/com/yahoo/config/codegen/CppClassBuilder.java
@@ -124,19 +124,29 @@ public class CppClassBuilder implements ClassBuilder {
* Class to generate noexcept specifier if default constructor, copy constructor or copy assignment is non-throwing
*/
private static class NoExceptSpecifier {
- private final boolean enabled;
+ private enum Variant {
+ COPY,
+ MOVE,
+ DEFAULT_CONSTRUCTOR
+ }
+ private final boolean copyEnabled;
+ private final boolean moveEnabled;
+ private final boolean defaultConstructorEnabled;
- public NoExceptSpecifier(CNode node) {
- enabled = checkNode(node);
+ public NoExceptSpecifier(CNode node)
+ {
+ copyEnabled = checkNode(node, Variant.COPY);
+ moveEnabled = checkNode(node, Variant.MOVE);
+ defaultConstructorEnabled = checkNode(node, Variant.DEFAULT_CONSTRUCTOR);
}
- private static boolean checkNode(CNode node) {
+ private static boolean checkNode(CNode node, Variant variant) {
if (node instanceof InnerCNode) {
for (CNode child: node.getChildren()) {
- if (child.isArray || child.isMap) {
+ if ((child.isArray || child.isMap) && variant != Variant.MOVE) {
return false;
}
- if (!checkNode(child)) {
+ if (!checkNode(child, variant)) {
return false;
}
}
@@ -144,13 +154,18 @@ public class CppClassBuilder implements ClassBuilder {
return true;
}
- public String toString() {
+ private static String qualifier(boolean enabled) {
if (enabled) {
return " noexcept";
} else {
return "";
}
}
+
+ public String copyQualifier() { return qualifier(copyEnabled); }
+ public String moveQualifier() { return qualifier(moveEnabled); }
+ public String defaultConstructorQualifier() { return qualifier(defaultConstructorEnabled); }
+ public String toString() { return copyQualifier(); }
}
void writeHeaderFile(Writer w, CNode root) throws IOException {
@@ -338,54 +353,54 @@ public class CppClassBuilder implements ClassBuilder {
}
void writeClassCopyConstructorDeclaration(Writer w, String className, NoExceptSpecifier noexcept, String indent) throws IOException {
- w.write(indent + className + "(const " + className + " & __rhs)" + noexcept + ";\n");
+ w.write(indent + className + "(const " + className + " & __rhs)" + noexcept.copyQualifier() + ";\n");
}
void writeClassAssignmentOperatorDeclaration(Writer w, String className, NoExceptSpecifier noexcept, String indent) throws IOException {
- w.write(indent + className + " & operator = (const " + className + " & __rhs)" + noexcept + ";\n");
+ w.write(indent + className + " & operator = (const " + className + " & __rhs)" + noexcept.copyQualifier() + ";\n");
}
void writeClassMoveConstructorDeclaration(Writer w, String className, NoExceptSpecifier noexcept, String indent) throws IOException {
- w.write(indent + className + "(" + className + " && __rhs)" + noexcept + ";\n");
+ w.write(indent + className + "(" + className + " && __rhs)" + noexcept.moveQualifier() + ";\n");
}
void writeClassMoveOperatorDeclaration(Writer w, String className, NoExceptSpecifier noexcept, String indent) throws IOException {
- w.write(indent + className + " & operator = (" + className + " && __rhs)" + noexcept + ";\n");
+ w.write(indent + className + " & operator = (" + className + " && __rhs)" + noexcept.moveQualifier() + ";\n");
}
void writeConfigClassCopyConstructorDefinition(Writer w, String parent, String className, NoExceptSpecifier noexcept) throws IOException {
- w.write(parent + "::" + className + "(const " + className + " & __rhs)" + noexcept + " = default;\n");
+ w.write(parent + "::" + className + "(const " + className + " & __rhs)" + noexcept.copyQualifier() + " = default;\n");
}
void writeConfigClassAssignmentOperatorDefinition(Writer w, String parent, String className, NoExceptSpecifier noexcept) throws IOException {
- w.write(parent + " & " + parent + "::" + "operator =(const " + className + " & __rhs)" + noexcept + " = default;\n");
+ w.write(parent + " & " + parent + "::" + "operator =(const " + className + " & __rhs)" + noexcept.copyQualifier() + " = default;\n");
}
void writeConfigClassMoveConstructorDefinition(Writer w, String parent, String className, NoExceptSpecifier noexcept) throws IOException {
- w.write(parent + "::" + className + "(" + className + " && __rhs)" + noexcept + " = default;\n");
+ w.write(parent + "::" + className + "(" + className + " && __rhs)" + noexcept.moveQualifier() + " = default;\n");
}
void writeConfigClassMoveOperatorDefinition(Writer w, String parent, String className, NoExceptSpecifier noexcept) throws IOException {
- w.write(parent + " & " + parent + "::" + "operator =(" + className + " && __rhs)" + noexcept + " = default;\n");
+ w.write(parent + " & " + parent + "::" + "operator =(" + className + " && __rhs)" + noexcept.moveQualifier() + " = default;\n");
}
void writeClassCopyConstructorDefinition(Writer w, String parent, CNode node) throws IOException {
String typeName = getTypeName(node, false);
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
- w.write(parent + "::" + typeName + "(const " + typeName + " & __rhs)" + noexcept + " = default;\n");
+ w.write(parent + "::" + typeName + "(const " + typeName + " & __rhs)" + noexcept.copyQualifier() + " = default;\n");
}
void writeClassMoveConstructorDefinition(Writer w, String parent, CNode node) throws IOException {
String typeName = getTypeName(node, false);
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
- w.write(parent + "::" + typeName + "(" + typeName + " && __rhs)" + noexcept + " = default;\n");
+ w.write(parent + "::" + typeName + "(" + typeName + " && __rhs)" + noexcept.moveQualifier() + " = default;\n");
}
void writeClassAssignmentOperatorDefinition(Writer w, String parent, CNode node) throws IOException {
String typeName = getTypeName(node, false);
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
// Write empty constructor
- w.write(parent + " & " + parent + "::" + "operator = (const " + typeName + " & __rhs)" + noexcept + " = default;\n");
+ w.write(parent + " & " + parent + "::" + "operator = (const " + typeName + " & __rhs)" + noexcept.copyQualifier() + " = default;\n");
}
void writeClassMoveOperatorDefinition(Writer w, String parent, CNode node) throws IOException {
String typeName = getTypeName(node, false);
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
// Write empty constructor
- w.write(parent + " & " + parent + "::" + "operator = (" + typeName + " && __rhs)" + noexcept + " = default;\n");
+ w.write(parent + " & " + parent + "::" + "operator = (" + typeName + " && __rhs)" + noexcept.moveQualifier() + " = default;\n");
}
void writeDestructor(Writer w, String parent, String className) throws IOException {
@@ -394,7 +409,7 @@ public class CppClassBuilder implements ClassBuilder {
void writeCommonFunctionDeclarations(Writer w, String className, CNode node, String indent) throws IOException {
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
- w.write("" + indent + className + "() " + noexcept + ";\n");
+ w.write("" + indent + className + "() " + noexcept.defaultConstructorQualifier() + ";\n");
writeClassCopyConstructorDeclaration(w, className, noexcept, indent);
writeClassAssignmentOperatorDeclaration(w, className, noexcept, indent);
writeClassMoveConstructorDeclaration(w, className, noexcept, indent);
@@ -694,7 +709,7 @@ public class CppClassBuilder implements ClassBuilder {
String typeName = root ? getInternalClassName(node) : tmpName;
NoExceptSpecifier noexcept = new NoExceptSpecifier(node);
// Write empty constructor
- w.write(parent + typeName + "()" + noexcept + "\n");
+ w.write(parent + typeName + "()" + noexcept.defaultConstructorQualifier() + "\n");
for (int i=0; i<node.getChildren().length; ++i) {
CNode child = node.getChildren()[i];
String childName = getIdentifier(child.getName());
@@ -795,8 +810,7 @@ public class CppClassBuilder implements ClassBuilder {
} else {
w.write("ConfigParser::parseStruct<" + childType + ">(\"" + child.getName() + "\", __lines");
}
- if (child instanceof LeafCNode && ((LeafCNode) child).getDefaultValue() != null) {
- LeafCNode leaf = (LeafCNode) child;
+ if (child instanceof LeafCNode leaf && leaf.getDefaultValue() != null) {
if (leaf.getDefaultValue().getValue() != null) {
String defaultVal = getDefaultValue(leaf);
if (leaf instanceof LeafCNode.EnumLeaf) {
diff --git a/configgen/src/main/java/com/yahoo/config/codegen/DefParser.java b/configgen/src/main/java/com/yahoo/config/codegen/DefParser.java
index 2ed0bc62d0b..cebb7ca8108 100644
--- a/configgen/src/main/java/com/yahoo/config/codegen/DefParser.java
+++ b/configgen/src/main/java/com/yahoo/config/codegen/DefParser.java
@@ -18,8 +18,10 @@ public class DefParser {
public static final String DEFAULT_PACKAGE_PREFIX = "com.yahoo.";
static final Pattern commentPattern = Pattern.compile("^\\s*#+\\s*(.*?)\\s*$");
+
// TODO: Version is ignored, remove in Vespa 9
public static final Pattern versionPattern = Pattern.compile("^(version\\s*=\\s*)([0-9][0-9-]*)$");
+
// Namespace/package must start with a letter, since Java (Java language Spec, section 3.8) and C++ identifiers cannot start with a digit
public static final Pattern namespacePattern = getNamespacePattern("namespace");
public static final Pattern packagePattern = getNamespacePattern("package");
@@ -32,7 +34,7 @@ public class DefParser {
private final String name;
private InnerCNode root = null;
private NormalizedDefinition normalizedDefinition = null;
-
+ private boolean systemErrEnabled = false;
private String comment = "";
@@ -54,6 +56,10 @@ public class DefParser {
}
}
+ void enableSystemErr() {
+ systemErrEnabled = true;
+ }
+
// If name contains namespace, return just name
private String createName(String name) {
if (name.contains(".")) {
@@ -127,7 +133,7 @@ public class DefParser {
}
Matcher versionMatch = versionPattern.matcher(line);
if (versionMatch.matches()) {
- System.err.println("Warning: In config definition '" + name + "': version is deprecated and ignored, please remove, support will be removed in Vespa 9");
+ printSystemErr("Warning: In config definition '" + name + "': version is deprecated and ignored, please remove, support will be removed in Vespa 9");
return;
}
Matcher namespaceMatcher = namespacePattern.matcher(line);
@@ -222,7 +228,11 @@ public class DefParser {
}
- class DefParserException extends Exception {
+ private void printSystemErr(String s) {
+ if (systemErrEnabled) System.err.println(s);
+ }
+
+ static class DefParserException extends Exception {
DefParserException(String s, Throwable cause) {
super(s, cause);
}
diff --git a/configgen/src/main/java/com/yahoo/config/codegen/MakeConfig.java b/configgen/src/main/java/com/yahoo/config/codegen/MakeConfig.java
index 684dd62a9a2..04f7c90c9b9 100644
--- a/configgen/src/main/java/com/yahoo/config/codegen/MakeConfig.java
+++ b/configgen/src/main/java/com/yahoo/config/codegen/MakeConfig.java
@@ -30,9 +30,12 @@ public class MakeConfig {
for (File specFile : properties.specFiles) {
String name = specFile.getName();
if (name.endsWith(".def")) name = name.substring(0, name.length() - 4);
+
DefParser parser = new DefParser(name, new FileReader(specFile));
+ parser.enableSystemErr();
InnerCNode configRoot = parser.getTree();
checkNamespaceAndPacakge(name, configRoot, isCpp(properties));
+
if (configRoot != null) {
MakeConfig mc = new MakeConfig(configRoot, parser.getNormalizedDefinition(), properties);
mc.buildClasses();
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
index 9cf363376cc..53d02689fed 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
@@ -1,12 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests parsing of a single line of a .def file
@@ -16,13 +13,15 @@ import static org.junit.Assert.assertTrue;
*/
public class DefLineParsingTest {
- @Test(expected = IllegalArgumentException.class)
- public void require_that_null_default_is_not_allowed() {
- new DefLine("s string default=null");
+ @Test
+ void require_that_null_default_is_not_allowed() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new DefLine("s string default=null");
+ });
}
@Test
- public void testParseIntArray() {
+ void testParseIntArray() {
DefLine l = new DefLine("foo[] int");
assertEquals("foo[]", l.getName());
@@ -31,7 +30,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseIntMap() {
+ void testParseIntMap() {
DefLine l = new DefLine("foo{} int");
assertEquals("foo{}", l.getName());
@@ -40,7 +39,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseInnerMap() {
+ void testParseInnerMap() {
DefLine l = new DefLine("foo{}.i int");
assertEquals("foo{}.i", l.getName());
@@ -49,7 +48,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseEnum() {
+ void testParseEnum() {
DefLine l = new DefLine("idtype enum { us_east, US_WEST, EMEA } default=EMEA");
assertEquals("idtype", l.getName());
@@ -62,7 +61,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultReference() {
+ void testParseDefaultReference() {
DefLine l = new DefLine("foo.bar reference default=\"value\"");
assertEquals("foo.bar", l.getName());
@@ -72,7 +71,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultReference() {
+ void testParseNoDefaultReference() {
DefLine l = new DefLine("foo.bar reference");
assertEquals("foo.bar", l.getName());
@@ -85,7 +84,7 @@ public class DefLineParsingTest {
* the future, so the test is included to verify that value and name can be retrieved.
*/
@Test
- public void testParseDefaultFile() {
+ void testParseDefaultFile() {
DefLine l = new DefLine("fileWithDef file default=\"value\"");
assertEquals("fileWithDef", l.getName());
@@ -95,7 +94,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultFile() {
+ void testParseNoDefaultFile() {
DefLine l = new DefLine("fileVal file");
assertEquals("fileVal", l.getName());
@@ -104,7 +103,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseUrls() {
+ void testParseUrls() {
DefLine l = new DefLine("urlVal url");
assertEquals("urlVal", l.getName());
@@ -113,7 +112,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultUrls() {
+ void testParseDefaultUrls() {
DefLine l = new DefLine("urlVal url default=\"http://docs.vespa.ai\"");
assertEquals("urlVal", l.getName());
@@ -124,7 +123,7 @@ public class DefLineParsingTest {
@Test
- public void testParseDefaultInt() {
+ void testParseDefaultInt() {
DefLine l = new DefLine("foo int default=1000");
assertEquals("foo", l.getName());
@@ -134,7 +133,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultLong() {
+ void testParseDefaultLong() {
DefLine l = new DefLine("foo long default=9223372036854775807");
assertEquals("foo", l.getName());
@@ -144,7 +143,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultDouble() {
+ void testParseDefaultDouble() {
DefLine l = new DefLine("foo double default=5.37");
assertEquals("foo", l.getName());
@@ -154,7 +153,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultFalseBoolean() {
+ void testParseDefaultFalseBoolean() {
DefLine l = new DefLine("foo bool default=false");
assertEquals("foo", l.getName());
@@ -164,7 +163,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultTrueBoolean() {
+ void testParseDefaultTrueBoolean() {
DefLine l = new DefLine("foo bool default=true");
assertEquals("foo", l.getName());
@@ -174,7 +173,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultString() {
+ void testParseNoDefaultString() {
DefLine l = new DefLine("foo.bar string");
assertEquals("foo.bar", l.getName());
@@ -183,7 +182,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultString() {
+ void testParseDefaultString() {
DefLine l = new DefLine("foo.bar string default=\"value\"");
assertEquals("foo.bar", l.getName());
@@ -193,7 +192,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultEmptyString() {
+ void testParseDefaultEmptyString() {
DefLine l = new DefLine("foo.bar string default=\"\"");
assertEquals("foo.bar", l.getName());
@@ -203,7 +202,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultStringUnquoted() {
+ void testParseDefaultStringUnquoted() {
DefLine l = new DefLine("foo.bar string default=value");
assertEquals("foo.bar", l.getName());
@@ -213,7 +212,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseStringnullDefaultString() {
+ void testParseStringnullDefaultString() {
DefLine l = new DefLine("foo.bar string default=\"null\"");
assertEquals("foo.bar", l.getName());
@@ -223,7 +222,7 @@ public class DefLineParsingTest {
}
@Test
- public void testRanges() {
+ void testRanges() {
DefLine i = new DefLine("i int range=[0, 100]");
DefLine l = new DefLine("l long range=[-1e10, 0]");
DefLine d = new DefLine("d double range=[0, 1.0]");
@@ -233,7 +232,7 @@ public class DefLineParsingTest {
}
@Test
- public void testRestartSpecification() {
+ void testRestartSpecification() {
DefLine r0 = new DefLine("i int");
DefLine r1 = new DefLine("i int restart");
assertFalse(r0.getRestart());
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
index 2eb86546e51..c57114a9ba8 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
@@ -1,15 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.codegen.DefParserTest.assertLineFails;
import static com.yahoo.config.codegen.DefParserTest.createDefTemplate;
import static com.yahoo.config.codegen.DefParserTest.createParser;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -18,49 +17,53 @@ import static org.junit.Assert.assertNotEquals;
public class DefParserNamespaceTest {
@Test
- public void namespace_is_set_on_root_node() {
+ void namespace_is_set_on_root_node() {
DefParser parser = createParser("namespace=myproject.config\n");
CNode root = parser.getTree();
assertEquals("myproject.config", root.getNamespace());
}
@Test
- public void package_is_used_as_namespace_when_no_namespace_is_given() {
+ void package_is_used_as_namespace_when_no_namespace_is_given() {
String PACKAGE = "com.github.myproject";
DefParser parser = createParser("package=" + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getNamespace());
}
- @Test(expected = CodegenRuntimeException.class)
- public void uppercase_chars_are_not_allowed() {
- createParser("namespace=Foo\n").getTree();
+ @Test
+ void uppercase_chars_are_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("namespace=Foo\n").getTree();
+ });
}
- @Test(expected = CodegenRuntimeException.class)
- public void explicit_com_yahoo_prefix_is_not_allowed() {
- createParser("namespace=com.yahoo.myproject.config\n").getTree();
+ @Test
+ void explicit_com_yahoo_prefix_is_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("namespace=com.yahoo.myproject.config\n").getTree();
+ });
}
@Test
- public void spaces_are_allowed_around_equals_sign() {
+ void spaces_are_allowed_around_equals_sign() {
DefParser parser = createParser("namespace = myproject.config\n");
CNode root = parser.getTree();
assertEquals("myproject.config", root.getNamespace());
}
@Test
- public void empty_namespace_is_not_allowed() {
+ void empty_namespace_is_not_allowed() {
assertLineFails("namespace");
}
@Test
- public void consecutive_dots_are_not_allowed() {
+ void consecutive_dots_are_not_allowed() {
assertLineFails("namespace=a..b");
}
@Test
- public void namespace_alters_def_md5() {
+ void namespace_alters_def_md5() {
DefParser parser = createParser("");
CNode root = parser.getTree();
@@ -72,7 +75,7 @@ public class DefParserNamespaceTest {
@Test
- public void number_is_allowed_as_non_leading_char_in_namespace() throws IOException, DefParser.DefParserException {
+ void number_is_allowed_as_non_leading_char_in_namespace() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "namespace=a.b.c2\n";
sb.append(line);
@@ -80,17 +83,17 @@ public class DefParserNamespaceTest {
}
@Test
- public void number_is_not_allowed_as_namespace_start_char() {
+ void number_is_not_allowed_as_namespace_start_char() {
assertLineFails("namespace=2.a.b");
}
@Test
- public void number_is_not_allowed_as_leading_char_in_namespace_token() {
+ void number_is_not_allowed_as_leading_char_in_namespace_token() {
assertLineFails("namespace=a.b.2c");
}
@Test
- public void underscore_in_namespace_is_allowed() throws IOException, DefParser.DefParserException {
+ void underscore_in_namespace_is_allowed() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "namespace=a_b.c\n";
sb.append(line);
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
index cd7ca1a89b9..4aa40ae902c 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
@@ -1,16 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.codegen.DefParserTest.assertLineFails;
import static com.yahoo.config.codegen.DefParserTest.createDefTemplate;
import static com.yahoo.config.codegen.DefParserTest.createParser;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests setting explicit java package in the def file.
@@ -21,17 +19,17 @@ public class DefParserPackageTest {
String PACKAGE = "com.github.myproject";
@Test
- public void package_is_set_on_root_node() {
+ void package_is_set_on_root_node() {
DefParser parser = createParser("package=" + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
}
@Test
- public void package_and_namespace_can_coexist() {
+ void package_and_namespace_can_coexist() {
String namespace = "test.namespace";
DefParser parser = createParser("package=" + PACKAGE +
- "\nnamespace=" + namespace +"\n");
+ "\nnamespace=" + namespace + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
assertEquals(namespace, root.getNamespace());
@@ -39,37 +37,39 @@ public class DefParserPackageTest {
// Required by JavaClassBuilder ctor.
@Test
- public void package_is_null_when_not_explicitly_given() {
+ void package_is_null_when_not_explicitly_given() {
String namespace = "test.namespace";
DefParser parser = createParser("namespace=" + namespace + "\n");
CNode root = parser.getTree();
assertNull(root.getPackage());
}
- @Test(expected = CodegenRuntimeException.class)
- public void uppercase_chars_are_not_allowed() {
- createParser("package=Foo.bar\n").getTree();
+ @Test
+ void uppercase_chars_are_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("package=Foo.bar\n").getTree();
+ });
}
@Test
- public void spaces_are_allowed_around_equals_sign() {
+ void spaces_are_allowed_around_equals_sign() {
DefParser parser = createParser("package = " + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
}
@Test
- public void empty_package_is_not_allowed() {
- assertLineFails("package");
+ void empty_package_is_not_allowed() {
+ assertLineFails("package");
}
@Test
- public void consecutive_dots_are_not_allowed() {
+ void consecutive_dots_are_not_allowed() {
assertLineFails("package=a..b");
}
@Test
- public void package_alters_def_md5() {
+ void package_alters_def_md5() {
DefParser parser = createParser("a string\n");
CNode root = parser.getTree();
@@ -81,7 +81,7 @@ public class DefParserPackageTest {
@Test
- public void number_is_allowed_as_non_leading_char() throws IOException, DefParser.DefParserException {
+ void number_is_allowed_as_non_leading_char() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "package=a.b.c2\n";
sb.append(line);
@@ -89,17 +89,17 @@ public class DefParserPackageTest {
}
@Test
- public void number_is_not_allowed_as_package_start_char() {
+ void number_is_not_allowed_as_package_start_char() {
assertLineFails("package=2.a.b");
}
@Test
- public void number_is_not_allowed_as_leading_char_in_package_token() {
+ void number_is_not_allowed_as_leading_char_in_package_token() {
assertLineFails("package=a.b.2c");
}
@Test
- public void underscore_in_package_is_allowed() throws IOException, DefParser.DefParserException {
+ void underscore_in_package_is_allowed() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "package=a_b.c\n";
sb.append(line);
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
index 915edce1440..4fbf01892cc 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
@@ -1,17 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for DefParser.
@@ -25,7 +23,7 @@ public class DefParserTest {
private static final String DEF_NAME = TEST_DIR + "configgen.allfeatures.def";
@Test
- public void testTraverseTree() throws IOException {
+ void testTraverseTree() throws IOException {
File defFile = new File(DEF_NAME);
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertNotNull(root);
@@ -62,21 +60,21 @@ public class DefParserTest {
}
@Test
- public void testFileWithNamespaceInFilename() throws IOException {
+ void testFileWithNamespaceInFilename() throws IOException {
File defFile = new File(TEST_DIR + "baz.bar.foo.def");
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertEquals("31a0f9bda0e5ff929762a29569575a7e", root.defMd5);
}
@Test
- public void testMd5Sum() throws IOException {
+ void testMd5Sum() throws IOException {
File defFile = new File(DEF_NAME);
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertEquals("f901bdc5c96e7005130399c63f247823", root.defMd5);
}
@Test
- public void testMd5Sum2() {
+ void testMd5Sum2() {
String def = "a string\n";
CNode root = new DefParser("testMd5Sum2", new StringReader(def)).getTree();
assertEquals("a5e5fdbb2b27e56ba7d5e60e335c598b", root.defMd5);
@@ -84,7 +82,7 @@ public class DefParserTest {
// TODO: Version is not used anymore, remove test in Vespa 9
@Test
- public void testValidVersions() {
+ void testValidVersions() {
try {
parse("version=8");
parse("version=8-1");
@@ -103,7 +101,7 @@ public class DefParserTest {
}
@Test
- public void testInvalidType() {
+ void testInvalidType() {
String line = "a sting";
assertLineFails(line, "Could not create sting a");
}
@@ -113,20 +111,23 @@ public class DefParserTest {
}
@Test
- public void verify_fail_on_default_for_file() {
+ void verify_fail_on_default_for_file() {
assertLineFails("f file default=\"file1.txt\"",
- "Invalid default value");
+ "Invalid default value");
}
- @Test(expected = CodegenRuntimeException.class)
- @Ignore("Not implemented yet")
- public void testInvalidEnum() {
- DefParser parser = createParser("anEnum enum {A, B, A}\n");
+ @Test
+ @Disabled("Not implemented yet")
+ void testInvalidEnum() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ DefParser parser = createParser("anEnum enum {A, B, A}\n");
+ //parser.validateDef(def);
+ });
//parser.validateDef(def);
}
@Test
- public void testEnum() {
+ void testEnum() {
StringBuilder sb = createDefTemplate();
sb.append("enum1 enum {A,B} default=A\n");
sb.append("enum2 enum {A, B} default=A\n");
@@ -148,20 +149,22 @@ public class DefParserTest {
assertEquals("A", node.getDefaultValue().getStringRepresentation());
}
- @Test(expected = DefParser.DefParserException.class)
- public void testInvalidCommaInEnum() throws DefParser.DefParserException, IOException {
- String invalidEnum = "anEnum enum {A, B, } default=A\n";
- String validEnum = "anotherEnum enum {A, B} default=A\n";
- StringBuilder sb = createDefTemplate();
- sb.append(invalidEnum);
- sb.append(validEnum);
- DefParser parser = createParser(sb.toString());
- parser.parse();
+ @Test
+ void testInvalidCommaInEnum() throws DefParser.DefParserException, IOException {
+ assertThrows(DefParser.DefParserException.class, () -> {
+ String invalidEnum = "anEnum enum {A, B, } default=A\n";
+ String validEnum = "anotherEnum enum {A, B} default=A\n";
+ StringBuilder sb = createDefTemplate();
+ sb.append(invalidEnum);
+ sb.append(validEnum);
+ DefParser parser = createParser(sb.toString());
+ parser.parse();
+ });
}
- @Ignore //TODO: finish this! The numeric leaf nodes must contain their range.
+ @Disabled //TODO: finish this! The numeric leaf nodes must contain their range.
@Test
- public void testRanges() {
+ void testRanges() {
StringBuilder sb = new StringBuilder();
sb.append("i int range=[0,10]");
sb.append("l long range=[-1e20,0]");
@@ -173,7 +176,7 @@ public class DefParserTest {
}
@Test
- public void duplicate_parameter_is_illegal() {
+ void duplicate_parameter_is_illegal() {
Class<?> exceptionClass = DefParser.DefParserException.class;
StringBuilder sb = createDefTemplate();
String duplicateLine = "b int\n";
@@ -189,76 +192,76 @@ public class DefParserTest {
}
@Test
- public void testIllegalCharacterInName() {
- assertLineFails("a-b int",
- "a-b contains unexpected character");
+ void testIllegalCharacterInName() {
+ assertLineFails("a-b int",
+ "a-b contains unexpected character");
}
@Test
- public void parameter_name_starting_with_digit_is_illegal() {
+ void parameter_name_starting_with_digit_is_illegal() {
assertLineFails("1a int",
- "1a must start with a non-digit character");
+ "1a must start with a non-digit character");
}
@Test
- public void parameter_name_starting_with_uppercase_is_illegal() {
+ void parameter_name_starting_with_uppercase_is_illegal() {
assertLineFails("SomeInt int",
- "'SomeInt' cannot start with an uppercase letter");
+ "'SomeInt' cannot start with an uppercase letter");
}
@Test
- public void parameter_name_starting_with_the_internal_prefix_is_illegal() {
+ void parameter_name_starting_with_the_internal_prefix_is_illegal() {
String internalPrefix = ReservedWords.INTERNAL_PREFIX;
assertLineFails(internalPrefix + "i int",
- "'" + internalPrefix + "i' cannot start with '" + internalPrefix + "'");
+ "'" + internalPrefix + "i' cannot start with '" + internalPrefix + "'");
}
@Test
- public void testIllegalArray() {
+ void testIllegalArray() {
assertLineFails("intArr[ int",
- "intArr[ Expected ] to terminate array definition");
+ "intArr[ Expected ] to terminate array definition");
}
@Test
- public void testIllegalDefault() {
+ void testIllegalDefault() {
assertLineFails("a int deflt 10",
- " deflt 10");
+ " deflt 10");
}
@Test
- public void testReservedWordInC() {
+ void testReservedWordInC() {
assertLineFails("auto int",
- "auto is a reserved word in C");
+ "auto is a reserved word in C");
}
@Test
- public void testReservedWordInCForArray() {
+ void testReservedWordInCForArray() {
assertLineFails("auto[] int",
- "auto is a reserved word in C");
+ "auto is a reserved word in C");
}
@Test
- public void testReservedWordInJava() {
+ void testReservedWordInJava() {
assertLineFails("abstract int",
- "abstract is a reserved word in Java");
+ "abstract is a reserved word in Java");
}
@Test
- public void testReservedWordInJavaForMap() {
+ void testReservedWordInJavaForMap() {
assertLineFails("abstract{} int",
- "abstract is a reserved word in Java");
+ "abstract is a reserved word in Java");
}
@Test
- public void testReservedWordInCAndJava() {
+ void testReservedWordInCAndJava() {
assertLineFails("continue int",
- "continue is a reserved word in C and Java");
+ "continue is a reserved word in C and Java");
}
@Test
- public void testReservedWordInCAndJavaForArray() {
+ void testReservedWordInCAndJavaForArray() {
assertLineFails("continue[] int",
- "continue is a reserved word in C and Java");
+ "continue is a reserved word in C and Java");
}
static StringBuilder createDefTemplate() {
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java b/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
index e6e86b2c2a3..69a690b0e82 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringReader;
@@ -12,9 +12,7 @@ import java.util.List;
import static com.yahoo.config.codegen.ConfiggenUtil.createClassName;
import static com.yahoo.config.codegen.JavaClassBuilder.createUniqueSymbol;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -26,44 +24,44 @@ public class JavaClassBuilderTest {
private static final String DEF_NAME = TEST_DIR + "configgen.allfeatures.def";
private static final String REFERENCE_NAME = TEST_DIR + "allfeatures.reference";
- @Ignore
+ @Disabled
@Test
- public void visual_inspection_of_generated_class() {
+ void visual_inspection_of_generated_class() {
final String testDefinition =
"namespace=test\n" + //
- "p path\n" + //
- "pathArr[] path\n" + //
- "u url\n" + //
- "urlArr[] url\n" + //
- "f file\n" + //
- "fileArr[] file\n" + //
- "i int default=0\n" + //
- "# A long value\n" + //
- "l long default=0\n" + //
- "s string default=\"\"\n" + //
- "b bool\n" + //
- "# An enum value\n" + //
- "e enum {A, B, C}\n" + //
- "intArr[] int\n" + //
- "boolArr[] bool\n" + //
- "enumArr[] enum {FOO, BAR}\n" + //
- "intMap{} int\n" + //
- "# A struct\n" + //
- "# with multi-line\n" + //
- "# comment and \"quotes\".\n" + //
- "myStruct.i int\n" + //
- "myStruct.s string\n" + //
- "# An inner array\n" + //
- "myArr[].i int\n" + //
- "myArr[].newStruct.s string\n" + //
- "myArr[].newStruct.b bool\n" + //
- "myArr[].intArr[] int\n" + //
- "# An inner map\n" + //
- "myMap{}.i int\n" + //
- "myMap{}.newStruct.s string\n" + //
- "myMap{}.newStruct.b bool\n" + //
- "myMap{}.intArr[] int\n" + //
- "intMap{} int\n";
+ "p path\n" + //
+ "pathArr[] path\n" + //
+ "u url\n" + //
+ "urlArr[] url\n" + //
+ "f file\n" + //
+ "fileArr[] file\n" + //
+ "i int default=0\n" + //
+ "# A long value\n" + //
+ "l long default=0\n" + //
+ "s string default=\"\"\n" + //
+ "b bool\n" + //
+ "# An enum value\n" + //
+ "e enum {A, B, C}\n" + //
+ "intArr[] int\n" + //
+ "boolArr[] bool\n" + //
+ "enumArr[] enum {FOO, BAR}\n" + //
+ "intMap{} int\n" + //
+ "# A struct\n" + //
+ "# with multi-line\n" + //
+ "# comment and \"quotes\".\n" + //
+ "myStruct.i int\n" + //
+ "myStruct.s string\n" + //
+ "# An inner array\n" + //
+ "myArr[].i int\n" + //
+ "myArr[].newStruct.s string\n" + //
+ "myArr[].newStruct.b bool\n" + //
+ "myArr[].intArr[] int\n" + //
+ "# An inner map\n" + //
+ "myMap{}.i int\n" + //
+ "myMap{}.newStruct.s string\n" + //
+ "myMap{}.newStruct.b bool\n" + //
+ "myMap{}.intArr[] int\n" + //
+ "intMap{} int\n";
DefParser parser = new DefParser("test", new StringReader(testDefinition));
InnerCNode root = parser.getTree();
@@ -73,11 +71,11 @@ public class JavaClassBuilderTest {
}
@Test
- public void testCreateUniqueSymbol() {
+ void testCreateUniqueSymbol() {
final String testDefinition =
"namespace=test\n" + //
- "m int\n" + //
- "n int\n";
+ "m int\n" + //
+ "n int\n";
InnerCNode root = new DefParser("test", new StringReader(testDefinition)).getTree();
assertEquals("f", createUniqueSymbol(root, "foo"));
@@ -90,7 +88,7 @@ public class JavaClassBuilderTest {
}
@Test
- public void testCreateClassName() {
+ void testCreateClassName() {
assertEquals("SimpleConfig", createClassName("simple"));
assertEquals("AConfig", createClassName("a"));
assertEquals("ABCConfig", createClassName("a-b-c"));
@@ -99,13 +97,15 @@ public class JavaClassBuilderTest {
assertEquals("MyAppConfig", createClassName("MyApp"));
}
- @Test(expected = CodegenRuntimeException.class)
- public void testIllegalClassName() {
- createClassName("+illegal");
+ @Test
+ void testIllegalClassName() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createClassName("+illegal");
+ });
}
@Test
- public void verify_generated_class_against_reference() throws IOException {
+ void verify_generated_class_against_reference() throws IOException {
String testDefinition = String.join("\n", Files.readAllLines(FileSystems.getDefault().getPath(DEF_NAME)));
List<String> referenceClassLines = Files.readAllLines(FileSystems.getDefault().getPath(REFERENCE_NAME));
@@ -114,11 +114,13 @@ public class JavaClassBuilderTest {
JavaClassBuilder builder = new JavaClassBuilder(root, parser.getNormalizedDefinition(), null, null);
String[] configClassLines = builder.getConfigClass("AllfeaturesConfig").split("\n");
- for (var line : configClassLines) { System.out.println(line); }
+ for (var line : configClassLines) {
+ System.out.println(line);
+ }
for (int i = 0; i < referenceClassLines.size(); i++) {
if (configClassLines.length <= i)
fail("Missing lines i generated config class. First missing line:\n" + referenceClassLines.get(i));
- assertEquals("Line " + i, referenceClassLines.get(i), configClassLines[i]);
+ assertEquals(referenceClassLines.get(i), configClassLines[i], "Line " + i);
}
}
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java b/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
index 9b3e9c31363..d967e16ba0b 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
@@ -1,26 +1,26 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.io.IOException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class MakeConfigTest {
private File dest;
- @Before
+ @BeforeEach
public void setUp() {
dest = new File("/tmp/"+System.currentTimeMillis()+File.separator);
dest.mkdir();
}
- @After
+ @AfterEach
public void tearDown() {
recursiveDeleteDir(dest);
}
@@ -40,9 +40,9 @@ public class MakeConfigTest {
// The directory is now empty so delete it
return dir.delete();
}
-
+
@Test
- public void testProps() throws PropertyException {
+ void testProps() throws PropertyException {
System.setProperty("config.dumpTree", "true");
System.setProperty("config.useFramework", "true");
System.setProperty("config.dest", dest.getAbsolutePath());
@@ -53,7 +53,7 @@ public class MakeConfigTest {
assertTrue(p.generateFrameworkCode);
assertEquals(p.specFiles.size(), 1);
assertEquals(p.specFiles.get(0).getAbsolutePath(), new File("src/test/resources/configgen.allfeatures.def").getAbsolutePath());
-
+
System.setProperty("config.dumpTree", "false");
System.setProperty("config.useFramework", "false");
System.setProperty("config.dest", dest.getAbsolutePath());
@@ -66,7 +66,7 @@ public class MakeConfigTest {
}
@Test
- public void testMake() throws IOException {
+ void testMake() throws IOException {
System.setProperty("config.dumpTree", "true");
System.setProperty("config.useFramework", "true");
System.setProperty("config.dest", dest.getAbsolutePath());
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java b/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
index d57210dd9ed..61b5eb5a759 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
@@ -9,10 +9,10 @@ import java.io.IOException;
import java.io.StringReader;
import java.util.List;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
@@ -21,13 +21,13 @@ import static org.junit.Assert.assertNotNull;
public class NormalizedDefinitionTest {
@Test
- public void testNormalizingFromReader() {
+ void testNormalizingFromReader() {
String def =
"aString string \n" +
- "anInt int #comment \n" +
- "aStringCommentCharacterAfter string default=\"ab\" #foo\n" +
- "aStringWithCommentCharacter string default=\"a#b\"\n" +
- "aStringWithEscapedQuote string default=\"a\"b\"\n";
+ "anInt int #comment \n" +
+ "aStringCommentCharacterAfter string default=\"ab\" #foo\n" +
+ "aStringWithCommentCharacter string default=\"a#b\"\n" +
+ "aStringWithEscapedQuote string default=\"a\"b\"\n";
StringReader reader = new StringReader(def);
@@ -52,7 +52,7 @@ public class NormalizedDefinitionTest {
}
@Test
- public void testNormalizingFromFile() throws IOException {
+ void testNormalizingFromFile() throws IOException {
FileReader fileReader = null;
try {
fileReader = new FileReader("src/test/resources/configgen.allfeatures.def");
diff --git a/configserver-flags/pom.xml b/configserver-flags/pom.xml
index 43263885371..e9c0c68685c 100644
--- a/configserver-flags/pom.xml
+++ b/configserver-flags/pom.xml
@@ -55,16 +55,16 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<scope>provided</scope>
<classifier>no_aop</classifier>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@@ -84,15 +84,29 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-test</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -100,6 +114,11 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
index 05802db6223..f0df08bfb6b 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
@@ -8,9 +8,9 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.RawFlag;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -20,8 +20,8 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -41,12 +41,12 @@ public class ConfigServerFlagSourceTest {
private ConfigServerFlagSource flagSource;
private BooleanFlag flag;
- @Before
+ @BeforeEach
public void setUp() {
flagsReplacer = Flags.clearFlagsForTesting();
}
- @After
+ @AfterEach
public void tearDown() {
flagsReplacer.close();
}
@@ -57,7 +57,7 @@ public class ConfigServerFlagSourceTest {
}
@Test
- public void testAbsentInFileSystemForwardsToFlagsDb() {
+ void testAbsentInFileSystemForwardsToFlagsDb() {
initialize();
when(flagsDb.getValue(flagId)).thenReturn(Optional.empty());
@@ -67,7 +67,7 @@ public class ConfigServerFlagSourceTest {
}
@Test
- public void testAvoidingZooKeeperWhenOverridingInFile() throws IOException {
+ void testAvoidingZooKeeperWhenOverridingInFile() throws IOException {
// Here is how to set the value of a flag, such that ZooKeeper will NOT be queried when getting that value:
// - Make a flag.db file with the override
Path flagPath = fileSystem.getPath(vespaHome + "/var/vespa/flag.db");
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
index f3087aa0e3b..36451e759fa 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
@@ -9,24 +9,22 @@ import com.yahoo.vespa.flags.json.Condition;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.Rule;
import com.yahoo.vespa.flags.json.WhitelistCondition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Optional;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class FlagsDbImplTest {
@Test
- public void test() {
+ void test() {
MockCurator curator = new MockCurator();
FlagsDbImpl db = new FlagsDbImpl(curator);
@@ -48,9 +46,9 @@ public class FlagsDbImplTest {
FlagData data2 = new FlagData(flagId2, new FetchVector().with(FetchVector.Dimension.ZONE_ID, "zone-a"), rule1);
db.setValue(flagId2, data2);
Map<FlagId, FlagData> flags = db.getAllFlagData();
- assertThat(flags.size(), equalTo(2));
- assertThat(flags.get(flagId), notNullValue());
- assertThat(flags.get(flagId2), notNullValue());
+ assertEquals(flags.size(), 2);
+ assertNotNull(flags.get(flagId));
+ assertNotNull(flags.get(flagId2));
db.removeValue(flagId2);
assertFalse(db.getValue(flagId2).isPresent());
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
index 3ca0567a1c5..2700ab114e9 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.UnboundBooleanFlag;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -23,10 +23,8 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -44,7 +42,7 @@ public class FlagsHandlerTest {
private final FlagsHandler handler = new FlagsHandler(FlagsHandler.testContext(), flagsDb);
@Test
- public void testV1() {
+ void testV1() {
String expectedResponse = "{" +
Stream.of("data", "defined")
.map(name -> "\"" + name + "\":{\"url\":\"https://foo.com:4443/flags/v1/" + name + "\"}")
@@ -55,7 +53,7 @@ public class FlagsHandlerTest {
}
@Test
- public void testDefined() {
+ void testDefined() {
try (Flags.Replacer replacer = Flags.clearFlagsForTesting()) {
fixUnusedWarning(replacer);
Flags.defineFeatureFlag("id", false, List.of("joe"), "2010-01-01", "2030-01-01", "desc", "mod", FetchVector.Dimension.HOSTNAME);
@@ -70,7 +68,7 @@ public class FlagsHandlerTest {
private void fixUnusedWarning(Flags.Replacer replacer) { }
@Test
- public void testData() {
+ void testData() {
// PUT flag with ID id1
verifySuccessfulRequest(Method.PUT, "/data/" + FLAG1.id(),
"{\n" +
@@ -96,8 +94,8 @@ public class FlagsHandlerTest {
"", "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com:4443/flags/v1/data/id1\"}]}");
// Verify absent port => absent in response
- assertThat(handleWithPort(Method.GET, -1, "/data", "", 200),
- is("{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com/flags/v1/data/id1\"}]}"));
+ assertEquals(handleWithPort(Method.GET, -1, "/data", "", 200),
+ "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com/flags/v1/data/id1\"}]}");
// PUT id2
verifySuccessfulRequest(Method.PUT, "/data/" + FLAG2.id(),
@@ -163,25 +161,24 @@ public class FlagsHandlerTest {
}
@Test
- public void testForcing() {
- assertThat(handle(Method.PUT, "/data/" + new FlagId("undef"), "", 400),
- containsString("There is no flag 'undef'"));
+ void testForcing() {
+ assertThat(handle(Method.PUT, "/data/" + new FlagId("undef"), "", 400)).contains("There is no flag 'undef'");
- assertThat(handle(Method.PUT, "/data/" + new FlagId("undef") + "?force=true", "", 400),
- containsString("No content to map due to end-of-input"));
+ assertThat(handle(Method.PUT, "/data/" + new FlagId("undef") + "?force=true", "", 400)).
+ contains("No content to map due to end-of-input");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{}", 400),
- containsString("Flag ID missing"));
+ assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{}", 400)).
+ contains("Flag ID missing");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 400),
- containsString("Wrong type of JsonNode: STRING"));
+ assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 400)).
+ contains("Wrong type of JsonNode: STRING");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id() + "?force=true", "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 200),
- is(""));
+ assertEquals(handle(Method.PUT, "/data/" + FLAG1.id() + "?force=true", "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 200),
+ "");
}
private void verifySuccessfulRequest(Method method, String pathSuffix, String requestBody, String expectedResponseBody) {
- assertThat(handle(method, pathSuffix, requestBody, 200), is(expectedResponseBody));
+ assertEquals(handle(method, pathSuffix, requestBody, 200), expectedResponseBody);
}
private String handle(Method method, String pathSuffix, String requestBody, int expectedStatus) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/ApplicationRepository.java b/configserver/src/main/java/com/yahoo/vespa/config/server/ApplicationRepository.java
index ca56a200c2c..2a15f724b29 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/ApplicationRepository.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/ApplicationRepository.java
@@ -96,6 +96,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -631,15 +632,7 @@ public class ApplicationRepository implements com.yahoo.config.provision.Deploye
.stream()
.filter(fileReference -> ! fileReferencesInUse.contains(fileReference))
.filter(fileReference -> isLastFileAccessBefore(new File(fileReferencesPath, fileReference), instant))
- .sorted((a, b) -> {
- if (a.equals(b))
- return 0;
- else if (lastAccessed(new File(fileReferencesPath, a))
- .isBefore(lastAccessed(new File(fileReferencesPath, b))))
- return -1;
- else
- return 1;
- })
+ .sorted(Comparator.comparing(a -> lastAccessed(new File(fileReferencesPath, a))))
.collect(Collectors.toList());
}
@@ -804,7 +797,8 @@ public class ApplicationRepository implements com.yahoo.config.provision.Deploye
.map(lock -> new ApplicationTransaction(lock, transaction));
try (var sessionLock = tenant.getApplicationRepo().lock(applicationId)) {
Optional<Session> activeSession = getActiveSession(applicationId);
- CompletionWaiter waiter = session.getSessionZooKeeperClient().createActiveWaiter();
+ var sessionZooKeeperClient = tenant.getSessionRepository().createSessionZooKeeperClient(session.getSessionId());
+ CompletionWaiter waiter = sessionZooKeeperClient.createActiveWaiter();
transaction.add(deactivateCurrentActivateNew(activeSession, session, force));
if (applicationTransaction.isPresent()) {
@@ -911,14 +905,10 @@ public class ApplicationRepository implements com.yahoo.config.provision.Deploye
sessionsPerTenant.keySet().forEach(tenant -> tenant.getSessionRepository().deleteExpiredSessions(activeSessions));
}
- public int deleteExpiredRemoteSessions(Duration expiryTime) {
- return deleteExpiredRemoteSessions(clock, expiryTime);
- }
-
- public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
+ public int deleteExpiredRemoteSessions(Clock clock) {
return tenantRepository.getAllTenants()
.stream()
- .map(tenant -> tenant.getSessionRepository().deleteExpiredRemoteSessions(clock, expiryTime))
+ .map(tenant -> tenant.getSessionRepository().deleteExpiredRemoteSessions(clock))
.mapToInt(i -> i)
.sum();
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/ReloadListener.java b/configserver/src/main/java/com/yahoo/vespa/config/server/ConfigActivationListener.java
index b41f31d9dcb..f7e9e270b9c 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/ReloadListener.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/ConfigActivationListener.java
@@ -7,13 +7,13 @@ import com.yahoo.vespa.config.server.application.ApplicationSet;
import java.util.Collection;
/**
- * A ReloadListener is used to signal to a component that config has been
- * reloaded. It only exists because the RpcServer cannot distinguish between a
- * successful reload of a new application and a reload of the same application.
+ * A ConfigActivationListener is used to signal to a component that config has been
+ * activated. It only exists because the RpcServer cannot distinguish between a
+ * successful activation of a new application and an activation of the same application.
*
* @author Ulf Lilleengen
*/
-public interface ReloadListener {
+public interface ConfigActivationListener {
/**
* Signals the listener that hosts used by a particular tenant.
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelController.java b/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelController.java
index f6ed98d904b..fd939b91388 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelController.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelController.java
@@ -16,7 +16,7 @@ import java.io.StringReader;
/**
* Handler for global configs that must be resolved using the global SuperModel instance. Deals with
- * reloading of config as well.
+ * activation of config as well.
*
* @author Ulf Lilleengen
*/
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelRequestHandler.java b/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelRequestHandler.java
index aa7dceba95c..93bb44e25d3 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelRequestHandler.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/SuperModelRequestHandler.java
@@ -43,12 +43,12 @@ public class SuperModelRequestHandler implements RequestHandler {
}
/**
- * Signals that config has been reloaded for an {@link com.yahoo.vespa.config.server.application.Application}
+ * Signals that config has been activated for an {@link com.yahoo.vespa.config.server.application.Application}
* belonging to a tenant.
*
- * @param applicationSet The reloaded set of {@link com.yahoo.vespa.config.server.application.Application}.
+ * @param applicationSet The activated set of {@link com.yahoo.vespa.config.server.application.Application}.
*/
- public synchronized void reloadConfig(ApplicationSet applicationSet) {
+ public synchronized void activateConfig(ApplicationSet applicationSet) {
superModelManager.configActivated(applicationSet);
updateHandler();
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java b/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java
index 23df938e0b7..c80faa2375a 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java
@@ -65,7 +65,7 @@ public class FileDistributionStatus extends AbstractComponent {
HostStatus getHostStatus(String hostname, int port, Duration timeout) {
Target target = supervisor.connect(new Spec(hostname, port));
Request request = new Request("filedistribution.getActiveFileReferencesStatus");
- target.invokeSync(request, timeout.toMillis() / 1000);
+ target.invokeSync(request, timeout);
HostStatus hostStatus = createHostStatusFromResponse(hostname, request);
target.close();
return hostStatus;
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/application/TenantApplications.java b/configserver/src/main/java/com/yahoo/vespa/config/server/application/TenantApplications.java
index 28487106268..2a0d62a1c9a 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/application/TenantApplications.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/application/TenantApplications.java
@@ -14,7 +14,7 @@ import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.GetConfigRequest;
import com.yahoo.vespa.config.protocol.ConfigResponse;
import com.yahoo.vespa.config.server.NotFoundException;
-import com.yahoo.vespa.config.server.ReloadListener;
+import com.yahoo.vespa.config.server.ConfigActivationListener;
import com.yahoo.vespa.config.server.RequestHandler;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
import com.yahoo.vespa.config.server.host.HostRegistry;
@@ -27,13 +27,11 @@ import com.yahoo.vespa.curator.CompletionTimeoutException;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.curator.transaction.CuratorTransaction;
-import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.ListFlag;
import com.yahoo.vespa.flags.PermanentFlags;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Clock;
@@ -69,7 +67,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
private final Executor zkWatcherExecutor;
private final Metrics metrics;
private final TenantName tenant;
- private final ReloadListener reloadListener;
+ private final ConfigActivationListener configActivationListener;
private final ConfigResponseFactory responseFactory;
private final HostRegistry hostRegistry;
private final ApplicationMapper applicationMapper = new ApplicationMapper();
@@ -80,7 +78,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
private final ListFlag<String> incompatibleVersions;
public TenantApplications(TenantName tenant, Curator curator, StripedExecutor<TenantName> zkWatcherExecutor,
- ExecutorService zkCacheExecutor, Metrics metrics, ReloadListener reloadListener,
+ ExecutorService zkCacheExecutor, Metrics metrics, ConfigActivationListener configActivationListener,
ConfigserverConfig configserverConfig, HostRegistry hostRegistry,
TenantFileSystemDirs tenantFileSystemDirs, Clock clock, FlagSource flagSource) {
this.curator = curator;
@@ -91,7 +89,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
this.metrics = metrics;
- this.reloadListener = reloadListener;
+ this.configActivationListener = configActivationListener;
this.responseFactory = ConfigResponseFactory.create(configserverConfig);
this.tenantMetricUpdater = metrics.getOrCreateMetricUpdater(Metrics.createDimensions(tenant));
this.hostRegistry = hostRegistry;
@@ -213,23 +211,22 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
@Override
public ConfigResponse resolveConfig(ApplicationId appId, GetConfigRequest req, Optional<Version> vespaVersion) {
Application application = getApplication(appId, vespaVersion);
- log.log(Level.FINE, () -> TenantRepository.logPre(appId) + "Resolving for tenant '" + tenant +
- "' with handler for application '" + application + "'");
+ log.log(Level.FINE, () -> TenantRepository.logPre(appId) + "Resolving config");
return application.resolveConfig(req, responseFactory);
}
- private void notifyReloadListeners(ApplicationSet applicationSet) {
+ private void notifyConfigActivationListeners(ApplicationSet applicationSet) {
if (applicationSet.getAllApplications().isEmpty()) throw new IllegalArgumentException("application set cannot be empty");
- reloadListener.hostsUpdated(applicationSet.getAllApplications().get(0).toApplicationInfo().getApplicationId(),
- applicationSet.getAllHosts());
- reloadListener.configActivated(applicationSet);
+ configActivationListener.hostsUpdated(applicationSet.getAllApplications().get(0).toApplicationInfo().getApplicationId(),
+ applicationSet.getAllHosts());
+ configActivationListener.configActivated(applicationSet);
}
/**
* Activates the config of the given app. Notifies listeners
*
- * @param applicationSet the {@link ApplicationSet} to be reloaded
+ * @param applicationSet the {@link ApplicationSet} to be activated
*/
public void activateApplication(ApplicationSet applicationSet, long activeSessionId) {
ApplicationId id = applicationSet.getId();
@@ -239,8 +236,8 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
if (applicationSet.getApplicationGeneration() != activeSessionId)
return; // Application activated a new session before we got here.
- setLiveApp(applicationSet);
- notifyReloadListeners(applicationSet);
+ setActiveApp(applicationSet);
+ notifyConfigActivationListeners(applicationSet);
}
}
@@ -257,7 +254,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
if (hasApplication(applicationId)) {
applicationMapper.remove(applicationId);
hostRegistry.removeHostsForKey(applicationId);
- reloadListenersOnRemove(applicationId);
+ configActivationListenersOnRemove(applicationId);
tenantMetricUpdater.setApplications(applicationMapper.numApplications());
metrics.removeMetricUpdater(Metrics.createDimensions(applicationId));
getRemoveApplicationWaiter(applicationId).notifyCompletion();
@@ -279,12 +276,12 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
}
}
- private void reloadListenersOnRemove(ApplicationId applicationId) {
- reloadListener.hostsUpdated(applicationId, hostRegistry.getHostsForKey(applicationId));
- reloadListener.applicationRemoved(applicationId);
+ private void configActivationListenersOnRemove(ApplicationId applicationId) {
+ configActivationListener.hostsUpdated(applicationId, hostRegistry.getHostsForKey(applicationId));
+ configActivationListener.applicationRemoved(applicationId);
}
- private void setLiveApp(ApplicationSet applicationSet) {
+ private void setActiveApp(ApplicationSet applicationSet) {
ApplicationId id = applicationSet.getId();
Collection<String> hostsForApp = applicationSet.getAllHosts();
hostRegistry.update(id, hostsForApp);
@@ -337,7 +334,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
}
/**
- * Given baseIdSegment search/ and id search/qrservers/default.0, return search/qrservers
+ * Given baseIdSegment search/ and id search/container/default.0, return search/container
* @return id segment with one extra level from the id appended
*/
String appendOneLevelOfId(String baseIdSegment, String id) {
@@ -402,7 +399,7 @@ public class TenantApplications implements RequestHandler, HostValidator<Applica
@Override
public void verifyHosts(ApplicationId applicationId, Collection<String> newHosts) {
hostRegistry.verifyHosts(applicationId, newHosts);
- reloadListener.verifyHostsAreAvailable(applicationId, newHosts);
+ configActivationListener.verifyHostsAreAvailable(applicationId, newHosts);
}
public HostValidator<ApplicationId> getHostValidator() {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ModelContextImpl.java b/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ModelContextImpl.java
index c31d4603353..068323f7784 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ModelContextImpl.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ModelContextImpl.java
@@ -197,7 +197,6 @@ public class ModelContextImpl implements ModelContext {
private final boolean useV8GeoPositions;
private final int maxCompactBuffers;
private final List<String> ignoredHttpUserAgents;
- private final boolean enableServerOcspStapling;
private final String mergeThrottlingPolicy;
private final double persistenceThrottlingWsDecrementFactor;
private final double persistenceThrottlingWsBackoff;
@@ -211,6 +210,16 @@ public class ModelContextImpl implements ModelContext {
private final boolean enableProxyProtocolMixedMode;
private final boolean sharedStringRepoNoReclaim;
private final String logFileCompressionAlgorithm;
+ private final boolean mbus_dispatch_on_decode;
+ private final boolean mbus_dispatch_on_encode;
+ private final int mbus_threads;
+ private final int mbus_network_threads;
+ private int mbus_java_num_targets;
+ private int mbus_java_events_before_wakeup;
+ private int mbus_cpp_num_targets;
+ private int mbus_cpp_events_before_wakeup;
+ private int rpc_num_targets;
+ private int rpc_events_before_wakeup;
public FeatureFlags(FlagSource source, ApplicationId appId, Version version) {
this.defaultTermwiseLimit = flagValue(source, appId, version, Flags.DEFAULT_TERM_WISE_LIMIT);
@@ -224,6 +233,10 @@ public class ModelContextImpl implements ModelContext {
this.useAsyncMessageHandlingOnSchedule = flagValue(source, appId, version, Flags.USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE);
this.feedConcurrency = flagValue(source, appId, version, Flags.FEED_CONCURRENCY);
this.feedNiceness = flagValue(source, appId, version, Flags.FEED_NICENESS);
+ this.mbus_dispatch_on_decode = flagValue(source, appId, version, Flags.MBUS_DISPATCH_ON_DECODE);
+ this.mbus_dispatch_on_encode = flagValue(source, appId, version, Flags.MBUS_DISPATCH_ON_ENCODE);
+ this.mbus_threads = flagValue(source, appId, version, Flags.MBUS_NUM_THREADS);
+ this.mbus_network_threads = flagValue(source, appId, version, Flags.MBUS_NUM_NETWORK_THREADS);
this.allowedAthenzProxyIdentities = flagValue(source, appId, version, Flags.ALLOWED_ATHENZ_PROXY_IDENTITIES);
this.maxActivationInhibitedOutOfSyncGroups = flagValue(source, appId, version, Flags.MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS);
this.jvmOmitStackTraceInFastThrow = type -> flagValueAsInt(source, appId, version, type, PermanentFlags.JVM_OMIT_STACK_TRACE_IN_FAST_THROW);
@@ -244,7 +257,6 @@ public class ModelContextImpl implements ModelContext {
this.useV8GeoPositions = flagValue(source, appId, version, Flags.USE_V8_GEO_POSITIONS);
this.maxCompactBuffers = flagValue(source, appId, version, Flags.MAX_COMPACT_BUFFERS);
this.ignoredHttpUserAgents = flagValue(source, appId, version, PermanentFlags.IGNORED_HTTP_USER_AGENTS);
- this.enableServerOcspStapling = flagValue(source, appId, version, Flags.ENABLE_SERVER_OCSP_STAPLING);
this.mergeThrottlingPolicy = flagValue(source, appId, version, Flags.MERGE_THROTTLING_POLICY);
this.persistenceThrottlingWsDecrementFactor = flagValue(source, appId, version, Flags.PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR);
this.persistenceThrottlingWsBackoff = flagValue(source, appId, version, Flags.PERSISTENCE_THROTTLING_WS_BACKOFF);
@@ -258,6 +270,12 @@ public class ModelContextImpl implements ModelContext {
this.enableProxyProtocolMixedMode = flagValue(source, appId, version, Flags.ENABLE_PROXY_PROTOCOL_MIXED_MODE);
this.sharedStringRepoNoReclaim = flagValue(source, appId, version, Flags.SHARED_STRING_REPO_NO_RECLAIM);
this.logFileCompressionAlgorithm = flagValue(source, appId, version, Flags.LOG_FILE_COMPRESSION_ALGORITHM);
+ this.mbus_java_num_targets = flagValue(source, appId, version, Flags.MBUS_JAVA_NUM_TARGETS);
+ this.mbus_java_events_before_wakeup = flagValue(source, appId, version, Flags.MBUS_JAVA_EVENTS_BEFORE_WAKEUP);
+ this.mbus_cpp_num_targets = flagValue(source, appId, version, Flags.MBUS_CPP_NUM_TARGETS);
+ this.mbus_cpp_events_before_wakeup = flagValue(source, appId, version, Flags.MBUS_CPP_EVENTS_BEFORE_WAKEUP);
+ this.rpc_num_targets = flagValue(source, appId, version, Flags.RPC_NUM_TARGETS);
+ this.rpc_events_before_wakeup = flagValue(source, appId, version, Flags.RPC_EVENTS_BEFORE_WAKEUP);
}
@Override public double defaultTermwiseLimit() { return defaultTermwiseLimit; }
@@ -271,6 +289,10 @@ public class ModelContextImpl implements ModelContext {
@Override public boolean useAsyncMessageHandlingOnSchedule() { return useAsyncMessageHandlingOnSchedule; }
@Override public double feedConcurrency() { return feedConcurrency; }
@Override public double feedNiceness() { return feedNiceness; }
+ @Override public boolean mbusDispatchOnDecode() { return mbus_dispatch_on_decode; }
+ @Override public boolean mbusDispatchOnEncode() { return mbus_dispatch_on_encode; }
+ @Override public int mbusNetworkThreads() { return mbus_network_threads; }
+ @Override public int mbusThreads() { return mbus_threads; }
@Override public List<String> allowedAthenzProxyIdentities() { return allowedAthenzProxyIdentities; }
@Override public int maxActivationInhibitedOutOfSyncGroups() { return maxActivationInhibitedOutOfSyncGroups; }
@Override public String jvmOmitStackTraceInFastThrowOption(ClusterSpec.Type type) {
@@ -293,7 +315,6 @@ public class ModelContextImpl implements ModelContext {
@Override public boolean useV8GeoPositions() { return useV8GeoPositions; }
@Override public int maxCompactBuffers() { return maxCompactBuffers; }
@Override public List<String> ignoredHttpUserAgents() { return ignoredHttpUserAgents; }
- @Override public boolean enableServerOcspStapling() { return enableServerOcspStapling; }
@Override public String mergeThrottlingPolicy() { return mergeThrottlingPolicy; }
@Override public double persistenceThrottlingWsDecrementFactor() { return persistenceThrottlingWsDecrementFactor; }
@Override public double persistenceThrottlingWsBackoff() { return persistenceThrottlingWsBackoff; }
@@ -306,6 +327,12 @@ public class ModelContextImpl implements ModelContext {
@Override public Architecture adminClusterArchitecture() { return adminClusterArchitecture; }
@Override public boolean enableProxyProtocolMixedMode() { return enableProxyProtocolMixedMode; }
@Override public boolean sharedStringRepoNoReclaim() { return sharedStringRepoNoReclaim; }
+ @Override public int mbusJavaRpcNumTargets() { return mbus_java_num_targets; }
+ @Override public int mbusJavaEventsBeforeWakeup() { return mbus_java_events_before_wakeup; }
+ @Override public int mbusCppRpcNumTargets() { return mbus_cpp_num_targets; }
+ @Override public int mbusCppEventsBeforeWakeup() { return mbus_cpp_events_before_wakeup; }
+ @Override public int rpcNumTargets() { return rpc_num_targets; }
+ @Override public int rpcEventsBeforeWakeup() { return rpc_events_before_wakeup; }
@Override public String logFileCompressionAlgorithm(String defVal) {
var fflag = this.logFileCompressionAlgorithm;
if (fflag != null && ! fflag.equals("")) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDirectory.java b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDirectory.java
index 46ae2fd15d5..7f120a88a05 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDirectory.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDirectory.java
@@ -60,16 +60,13 @@ public class FileDirectory {
public File getFile(FileReference reference) {
ensureRootExist();
File dir = new File(getPath(reference));
- if (!dir.exists()) {
+ if (!dir.exists())
throw new IllegalArgumentException("File reference '" + reference.value() + "' with absolute path '" + dir.getAbsolutePath() + "' does not exist.");
- }
- if (!dir.isDirectory()) {
+ if (!dir.isDirectory())
throw new IllegalArgumentException("File reference '" + reference.value() + "' with absolute path '" + dir.getAbsolutePath() + "' is not a directory.");
- }
File [] files = dir.listFiles(new Filter());
- if (files == null || files.length == 0) {
+ if (files == null || files.length == 0)
throw new IllegalArgumentException("File reference '" + reference.value() + "' with absolute path '" + dir.getAbsolutePath() + " does not contain any files");
- }
return files[0];
}
@@ -82,7 +79,7 @@ public class FileDirectory {
if (file.isDirectory()) {
return Files.walk(file.toPath(), 100).map(path -> {
try {
- log.log(Level.FINE, () -> "Calculating hash for '" + path + "'");
+ log.log(Level.FINEST, () -> "Calculating hash for '" + path + "'");
return hash(path.toFile(), hasher);
} catch (IOException e) {
log.log(Level.WARNING, "Failed getting hash from '" + path + "'");
@@ -144,7 +141,7 @@ public class FileDirectory {
File destination = new File(tempDestinationDir.toFile(), source.getName());
if (!destinationDir.exists()) {
destinationDir.mkdir();
- log.log(Level.FINE, () -> "file reference ' " + reference.value() + "', source: " + source.getAbsolutePath() );
+ log.log(Level.FINE, () -> "file reference '" + reference.value() + "', source: " + source.getAbsolutePath() );
if (source.isDirectory()) {
log.log(Level.FINE, () -> "Copying source " + source.getAbsolutePath() + " to " + destination.getAbsolutePath());
IOUtils.copyDirectory(source, destination, -1);
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDistributionImpl.java b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDistributionImpl.java
index abb8a3e8487..7d7d4aa1d7d 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDistributionImpl.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileDistributionImpl.java
@@ -10,6 +10,7 @@ import com.yahoo.jrt.StringArray;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
+import java.time.Duration;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -20,7 +21,7 @@ import java.util.logging.Logger;
public class FileDistributionImpl implements FileDistribution, RequestWaiter {
private final static Logger log = Logger.getLogger(FileDistributionImpl.class.getName());
- private final static double rpcTimeout = 1.0;
+ private final static Duration rpcTimeout = Duration.ofSeconds(1);
private final Supervisor supervisor;
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileServer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileServer.java
index 88405b3eef9..770352e6bfc 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileServer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/filedistribution/FileServer.java
@@ -13,14 +13,16 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Transport;
import com.yahoo.vespa.config.ConnectionPool;
import com.yahoo.vespa.defaults.Defaults;
-import com.yahoo.vespa.filedistribution.FileReferenceCompressor;
import com.yahoo.vespa.filedistribution.EmptyFileReferenceData;
import com.yahoo.vespa.filedistribution.FileDistributionConnectionPool;
import com.yahoo.vespa.filedistribution.FileDownloader;
+import com.yahoo.vespa.filedistribution.FileReferenceCompressor;
import com.yahoo.vespa.filedistribution.FileReferenceData;
import com.yahoo.vespa.filedistribution.FileReferenceDownload;
import com.yahoo.vespa.filedistribution.LazyFileReferenceData;
import com.yahoo.vespa.filedistribution.LazyTemporaryStorageFileReferenceData;
+import com.yahoo.vespa.flags.FlagSource;
+import com.yahoo.vespa.flags.Flags;
import com.yahoo.yolean.Exceptions;
import java.io.File;
import java.io.IOException;
@@ -28,15 +30,21 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
+import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import static com.yahoo.vespa.config.server.filedistribution.FileDistributionUtil.getOtherConfigServersInCluster;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.compressed;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.Type;
public class FileServer {
@@ -48,10 +56,13 @@ public class FileServer {
private final FileDirectory root;
private final ExecutorService executor;
private final FileDownloader downloader;
+ private final List<CompressionType> compressionTypes; // compression types to use, in preferred order
+ // TODO: Move to filedistribution module, so that it can be used by both clients and servers
private enum FileApiErrorCodes {
OK(0, "OK"),
- NOT_FOUND(1, "Filereference not found");
+ NOT_FOUND(1, "File reference not found"),
+ TIMEOUT(2, "Timeout");
private final int code;
private final String description;
FileApiErrorCodes(int code, String description) {
@@ -80,21 +91,24 @@ public class FileServer {
@SuppressWarnings("WeakerAccess") // Created by dependency injection
@Inject
- public FileServer(ConfigserverConfig configserverConfig) {
+ public FileServer(ConfigserverConfig configserverConfig, FlagSource flagSource) {
this(new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir())),
- createFileDownloader(getOtherConfigServersInCluster(configserverConfig)));
+ createFileDownloader(getOtherConfigServersInCluster(configserverConfig),
+ compressionTypes(Flags.FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES.bindTo(flagSource).value())),
+ compressionTypesAsList(Flags.FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE.bindTo(flagSource).value()));
}
// For testing only
public FileServer(File rootDir) {
- this(rootDir, createFileDownloader(List.of()));
+ this(rootDir, createFileDownloader(List.of(), Set.of(gzip)), List.of(gzip));
}
- public FileServer(File rootDir, FileDownloader fileDownloader) {
+ FileServer(File rootDir, FileDownloader fileDownloader, List<CompressionType> compressionTypes) {
this.downloader = fileDownloader;
this.root = new FileDirectory(rootDir);
this.executor = Executors.newFixedThreadPool(Math.max(8, Runtime.getRuntime().availableProcessors()),
new DaemonThreadFactory("file-server-"));
+ this.compressionTypes = compressionTypes;
}
boolean hasFile(String fileReference) {
@@ -112,21 +126,14 @@ public class FileServer {
FileDirectory getRootDir() { return root; }
- void startFileServing(String fileName, Receiver target) {
- FileReference reference = new FileReference(fileName);
- File file = root.getFile(reference);
+ void startFileServing(FileReference reference, Receiver target, Set<CompressionType> acceptedCompressionTypes) {
+ if ( ! root.getFile(reference).exists()) return;
- if (file.exists()) {
- serveFile(reference, target);
- }
- }
-
- private void serveFile(FileReference reference, Receiver target) {
File file = root.getFile(reference);
log.log(Level.FINE, () -> "Start serving " + reference + " with file '" + file.getAbsolutePath() + "'");
FileReferenceData fileData = EmptyFileReferenceData.empty(reference, file.getName());
try {
- fileData = readFileReferenceData(reference);
+ fileData = readFileReferenceData(reference, acceptedCompressionTypes);
target.receive(fileData, new ReplayStatus(0, "OK"));
log.log(Level.FINE, () -> "Done serving " + reference.value() + " with file '" + file.getAbsolutePath() + "'");
} catch (IOException e) {
@@ -140,56 +147,71 @@ public class FileServer {
}
}
- private FileReferenceData readFileReferenceData(FileReference reference) throws IOException {
+ private FileReferenceData readFileReferenceData(FileReference reference, Set<CompressionType> acceptedCompressionTypes) throws IOException {
File file = root.getFile(reference);
if (file.isDirectory()) {
Path tempFile = Files.createTempFile("filereferencedata", reference.value());
- File compressedFile = new FileReferenceCompressor(compressed).compress(file.getParentFile(), tempFile.toFile());
- return new LazyTemporaryStorageFileReferenceData(reference, file.getName(), compressed, compressedFile);
+ CompressionType compressionType = chooseCompressionType(acceptedCompressionTypes);
+ log.log(Level.FINE, () -> "accepted compression types=" + acceptedCompressionTypes + ", compression type to use=" + compressionType);
+ File compressedFile = new FileReferenceCompressor(compressed, compressionType).compress(file.getParentFile(), tempFile.toFile());
+ return new LazyTemporaryStorageFileReferenceData(reference, file.getName(), compressed, compressedFile, compressionType);
} else {
- return new LazyFileReferenceData(reference, file.getName(), FileReferenceData.Type.file, file);
+ return new LazyFileReferenceData(reference, file.getName(), Type.file, file, gzip);
}
}
- public void serveFile(String fileReference, boolean downloadFromOtherSourceIfNotFound, Request request, Receiver receiver) {
+ public void serveFile(FileReference fileReference,
+ boolean downloadFromOtherSourceIfNotFound,
+ Set<CompressionType> acceptedCompressionTypes,
+ Request request, Receiver receiver) {
if (executor instanceof ThreadPoolExecutor)
log.log(Level.FINE, () -> "Active threads: " + ((ThreadPoolExecutor) executor).getActiveCount());
log.log(Level.FINE, () -> "Received request for file reference '" + fileReference + "' from " + request.target());
Instant deadline = Instant.now().plus(timeout);
- executor.execute(() -> serveFileInternal(fileReference, downloadFromOtherSourceIfNotFound, request, receiver, deadline));
+ String client = request.target().toString();
+ executor.execute(() -> {
+ var result = serveFileInternal(fileReference, downloadFromOtherSourceIfNotFound, client, receiver, deadline, acceptedCompressionTypes);
+ request.returnValues()
+ .add(new Int32Value(result.getCode()))
+ .add(new StringValue(result.getDescription()));
+ request.returnRequest();
+ });
}
- private void serveFileInternal(String fileReference,
- boolean downloadFromOtherSourceIfNotFound,
- Request request,
- Receiver receiver,
- Instant deadline) {
+ private FileApiErrorCodes serveFileInternal(FileReference fileReference,
+ boolean downloadFromOtherSourceIfNotFound,
+ String client,
+ Receiver receiver,
+ Instant deadline,
+ Set<CompressionType> acceptedCompressionTypes) {
if (Instant.now().isAfter(deadline)) {
- log.log(Level.INFO, () -> "Deadline exceeded for request for file reference '" + fileReference + "' from " + request.target() +
- " , giving up");
- return;
+ log.log(Level.INFO, () -> "Deadline exceeded for request for file reference '" + fileReference + "' from " + client);
+ return FileApiErrorCodes.TIMEOUT;
}
boolean fileExists;
try {
- String client = request.target().toString();
- FileReferenceDownload fileReferenceDownload = new FileReferenceDownload(new FileReference(fileReference),
- client,
- downloadFromOtherSourceIfNotFound);
+ var fileReferenceDownload = new FileReferenceDownload(fileReference, client, downloadFromOtherSourceIfNotFound);
fileExists = hasFileDownloadIfNeeded(fileReferenceDownload);
- if (fileExists) startFileServing(fileReference, receiver);
+ if (fileExists) startFileServing(fileReference, receiver, acceptedCompressionTypes);
} catch (IllegalArgumentException e) {
fileExists = false;
- log.warning("Failed serving file reference '" + fileReference + "', request was from " + request.target() + ", with error " + e.toString());
+ log.warning("Failed serving file reference '" + fileReference + "', request from " + client + " failed with: " + e.getMessage());
}
- FileApiErrorCodes result = fileExists ? FileApiErrorCodes.OK : FileApiErrorCodes.NOT_FOUND;
- request.returnValues()
- .add(new Int32Value(result.getCode()))
- .add(new StringValue(result.getDescription()));
- request.returnRequest();
+ return (fileExists ? FileApiErrorCodes.OK : FileApiErrorCodes.NOT_FOUND);
+ }
+
+ /* Choose the first compression type (list is in preferred order) that matches an accepted compression type, or fail */
+ private CompressionType chooseCompressionType(Set<CompressionType> acceptedCompressionTypes) {
+ for (CompressionType compressionType : compressionTypes) {
+ if (acceptedCompressionTypes.contains(compressionType))
+ return compressionType;
+ }
+ throw new RuntimeException("Could not find a compression type that can be used. Accepted compression types: " +
+ acceptedCompressionTypes + ", compression types server can use: " + compressionTypes);
}
boolean hasFileDownloadIfNeeded(FileReferenceDownload fileReferenceDownload) {
@@ -199,17 +221,16 @@ public class FileServer {
if (fileReferenceDownload.downloadFromOtherSourceIfNotFound()) {
log.log(Level.FINE, "File not found, downloading from another source");
// Create new FileReferenceDownload with downloadFromOtherSourceIfNotFound set to false
- // to avoid config servers requesting a file reference perpetually, e.g. for a file that
- // does not exist anymore
+ // to avoid requesting a file reference perpetually, e.g. for a file that does not exist anymore
FileReferenceDownload newDownload = new FileReferenceDownload(fileReference,
fileReferenceDownload.client(),
false);
boolean fileExists = downloader.getFile(newDownload).isPresent();
if ( ! fileExists)
- log.log(Level.WARNING, "Failed downloading '" + fileReferenceDownload + "'");
+ log.log(Level.INFO, "Failed downloading '" + fileReferenceDownload + "'");
return fileExists;
} else {
- log.log(Level.FINE, "File not found, will not download from another source, since request came from another config server");
+ log.log(Level.FINE, "File not found, will not download from another source");
return false;
}
}
@@ -221,14 +242,27 @@ public class FileServer {
executor.shutdown();
}
- private static FileDownloader createFileDownloader(List<String> configServers) {
+ private static FileDownloader createFileDownloader(List<String> configServers, Set<CompressionType> acceptedCompressionTypes) {
Supervisor supervisor = new Supervisor(new Transport("filedistribution-pool")).setDropEmptyBuffers(true);
return new FileDownloader(configServers.isEmpty()
? FileDownloader.emptyConnectionPool()
: createConnectionPool(configServers, supervisor),
supervisor,
- timeout);
+ timeout,
+ acceptedCompressionTypes);
+ }
+
+ private static LinkedHashSet<CompressionType> compressionTypes(List<String> compressionTypes) {
+ return compressionTypes.stream()
+ .map(CompressionType::valueOf)
+ .collect(Collectors.toCollection(LinkedHashSet::new));
+ }
+
+ private static List<CompressionType> compressionTypesAsList(List<String> compressionTypes) {
+ return compressionTypes.stream()
+ .map(CompressionType::valueOf)
+ .collect(Collectors.toList());
}
private static ConnectionPool createConnectionPool(List<String> configServers, Supervisor supervisor) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/http/ProxyResponse.java b/configserver/src/main/java/com/yahoo/vespa/config/server/http/ProxyResponse.java
index f7042b49c3f..0d4baa7dc56 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/http/ProxyResponse.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/http/ProxyResponse.java
@@ -38,4 +38,9 @@ class ProxyResponse extends HttpResponse {
}
}
+ @Override
+ public long maxPendingBytes() {
+ return 1 << 25; // 32MB
+ }
+
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/ApplicationPackageMaintainer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/ApplicationPackageMaintainer.java
index ae4b205c06e..12972e5c465 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/ApplicationPackageMaintainer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/ApplicationPackageMaintainer.java
@@ -18,20 +18,23 @@ import com.yahoo.vespa.filedistribution.FileDistributionConnectionPool;
import com.yahoo.vespa.filedistribution.FileDownloader;
import com.yahoo.vespa.filedistribution.FileReferenceDownload;
import com.yahoo.vespa.flags.FlagSource;
-
+import com.yahoo.vespa.flags.Flags;
import java.io.File;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import static com.yahoo.vespa.config.server.filedistribution.FileDistributionUtil.fileReferenceExistsOnDisk;
import static com.yahoo.vespa.config.server.filedistribution.FileDistributionUtil.getOtherConfigServersInCluster;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
/**
* Verifies that all active sessions has an application package on local disk.
* If not, the package is downloaded with file distribution. This can happen e.g.
- * if a configserver is down when the application is deployed.
+ * if a config server is down when the application is deployed.
*
* @author gjoranv
*/
@@ -53,7 +56,10 @@ public class ApplicationPackageMaintainer extends ConfigServerMaintainer {
this.applicationRepository = applicationRepository;
this.configserverConfig = applicationRepository.configserverConfig();
this.downloadDirectory = new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir()));
- this.fileDownloader = createFileDownloader(configserverConfig, downloadDirectory, supervisor);
+ this.fileDownloader = createFileDownloader(configserverConfig,
+ downloadDirectory,
+ supervisor,
+ Flags.FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES.bindTo(flagSource).value());
}
@Override
@@ -94,14 +100,18 @@ public class ApplicationPackageMaintainer extends ConfigServerMaintainer {
private static FileDownloader createFileDownloader(ConfigserverConfig configserverConfig,
File downloadDirectory,
- Supervisor supervisor) {
+ Supervisor supervisor,
+ List<String> flagValues) {
List<String> otherConfigServersInCluster = getOtherConfigServersInCluster(configserverConfig);
ConfigSourceSet configSourceSet = new ConfigSourceSet(otherConfigServersInCluster);
ConnectionPool connectionPool = (otherConfigServersInCluster.isEmpty())
? FileDownloader.emptyConnectionPool()
: new FileDistributionConnectionPool(configSourceSet, supervisor);
- return new FileDownloader(connectionPool, supervisor, downloadDirectory, Duration.ofSeconds(300));
+ Set<CompressionType> acceptedCompressionTypes = flagValues.stream()
+ .map(CompressionType::valueOf)
+ .collect(Collectors.toSet());
+ return new FileDownloader(connectionPool, supervisor, downloadDirectory, Duration.ofSeconds(300), acceptedCompressionTypes);
}
@Override
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/SessionsMaintainer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/SessionsMaintainer.java
index d980fb079e7..38ac41d0eb9 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/SessionsMaintainer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/maintenance/SessionsMaintainer.java
@@ -16,22 +16,17 @@ import java.util.logging.Level;
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
- private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval, true);
- this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected double maintain() {
applicationRepository.deleteExpiredLocalSessions();
- if (hostedVespa) {
- Duration expiryTime = Duration.ofMinutes(90);
- int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
- log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
- }
+ int deleted = applicationRepository.deleteExpiredRemoteSessions(applicationRepository.clock());
+ log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions");
return 1.0;
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/modelfactory/ModelsBuilder.java b/configserver/src/main/java/com/yahoo/vespa/config/server/modelfactory/ModelsBuilder.java
index cce6429f84a..8a541abf4ae 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/modelfactory/ModelsBuilder.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/modelfactory/ModelsBuilder.java
@@ -130,7 +130,7 @@ public abstract class ModelsBuilder<MODELRESULT extends ModelResult> {
}
catch (RuntimeException e) {
if (shouldSkipCreatingMajorVersionOnError(majorVersions, majorVersion, wantedNodeVespaVersion, allocatedHosts)) {
- log.log(Level.INFO, applicationId + ": Skipping major version " + majorVersion, e);
+ log.log(Level.FINE, applicationId + ": Skipping major version " + majorVersion, e);
}
else {
if (e instanceof IllegalArgumentException) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponses.java b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponses.java
index 7e6fccb6d2f..0b54a09d963 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponses.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponses.java
@@ -2,16 +2,14 @@
package com.yahoo.vespa.config.server.rpc;
import com.yahoo.concurrent.ThreadFactoryFactory;
+import com.yahoo.config.provision.ApplicationId;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.TargetWatcher;
-import java.util.logging.Level;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
import com.yahoo.vespa.config.server.GetConfigContext;
import com.yahoo.vespa.config.server.monitoring.MetricUpdater;
import com.yahoo.vespa.config.server.monitoring.Metrics;
-import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -22,6 +20,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -40,7 +39,7 @@ public class DelayedConfigResponses {
private final Map<ApplicationId, MetricUpdater> metrics = new ConcurrentHashMap<>();
- /* Requests that resolve to config that has not changed are put on this queue. When reloading
+ /* Requests that resolve to config that has not changed are put on this queue. When activating
config, all requests on this queue are reprocessed as if they were a new request */
private final Map<ApplicationId, BlockingQueue<DelayedConfigResponse>> delayedResponses =
new ConcurrentHashMap<>();
@@ -183,7 +182,7 @@ public class DelayedConfigResponses {
response.getRequest().getShortDescription());
}
// Config will be resolved in the run() method of DelayedConfigResponse,
- // when the timer expires or config is updated/reloaded.
+ // when the timer expires or config is updated/activated.
response.schedule(Math.max(0, request.getTimeout()));
metricDelayedResponses(context.applicationId(), delayedResponsesQueue.size());
} catch (InterruptedException e) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/GetConfigProcessor.java b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/GetConfigProcessor.java
index c31015b533a..b7327ef3aa7 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/GetConfigProcessor.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/GetConfigProcessor.java
@@ -6,13 +6,11 @@ import com.yahoo.collections.Pair;
import com.yahoo.component.Version;
import com.yahoo.config.provision.TenantName;
import com.yahoo.container.di.config.ApplicationBundlesConfig;
-import com.yahoo.net.HostName;
-import com.yahoo.vespa.config.PayloadChecksum;
-import com.yahoo.vespa.config.PayloadChecksum.Type;
-import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.jrt.Request;
+import com.yahoo.net.HostName;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.ErrorCode;
+import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.vespa.config.UnknownConfigIdException;
import com.yahoo.vespa.config.protocol.ConfigResponse;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
@@ -22,11 +20,13 @@ import com.yahoo.vespa.config.protocol.VespaVersion;
import com.yahoo.vespa.config.server.GetConfigContext;
import com.yahoo.vespa.config.server.UnknownConfigDefinitionException;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
-
import java.util.Optional;
+import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static com.yahoo.vespa.config.ErrorCode.APPLICATION_NOT_LOADED;
+import static com.yahoo.vespa.config.ErrorCode.UNKNOWN_VESPA_VERSION;
import static com.yahoo.vespa.config.protocol.SlimeConfigResponse.fromConfigPayload;
/**
@@ -56,7 +56,7 @@ class GetConfigProcessor implements Runnable {
private void respond(JRTServerConfigRequest request) {
Request req = request.getRequest();
if (req.isError()) {
- Level logLevel = (req.errorCode() == ErrorCode.APPLICATION_NOT_LOADED) ? Level.FINE : Level.INFO;
+ Level logLevel = Set.of(APPLICATION_NOT_LOADED, UNKNOWN_VESPA_VERSION).contains(req.errorCode()) ? Level.FINE : Level.INFO;
log.log(logLevel, () -> logPre + req.errorMessage());
}
rpcServer.respond(request);
@@ -83,9 +83,7 @@ class GetConfigProcessor implements Runnable {
return null;
}
Trace trace = request.getRequestTrace();
- if (logDebug(trace)) {
- debugLog(trace, "GetConfigProcessor.run() on " + localHostName);
- }
+ debugLog(trace, "GetConfigProcessor.run() on " + localHostName);
Optional<TenantName> tenant = rpcServer.resolveTenant(request, trace);
@@ -98,23 +96,21 @@ class GetConfigProcessor implements Runnable {
GetConfigContext context = rpcServer.createGetConfigContext(tenant, request, trace);
if (context == null || ! context.requestHandler().hasApplication(context.applicationId(), Optional.empty())) {
- handleError(request, ErrorCode.APPLICATION_NOT_LOADED, "No application exists");
+ handleError(request, APPLICATION_NOT_LOADED, "No application exists");
return null;
}
+ logPre = TenantRepository.logPre(context.applicationId());
Optional<Version> vespaVersion = rpcServer.useRequestVersion() ?
request.getVespaVersion().map(VespaVersion::toString).map(Version::fromString) :
Optional.empty();
- if (logDebug(trace)) {
- debugLog(trace, "Using version " + printableVespaVersion(vespaVersion));
- }
+ debugLog(trace, "Using version " + printableVespaVersion(vespaVersion));
if ( ! context.requestHandler().hasApplication(context.applicationId(), vespaVersion)) {
handleError(request, ErrorCode.UNKNOWN_VESPA_VERSION, "Unknown Vespa version in request: " + printableVespaVersion(vespaVersion));
return null;
}
- this.logPre = TenantRepository.logPre(context.applicationId());
ConfigResponse config;
try {
config = rpcServer.resolveConfig(request, context, vespaVersion);
@@ -143,14 +139,10 @@ class GetConfigProcessor implements Runnable {
// debugLog(trace, "config response before encoding:" + config.toString());
request.addOkResponse(request.payloadFromResponse(config), config.getGeneration(), config.applyOnRestart(), config.getPayloadChecksums());
- if (logDebug(trace)) {
- debugLog(trace, "return response: " + request.getShortDescription());
- }
+ debugLog(trace, "return response: " + request.getShortDescription());
respond(request);
} else {
- if (logDebug(trace)) {
- debugLog(trace, "delaying response " + request.getShortDescription());
- }
+ debugLog(trace, "delaying response " + request.getShortDescription());
return new Pair<>(context, config != null ? config.getGeneration() : 0);
}
return null;
@@ -164,9 +156,9 @@ class GetConfigProcessor implements Runnable {
if (delayed != null) {
rpcServer.delayResponse(request, delayed.getFirst());
if (rpcServer.hasNewerGeneration(delayed.getFirst().applicationId(), delayed.getSecond())) {
- // This will ensure that if the reload train left the station while I was boarding, another train will
- // immediately be scheduled.
- rpcServer.configReloaded(delayed.getFirst().applicationId());
+ // This will ensure that if the config activation train left the station while I was boarding,
+ // another train will immediately be scheduled.
+ rpcServer.configActivated(delayed.getFirst().applicationId());
}
}
}
@@ -177,7 +169,7 @@ class GetConfigProcessor implements Runnable {
}
private static String printableVespaVersion(Optional<Version> vespaVersion) {
- return (vespaVersion.isPresent() ? vespaVersion.get().toFullString() : "LATEST");
+ return vespaVersion.map(Version::toFullString).orElse("LATEST");
}
private void returnEmpty(JRTServerConfigRequest request) {
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java
index 6a8141032df..b36967d76a4 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc;
-import com.yahoo.component.annotation.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.component.Version;
+import com.yahoo.component.annotation.Inject;
import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.config.FileReference;
import com.yahoo.config.provision.ApplicationId;
@@ -28,7 +28,7 @@ import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
import com.yahoo.vespa.config.protocol.Trace;
import com.yahoo.vespa.config.server.GetConfigContext;
-import com.yahoo.vespa.config.server.ReloadListener;
+import com.yahoo.vespa.config.server.ConfigActivationListener;
import com.yahoo.vespa.config.server.RequestHandler;
import com.yahoo.vespa.config.server.SuperModelRequestHandler;
import com.yahoo.vespa.config.server.application.ApplicationSet;
@@ -44,13 +44,15 @@ import com.yahoo.vespa.filedistribution.FileDownloader;
import com.yahoo.vespa.filedistribution.FileReceiver;
import com.yahoo.vespa.filedistribution.FileReferenceData;
import com.yahoo.vespa.filedistribution.FileReferenceDownload;
-
import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentHashMap;
@@ -62,8 +64,11 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import java.util.stream.Stream;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+
/**
* An RPC server class that handles the config protocol RPC method "getConfigV3".
* Mandatory hooks need to be implemented by subclasses.
@@ -71,7 +76,7 @@ import java.util.stream.Stream;
* @author hmusum
*/
// TODO: Split business logic out of this
-public class RpcServer implements Runnable, ReloadListener, TenantListener {
+public class RpcServer implements Runnable, ConfigActivationListener, TenantListener {
static final String getConfigMethodName = "getConfigV3";
@@ -221,7 +226,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
getSupervisor().addMethod(new Method("printStatistics", "", "s", this::printStatistics)
.methodDesc("printStatistics")
.returnDesc(0, "statistics", "Statistics for server"));
- getSupervisor().addMethod(new Method("filedistribution.serveFile", "si", "is", this::serveFile));
+ getSupervisor().addMethod(new Method("filedistribution.serveFile", "si*", "is", this::serveFile));
getSupervisor().addMethod(new Method("filedistribution.setFileReferencesToDownload", "S", "i", this::setFileReferencesToDownload)
.methodDesc("set which file references to download")
.paramDesc(0, "file references", "file reference to download")
@@ -252,7 +257,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
/**
* Checks all delayed responses for config changes and waits until all has been answered.
- * This method should be called when config is reloaded in the server.
+ * This method should be called when config is activated in the server.
*/
@Override
public void configActivated(ApplicationSet applicationSet) {
@@ -260,19 +265,19 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
ApplicationState state = getState(applicationId);
state.setActiveGeneration(applicationSet.getApplicationGeneration());
reloadSuperModel(applicationSet);
- configReloaded(applicationId);
+ configActivated(applicationId);
}
private void reloadSuperModel(ApplicationSet applicationSet) {
- superModelRequestHandler.reloadConfig(applicationSet);
- configReloaded(ApplicationId.global());
+ superModelRequestHandler.activateConfig(applicationSet);
+ configActivated(ApplicationId.global());
}
- void configReloaded(ApplicationId applicationId) {
+ void configActivated(ApplicationId applicationId) {
List<DelayedConfigResponses.DelayedConfigResponse> responses = delayedConfigResponses.drainQueue(applicationId);
String logPre = TenantRepository.logPre(applicationId);
if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, logPre + "Start of configReload: " + responses.size() + " requests on delayed requests queue");
+ log.log(Level.FINE, logPre + "Start of configActivated: " + responses.size() + " requests on delayed requests queue");
}
int responsesSent = 0;
CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executorService);
@@ -303,7 +308,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
}
if (log.isLoggable(Level.FINE))
- log.log(Level.FINE, logPre + "Finished reloading " + responsesSent + " requests");
+ log.log(Level.FINE, logPre + "Finished activating " + responsesSent + " requests");
}
private void logRequestDebug(Level level, String message, JRTServerConfigRequest request) {
@@ -326,8 +331,8 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
@Override
public void applicationRemoved(ApplicationId applicationId) {
superModelRequestHandler.removeApplication(applicationId);
- configReloaded(applicationId);
- configReloaded(ApplicationId.global());
+ configActivated(applicationId);
+ configActivated(ApplicationId.global());
}
public void respond(JRTServerConfigRequest request) {
@@ -487,6 +492,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
sendParts(session, fileData);
sendEof(session, fileData, status);
}
+
private void sendParts(int session, FileReferenceData fileData) {
ByteBuffer bb = ByteBuffer.allocate(0x100000);
for (int partId = 0, read = fileData.nextContent(bb); read >= 0; partId++, read = fileData.nextContent(bb)) {
@@ -500,12 +506,9 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
bb.clear();
}
}
+
private int sendMeta(FileReferenceData fileData) {
- Request request = new Request(FileReceiver.RECEIVE_META_METHOD);
- request.parameters().add(new StringValue(fileData.fileReference().value()));
- request.parameters().add(new StringValue(fileData.filename()));
- request.parameters().add(new StringValue(fileData.type().name()));
- request.parameters().add(new Int64Value(fileData.size()));
+ Request request = createMetaRequest(fileData);
invokeRpcIfValidConnection(request);
if (request.isError()) {
log.warning("Failed delivering meta for reference '" + fileData.fileReference().value() + "' with file '" + fileData.filename() + "' to " +
@@ -518,6 +521,20 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
return request.returnValues().get(1).asInt32();
}
}
+
+ // non-private for testing
+ static Request createMetaRequest(FileReferenceData fileData) {
+ Request request = new Request(FileReceiver.RECEIVE_META_METHOD);
+ request.parameters().add(new StringValue(fileData.fileReference().value()));
+ request.parameters().add(new StringValue(fileData.filename()));
+ request.parameters().add(new StringValue(fileData.type().name()));
+ request.parameters().add(new Int64Value(fileData.size()));
+ // Only add paramter if not gzip, this is default and old clients will not handle the extra parameter
+ if (fileData.compressionType() != CompressionType.gzip)
+ request.parameters().add(new StringValue(fileData.compressionType().name()));
+ return request;
+ }
+
private void sendPart(int session, FileReference ref, int partId, byte [] buf) {
Request request = new Request(FileReceiver.RECEIVE_PART_METHOD);
request.parameters().add(new StringValue(ref.value()));
@@ -534,6 +551,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
}
}
}
+
private void sendEof(int session, FileReferenceData fileData, FileServer.ReplayStatus status) {
Request request = new Request(FileReceiver.RECEIVE_EOF_METHOD);
request.parameters().add(new StringValue(fileData.fileReference().value()));
@@ -554,7 +572,7 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
private void invokeRpcIfValidConnection(Request request) {
if (target.isValid()) {
- target.invokeSync(request, 600);
+ target.invokeSync(request, Duration.ofMinutes(10));
} else {
throw new RuntimeException("Connection to " + target + " is invalid", target.getConnectionLostReason());
}
@@ -566,7 +584,18 @@ public class RpcServer implements Runnable, ReloadListener, TenantListener {
rpcAuthorizer.authorizeFileRequest(request)
.thenRun(() -> { // okay to do in authorizer thread as serveFile is async
FileServer.Receiver receiver = new ChunkedFileReceiver(request.target());
- fileServer.serveFile(request.parameters().get(0).asString(), request.parameters().get(1).asInt32() == 0, request, receiver);
+
+ FileReference reference = new FileReference(request.parameters().get(0).asString());
+ boolean downloadFromOtherSourceIfNotFound = request.parameters().get(1).asInt32() == 0;
+ Set<FileReferenceData.CompressionType> acceptedCompressionTypes = Set.of(CompressionType.gzip);
+ // Newer clients specify accepted compression types in request
+ if (request.parameters().size() > 2)
+ acceptedCompressionTypes = Arrays.stream(request.parameters().get(2).asStringArray())
+ .map(CompressionType::valueOf)
+ .collect(Collectors.toSet());
+ log.log(Level.FINE, "acceptedCompressionTypes=" + acceptedCompressionTypes);
+
+ fileServer.serveFile(reference, downloadFromOtherSourceIfNotFound, acceptedCompressionTypes, request, receiver);
});
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizer.java
index f5b570fed40..536a446df2f 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizer.java
@@ -10,9 +10,9 @@ import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.config.provision.security.NodeIdentifierException;
import com.yahoo.config.provision.security.NodeIdentity;
import com.yahoo.jrt.Request;
-import com.yahoo.jrt.SecurityContext;
import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.TransportSecurityUtils;
+import com.yahoo.security.tls.ConnectionAuthContext;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
import com.yahoo.vespa.config.server.RequestHandler;
@@ -166,14 +166,14 @@ public class MultiTenantRpcAuthorizer implements RpcAuthorizer {
// TODO Make peer identity mandatory once TLS mixed mode is removed
private Optional<NodeIdentity> getPeerIdentity(Request request) {
- Optional<SecurityContext> securityContext = request.target().getSecurityContext();
- if (securityContext.isEmpty()) {
+ ConnectionAuthContext authCtx = request.target().connectionAuthContext();
+ if (authCtx.peerCertificate().isEmpty()) {
if (TransportSecurityUtils.getInsecureMixedMode() == MixedMode.DISABLED) {
throw new IllegalStateException("Security context missing"); // security context should always be present
}
return Optional.empty(); // client choose to communicate over insecure channel
}
- List<X509Certificate> certChain = securityContext.get().peerCertificateChain();
+ List<X509Certificate> certChain = authCtx.peerCertificateChain();
if (certChain.isEmpty()) {
throw new IllegalStateException("Client authentication is not enforced!"); // clients should be required to authenticate when TLS is enabled
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/session/Session.java b/configserver/src/main/java/com/yahoo/vespa/config/server/session/Session.java
index edc166d0989..82faeae01e8 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/session/Session.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/session/Session.java
@@ -61,10 +61,6 @@ public abstract class Session implements Comparable<Session> {
return sessionZooKeeperClient.readStatus();
}
- public SessionZooKeeperClient getSessionZooKeeperClient() {
- return sessionZooKeeperClient;
- }
-
@Override
public String toString() {
return "Session,id=" + sessionId + ",status=" + getStatus();
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionPreparer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionPreparer.java
index 1e073ac3458..63ba8197960 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionPreparer.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionPreparer.java
@@ -6,6 +6,9 @@ import com.yahoo.component.Version;
import com.yahoo.component.Vtag;
import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.config.FileReference;
+import com.yahoo.config.application.ValidationProcessor;
+import com.yahoo.config.application.XmlPreProcessor;
+import com.yahoo.config.application.api.ApplicationMetaData;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.application.api.FileRegistry;
@@ -26,6 +29,7 @@ import com.yahoo.config.provision.Zone;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import com.yahoo.net.HostName;
import com.yahoo.path.Path;
+import com.yahoo.text.XML;
import com.yahoo.vespa.config.server.ConfigServerSpec;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.config.server.application.ApplicationSet;
@@ -47,9 +51,14 @@ import com.yahoo.vespa.config.server.tenant.EndpointCertificateRetriever;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;
+import com.yahoo.vespa.model.application.validation.BundleValidator;
+import org.xml.sax.SAXException;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.Collection;
@@ -58,9 +67,11 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
+import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
+import java.util.zip.ZipException;
import static com.yahoo.vespa.config.server.ConfigServerSpec.fromConfig;
@@ -238,6 +249,7 @@ public class SessionPreparer {
void preprocess() {
try {
+ validateXmlFeatures(applicationPackage, logger);
this.preprocessedApplicationPackage = applicationPackage.preprocess(zone, logger);
} catch (IOException | RuntimeException e) {
throw new IllegalArgumentException("Error preprocessing application package for " + applicationId +
@@ -246,6 +258,74 @@ public class SessionPreparer {
checkTimeout("preprocess");
}
+ /**
+ * Warn on use of deprecated XML features
+ */
+ private void validateXmlFeatures(ApplicationPackage applicationPackage, DeployLogger logger) {
+ // TODO: Validate no use of XInclude, datatype definitions or external entities
+ // in any xml file we parse, such as services.xml, deployment.xml, hosts.xml,
+ // validation-overrides.xml and any pom.xml files in OSGi bundles
+ // services.xml and hosts.xml will need to be preprocessed by our own processors first
+
+ File applicationPackageDir = applicationPackage.getFileReference(Path.fromString("."));
+ File servicesXml = applicationPackage.getFileReference(Path.fromString("services.xml"));
+ File hostsXml = applicationPackage.getFileReference(Path.fromString("hosts.xml"));
+
+ // Validate after doing our own preprocessing on these two files
+ if(servicesXml.exists()) {
+ vespaPreprocess(applicationPackageDir.getAbsoluteFile(), servicesXml, applicationPackage.getMetaData());
+ }
+ if(hostsXml.exists()) {
+ vespaPreprocess(applicationPackageDir.getAbsoluteFile(), hostsXml, applicationPackage.getMetaData());
+ }
+
+ if (zone.system().isPublic()) {
+ // Validate all other XML files
+ try (var paths = Files.find(applicationPackageDir.getAbsoluteFile().toPath(), Integer.MAX_VALUE,
+ (path, attr) -> attr.isRegularFile() && path.getFileName().toString().matches(".*\\.[Xx][Mm][Ll]"))) {
+ paths.filter(p -> !(p.equals(servicesXml.getAbsoluteFile().toPath()) || p.equals(hostsXml.getAbsoluteFile().toPath())))
+ .forEach(xmlPath -> {
+ try {
+ new ValidationProcessor().process(XML.getDocument(xmlPath.toFile()));
+ } catch (IOException | TransformerException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // Validate pom.xml files in OSGi bundles
+ try (var paths = Files.find(applicationPackageDir.getAbsoluteFile().toPath(), Integer.MAX_VALUE,
+ (path, attr) -> attr.isRegularFile() && path.getFileName().toString().matches(".*\\.[Jj][Aa][Rr]"))) {
+ paths.forEach(jarPath -> {
+ try {
+ new BundleValidator().getPomXmlContent(logger, new JarFile(jarPath.toFile()));
+ } catch (ZipException e) {
+ // ignore for tests
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ void vespaPreprocess(File appDir, File inputXml, ApplicationMetaData metaData) {
+ try {
+ new XmlPreProcessor(appDir,
+ inputXml,
+ metaData.getApplicationId().instance(),
+ zone.environment(),
+ zone.region())
+ .run();
+ } catch (ParserConfigurationException | IOException | SAXException | TransformerException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
AllocatedHosts buildModels(Instant now) {
var allocatedHosts = new AllocatedHostsFromAllModels();
this.modelResultList = preparedModelsBuilder.buildModels(applicationId, dockerImageRepository, vespaVersion,
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java
index 059d192e7d2..a6bbd6c20a2 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java
@@ -44,13 +44,12 @@ import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.Flags;
-import com.yahoo.vespa.flags.StringFlag;
+import com.yahoo.vespa.flags.UnboundStringFlag;
import com.yahoo.yolean.Exceptions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.zookeeper.KeeperException;
-
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
@@ -83,6 +82,7 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.yahoo.vespa.curator.Curator.CompletionWaiter;
+import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static java.nio.file.Files.readAttributes;
/**
@@ -128,7 +128,6 @@ public class SessionRepository {
private final ModelFactoryRegistry modelFactoryRegistry;
private final ConfigDefinitionRepo configDefinitionRepo;
private final int maxNodeSize;
- private final StringFlag failDeploymentForFilesWithUnknownExtension;
public SessionRepository(TenantName tenantName,
TenantApplications applicationRepo,
@@ -172,7 +171,6 @@ public class SessionRepository {
this.modelFactoryRegistry = modelFactoryRegistry;
this.configDefinitionRepo = configDefinitionRepo;
this.maxNodeSize = maxNodeSize;
- this.failDeploymentForFilesWithUnknownExtension = Flags.APPLICATION_FILES_WITH_UNKNOWN_EXTENSION.bindTo(flagSource);
loadSessions(); // Needs to be done before creating cache below
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, zkCacheExecutor);
@@ -347,39 +345,44 @@ public class SessionRepository {
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient);
- RemoteSession newSession = loadSessionIfActive(session).orElse(session);
- remoteSessionCache.put(sessionId, newSession);
- updateSessionStateWatcher(sessionId, newSession);
- return newSession;
+ loadSessionIfActive(session);
+ remoteSessionCache.put(sessionId, session);
+ updateSessionStateWatcher(sessionId);
+ return session;
}
- public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
+ public int deleteExpiredRemoteSessions(Clock clock) {
+ Duration expiryTime = configserverConfig.hostedVespa()
+ ? sessionLifetime.multipliedBy(2)
+ : sessionLifetime.multipliedBy(24); // TODO: Remove when tested more (Sep. 2022 at the latest)
+
List<Long> remoteSessionsFromZooKeeper = getRemoteSessionsFromZooKeeper();
log.log(Level.FINE, () -> "Remote sessions for tenant " + tenantName + ": " + remoteSessionsFromZooKeeper);
int deleted = 0;
+ // Avoid deleting too many in one run
+ int deleteMax = (int) Math.min(1000, Math.max(10, remoteSessionsFromZooKeeper.size() * 0.01));
for (long sessionId : remoteSessionsFromZooKeeper) {
Session session = remoteSessionCache.get(sessionId);
- if (session == null) {
- log.log(Level.FINE, () -> "Remote session " + sessionId + " is null, creating a new one");
+ if (session == null)
session = new RemoteSession(tenantName, sessionId, createSessionZooKeeperClient(sessionId));
- }
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.FINE, () -> "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
deleteRemoteSessionFromZooKeeper(session);
deleted++;
}
- // Avoid deleting too many in one run
- if (deleted >= 2)
+ if (deleted >= deleteMax)
break;
}
return deleted;
}
- public void deactivateAndUpdateCache(RemoteSession remoteSession) {
- RemoteSession session = remoteSession.deactivated();
- remoteSessionCache.put(session.getSessionId(), session);
+ public void deactivateSession(long sessionId) {
+ var s = remoteSessionCache.get(sessionId);
+ if (s == null) return;
+
+ remoteSessionCache.put(sessionId, s.deactivated());
}
public void deleteRemoteSessionFromZooKeeper(Session session) {
@@ -390,7 +393,7 @@ public class SessionRepository {
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
- return (created.plus(expiryTime).isBefore(clock.instant()));
+ return created.plus(expiryTime).isBefore(clock.instant());
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
@@ -441,8 +444,11 @@ public class SessionRepository {
return session.getStatus() == Session.Status.DELETE;
}
- void activate(RemoteSession session) {
- long sessionId = session.getSessionId();
+ void activate(long sessionId) {
+ createLocalSessionFromDistributedApplicationPackage(sessionId);
+ RemoteSession session = remoteSessionCache.get(sessionId);
+ if (session == null) return;
+
CompletionWaiter waiter = createSessionZooKeeperClient(sessionId).getActiveWaiter();
log.log(Level.FINE, () -> session.logPre() + "Activating " + sessionId);
applicationRepo.activateApplication(ensureApplicationLoaded(session), sessionId);
@@ -451,21 +457,25 @@ public class SessionRepository {
log.log(Level.INFO, session.logPre() + "Session activated: " + sessionId);
}
- private Optional<RemoteSession> loadSessionIfActive(RemoteSession session) {
+ private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
Optional<Long> activeSession = applicationRepo.activeSessionOf(applicationId);
if (activeSession.isPresent() && activeSession.get() == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.activateApplication(ensureApplicationLoaded(session), session.getSessionId());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
- return Optional.ofNullable(remoteSessionCache.get(session.getSessionId()));
+ return;
}
}
- return Optional.empty();
}
- void prepareRemoteSession(RemoteSession session) {
- SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
+ void prepareRemoteSession(long sessionId) {
+ // Might need to create local session first
+ createLocalSessionFromDistributedApplicationPackage(sessionId);
+ RemoteSession session = remoteSessionCache.get(sessionId);
+ if (session == null) return;
+
+ SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
CompletionWaiter waiter = sessionZooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded(session);
notifyCompletion(waiter);
@@ -482,13 +492,13 @@ public class SessionRepository {
RemoteSession activated = session.activated(applicationSet);
long sessionId = activated.getSessionId();
remoteSessionCache.put(sessionId, activated);
- updateSessionStateWatcher(sessionId, activated);
+ updateSessionStateWatcher(sessionId);
return applicationSet;
}
void confirmUpload(Session session) {
- CompletionWaiter waiter = session.getSessionZooKeeperClient().getUploadWaiter();
+ CompletionWaiter waiter = createSessionZooKeeperClient(session.getSessionId()).getUploadWaiter();
long sessionId = session.getSessionId();
log.log(Level.FINE, () -> "Notifying upload waiter for session " + sessionId);
notifyCompletion(waiter);
@@ -575,32 +585,31 @@ public class SessionRepository {
// ---------------- Common stuff ----------------------------------------------------------------
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
- log.log(Level.FINE, () -> "Purging old sessions for tenant '" + tenantName + "'");
+ log.log(Level.FINE, () -> "Deleting expired local sessions for tenant '" + tenantName + "'");
Set<LocalSession> toDelete = new HashSet<>();
Set<Long> newSessions = findNewSessionsInFileSystem();
try {
for (LocalSession candidate : getLocalSessionsFromFileSystem()) {
// Skip sessions newly added (we might have a session in the file system, but not in ZooKeeper,
// we don't want to touch any of them)
- if (newSessions.contains(candidate.getSessionId())) {
- log.log(Level.FINE, () -> "Skipping expiring newly created session " + candidate.getSessionId());
+ if (newSessions.contains(candidate.getSessionId()))
continue;
- }
Instant createTime = candidate.getCreateTime();
- log.log(Level.FINE, () -> "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
+ log.log(Level.FINE, () -> "Candidate local session for deletion: " + candidate.getSessionId() +
+ ", created: " + createTime + ", state " + candidate.getStatus() + ", can be deleted: " + canBeDeleted(candidate));
- if (hasExpired(candidate) && canBeDeleted(candidate)) {
+ if (hasExpired(createTime) && canBeDeleted(candidate)) {
toDelete.add(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
- // Sessions with state ACTIVATE, but which are not actually active
Optional<ApplicationId> applicationId = candidate.getOptionalApplicationId();
if (applicationId.isEmpty()) continue;
+
Long activeSession = activeSessions.get(applicationId.get());
if (activeSession == null || activeSession != candidate.getSessionId()) {
toDelete.add(candidate);
- log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
- createTime + " for '" + applicationId + "'");
+ log.log(Level.FINE, () -> "Will delete inactive session " + candidate.getSessionId() + " created " +
+ createTime + " for '" + applicationId + "'");
}
}
}
@@ -614,21 +623,22 @@ public class SessionRepository {
log.log(Level.FINE, () -> "Done purging old sessions");
}
- private boolean hasExpired(LocalSession candidate) {
- return candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant());
+ private boolean hasExpired(Instant created) {
+ return created.plus(sessionLifetime).isBefore(clock.instant());
}
// Sessions with state other than UNKNOWN or ACTIVATE or old sessions in UNKNOWN state
private boolean canBeDeleted(LocalSession candidate) {
- return ! List.of(Session.Status.UNKNOWN, Session.Status.ACTIVATE).contains(candidate.getStatus())
- || oldSessionDirWithNonExistingSession(candidate);
+ return ( ! List.of(Session.Status.UNKNOWN, Session.Status.ACTIVATE).contains(candidate.getStatus()))
+ || oldSessionDirWithUnknownStatus(candidate);
}
- private boolean oldSessionDirWithNonExistingSession(LocalSession session) {
+ private boolean oldSessionDirWithUnknownStatus(LocalSession session) {
+ Duration expiryTime = Duration.ofHours(configserverConfig.keepSessionsWithUnknownStatusHours());
File sessionDir = tenantFileSystemDirs.getUserApplicationDir(session.getSessionId());
return sessionDir.exists()
&& session.getStatus() == Session.Status.UNKNOWN
- && created(sessionDir).plus(Duration.ofDays(30)).isBefore(clock.instant());
+ && created(sessionDir).plus(expiryTime).isBefore(clock.instant());
}
private Set<Long> findNewSessionsInFileSystem() {
@@ -673,29 +683,30 @@ public class SessionRepository {
boolean internalRedeploy,
Optional<DeployLogger> deployLogger) {
long deployTimestamp = System.currentTimeMillis();
- String user = System.getenv("USER");
- if (user == null) {
- user = "unknown";
- }
- DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
- internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId));
+ DeployData deployData = new DeployData(userDir.getAbsolutePath(), applicationId, deployTimestamp, internalRedeploy,
+ sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId));
FilesApplicationPackage app = FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
+ validateFileExtensions(applicationId, deployLogger, app);
+
+ return app;
+ }
+
+ private void validateFileExtensions(ApplicationId applicationId, Optional<DeployLogger> deployLogger, FilesApplicationPackage app) {
try {
app.validateFileExtensions();
} catch (IllegalArgumentException e) {
- switch (failDeploymentForFilesWithUnknownExtension.value()) {
- case "FAIL":
- throw e;
- case "LOG":
- deployLogger.ifPresent(logger -> logger.logApplicationPackage(Level.WARNING, e.getMessage()));
- break;
- case "NOOP":
- default:
- break;
+ if (configserverConfig.hostedVespa()) {
+ UnboundStringFlag flag = Flags.APPLICATION_FILES_WITH_UNKNOWN_EXTENSION;
+ String value = flag.bindTo(flagSource).with(APPLICATION_ID, applicationId.serializedForm()).value();
+ switch (value) {
+ case "FAIL" -> throw e;
+ case "LOG" -> deployLogger.ifPresent(logger -> logger.logApplicationPackage(Level.WARNING, e.getMessage()));
+ default -> log.log(Level.WARNING, "Unknown value for flag " + flag.id() + ": " + value);
+ }
+ } else {
+ deployLogger.ifPresent(logger -> logger.logApplicationPackage(Level.WARNING, e.getMessage()));
}
}
-
- return app;
}
private LocalSession createSessionFromApplication(File applicationDirectory,
@@ -816,8 +827,9 @@ public class SessionRepository {
}
/**
- * Returns a new local session for the given session id if it does not already exist.
- * Will also add the session to the local session cache if necessary
+ * Create a new local session for the given session id if it does not already exist.
+ * Will also add the session to the local session cache if necessary. If there is no
+ * remote session matching the session it will also be created.
*/
public void createLocalSessionFromDistributedApplicationPackage(long sessionId) {
if (applicationRepo.sessionExistsInFileSystem(sessionId)) {
@@ -864,7 +876,7 @@ public class SessionRepository {
return getSessionPath(sessionId).append(ZKApplication.SESSIONSTATE_ZK_SUBPATH);
}
- private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
+ public SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
return new SessionZooKeeperClient(curator,
tenantName,
sessionId,
@@ -885,15 +897,12 @@ public class SessionRepository {
return new TenantFileSystemDirs(configServerDB, tenantName).getUserApplicationDir(sessionId);
}
- private void updateSessionStateWatcher(long sessionId, RemoteSession remoteSession) {
- SessionStateWatcher sessionStateWatcher = sessionStateWatchers.get(sessionId);
- if (sessionStateWatcher == null) {
- Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
+ private void updateSessionStateWatcher(long sessionId) {
+ sessionStateWatchers.computeIfAbsent(sessionId, (id) -> {
+ Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(id).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
- sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, remoteSession, metricUpdater, zkWatcherExecutor, this));
- } else {
- sessionStateWatcher.updateRemoteSession(remoteSession);
- }
+ return new SessionStateWatcher(fileCache, id, metricUpdater, zkWatcherExecutor, this);
+ });
}
@Override
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionStateWatcher.java b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionStateWatcher.java
index 6c6f60426fe..082743e48f9 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionStateWatcher.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionStateWatcher.java
@@ -13,7 +13,7 @@ import java.util.logging.Logger;
import static com.yahoo.vespa.config.server.session.Session.Status;
/**
- * Watches one particular session (/config/v2/tenants/&lt;tenantName&gt;/sessions/&lt;n&gt;/sessionState in ZooKeeper)
+ * Watches session state for a session (/config/v2/tenants/&lt;tenantName&gt;/sessions/&lt;n&gt;/sessionState in ZooKeeper)
* The session must be in the session repo.
*
* @author Vegard Havdal
@@ -24,18 +24,18 @@ public class SessionStateWatcher {
private static final Logger log = Logger.getLogger(SessionStateWatcher.class.getName());
private final Curator.FileCache fileCache;
- private volatile RemoteSession session;
+ private final long sessionId;
private final MetricUpdater metrics;
private final Executor zkWatcherExecutor;
private final SessionRepository sessionRepository;
SessionStateWatcher(Curator.FileCache fileCache,
- RemoteSession session,
+ long sessionId,
MetricUpdater metrics,
Executor zkWatcherExecutor,
SessionRepository sessionRepository) {
this.fileCache = fileCache;
- this.session = session;
+ this.sessionId = sessionId;
this.metrics = metrics;
this.fileCache.addListener(this::nodeChanged);
this.fileCache.start();
@@ -44,39 +44,25 @@ public class SessionStateWatcher {
}
private synchronized void sessionStatusChanged(Status newStatus) {
- long sessionId = session.getSessionId();
-
switch (newStatus) {
case NEW:
case UNKNOWN:
break;
case DELETE:
- sessionRepository.deactivateAndUpdateCache(session);
+ case DEACTIVATE:
+ sessionRepository.deactivateSession(sessionId);
break;
case PREPARE:
- createLocalSession(sessionId);
- sessionRepository.prepareRemoteSession(session);
+ sessionRepository.prepareRemoteSession(sessionId);
break;
case ACTIVATE:
- createLocalSession(sessionId);
- sessionRepository.activate(session);
- break;
- case DEACTIVATE:
- sessionRepository.deactivateAndUpdateCache(session);
+ sessionRepository.activate(sessionId);
break;
default:
throw new IllegalStateException("Unknown status " + newStatus);
}
}
- private void createLocalSession(long sessionId) {
- sessionRepository.createLocalSessionFromDistributedApplicationPackage(sessionId);
- }
-
- public long getSessionId() {
- return session.getSessionId();
- }
-
public void close() {
try {
fileCache.close();
@@ -92,27 +78,13 @@ public class SessionStateWatcher {
ChildData node = fileCache.getCurrentData();
if (node != null) {
newStatus = Status.parse(Utf8.toString(node.getData()));
-
- String debugMessage = log.isLoggable(Level.FINE) ?
- session.logPre() + "Session " + session.getSessionId()
- + " changed status to " + newStatus.name() :
- null;
- if (debugMessage != null) log.fine(debugMessage);
-
sessionStatusChanged(newStatus);
-
- if (debugMessage != null) log.fine(debugMessage + ": Done");
}
} catch (Exception e) {
- log.log(Level.WARNING, session.logPre() + "Error handling session change to " +
- newStatus.name() + " for session " + getSessionId(), e);
+ log.log(Level.WARNING, "Error handling session change to " + newStatus.name() + " for session " + sessionId, e);
metrics.incSessionChangeErrors();
}
});
}
- public synchronized void updateRemoteSession(RemoteSession session) {
- this.session = session;
- }
-
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/EndpointCertificateRetriever.java b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/EndpointCertificateRetriever.java
index a3ddae8f7aa..4a1e81b9058 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/EndpointCertificateRetriever.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/EndpointCertificateRetriever.java
@@ -19,13 +19,7 @@ import java.util.logging.Logger;
*
* @author andreer
*/
-public class EndpointCertificateRetriever {
-
- private final SecretStore secretStore;
-
- public EndpointCertificateRetriever(SecretStore secretStore) {
- this.secretStore = secretStore;
- }
+public record EndpointCertificateRetriever(SecretStore secretStore) {
private static final Logger log = Logger.getLogger(EndpointCertificateRetriever.class.getName());
@@ -40,11 +34,11 @@ public class EndpointCertificateRetriever {
verifyKeyMatchesCertificate(endpointCertificateMetadata, cert, key);
- return new EndpointCertificateSecrets(cert, key);
+ return new EndpointCertificateSecrets(cert, key, endpointCertificateMetadata.version());
} catch (RuntimeException e) {
log.log(Level.WARNING, "Exception thrown during certificate retrieval", e);
// Assume not ready yet
- return EndpointCertificateSecrets.MISSING;
+ return EndpointCertificateSecrets.missing(endpointCertificateMetadata.version());
}
}
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java
index 1325f065ebd..9cb90d7f50c 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java
@@ -19,7 +19,7 @@ import com.yahoo.path.Path;
import com.yahoo.text.Utf8;
import com.yahoo.transaction.Transaction;
import com.yahoo.vespa.config.server.ConfigServerDB;
-import com.yahoo.vespa.config.server.ReloadListener;
+import com.yahoo.vespa.config.server.ConfigActivationListener;
import com.yahoo.vespa.config.server.application.PermanentApplicationPackage;
import com.yahoo.vespa.config.server.application.TenantApplications;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
@@ -115,7 +115,7 @@ public class TenantRepository {
private final Clock clock;
private final ModelFactoryRegistry modelFactoryRegistry;
private final ConfigDefinitionRepo configDefinitionRepo;
- private final ReloadListener reloadListener;
+ private final ConfigActivationListener configActivationListener;
private final ScheduledExecutorService checkForRemovedApplicationsService =
new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory("check for removed applications"));
private final Curator.DirectoryCache directoryCache;
@@ -136,7 +136,7 @@ public class TenantRepository {
Zone zone,
ModelFactoryRegistry modelFactoryRegistry,
ConfigDefinitionRepo configDefinitionRepo,
- ReloadListener reloadListener,
+ ConfigActivationListener configActivationListener,
TenantListener tenantListener,
ZookeeperServerConfig zookeeperServerConfig) {
this(hostRegistry,
@@ -155,7 +155,7 @@ public class TenantRepository {
Clock.systemUTC(),
modelFactoryRegistry,
configDefinitionRepo,
- reloadListener,
+ configActivationListener,
tenantListener,
zookeeperServerConfig);
}
@@ -176,7 +176,7 @@ public class TenantRepository {
Clock clock,
ModelFactoryRegistry modelFactoryRegistry,
ConfigDefinitionRepo configDefinitionRepo,
- ReloadListener reloadListener,
+ ConfigActivationListener configActivationListener,
TenantListener tenantListener,
ZookeeperServerConfig zookeeperServerConfig) {
this.hostRegistry = hostRegistry;
@@ -196,7 +196,7 @@ public class TenantRepository {
this.clock = clock;
this.modelFactoryRegistry = modelFactoryRegistry;
this.configDefinitionRepo = configDefinitionRepo;
- this.reloadListener = reloadListener;
+ this.configActivationListener = configActivationListener;
this.tenantListener = tenantListener;
this.zookeeperServerConfig = zookeeperServerConfig;
// This we should control with a feature flag.
@@ -338,7 +338,7 @@ public class TenantRepository {
zkApplicationWatcherExecutor,
zkCacheExecutor,
metrics,
- reloadListener,
+ configActivationListener,
configserverConfig,
hostRegistry,
new TenantFileSystemDirs(configServerDB, tenantName),
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplication.java b/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplication.java
index 107bd8be367..4c262379c35 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplication.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplication.java
@@ -84,7 +84,7 @@ public class ZKApplication {
}
/**
- * Retrieves a node relative to the node of the live application
+ * Retrieves a node relative to the node of the active application
*
* @param path a path relative to the currently active application
* @return a Reader that can be used to get the data
@@ -129,7 +129,7 @@ public class ZKApplication {
}
/**
- * Checks if the given node exists under path under this live app
+ * Checks if the given node exists under path under this active app
*
* @param path a zookeeper path
* @return true if the node exists in the path, false otherwise
diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplicationPackage.java b/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplicationPackage.java
index 0fa6e9a0704..9b23037ed19 100644
--- a/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplicationPackage.java
+++ b/configserver/src/main/java/com/yahoo/vespa/config/server/zookeeper/ZKApplicationPackage.java
@@ -5,7 +5,6 @@ import com.google.common.base.Joiner;
import com.yahoo.component.Version;
import com.yahoo.config.application.api.ApplicationFile;
import com.yahoo.config.application.api.ApplicationMetaData;
-import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.ComponentInfo;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.application.api.UnparsedConfigDefinition;
@@ -59,7 +58,7 @@ public class ZKApplicationPackage extends AbstractApplicationPackage {
public ZKApplicationPackage(AddFileInterface fileManager, Curator curator, Path sessionPath, int maxNodeSize) {
verifyAppPath(curator, sessionPath);
zkApplication = new ZKApplication(curator, sessionPath, maxNodeSize);
- metaData = readMetaDataFromLiveApp(zkApplication);
+ metaData = readMetaDataFromActiveApp(zkApplication);
importFileRegistries(fileManager);
allocatedHosts = importAllocatedHosts();
}
@@ -102,13 +101,13 @@ public class ZKApplicationPackage extends AbstractApplicationPackage {
}
}
- private ApplicationMetaData readMetaDataFromLiveApp(ZKApplication liveApp) {
+ private ApplicationMetaData readMetaDataFromActiveApp(ZKApplication activeApp) {
Path metaPath = Path.fromString(ZKApplication.META_ZK_PATH);
- String metaDataString = liveApp.getData(metaPath);
+ String metaDataString = activeApp.getData(metaPath);
if (metaDataString == null || metaDataString.isEmpty()) {
return null;
}
- return ApplicationMetaData.fromJsonString(liveApp.getData(metaPath));
+ return ApplicationMetaData.fromJsonString(activeApp.getData(metaPath));
}
@Override
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/ApplicationRepositoryTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/ApplicationRepositoryTest.java
index ee2a979be7a..d1d8c165124 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/ApplicationRepositoryTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/ApplicationRepositoryTest.java
@@ -233,7 +233,6 @@ public class ApplicationRepositoryTest {
assertEquals(originalApplicationMetaData.getApplicationId(), applicationMetaData.getApplicationId());
assertEquals(originalApplicationMetaData.getGeneration().longValue(), applicationMetaData.getPreviousActiveGeneration());
assertNotEquals(originalApplicationMetaData.getGeneration(), applicationMetaData.getGeneration());
- assertEquals(originalApplicationMetaData.getDeployedByUser(), applicationMetaData.getDeployedByUser());
}
@Test
@@ -446,7 +445,7 @@ public class ApplicationRepositoryTest {
assertEquals(3, localSession.getSessionId());
// All sessions except 3 should be removed after the call to deleteExpiredRemoteSessions
- assertEquals(2, tester.applicationRepository().deleteExpiredRemoteSessions(clock, Duration.ofSeconds(0)));
+ assertEquals(2, tester.applicationRepository().deleteExpiredRemoteSessions(clock));
ArrayList<Long> remoteSessions = new ArrayList<>(sessionRepository.getRemoteSessionsFromZooKeeper());
Session remoteSession = sessionRepository.getRemoteSession(remoteSessions.get(0));
assertEquals(3, remoteSession.getSessionId());
@@ -464,7 +463,8 @@ public class ApplicationRepositoryTest {
// and check that expiring local sessions still works
int sessionId = 6;
TenantName tenantName = tester.tenant().getName();
- java.nio.file.Path dir = Files.createDirectory(new TenantFileSystemDirs(serverdb, tenantName).getUserApplicationDir(sessionId).toPath());
+ Instant session6CreateTime = clock.instant();
+ Files.createDirectory(new TenantFileSystemDirs(serverdb, tenantName).getUserApplicationDir(sessionId).toPath());
LocalSession localSession2 = new LocalSession(tenant1,
sessionId,
FilesApplicationPackage.fromFile(testApp),
@@ -479,7 +479,7 @@ public class ApplicationRepositoryTest {
// so will be candidate for expiry)
Session session = sessionRepository.createRemoteSession(7);
sessionRepository.createSetStatusTransaction(session, Session.Status.UNKNOWN);
- assertEquals(2, sessionRepository.getLocalSessions().size()); // Still 2, no new local session
+ assertEquals(2, sessionRepository.getLocalSessions().size()); // Still 2, no new local session
// Check that trying to expire local session when there exists a local session without any data in zookeeper
// should not delete session if this is a new file ...
@@ -489,8 +489,11 @@ public class ApplicationRepositoryTest {
clock.advance(Duration.ofSeconds(60));
deleteExpiredLocalSessionsAndAssertNumberOfSessions(1, tester, sessionRepository);
- // Set older created timestamp for session dir for local session without any data in zookeeper, should be deleted
- setCreatedTime(dir, Instant.now().minus(Duration.ofDays(31)));
+ // Reset clock to the time session was created, session should NOT be deleted
+ clock.setInstant(session6CreateTime);
+ deleteExpiredLocalSessionsAndAssertNumberOfSessions(1, tester, sessionRepository);
+ // Advance time, session SHOULD be deleted
+ clock.advance(Duration.ofHours(configserverConfig.keepSessionsWithUnknownStatusHours()).plus(Duration.ofMinutes(1)));
deleteExpiredLocalSessionsAndAssertNumberOfSessions(0, tester, sessionRepository);
}
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java
index 3f329894cef..c3766ad9b83 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java
@@ -58,14 +58,14 @@ public class SuperModelRequestHandlerTest {
assertNotNull(controller.getHandler());
long gen = counter.get();
- controller.reloadConfig(createApp(foo, 3L));
+ controller.activateConfig(createApp(foo, 3L));
assertNotNull(controller.getHandler());
assertEquals(gen + 1, controller.getHandler().getGeneration());
- controller.reloadConfig(createApp(foo, 4L));
+ controller.activateConfig(createApp(foo, 4L));
assertEquals(gen + 2, controller.getHandler().getGeneration());
// Test that a new app is used when there already exist an application with the same id
assertEquals(4, controller.getHandler().getSuperModel().applicationModels().get(foo).getGeneration());
- controller.reloadConfig(createApp(bar, 2L));
+ controller.activateConfig(createApp(bar, 2L));
assertEquals(gen + 3, controller.getHandler().getGeneration());
}
@@ -76,9 +76,9 @@ public class SuperModelRequestHandlerTest {
ApplicationId baz = applicationId("b", "baz");
long gen = counter.get();
- controller.reloadConfig(createApp(foo, 3L));
- controller.reloadConfig(createApp(bar, 30L));
- controller.reloadConfig(createApp(baz, 9L));
+ controller.activateConfig(createApp(foo, 3L));
+ controller.activateConfig(createApp(bar, 30L));
+ controller.activateConfig(createApp(baz, 9L));
assertEquals(gen + 3, controller.getHandler().getGeneration());
assertEquals(3, controller.getHandler().getSuperModel().applicationModels().size());
assertTrue(controller.getHandler().getSuperModel().applicationModels().keySet().containsAll(List.of(foo, bar, baz)));
@@ -101,7 +101,7 @@ public class SuperModelRequestHandlerTest {
controller = new SuperModelRequestHandler(new TestConfigDefinitionRepo(), configserverConfig, manager);
long gen = counter.get();
- controller.reloadConfig(createApp(foo, 3L));
+ controller.activateConfig(createApp(foo, 3L));
assertEquals(masterGen + gen + 1, controller.getHandler().getGeneration());
}
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java
index abb8f9a9df3..85e64b4a32d 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java
@@ -3,7 +3,6 @@ package com.yahoo.vespa.config.server.application;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.component.Version;
-import com.yahoo.component.Vtag;
import com.yahoo.concurrent.InThreadExecutorService;
import com.yahoo.concurrent.StripedExecutor;
import com.yahoo.config.model.NullConfigModelRegistry;
@@ -14,7 +13,7 @@ import com.yahoo.config.provision.TenantName;
import com.yahoo.text.Utf8;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.server.ConfigServerDB;
-import com.yahoo.vespa.config.server.ReloadListener;
+import com.yahoo.vespa.config.server.ConfigActivationListener;
import com.yahoo.vespa.config.server.ServerCache;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
import com.yahoo.vespa.config.server.host.HostRegistry;
@@ -51,8 +50,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Function;
-import java.util.function.Supplier;
import java.util.stream.IntStream;
import static com.yahoo.vespa.config.server.application.TenantApplications.RemoveApplicationWaiter;
@@ -195,14 +192,14 @@ public class TenantApplicationsTest {
assertTrue("Node is compatible after upgrading", applications.compatibleWith(Optional.of(nodeVersion1), app1));
}
- public static class MockReloadListener implements ReloadListener {
- public final AtomicInteger reloaded = new AtomicInteger(0);
+ public static class MockConfigActivationListener implements ConfigActivationListener {
+ public final AtomicInteger activated = new AtomicInteger(0);
final AtomicInteger removed = new AtomicInteger(0);
final Map<String, Collection<String>> tenantHosts = new LinkedHashMap<>();
@Override
public void configActivated(ApplicationSet application) {
- reloaded.incrementAndGet();
+ activated.incrementAndGet();
}
@Override
@@ -222,7 +219,7 @@ public class TenantApplicationsTest {
@Test
public void testListConfigs() throws IOException, SAXException {
- TenantApplications applications = createTenantApplications(TenantName.defaultName(), new MockCurator(), configserverConfig, new MockReloadListener(), new InMemoryFlagSource());
+ TenantApplications applications = createTenantApplications(TenantName.defaultName(), new MockCurator(), configserverConfig, new MockConfigActivationListener(), new InMemoryFlagSource());
assertFalse(applications.hasApplication(ApplicationId.defaultId(), Optional.of(vespaVersion)));
VespaModel model = new VespaModel(FilesApplicationPackage.fromFile(new File("src/test/apps/app")));
@@ -250,11 +247,11 @@ public class TenantApplicationsTest {
@Test
public void testAppendIdsInNonRecursiveListing() {
- TenantApplications applications = createTenantApplications(tenantName, curator, configserverConfig, new MockReloadListener(), new InMemoryFlagSource());
- assertEquals(applications.appendOneLevelOfId("search/music", "search/music/qrservers/default/qr.0"), "search/music/qrservers");
- assertEquals(applications.appendOneLevelOfId("search", "search/music/qrservers/default/qr.0"), "search/music");
- assertEquals(applications.appendOneLevelOfId("search/music/qrservers/default/qr.0", "search/music/qrservers/default/qr.0"), "search/music/qrservers/default/qr.0");
- assertEquals(applications.appendOneLevelOfId("", "search/music/qrservers/default/qr.0"), "search");
+ TenantApplications applications = createTenantApplications(tenantName, curator, configserverConfig, new MockConfigActivationListener(), new InMemoryFlagSource());
+ assertEquals(applications.appendOneLevelOfId("search/music", "search/music/container/default/qr.0"), "search/music/container");
+ assertEquals(applications.appendOneLevelOfId("search", "search/music/container/default/qr.0"), "search/music");
+ assertEquals(applications.appendOneLevelOfId("search/music/container/default/qr.0", "search/music/container/default/qr.0"), "search/music/container/default/qr.0");
+ assertEquals(applications.appendOneLevelOfId("", "search/music/container/default/qr.0"), "search");
}
@Test
@@ -297,7 +294,7 @@ public class TenantApplicationsTest {
}
private TenantApplications createZKAppRepo(InMemoryFlagSource flagSource) {
- return createTenantApplications(tenantName, curator, configserverConfig, new MockReloadListener(), flagSource);
+ return createTenantApplications(tenantName, curator, configserverConfig, new MockConfigActivationListener(), flagSource);
}
private static ApplicationId createApplicationId() {
@@ -328,15 +325,15 @@ public class TenantApplicationsTest {
// For testing only
private TenantApplications createTenantApplications(TenantName tenantName,
- Curator curator,
- ConfigserverConfig configserverConfig,
- ReloadListener reloadListener, InMemoryFlagSource flagSource) {
+ Curator curator,
+ ConfigserverConfig configserverConfig,
+ ConfigActivationListener configActivationListener, InMemoryFlagSource flagSource) {
return new TenantApplications(tenantName,
curator,
new StripedExecutor<>(new InThreadExecutorService()),
new InThreadExecutorService(),
Metrics.createTestMetrics(),
- reloadListener,
+ configActivationListener,
configserverConfig,
new HostRegistry(),
new TenantFileSystemDirs(new ConfigServerDB(configserverConfig), tenantName),
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/ZooKeeperClientTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/ZooKeeperClientTest.java
index 41ac081f68b..fd6440a9632 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/ZooKeeperClientTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/ZooKeeperClientTest.java
@@ -57,8 +57,7 @@ public class ZooKeeperClientTest {
zk = new MockCurator();
ZooKeeperClient zkc = new ZooKeeperClient(zk, new BaseDeployLogger(), appPath);
ApplicationPackage app = FilesApplicationPackage.fromFileWithDeployData(new File("src/test/apps/zkfeed"),
- new DeployData("foo",
- "/bar/baz",
+ new DeployData("/bar/baz",
ApplicationId.from("default", "appName", "default"),
1345L,
true,
@@ -121,7 +120,6 @@ public class ZooKeeperClientTest {
Utf8.toString(zk.getData(appPath.append(META_ZK_PATH)).get()));
assertTrue(metaData.getChecksum().length() > 0);
assertTrue(metaData.isInternalRedeploy());
- assertEquals("foo", metaData.getDeployedByUser());
assertEquals("/bar/baz", metaData.getDeployPath());
assertEquals(1345, metaData.getDeployTimestamp().longValue());
assertEquals(3, metaData.getGeneration().longValue());
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/filedistribution/FileServerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/filedistribution/FileServerTest.java
index 67c40f94b6a..39219471bb1 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/filedistribution/FileServerTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/filedistribution/FileServerTest.java
@@ -8,21 +8,25 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Transport;
import com.yahoo.net.HostName;
import com.yahoo.vespa.filedistribution.FileDownloader;
+import com.yahoo.vespa.filedistribution.FileReferenceCompressor;
import com.yahoo.vespa.filedistribution.FileReferenceData;
import com.yahoo.vespa.filedistribution.FileReferenceDownload;
+import com.yahoo.vespa.flags.InMemoryFlagSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.lz4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -37,7 +41,7 @@ public class FileServerTest {
@Before
public void setup() throws IOException {
File rootDir = new File(temporaryFolder.newFolder("fileserver-root").getAbsolutePath());
- fileServer = new FileServer(rootDir, new MockFileDownloader(rootDir));
+ fileServer = new FileServer(rootDir, new MockFileDownloader(rootDir), List.of(gzip, lz4));
}
@Test
@@ -75,11 +79,30 @@ public class FileServerTest {
File dir = getFileServerRootDir();
IOUtils.writeFile(dir + "/12y/f1", "dummy-data", true);
CompletableFuture<byte []> content = new CompletableFuture<>();
- fileServer.startFileServing("12y", new FileReceiver(content));
+ fileServer.startFileServing(new FileReference("12y"), new FileReceiver(content), Set.of(gzip));
assertEquals(new String(content.get()), "dummy-data");
}
@Test
+ public void requireThatWeCanReplayDirWithLz4() throws IOException, InterruptedException, ExecutionException {
+ File rootDir = new File(temporaryFolder.newFolder("fileserver-root-3").getAbsolutePath());
+ fileServer = new FileServer(rootDir, new MockFileDownloader(rootDir), List.of(lz4, gzip)); // prefer lz4
+ File dir = getFileServerRootDir();
+ IOUtils.writeFile(dir + "/subdir/12z/f1", "dummy-data-2", true);
+ CompletableFuture<byte []> content = new CompletableFuture<>();
+ fileServer.startFileServing(new FileReference("subdir"), new FileReceiver(content), Set.of(gzip, lz4));
+
+ // Decompress with lz4 and check contents
+ var compressor = new FileReferenceCompressor(FileReferenceData.Type.compressed, lz4);
+ File downloadedFileCompressed = new File(dir + "/downloaded-file-compressed");
+ IOUtils.writeFile(downloadedFileCompressed, content.get());
+ File downloadedFileUncompressed = new File(dir + "/downloaded-file-uncompressed");
+ compressor.decompress(downloadedFileCompressed, downloadedFileUncompressed);
+ assertTrue(downloadedFileUncompressed.isDirectory());
+ assertEquals("dummy-data-2", IOUtils.readFile(new File(downloadedFileUncompressed, "12z/f1")));
+ }
+
+ @Test
public void requireThatDifferentNumberOfConfigServersWork() throws IOException {
// Empty connection pool in tests etc.
ConfigserverConfig.Builder builder = new ConfigserverConfig.Builder()
@@ -117,7 +140,7 @@ public class FileServerTest {
private FileServer createFileServer(ConfigserverConfig.Builder configBuilder) throws IOException {
File fileReferencesDir = temporaryFolder.newFolder();
configBuilder.fileReferencesDir(fileReferencesDir.getAbsolutePath());
- return new FileServer(new ConfigserverConfig(configBuilder));
+ return new FileServer(new ConfigserverConfig(configBuilder), new InMemoryFlagSource());
}
private static class FileReceiver implements FileServer.Receiver {
@@ -142,7 +165,8 @@ public class FileServerTest {
new Supervisor(new Transport("mock")).setDropEmptyBuffers(true),
downloadDirectory,
Duration.ofMillis(100),
- Duration.ofMillis(100));
+ Duration.ofMillis(100),
+ Set.of(gzip));
}
}
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcServerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcServerTest.java
index 7ad237e45ed..8607fc0e2dc 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcServerTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcServerTest.java
@@ -5,6 +5,7 @@ import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.cloud.config.LbServicesConfig;
import com.yahoo.cloud.config.SentinelConfig;
import com.yahoo.component.Version;
+import com.yahoo.config.FileReference;
import com.yahoo.config.SimpletypesConfig;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.ApplicationId;
@@ -27,16 +28,20 @@ import com.yahoo.vespa.config.server.application.Application;
import com.yahoo.vespa.config.server.application.ApplicationSet;
import com.yahoo.vespa.config.server.monitoring.MetricUpdater;
import com.yahoo.vespa.config.server.session.PrepareParams;
+import com.yahoo.vespa.filedistribution.LazyFileReferenceData;
import com.yahoo.vespa.model.VespaModel;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.xml.sax.SAXException;
-
import java.io.File;
import java.io.IOException;
import java.util.Optional;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.lz4;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.compressed;
+import static com.yahoo.vespa.config.server.rpc.RpcServer.ChunkedFileReceiver.createMetaRequest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -97,6 +102,25 @@ public class RpcServerTest {
}
}
+ @Test
+ public void testFileReceiverMetaRequest() throws IOException {
+ File file = temporaryFolder.newFile();
+ Request request = createMetaRequest(new LazyFileReferenceData(new FileReference("foo"), "fileA", compressed, file, gzip));
+ assertEquals(4, request.parameters().size());
+ assertEquals("foo", request.parameters().get(0).asString());
+ assertEquals("fileA", request.parameters().get(1).asString());
+ assertEquals("compressed", request.parameters().get(2).asString());
+ assertEquals(0, request.parameters().get(3).asInt64());
+
+ request = createMetaRequest(new LazyFileReferenceData(new FileReference("foo"), "fileA", compressed, file, lz4));
+ assertEquals(5, request.parameters().size());
+ assertEquals("foo", request.parameters().get(0).asString());
+ assertEquals("fileA", request.parameters().get(1).asString());
+ assertEquals("compressed", request.parameters().get(2).asString());
+ assertEquals(0, request.parameters().get(3).asInt64());
+ assertEquals("lz4", request.parameters().get(4).asString());
+ }
+
private JRTClientConfigRequest createSimpleRequest() {
ConfigKey<?> key = new ConfigKey<>(SimpletypesConfig.class, "");
JRTClientConfigRequest clientReq = createRequest(new RawConfig(key, SimpletypesConfig.getDefMd5()));
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcTester.java b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcTester.java
index 40ed20b7969..441f6c3a6ce 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcTester.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/RpcTester.java
@@ -166,7 +166,7 @@ public class RpcTester implements AutoCloseable {
void performRequest(Request req) {
clock.advance(Duration.ofMillis(10));
- sup.connect(spec).invokeSync(req, 10.0);
+ sup.connect(spec).invokeSync(req, Duration.ofSeconds(10));
if (req.methodName().equals(RpcServer.getConfigMethodName))
assertEquals(clock.instant(), hostLivenessTracker.lastRequestFrom(myHostname).get());
}
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizerTest.java
index 2650b23a38e..2ab959fcaa0 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizerTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/security/MultiTenantRpcAuthorizerTest.java
@@ -11,7 +11,6 @@ import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.config.provision.security.NodeIdentifierException;
import com.yahoo.config.provision.security.NodeIdentity;
import com.yahoo.jrt.Request;
-import com.yahoo.jrt.SecurityContext;
import com.yahoo.jrt.StringValue;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.Values;
@@ -19,6 +18,9 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
+import com.yahoo.security.tls.CapabilityMode;
+import com.yahoo.security.tls.CapabilitySet;
+import com.yahoo.security.tls.ConnectionAuthContext;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.JsonFormat;
import com.yahoo.slime.Slime;
@@ -248,10 +250,10 @@ public class MultiTenantRpcAuthorizerTest {
}
private static Request mockJrtRpcRequest(String payload) {
- SecurityContext securityContext = mock(SecurityContext.class);
- when(securityContext.peerCertificateChain()).thenReturn(PEER_CERTIFICATE_CHAIN);
+ ConnectionAuthContext authContext =
+ new ConnectionAuthContext(PEER_CERTIFICATE_CHAIN, CapabilitySet.all(), Set.of(), CapabilityMode.ENFORCE);
Target target = mock(Target.class);
- when(target.getSecurityContext()).thenReturn(Optional.of(securityContext));
+ when(target.connectionAuthContext()).thenReturn(authContext);
Request request = mock(Request.class);
when(request.target()).thenReturn(target);
Values values = new Values();
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java
index 86f8dc03af3..1960ba43747 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java
@@ -6,7 +6,6 @@ import com.yahoo.cloud.config.ZookeeperServerConfig;
import com.yahoo.component.Version;
import com.yahoo.concurrent.InThreadExecutorService;
import com.yahoo.concurrent.StripedExecutor;
-import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
@@ -59,7 +58,7 @@ public class TenantRepositoryTest {
private static final TenantName tenant3 = TenantName.from("tenant3");
private TenantRepository tenantRepository;
- private TenantApplicationsTest.MockReloadListener listener;
+ private TenantApplicationsTest.MockConfigActivationListener listener;
private MockTenantListener tenantListener;
private Curator curator;
private ConfigserverConfig configserverConfig;
@@ -74,7 +73,7 @@ public class TenantRepositoryTest {
@Before
public void setupSessions() throws IOException {
curator = new MockCurator();
- listener = new TenantApplicationsTest.MockReloadListener();
+ listener = new TenantApplicationsTest.MockConfigActivationListener();
tenantListener = new MockTenantListener();
assertFalse(tenantListener.tenantsLoaded);
configserverConfig = new ConfigserverConfig.Builder()
@@ -83,7 +82,7 @@ public class TenantRepositoryTest {
.build();
tenantRepository = new TestTenantRepository.Builder().withConfigserverConfig(configserverConfig)
.withCurator(curator)
- .withReloadListener(listener)
+ .withConfigActivationListener(listener)
.withTenantListener(tenantListener)
.build();
assertTrue(tenantListener.tenantsLoaded);
@@ -115,7 +114,7 @@ public class TenantRepositoryTest {
MetricUpdater.createTestUpdater(),
id)),
4);
- assertEquals(1, listener.reloaded.get());
+ assertEquals(1, listener.activated.get());
}
@Test
@@ -224,7 +223,7 @@ public class TenantRepositoryTest {
Clock.systemUTC(),
new ModelFactoryRegistry(List.of(VespaModelFactory.createTestFactory())),
new TestConfigDefinitionRepo(),
- new TenantApplicationsTest.MockReloadListener(),
+ new TenantApplicationsTest.MockConfigActivationListener(),
new MockTenantListener(),
new ZookeeperServerConfig.Builder().myid(0).build());
}
diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TestTenantRepository.java b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TestTenantRepository.java
index 42bb62b06c2..b8c46c2bdc4 100644
--- a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TestTenantRepository.java
+++ b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TestTenantRepository.java
@@ -5,12 +5,11 @@ import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.cloud.config.ZookeeperServerConfig;
import com.yahoo.concurrent.InThreadExecutorService;
import com.yahoo.concurrent.StripedExecutor;
-import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.api.ConfigDefinitionRepo;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.config.server.ConfigServerDB;
import com.yahoo.vespa.config.server.MockSecretStore;
-import com.yahoo.vespa.config.server.ReloadListener;
+import com.yahoo.vespa.config.server.ConfigActivationListener;
import com.yahoo.vespa.config.server.TestConfigDefinitionRepo;
import com.yahoo.vespa.config.server.application.TenantApplicationsTest;
import com.yahoo.vespa.config.server.filedistribution.FileDistributionFactory;
@@ -44,7 +43,7 @@ public class TestTenantRepository extends TenantRepository {
Clock clock,
ModelFactoryRegistry modelFactoryRegistry,
ConfigDefinitionRepo configDefinitionRepo,
- ReloadListener reloadListener,
+ ConfigActivationListener configActivationListener,
TenantListener tenantListener) {
super(hostRegistry,
curator,
@@ -62,7 +61,7 @@ public class TestTenantRepository extends TenantRepository {
clock,
modelFactoryRegistry,
configDefinitionRepo,
- reloadListener,
+ configActivationListener,
tenantListener,
new ZookeeperServerConfig.Builder().myid(0).build());
}
@@ -78,7 +77,7 @@ public class TestTenantRepository extends TenantRepository {
HostProvisionerProvider hostProvisionerProvider = HostProvisionerProvider.empty();
ModelFactoryRegistry modelFactoryRegistry = new ModelFactoryRegistry(List.of(VespaModelFactory.createTestFactory()));
ConfigserverConfig configserverConfig = new ConfigserverConfig.Builder().build();
- ReloadListener reloadListener = new TenantApplicationsTest.MockReloadListener();
+ ConfigActivationListener configActivationListener = new TenantApplicationsTest.MockConfigActivationListener();
TenantListener tenantListener = new MockTenantListener();
Zone zone = Zone.defaultZone();
@@ -127,8 +126,8 @@ public class TestTenantRepository extends TenantRepository {
return this;
}
- public Builder withReloadListener(ReloadListener reloadListener) {
- this.reloadListener = reloadListener;
+ public Builder withConfigActivationListener(ConfigActivationListener configActivationListener) {
+ this.configActivationListener = configActivationListener;
return this;
}
@@ -156,7 +155,7 @@ public class TestTenantRepository extends TenantRepository {
clock,
modelFactoryRegistry,
configDefinitionRepo,
- reloadListener,
+ configActivationListener,
tenantListener);
}
diff --git a/container-core/abi-spec.json b/container-core/abi-spec.json
index 12949be12b1..9c14c03ba21 100644
--- a/container-core/abi-spec.json
+++ b/container-core/abi-spec.json
@@ -1091,6 +1091,8 @@
"public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder enable(boolean)",
"public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder port(int)",
"public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder clientTimeout(double)",
+ "public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder handlerTimeout(double)",
+ "public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder cacheExpiry(double)",
"public com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy build()"
],
"fields": []
@@ -1106,7 +1108,9 @@
"public void <init>(com.yahoo.jdisc.http.ConnectorConfig$HealthCheckProxy$Builder)",
"public boolean enable()",
"public int port()",
- "public double clientTimeout()"
+ "public double clientTimeout()",
+ "public double handlerTimeout()",
+ "public double cacheExpiry()"
],
"fields": []
},
diff --git a/container-core/pom.xml b/container-core/pom.xml
index ed1ec8adca2..ed4b05495e3 100644
--- a/container-core/pom.xml
+++ b/container-core/pom.xml
@@ -256,12 +256,6 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
@@ -275,7 +269,7 @@
<!-- TEST scope -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-standalone</artifactId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -283,11 +277,12 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@@ -310,11 +305,6 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
diff --git a/container-core/src/main/java/com/yahoo/component/chain/model/ChainSpecification.java b/container-core/src/main/java/com/yahoo/component/chain/model/ChainSpecification.java
index a1c169dc387..f53b431265c 100644
--- a/container-core/src/main/java/com/yahoo/component/chain/model/ChainSpecification.java
+++ b/container-core/src/main/java/com/yahoo/component/chain/model/ChainSpecification.java
@@ -6,7 +6,15 @@ import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.component.chain.Phase;
-import java.util.*;
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+
/**
* Specifies how the components should be selected to create a chain. Immutable.
@@ -20,7 +28,7 @@ public class ChainSpecification {
public final Set<ComponentSpecification> excludedComponents;
Inheritance flattened() {
- return new Inheritance(Collections.<ComponentSpecification>emptySet(), excludedComponents);
+ return new Inheritance(Set.of(), excludedComponents);
}
public Inheritance(Set<ComponentSpecification> inheritedChains, Set<ComponentSpecification> excludedComponents) {
@@ -38,7 +46,7 @@ public class ChainSpecification {
public final ComponentId componentId;
public final Inheritance inheritance;
- final Map<String, Phase> phases;
+ private final Map<String, Phase> phases;
public final Set<ComponentSpecification> componentReferences;
public ChainSpecification(ComponentId componentId, Inheritance inheritance,
diff --git a/container-core/src/main/java/com/yahoo/container/bundle/BundleInstantiationSpecification.java b/container-core/src/main/java/com/yahoo/container/bundle/BundleInstantiationSpecification.java
index d61df4310f0..926c67df0ba 100644
--- a/container-core/src/main/java/com/yahoo/container/bundle/BundleInstantiationSpecification.java
+++ b/container-core/src/main/java/com/yahoo/container/bundle/BundleInstantiationSpecification.java
@@ -14,6 +14,8 @@ import com.yahoo.component.ComponentSpecification;
*/
public final class BundleInstantiationSpecification {
+ public static final String CONTAINER_SEARCH_AND_DOCPROC = "container-search-and-docproc";
+
public final ComponentId id;
public final ComponentSpecification classId;
public final ComponentSpecification bundle;
@@ -31,34 +33,21 @@ public final class BundleInstantiationSpecification {
assert (classId!= null);
}
- private static final String defaultInternalBundle = "container-search-and-docproc";
-
- private static BundleInstantiationSpecification getInternalSpecificationFromString(String idSpec, String classSpec) {
- return new BundleInstantiationSpecification(
- new ComponentSpecification(idSpec),
- (classSpec == null || classSpec.isEmpty())? null : new ComponentSpecification(classSpec),
- new ComponentSpecification(defaultInternalBundle));
- }
-
- public static BundleInstantiationSpecification getInternalSearcherSpecification(ComponentSpecification idSpec,
- ComponentSpecification classSpec) {
- return new BundleInstantiationSpecification(idSpec, classSpec, new ComponentSpecification(defaultInternalBundle));
- }
-
- // TODO: These are the same for now because they are in the same bundle.
- public static BundleInstantiationSpecification getInternalHandlerSpecificationFromStrings(String idSpec, String classSpec) {
- return getInternalSpecificationFromString(idSpec, classSpec);
- }
-
- public static BundleInstantiationSpecification getInternalProcessingSpecificationFromStrings(String idSpec, String classSpec) {
- return getInternalSpecificationFromString(idSpec, classSpec);
+ /**
+ * Create spec for a component from the container-search-and-docproc bundle with the given class name as id.
+ */
+ public static BundleInstantiationSpecification fromSearchAndDocproc(String className) {
+ return fromSearchAndDocproc(new ComponentSpecification(className), null);
}
- public static BundleInstantiationSpecification getInternalSearcherSpecificationFromStrings(String idSpec, String classSpec) {
- return getInternalSpecificationFromString(idSpec, classSpec);
+ /**
+ * Create spec for a component from the container-search-and-docproc bundle with the given id and classId.
+ */
+ public static BundleInstantiationSpecification fromSearchAndDocproc(ComponentSpecification id, ComponentSpecification classId) {
+ return new BundleInstantiationSpecification(id, classId, new ComponentSpecification(CONTAINER_SEARCH_AND_DOCPROC));
}
- public static BundleInstantiationSpecification getFromStrings(String idSpec, String classSpec, String bundleSpec) {
+ public static BundleInstantiationSpecification fromStrings(String idSpec, String classSpec, String bundleSpec) {
return new BundleInstantiationSpecification(
new ComponentSpecification(idSpec),
(classSpec == null || classSpec.isEmpty())? null : new ComponentSpecification(classSpec),
diff --git a/container-core/src/main/java/com/yahoo/container/di/Container.java b/container-core/src/main/java/com/yahoo/container/di/Container.java
index 68dda5fbc4c..1baf217da6b 100644
--- a/container-core/src/main/java/com/yahoo/container/di/Container.java
+++ b/container-core/src/main/java/com/yahoo/container/di/Container.java
@@ -299,7 +299,7 @@ public class Container {
}
private static BundleInstantiationSpecification bundleInstantiationSpecification(ComponentsConfig.Components config) {
- return BundleInstantiationSpecification.getFromStrings(config.id(), config.classId(), config.bundle());
+ return BundleInstantiationSpecification.fromStrings(config.id(), config.classId(), config.bundle());
}
public static class ComponentGraphResult {
diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandler.java b/container-core/src/main/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandler.java
index 11355dee24f..fb7ba1ab39e 100644
--- a/container-core/src/main/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandler.java
+++ b/container-core/src/main/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandler.java
@@ -50,7 +50,7 @@ public abstract class ThreadedHttpRequestHandler extends ThreadedRequestHandler
this(executor, metric, false);
}
- // TODO: move Inject annotation here!
+ // TODO: deprecate this and the Context class. The context component set up in the model does not get a dedicated thread pool.
public ThreadedHttpRequestHandler(Context context) {
this(context.executor, context.metric);
}
diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java b/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java
index b949edefb31..8fa658bf7fc 100644
--- a/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java
+++ b/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java
@@ -22,9 +22,9 @@ import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import static com.yahoo.container.jdisc.state.JsonUtil.sanitizeDouble;
@@ -61,6 +61,7 @@ public class MetricsPacketsHandler extends AbstractRequestHandler {
private final Timer timer;
private final SnapshotProvider snapshotProvider;
private final String applicationName;
+ private final String hostDimension;
@Inject
public MetricsPacketsHandler(StateMonitor monitor,
@@ -71,6 +72,7 @@ public class MetricsPacketsHandler extends AbstractRequestHandler {
this.timer = timer;
snapshotProvider = getSnapshotProviderOrThrow(snapshotProviders);
applicationName = config.application();
+ hostDimension = config.hostname();
}
@@ -173,16 +175,16 @@ public class MetricsPacketsHandler extends AbstractRequestHandler {
}
private void addDimensions(MetricDimensions metricDimensions, ObjectNode packet) {
- if (metricDimensions == null) return;
-
- Iterator<Map.Entry<String, String>> dimensionsIterator = metricDimensions.iterator();
- if (dimensionsIterator.hasNext()) {
- ObjectNode jsonDim = jsonMapper.createObjectNode();
- packet.set(DIMENSIONS_KEY, jsonDim);
- for (Map.Entry<String, String> dimensionEntry : metricDimensions) {
- jsonDim.put(dimensionEntry.getKey(), dimensionEntry.getValue());
- }
+ if (metricDimensions == null && hostDimension.isEmpty()) return;
+
+ ObjectNode jsonDim = jsonMapper.createObjectNode();
+ packet.set(DIMENSIONS_KEY, jsonDim);
+ Iterable<Map.Entry<String, String>> dimensionIterator = metricDimensions == null ? Set.of() : metricDimensions;
+ for (Map.Entry<String, String> dimensionEntry : dimensionIterator) {
+ jsonDim.put(dimensionEntry.getKey(), dimensionEntry.getValue());
}
+ if (!hostDimension.isEmpty() && !jsonDim.has("host"))
+ jsonDim.put("host", hostDimension);
}
private void addMetrics(MetricSet metricSet, ObjectNode packet) {
diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/util/FilterUtils.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/util/FilterUtils.java
index 9bf3b78a3b8..82eee394099 100644
--- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/util/FilterUtils.java
+++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/util/FilterUtils.java
@@ -64,12 +64,13 @@ public class FilterUtils {
return response;
}
- public static URI createUriFromRequest(DiscFilterRequest request, String path) {
+ public static URI createUriFromRequest(DiscFilterRequest request, String path, Optional<String> hostOverride) {
try {
// Prefer local port as observed by client over local listen port
int port = Optional.ofNullable((Integer)request.getAttribute(RequestUtils.JDICS_REQUEST_PORT))
.orElse(request.getUri().getPort());
- return new URI(request.getScheme(), null, request.getServerName(), port, path, null, null);
+ String host = hostOverride.orElse(request.getServerName());
+ return new URI(request.getScheme(), null, host, port, path, null, null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java
index ae2871e266d..18490765576 100644
--- a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java
+++ b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.http.ConnectorConfig;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.tls.TransportSecurityOptions;
import com.yahoo.security.tls.TransportSecurityUtils;
-import com.yahoo.security.tls.TrustAllX509TrustManager;
+import com.yahoo.security.TrustAllX509TrustManager;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory;
import org.eclipse.jetty.client.api.ContentResponse;
@@ -20,6 +20,8 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.AsyncContext;
+import javax.servlet.AsyncEvent;
+import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
@@ -31,9 +33,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -50,7 +53,7 @@ class HealthCheckProxyHandler extends HandlerWrapper {
private static final String HEALTH_CHECK_PATH = "/status.html";
- private final Executor executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory("health-check-proxy-client-"));
+ private final ExecutorService executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory("health-check-proxy-client-"));
private final Map<Integer, ProxyTarget> portToProxyTargetMapping;
HealthCheckProxyHandler(List<JDiscServerConnector> connectors) {
@@ -63,7 +66,11 @@ class HealthCheckProxyHandler extends HandlerWrapper {
ConnectorConfig.HealthCheckProxy proxyConfig = connector.connectorConfig().healthCheckProxy();
if (proxyConfig.enable()) {
Duration targetTimeout = Duration.ofMillis((int) (proxyConfig.clientTimeout() * 1000));
- mapping.put(connector.listenPort(), createProxyTarget(proxyConfig.port(), targetTimeout, connectors));
+ Duration handlerTimeout = Duration.ofMillis((int) (proxyConfig.handlerTimeout() * 1000));
+ Duration cacheExpiry = Duration.ofMillis((int) (proxyConfig.cacheExpiry() * 1000));
+ ProxyTarget target = createProxyTarget(
+ proxyConfig.port(), targetTimeout, handlerTimeout, cacheExpiry, connectors);
+ mapping.put(connector.listenPort(), target);
log.info(String.format("Port %1$d is configured as a health check proxy for port %2$d. " +
"HTTP requests to '%3$s' on %1$d are proxied as HTTPS to %2$d.",
connector.listenPort(), proxyConfig.port(), HEALTH_CHECK_PATH));
@@ -72,7 +79,8 @@ class HealthCheckProxyHandler extends HandlerWrapper {
return mapping;
}
- private static ProxyTarget createProxyTarget(int targetPort, Duration targetTimeout, List<JDiscServerConnector> connectors) {
+ private static ProxyTarget createProxyTarget(int targetPort, Duration clientTimeout, Duration handlerTimeout,
+ Duration cacheExpiry, List<JDiscServerConnector> connectors) {
JDiscServerConnector targetConnector = connectors.stream()
.filter(connector -> connector.listenPort() == targetPort)
.findAny()
@@ -85,7 +93,7 @@ class HealthCheckProxyHandler extends HandlerWrapper {
.orElseThrow(() -> new IllegalArgumentException("Health check proxy can only target https port"));
ConnectorConfig.ProxyProtocol proxyProtocolCfg = targetConnector.connectorConfig().proxyProtocol();
boolean proxyProtocol = proxyProtocolCfg.enabled() && !proxyProtocolCfg.mixedMode();
- return new ProxyTarget(targetPort, targetTimeout, sslContextFactory, proxyProtocol);
+ return new ProxyTarget(targetPort, clientTimeout,handlerTimeout, cacheExpiry, sslContextFactory, proxyProtocol);
}
@Override
@@ -96,7 +104,35 @@ class HealthCheckProxyHandler extends HandlerWrapper {
AsyncContext asyncContext = servletRequest.startAsync();
ServletOutputStream out = servletResponse.getOutputStream();
if (servletRequest.getRequestURI().equals(HEALTH_CHECK_PATH)) {
- executor.execute(new ProxyRequestTask(asyncContext, proxyTarget, servletResponse, out));
+ ProxyRequestTask task = new ProxyRequestTask(asyncContext, proxyTarget, servletResponse, out);
+ asyncContext.setTimeout(proxyTarget.handlerTimeout.toMillis());
+ asyncContext.addListener(new AsyncListener() {
+ @Override public void onStartAsync(AsyncEvent event) {}
+ @Override public void onComplete(AsyncEvent event) {}
+
+ @Override
+ public void onError(AsyncEvent event) {
+ log.log(Level.FINE, event.getThrowable(), () -> "AsyncListener.onError()");
+ synchronized (task.monitor) {
+ if (task.state == ProxyRequestTask.State.DONE) return;
+ task.state = ProxyRequestTask.State.DONE;
+ servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ asyncContext.complete();
+ }
+ }
+
+ @Override
+ public void onTimeout(AsyncEvent event) {
+ log.log(Level.FINE, event.getThrowable(), () -> "AsyncListener.onTimeout()");
+ synchronized (task.monitor) {
+ if (task.state == ProxyRequestTask.State.DONE) return;
+ task.state = ProxyRequestTask.State.DONE;
+ servletResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
+ asyncContext.complete();
+ }
+ }
+ });
+ executor.execute(task);
} else {
servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
asyncContext.complete();
@@ -109,6 +145,10 @@ class HealthCheckProxyHandler extends HandlerWrapper {
@Override
protected void doStop() throws Exception {
+ executor.shutdown();
+ if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
+ log.warning("Failed to shutdown executor in time");
+ }
for (ProxyTarget target : portToProxyTargetMapping.values()) {
target.close();
}
@@ -117,10 +157,14 @@ class HealthCheckProxyHandler extends HandlerWrapper {
private static class ProxyRequestTask implements Runnable {
+ enum State { INITIALIZED, DONE }
+
+ final Object monitor = new Object();
final AsyncContext asyncContext;
final ProxyTarget target;
final HttpServletResponse servletResponse;
final ServletOutputStream output;
+ State state = State.INITIALIZED;
ProxyRequestTask(AsyncContext asyncContext, ProxyTarget target, HttpServletResponse servletResponse, ServletOutputStream output) {
this.asyncContext = asyncContext;
@@ -131,27 +175,38 @@ class HealthCheckProxyHandler extends HandlerWrapper {
@Override
public void run() {
+ synchronized (monitor) { if (state == State.DONE) return; }
StatusResponse statusResponse = target.requestStatusHtml();
- servletResponse.setStatus(statusResponse.statusCode);
- if (statusResponse.contentType != null) {
- servletResponse.setHeader("Content-Type", statusResponse.contentType);
- }
- servletResponse.setHeader("Vespa-Health-Check-Proxy-Target", Integer.toString(target.port));
+ synchronized (monitor) { if (state == State.DONE) return; }
output.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
if (output.isReady()) {
- if (statusResponse.content != null) {
- output.write(statusResponse.content);
+ synchronized (monitor) {
+ if (state == State.DONE) return;
+ servletResponse.setStatus(statusResponse.statusCode);
+ if (statusResponse.contentType != null) {
+ servletResponse.setHeader("Content-Type", statusResponse.contentType);
+ }
+ servletResponse.setHeader("Vespa-Health-Check-Proxy-Target", Integer.toString(target.port));
+ if (statusResponse.content != null) {
+ output.write(statusResponse.content);
+ }
+ state = State.DONE;
+ asyncContext.complete();
}
- asyncContext.complete();
}
}
@Override
public void onError(Throwable t) {
log.log(Level.FINE, t, () -> "Failed to write status response: " + t.getMessage());
- asyncContext.complete();
+ synchronized (monitor) {
+ if (state == State.DONE) return;
+ state = State.DONE;
+ servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ asyncContext.complete();
+ }
}
});
}
@@ -159,22 +214,27 @@ class HealthCheckProxyHandler extends HandlerWrapper {
private static class ProxyTarget implements AutoCloseable {
final int port;
- final Duration timeout;
+ final Duration clientTimeout;
+ final Duration handlerTimeout;
+ final Duration cacheExpiry;
final SslContextFactory.Server serverSsl;
final boolean proxyProtocol;
volatile HttpClient client;
volatile StatusResponse lastResponse;
- ProxyTarget(int port, Duration timeout, SslContextFactory.Server serverSsl, boolean proxyProtocol) {
+ ProxyTarget(int port, Duration clientTimeout, Duration handlerTimeout, Duration cacheExpiry,
+ SslContextFactory.Server serverSsl, boolean proxyProtocol) {
this.port = port;
- this.timeout = timeout;
+ this.clientTimeout = clientTimeout;
+ this.cacheExpiry = cacheExpiry;
this.serverSsl = serverSsl;
this.proxyProtocol = proxyProtocol;
+ this.handlerTimeout = handlerTimeout;
}
StatusResponse requestStatusHtml() {
StatusResponse response = lastResponse;
- if (response != null && !response.isExpired()) {
+ if (response != null && !response.isExpired(cacheExpiry)) {
return response;
}
return this.lastResponse = getStatusResponse();
@@ -183,8 +243,8 @@ class HealthCheckProxyHandler extends HandlerWrapper {
private StatusResponse getStatusResponse() {
try {
var request = client().newRequest("https://localhost:" + port + HEALTH_CHECK_PATH);
- request.timeout(timeout.toMillis(), TimeUnit.MILLISECONDS);
- request.idleTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS);
+ request.timeout(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
+ request.idleTimeout(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
if (proxyProtocol) {
request.tag(new ProxyProtocolClientConnectionFactory.V1.Tag());
}
@@ -195,8 +255,11 @@ class HealthCheckProxyHandler extends HandlerWrapper {
} else {
return new StatusResponse(response.getStatus(), null, null);
}
+ } catch (TimeoutException e) {
+ log.log(Level.FINE, e, () -> "Proxy request timeout ('" + e.getMessage() + "')");
+ return new StatusResponse(503, null, null);
} catch (Exception e) {
- log.log(Level.FINE, e, () -> "Proxy request failed" + e.getMessage());
+ log.log(Level.FINE, e, () -> "Proxy request failed ('" + e.getMessage() + "')");
return new StatusResponse(500, "text/plain", e.getMessage().getBytes());
}
}
@@ -206,7 +269,7 @@ class HealthCheckProxyHandler extends HandlerWrapper {
if (client == null) {
synchronized (this) {
if (client == null) {
- int timeoutMillis = (int) timeout.toMillis();
+ int timeoutMillis = (int) clientTimeout.toMillis();
SslContextFactory.Client clientSsl = new SslContextFactory.Client();
clientSsl.setHostnameVerifier((__, ___) -> true);
clientSsl.setSslContext(getSslContext(serverSsl));
@@ -271,6 +334,6 @@ class HealthCheckProxyHandler extends HandlerWrapper {
this.content = content;
}
- boolean isExpired() { return System.nanoTime() - createdAt > Duration.ofSeconds(1).toNanos(); }
+ boolean isExpired(Duration expiry) { return System.nanoTime() - createdAt > expiry.toNanos(); }
}
}
diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/ssl/impl/ConfiguredSslContextFactoryProvider.java b/container-core/src/main/java/com/yahoo/jdisc/http/ssl/impl/ConfiguredSslContextFactoryProvider.java
index 05a013c036e..27c5aff22a9 100644
--- a/container-core/src/main/java/com/yahoo/jdisc/http/ssl/impl/ConfiguredSslContextFactoryProvider.java
+++ b/container-core/src/main/java/com/yahoo/jdisc/http/ssl/impl/ConfiguredSslContextFactoryProvider.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.http.SslProvider;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.tls.AutoReloadingX509KeyManager;
+import com.yahoo.security.AutoReloadingX509KeyManager;
import com.yahoo.security.tls.TlsContext;
import javax.net.ssl.SSLContext;
diff --git a/container-core/src/main/java/com/yahoo/osgi/provider/model/ComponentModel.java b/container-core/src/main/java/com/yahoo/osgi/provider/model/ComponentModel.java
index 5bed6fbca9f..84d52bb01c3 100644
--- a/container-core/src/main/java/com/yahoo/osgi/provider/model/ComponentModel.java
+++ b/container-core/src/main/java/com/yahoo/osgi/provider/model/ComponentModel.java
@@ -26,7 +26,7 @@ public class ComponentModel {
}
public ComponentModel(String idSpec, String classSpec, String bundleSpec, String configId) {
- this(BundleInstantiationSpecification.getFromStrings(idSpec, classSpec, bundleSpec), configId);
+ this(BundleInstantiationSpecification.fromStrings(idSpec, classSpec, bundleSpec), configId);
}
// For vespamodel
@@ -36,7 +36,7 @@ public class ComponentModel {
// For vespamodel
public ComponentModel(String idSpec, String classSpec, String bundleSpec) {
- this(BundleInstantiationSpecification.getFromStrings(idSpec, classSpec, bundleSpec));
+ this(BundleInstantiationSpecification.fromStrings(idSpec, classSpec, bundleSpec));
}
public ComponentId getComponentId() {
diff --git a/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java b/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java
index efed58f4ab0..5e52f8d8b37 100644
--- a/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java
+++ b/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java
@@ -1,8 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.processing.request;
-import com.google.common.collect.ImmutableList;
-
+import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -25,7 +24,7 @@ public final class CompoundName {
private final String name;
private final String lowerCasedName;
- private final ImmutableList<String> compounds;
+ private final List<String> compounds;
/** A hashcode which is always derived from the compounds (NEVER the string) */
private final int hashCode;
@@ -42,16 +41,20 @@ public final class CompoundName {
* @throws NullPointerException if name is null
*/
public CompoundName(String name) {
- this(name, parse(name));
+ this(name, parse(name).toArray(new String[1]));
}
/** Constructs this from an array of name components which are assumed not to contain dots */
public static CompoundName fromComponents(String ... components) {
- return new CompoundName(Arrays.asList(components));
+ return new CompoundName(List.of(components));
}
/** Constructs this from a list of compounds. */
public CompoundName(List<String> compounds) {
+ this(compounds.toArray(new String[compounds.size()]));
+ }
+
+ private CompoundName(String [] compounds) {
this(toCompoundString(compounds), compounds);
}
@@ -62,25 +65,26 @@ public final class CompoundName {
* @param name the string representation of the compounds
* @param compounds the compounds of this name
*/
- private CompoundName(String name, List<String> compounds) {
+ private CompoundName(String name, String [] compounds) {
if (name == null) throw new NullPointerException("Name can not be null");
this.name = name;
this.lowerCasedName = toLowerCase(name);
- if (compounds.size() == 1 && compounds.get(0).isEmpty())
- this.compounds = ImmutableList.of();
- else
- this.compounds = ImmutableList.copyOf(compounds);
+ if (compounds.length == 1 && compounds[0].isEmpty()) {
+ this.compounds = List.of();
+ this.hashCode = 0;
+ rest = this;
+ return;
+ }
+ this.compounds = new ImmutableArrayList(compounds);
this.hashCode = this.compounds.hashCode();
- int size = this.compounds.size();
- rest = size > 1 ? new CompoundName(compounds.subList(1, size))
- : size == 1 ? empty : this; // size==0 -> this needed during construction of empty
+ rest = compounds.length > 1 ? new CompoundName(name.substring(compounds[0].length()+1), Arrays.copyOfRange(compounds, 1, compounds.length))
+ : empty;
}
private static List<String> parse(String s) {
ArrayList<String> l = null;
-
int p = 0;
final int m = s.length();
for (int i = 0; i < m; i++) {
@@ -91,7 +95,8 @@ public final class CompoundName {
}
}
if (p == 0) {
- return ImmutableList.of(s);
+ if (l == null) return List.of(s);
+ l.add(s);
} else if (p < m) {
l.add(s.substring(p, m));
} else {
@@ -107,10 +112,7 @@ public final class CompoundName {
*/
public CompoundName append(String name) {
if (name.isEmpty()) return this;
- if (isEmpty()) return new CompoundName(name);
- List<String> newCompounds = new ArrayList<>(compounds);
- newCompounds.addAll(parse(name));
- return new CompoundName(concat(this.name, name), newCompounds);
+ return append(new CompoundName(name));
}
/**
@@ -121,12 +123,14 @@ public final class CompoundName {
public CompoundName append(CompoundName name) {
if (name.isEmpty()) return this;
if (isEmpty()) return name;
- List<String> newCompounds = new ArrayList<>(compounds);
- newCompounds.addAll(name.compounds);
+ String [] newCompounds = new String[compounds.size() + name.compounds.size()];
+ int count = 0;
+ for (String s : compounds) { newCompounds[count++] = s; }
+ for (String s : name.compounds) { newCompounds[count++] = s; }
return new CompoundName(concat(this.name, name.name), newCompounds);
}
- private String concat(String name1, String name2) {
+ private static String concat(String name1, String name2) {
return name1 + "." + name2;
}
@@ -215,7 +219,7 @@ public final class CompoundName {
* As an optimization, if the given name == the name component at this index, this is returned.
*/
public CompoundName set(int i, String name) {
- if (get(i) == name) return this;
+ if (get(i).equals(name)) return this;
List<String> newCompounds = new ArrayList<>(compounds);
newCompounds.set(i, name);
return new CompoundName(newCompounds);
@@ -261,11 +265,9 @@ public final class CompoundName {
public int hashCode() { return hashCode; }
@Override
- public boolean equals(Object o) {
- if (o == this) return true;
- if ( ! (o instanceof CompoundName)) return false;
- CompoundName other = (CompoundName)o;
- return this.name.equals(other.name);
+ public boolean equals(Object arg) {
+ if (arg == this) return true;
+ return (arg instanceof CompoundName o) && name.equals(o.name);
}
/**
@@ -278,13 +280,42 @@ public final class CompoundName {
return lowerCasedName;
}
- private static String toCompoundString(List<String> compounds) {
- StringBuilder b = new StringBuilder();
- for (String compound : compounds)
- b.append(compound).append(".");
+ private static String toCompoundString(String [] compounds) {
+ int all = compounds.length;
+ for (int i = 0; i < compounds.length; i++)
+ all += compounds[i].length();
+ StringBuilder b = new StringBuilder(all);
+ for (int i = 0; i < compounds.length; i++)
+ b.append(compounds[i]).append(".");
return b.length()==0 ? "" : b.substring(0, b.length()-1);
}
public static CompoundName from(String name) { return new CompoundName(name); }
+ private static class ImmutableArrayList extends AbstractList<String> {
+
+ private final String [] array;
+ ImmutableArrayList(String [] array) {
+ this.array = array;
+ }
+ @Override
+ public String get(int index) {
+ return array[index];
+ }
+
+ @Override
+ public int size() {
+ return array.length;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ for (String s : array) {
+ hashCode = hashCode ^ s.hashCode();
+ }
+ return hashCode;
+ }
+ }
+
}
diff --git a/container-core/src/main/resources/configdefinitions/container.core.application-metadata.def b/container-core/src/main/resources/configdefinitions/container.core.application-metadata.def
index 82e9868f793..4caa15e240a 100644
--- a/container-core/src/main/resources/configdefinitions/container.core.application-metadata.def
+++ b/container-core/src/main/resources/configdefinitions/container.core.application-metadata.def
@@ -7,7 +7,8 @@ namespace=container.core
name string default=""
# The user name that deployed the application
-user string default=""
+# TODO: Remove in Vespa 9
+user string default="unknown"
# The directory the application was deployed from
path string default=""
diff --git a/container-core/src/main/resources/configdefinitions/container.jdisc.state.metrics-packets-handler.def b/container-core/src/main/resources/configdefinitions/container.jdisc.state.metrics-packets-handler.def
index 9ec81b7db1b..ab0362c3995 100644
--- a/container-core/src/main/resources/configdefinitions/container.jdisc.state.metrics-packets-handler.def
+++ b/container-core/src/main/resources/configdefinitions/container.jdisc.state.metrics-packets-handler.def
@@ -4,3 +4,5 @@ namespace=container.jdisc.state
# The name of the application that is reporting metrics.
application string
+# Optional hostname to add as dimension
+hostname string default="" \ No newline at end of file
diff --git a/container-core/src/main/resources/configdefinitions/jdisc.http.jdisc.http.connector.def b/container-core/src/main/resources/configdefinitions/jdisc.http.jdisc.http.connector.def
index ca02c245015..e808b565e8b 100644
--- a/container-core/src/main/resources/configdefinitions/jdisc.http.jdisc.http.connector.def
+++ b/container-core/src/main/resources/configdefinitions/jdisc.http.jdisc.http.connector.def
@@ -101,9 +101,15 @@ healthCheckProxy.enable bool default=false
# Which port to proxy
healthCheckProxy.port int default=8080
-# Low-level timeout for proxy client (socket connect, socket read, connection pool). Aggregate timeout will be longer.
+# Low-level timeout for proxy client (socket connect, socket read, connection pool).
healthCheckProxy.clientTimeout double default=1.0
+# Servlet async request timeout. Must be larger than 'clientTimeout' to cover cost of queueing and response handling.
+healthCheckProxy.handlerTimeout double default=1.5
+
+# Expiry for cached health response
+healthCheckProxy.cacheExpiry double default=1.0
+
# Enable PROXY protocol V1/V2 support (only for https connectors).
proxyProtocol.enabled bool default=false
diff --git a/container-core/src/main/sh/find-pid b/container-core/src/main/sh/find-pid
index 4db6562db1b..57393140e0b 100755
--- a/container-core/src/main/sh/find-pid
+++ b/container-core/src/main/sh/find-pid
@@ -74,7 +74,7 @@ findhost
# END environment bootstrap section
-set -euo pipefail
+set -uo pipefail
if (( $# != 1 )); then
echo "Usage: $0 <service-name-or-config-id>" >&2
diff --git a/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java b/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java
index 07e1d806bfb..7d8491e4826 100644
--- a/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class ComponentSpecTestCase {
@Test
- public void testMatches() {
+ void testMatches() {
ComponentId a = new ComponentId("test:1");
ComponentId b = new ComponentId("test:1.1.1");
ComponentId c = new ComponentId("test:2");
@@ -52,14 +50,14 @@ public class ComponentSpecTestCase {
}
@Test
- public void testMatchesWithNamespace() {
+ void testMatchesWithNamespace() {
ComponentId namespace = new ComponentId("namespace:2");
ComponentId a = new ComponentId("test", new Version(1), namespace);
ComponentId b = new ComponentId("test:1@namespace:2");
ComponentId c = new ComponentId("test:1@namespace");
assertEquals(a, b);
- assertFalse(a.equals(c));
+ assertNotEquals(a, c);
ComponentSpecification spec = new ComponentSpecification("test", null, namespace);
assertTrue(spec.matches(a));
@@ -68,7 +66,7 @@ public class ComponentSpecTestCase {
}
@Test
- public void testStringValue() {
+ void testStringValue() {
assertStringValueEqualsInputSpec("a:1.0.0.alpha@namespace");
assertStringValueEqualsInputSpec("a:1.0.0.alpha");
assertStringValueEqualsInputSpec("a:1.0");
diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
index a83de433968..6e107bf9934 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
@@ -8,7 +8,7 @@ import com.yahoo.component.chain.Phase;
import com.yahoo.component.chain.dependencies.After;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.component.chain.dependencies.Provides;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -18,8 +18,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -56,7 +56,7 @@ public class ChainBuilderTest {
}
@Test
- public void testRegular() throws Exception {
+ void testRegular() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
addAtoG(chainBuilder);
@@ -64,13 +64,13 @@ public class ChainBuilderTest {
Chain<ChainedComponent> res = chainBuilder.orderNodes();
Iterator<ChainedComponent> i = res.components().iterator();
- for (char j=0; j< 'G' - 'A'; ++j) {
- assertEquals(String.valueOf((char)('A' + j)), name(i.next()));
+ for (char j = 0; j < 'G' - 'A'; ++j) {
+ assertEquals(String.valueOf((char) ('A' + j)), name(i.next()));
}
}
@Test
- public void testCycle() throws Exception {
+ void testCycle() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
@@ -88,7 +88,7 @@ public class ChainBuilderTest {
@Test
- public void testPhaseAndSearcher() {
+ void testPhaseAndSearcher() {
ChainBuilder depHandler = newChainBuilder();
depHandler.addPhase(new Phase("phase1", set("phase2"), Collections.<String>emptySet()));
depHandler.addPhase(new Phase("phase2", set("phase3"), set("phase1")));
@@ -103,7 +103,7 @@ public class ChainBuilderTest {
}
@Test
- public void testInputOrderPreservedWhenProvidesOverlap() {
+ void testInputOrderPreservedWhenProvidesOverlap() {
ChainBuilder chainBuilder = newChainBuilder();
A a1 = new A();
@@ -136,38 +136,38 @@ public class ChainBuilderTest {
}
@Test
- public void testAfterAll1() throws Exception {
+ void testAfterAll1() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
ChainedComponent afterAll1 = new AfterAll();
chainBuilder.addComponent(afterAll1);
addAtoG(chainBuilder);
- List<ChainedComponent> resolution= chainBuilder.orderNodes().components();
- assertEquals(afterAll1,resolution.get(resolution.size()-1));
+ List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
+ assertEquals(afterAll1, resolution.get(resolution.size() - 1));
}
@Test
- public void testAfterAll2() throws Exception {
+ void testAfterAll2() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
addAtoG(chainBuilder);
ChainedComponent afterAll1 = new AfterAll();
chainBuilder.addComponent(afterAll1);
List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
- assertEquals(afterAll1,resolution.get(resolution.size()-1));
+ assertEquals(afterAll1, resolution.get(resolution.size() - 1));
}
@Test
- public void testAfterImplicitProvides()
+ void testAfterImplicitProvides()
throws InstantiationException, IllegalAccessException {
ChainBuilder chainBuilder = createDependencyHandler();
- ChainedComponent afterProvidesNothing=new AfterProvidesNothing();
- ChainedComponent providesNothing=new ProvidesNothing();
+ ChainedComponent afterProvidesNothing = new AfterProvidesNothing();
+ ChainedComponent providesNothing = new ProvidesNothing();
chainBuilder.addComponent(afterProvidesNothing);
chainBuilder.addComponent(providesNothing);
List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
- assertEquals(providesNothing,resolution.get(0));
- assertEquals(afterProvidesNothing,resolution.get(1));
+ assertEquals(providesNothing, resolution.get(0));
+ assertEquals(afterProvidesNothing, resolution.get(1));
}
private ChainBuilder createDependencyHandler() {
diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
index c33fb71a07c..a5704b51bbe 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
@@ -1,19 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component.chain.dependencies.ordering;
-import static org.junit.Assert.assertEquals;
-
import java.util.Arrays;
import com.yahoo.component.chain.ChainedComponent;
-import com.yahoo.component.chain.dependencies.Dependencies;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import com.yahoo.component.chain.dependencies.Dependencies;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.ComponentId;
-
/**
* Test for OrderedReadyNodes.
*
@@ -41,13 +39,13 @@ public class OrderedReadyNodesTest {
private OrderedReadyNodes readyNodes;
- @Before
+ @BeforeEach
public void setup() {
readyNodes = new OrderedReadyNodes();
}
@Test
- public void require_NameProviders_before_SearcherNodes() {
+ void require_NameProviders_before_SearcherNodes() {
NameProvider nameProvider = createDummyNameProvider(100);
ComponentNode componentNode = new ComponentNode<>(createFakeComponentA("a"), 1);
@@ -72,7 +70,7 @@ public class OrderedReadyNodesTest {
}
@Test
- public void require_SearcherNodes_ordered_by_insertion_order() {
+ void require_SearcherNodes_ordered_by_insertion_order() {
int priority = 0;
ComponentNode a = new ComponentNode<>(createFakeComponentB("1"), priority++);
ComponentNode b = new ComponentNode<>(createFakeComponentA("2"), priority++);
diff --git a/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java b/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
index 54b57789ba8..0871b36b0b3 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
@@ -4,15 +4,15 @@ package com.yahoo.component.chain.model;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.container.core.ChainsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
import static com.yahoo.container.core.ChainsConfig.Components;
import static com.yahoo.container.core.ChainsConfig.Chains;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -20,27 +20,27 @@ import static org.junit.Assert.assertTrue;
public class ChainsModelBuilderTest {
@Test
- public void components_are_added_to_componentModels() throws Exception {
+ void components_are_added_to_componentModels() throws Exception {
ChainsModel model = chainsModel();
assertEquals(2, model.allComponents().size());
assertTrue(model.componentModels().containsKey(new ComponentId("componentA")));
}
@Test
- public void components_are_added_to_chainSpecification() throws Exception {
+ void components_are_added_to_chainSpecification() throws Exception {
ChainsModel model = chainsModel();
ChainSpecification chainSpec = model.chainSpecifications().get(new ComponentId("chain1")).model();
assertTrue(getComponentsByName(chainSpec.componentReferences).containsKey("componentA"));
}
@Test
- public void inherited_chains_are_added_to_chainSpecification() throws Exception {
+ void inherited_chains_are_added_to_chainSpecification() throws Exception {
ChainsModel model = chainsModel();
ChainSpecification inheritsChain1 = model.chainSpecifications().get(new ComponentId("inheritsChain1")).model();
assertEquals(2, model.allChainsFlattened().size());
assertTrue(getComponentsByName(inheritsChain1.inheritance.chainSpecifications).containsKey("chain1"));
assertTrue(getComponentsByName(inheritsChain1.inheritance.excludedComponents).containsKey("componentA"));
- }
+ }
private ChainsModel chainsModel() {
ChainsConfig.Builder builder = new ChainsConfig.Builder()
diff --git a/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java b/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
index 5f8fec564bc..eb7439df0ff 100644
--- a/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
@@ -1,12 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component.provider.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
@@ -48,7 +47,7 @@ public class ComponentRegistryTestCase {
return new TestComponent(idInNamespace(namespace));
}
- @Before
+ @BeforeEach
public void before() {
registry = new ComponentRegistry<>();
@@ -58,19 +57,19 @@ public class ComponentRegistryTestCase {
}
@Test
- public void testAllPresent() {
+ void testAllPresent() {
assertEquals(3, registry.getComponentCount());
}
@Test
- public void testIdNamespaceLookup() {
+ void testIdNamespaceLookup() {
assertEquals(component1, registry.getComponent(idInNamespace(namespace1)));
assertEquals(component2, registry.getComponent(idInNamespace(namespace2)));
assertEquals(component21, registry.getComponent(idInNamespace(namespace21)));
}
@Test
- public void testSpecNamespaceLookup() {
+ void testSpecNamespaceLookup() {
assertEquals(component1, registry.getComponent(specInNamespace(namespace1)));
// Version for namespace must match the specification exactly, so do not return version '1' when an
@@ -80,7 +79,7 @@ public class ComponentRegistryTestCase {
}
@Test
- public void testInnerComponentNotMixedWithTopLevelComponent() {
+ void testInnerComponentNotMixedWithTopLevelComponent() {
assertNull(registry.getComponent(componentName));
TestComponent topLevel = new TestComponent(new ComponentId(componentName));
diff --git a/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java b/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
index 8d86010ea5a..4561c18bc3d 100644
--- a/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.component.test;
import com.yahoo.component.ComponentId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -12,27 +12,26 @@ import static org.junit.Assert.assertEquals;
public class ComponentIdTestCase {
@Test
- public void testFileNameConversion() {
- assertFileNameEquals("a","a");
- assertFileNameEquals("a-1","a-1");
- assertFileNameEquals("a-1","a-1.0.0");
- assertFileNameEquals("a-1.0.0.qualifier","a-1.0.0.qualifier");
- assertFileNameEquals("a.b-1.0.0.qualifier","a.b-1.0.0.qualifier");
- assertFileNameEquals("a@space","a@space");
- assertFileNameEquals("a-1@space","a-1@space");
- assertFileNameEquals("a-1@space","a-1.0.0@space");
- assertFileNameEquals("a-1.0.0.qualifier@space","a-1.0.0.qualifier@space");
- assertFileNameEquals("a.b-1.0.0.qualifier@space","a.b-1.0.0.qualifier@space");
+ void testFileNameConversion() {
+ assertFileNameEquals("a", "a");
+ assertFileNameEquals("a-1", "a-1");
+ assertFileNameEquals("a-1", "a-1.0.0");
+ assertFileNameEquals("a-1.0.0.qualifier", "a-1.0.0.qualifier");
+ assertFileNameEquals("a.b-1.0.0.qualifier", "a.b-1.0.0.qualifier");
+ assertFileNameEquals("a@space", "a@space");
+ assertFileNameEquals("a-1@space", "a-1@space");
+ assertFileNameEquals("a-1@space", "a-1.0.0@space");
+ assertFileNameEquals("a-1.0.0.qualifier@space", "a-1.0.0.qualifier@space");
+ assertFileNameEquals("a.b-1.0.0.qualifier@space", "a.b-1.0.0.qualifier@space");
}
/** Takes two id file names as input */
private void assertFileNameEquals(String expected,String initial) {
- assertEquals("'" + initial + "' became id '" + ComponentId.fromFileName(initial) + "' which should become '" + expected + "'",
- expected,ComponentId.fromFileName(initial).toFileName());
+ assertEquals(expected,ComponentId.fromFileName(initial).toFileName(),"'" + initial + "' became id '" + ComponentId.fromFileName(initial) + "' which should become '" + expected + "'");
}
@Test
- public void testCompareWithNameSpace() {
+ void testCompareWithNameSpace() {
ComponentId withNS = ComponentId.fromString("foo@ns");
ComponentId withoutNS = ComponentId.fromString("foo"); // Should be less than withNs
diff --git a/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java b/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
index 4f6fea76828..cf8cc6053cd 100644
--- a/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
@@ -5,16 +5,16 @@ import com.yahoo.config.FileReference;
import com.yahoo.filedistribution.fileacquirer.FileAcquirer;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
import com.yahoo.osgi.Osgi;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -29,7 +29,7 @@ public class ApplicationBundleLoaderTest {
private ApplicationBundleLoader bundleLoader;
private TestOsgi osgi;
- @Before
+ @BeforeEach
public void setup() {
osgi = new TestOsgi(testBundles());
var bundleInstaller = new TestBundleInstaller(MockFileAcquirer.returnFile(null));
@@ -38,12 +38,12 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void bundles_are_installed_and_started() {
+ void bundles_are_installed_and_started() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
assertEquals(1, osgi.getInstalledBundles().size());
// The bundle is installed and started
- TestBundle installedBundle = (TestBundle)osgi.getInstalledBundles().get(0);
+ TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0);
assertEquals(BUNDLE_1.getSymbolicName(), installedBundle.getSymbolicName());
assertTrue(installedBundle.started);
@@ -53,7 +53,7 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void new_bundle_can_be_installed_in_reconfig() {
+ void new_bundle_can_be_installed_in_reconfig() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
Set<Bundle> obsoleteBundles = bundleLoader.useBundles(List.of(BUNDLE_1_REF, BUNDLE_2_REF));
@@ -78,7 +78,7 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void unused_bundle_is_marked_obsolete_after_reconfig() {
+ void unused_bundle_is_marked_obsolete_after_reconfig() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
Set<Bundle> obsoleteBundles = bundleLoader.useBundles(List.of(BUNDLE_2_REF));
diff --git a/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java b/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
index 3cd9779f878..21d99915c5c 100644
--- a/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
@@ -2,15 +2,15 @@
package com.yahoo.container.core.config;
import com.yahoo.osgi.Osgi;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -25,25 +25,25 @@ public class PlatformBundleLoaderTest {
private PlatformBundleLoader bundleLoader;
private TestOsgi osgi;
- @Before
+ @BeforeEach
public void setup() {
osgi = new TestOsgi(testBundles());
bundleLoader = new PlatformBundleLoader(osgi, new TestBundleInstaller());
}
@Test
- public void bundles_are_installed_and_started() {
+ void bundles_are_installed_and_started() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
assertEquals(1, osgi.getInstalledBundles().size());
// The bundle is installed and started
- TestBundle installedBundle = (TestBundle)osgi.getInstalledBundles().get(0);
+ TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0);
assertEquals(BUNDLE_1.getSymbolicName(), installedBundle.getSymbolicName());
assertTrue(installedBundle.started);
}
@Test
- public void bundles_cannot_be_added_by_later_calls() {
+ void bundles_cannot_be_added_by_later_calls() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
bundleLoader.useBundles(List.of(BUNDLE_2_REF)); // Should be a NOP
diff --git a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
index 695efbf7c17..942555e391d 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
@@ -9,18 +9,20 @@ import com.yahoo.container.di.ConfigRetriever.BootstrapConfigs;
import com.yahoo.container.di.ConfigRetriever.ComponentsConfigs;
import com.yahoo.container.di.ConfigRetriever.ConfigSnapshot;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
*
@@ -32,18 +34,21 @@ public class ConfigRetrieverTest {
private DirConfigSource dirConfigSource = null;
- @Before
+ @TempDir
+ File tmpDir;
+
+ @BeforeEach
public void setup() {
- dirConfigSource = new DirConfigSource("ConfigRetrieverTest-");
+ dirConfigSource = new DirConfigSource(tmpDir, "ConfigRetrieverTest-");
}
- @After
+ @AfterEach
public void cleanup() {
dirConfigSource.cleanup();
}
@Test
- public void require_that_bootstrap_configs_come_first() {
+ void require_that_bootstrap_configs_come_first() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true);
@@ -53,7 +58,7 @@ public class ConfigRetrieverTest {
@Test
@SuppressWarnings("unused")
- public void require_that_components_comes_after_bootstrap() {
+ void require_that_components_comes_after_bootstrap() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true);
@@ -68,7 +73,7 @@ public class ConfigRetrieverTest {
}
}
- @Ignore
+ @Disabled
@SuppressWarnings("unused")
public void require_exception_upon_modified_components_keys_without_bootstrap() {
@@ -89,7 +94,7 @@ public class ConfigRetrieverTest {
}
@Test
- public void require_that_empty_components_keys_after_bootstrap_returns_components_configs() {
+ void require_that_empty_components_keys_after_bootstrap_returns_components_configs() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
assertTrue(retriever.getConfigs(Collections.emptySet(), 0, true) instanceof BootstrapConfigs);
diff --git a/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java b/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
index 30dc4f313e4..04091c25ad6 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent;
import com.yahoo.container.di.componentgraph.core.ComponentNode.ComponentConstructorException;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import java.util.Collection;
@@ -20,13 +20,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -36,7 +30,7 @@ import static org.junit.Assert.fail;
public class ContainerTest extends ContainerTestBase {
@Test
- public void components_can_be_created_from_config() {
+ void components_can_be_created_from_config() {
writeBootstrapConfigs();
dirConfigSource.writeConfig("test", "stringVal \"myString\"");
@@ -49,7 +43,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void components_are_reconfigured_after_config_update_without_bootstrap_configs() {
+ void components_are_reconfigured_after_config_update_without_bootstrap_configs() {
writeBootstrapConfigs();
dirConfigSource.writeConfig("test", "stringVal \"original\"");
@@ -71,7 +65,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void graph_is_updated_after_bootstrap_update() {
+ void graph_is_updated_after_bootstrap_update() {
dirConfigSource.writeConfig("test", "stringVal \"original\"");
writeBootstrapConfigs("id1");
@@ -99,7 +93,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void component_is_deconstructed_when_not_reused() {
+ void component_is_deconstructed_when_not_reused() {
writeBootstrapConfigs("id1", DestructableComponent.class);
Container container = newContainer(dirConfigSource);
@@ -113,9 +107,9 @@ public class ContainerTest extends ContainerTestBase {
assertTrue(componentToDestruct.deconstructed);
}
- @Ignore // because logAndDie is impossible(?) to verify programmatically
+ @Disabled // because logAndDie is impossible(?) to verify programmatically
@Test
- public void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
+ void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
writeBootstrapConfigs("thrower", ComponentThrowingExceptionInConstructor.class);
Container container = newContainer(dirConfigSource);
try {
@@ -127,7 +121,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void previous_graph_is_retained_when_new_graph_contains_component_that_throws_exception_in_ctor() {
+ void previous_graph_is_retained_when_new_graph_contains_component_that_throws_exception_in_ctor() {
ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);
writeBootstrapConfigs(simpleComponentEntry);
@@ -161,7 +155,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
+ void previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);
writeBootstrapConfigs(simpleComponentEntry);
@@ -185,7 +179,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void getNewComponentGraph_hangs_waiting_for_valid_config_after_invalid_config() throws Exception {
+ void getNewComponentGraph_hangs_waiting_for_valid_config_after_invalid_config() throws Exception {
dirConfigSource.writeConfig("test", "stringVal \"original\"");
writeBootstrapConfigs("myId", ComponentTakingConfig.class);
@@ -196,7 +190,7 @@ public class ContainerTest extends ContainerTestBase {
container.reloadConfig(2);
assertThrows(IllegalArgumentException.class,
- () -> getNewComponentGraph(container, currentGraph));
+ () -> getNewComponentGraph(container, currentGraph));
ExecutorService exec = Executors.newFixedThreadPool(1);
Future<ComponentGraph> newGraph = exec.submit(() -> getNewComponentGraph(container, currentGraph));
@@ -215,7 +209,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void providers_are_destructed() {
+ void providers_are_destructed() {
writeBootstrapConfigs("id1", DestructableProvider.class);
ComponentDeconstructor deconstructor = (generation, components, bundles) -> {
@@ -226,7 +220,7 @@ public class ContainerTest extends ContainerTestBase {
((Provider<?>) component).deconstruct();
}
});
- if (! bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
+ if (!bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
};
Container container = newContainer(dirConfigSource, deconstructor);
@@ -242,7 +236,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void providers_are_invoked_only_when_needed() {
+ void providers_are_invoked_only_when_needed() {
writeBootstrapConfigs("id1", FailOnGetProvider.class);
Container container = newContainer(dirConfigSource);
diff --git a/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java b/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
index e7f12d3f228..4383bd08f71 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
@@ -7,10 +7,12 @@ import com.yahoo.config.FileReference;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.di.ContainerTest.ComponentTakingConfig;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
import org.osgi.framework.Bundle;
+import java.io.File;
import java.util.Collection;
import java.util.Set;
@@ -26,17 +28,20 @@ public class ContainerTestBase {
private ComponentGraph componentGraph;
protected DirConfigSource dirConfigSource = null;
- @Before
+ @TempDir
+ File tmpDir;
+
+ @BeforeEach
public void setup() {
- dirConfigSource = new DirConfigSource("ContainerTest-");
+ dirConfigSource = new DirConfigSource(tmpDir, "ContainerTest-");
}
- @After
+ @AfterEach
public void cleanup() {
dirConfigSource.cleanup();
}
- @Before
+ @BeforeEach
public void createGraph() {
componentGraph = new ComponentGraph(0);
}
diff --git a/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java b/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
index 43b2c8ad8e6..db7e93f7c6e 100644
--- a/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
+++ b/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
@@ -3,7 +3,6 @@ package com.yahoo.container.di;
import com.yahoo.config.subscription.ConfigSource;
import com.yahoo.config.subscription.ConfigSourceSet;
-import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileOutputStream;
@@ -18,15 +17,16 @@ import java.util.Random;
*/
public class DirConfigSource {
- private final TemporaryFolder tempFolder = createTemporaryFolder();
+ private final File tempFolder;
public final ConfigSource configSource;
- public DirConfigSource(String testSourcePrefix) {
+ public DirConfigSource(File tmpDir, String testSourcePrefix) {
+ this.tempFolder = tmpDir;
this.configSource = new ConfigSourceSet(testSourcePrefix + new Random().nextLong());
}
public void writeConfig(String name, String contents) {
- File file = new File(tempFolder.getRoot(), name + ".cfg");
+ File file = new File(tempFolder, name + ".cfg");
if (!file.exists()) {
try {
file.createNewFile();
@@ -39,7 +39,7 @@ public class DirConfigSource {
}
public String configId() {
- return "dir:" + tempFolder.getRoot().getPath();
+ return "dir:" + tempFolder.getPath();
}
public ConfigSource configSource() {
@@ -58,14 +58,4 @@ public class DirConfigSource {
}
}
- private static TemporaryFolder createTemporaryFolder() {
- TemporaryFolder folder = new TemporaryFolder();
- try {
- folder.create();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return folder;
- }
-
}
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
index 4d44281658c..c21c1b35782 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
@@ -18,7 +18,7 @@ import com.yahoo.config.test.Test2Config;
import com.yahoo.config.test.TestConfig;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.util.Collections;
@@ -30,13 +30,7 @@ import java.util.concurrent.Executors;
import java.util.function.Supplier;
import static com.yahoo.container.di.componentgraph.core.ComponentGraph.isBindingAnnotation;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -50,6 +44,7 @@ public class ComponentGraphTest {
super();
}
+ @SuppressWarnings("deprecation")
public <T extends ConfigInstance> ConfigMap add(Class<T> clazz, String configId) {
ConfigKey<T> key = new ConfigKey<>(clazz, configId);
put(key, ConfigGetter.getConfig(key.getConfigClass(), key.getConfigId()));
@@ -64,7 +59,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_taking_config_can_be_instantiated() {
+ void component_taking_config_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
String configId = "raw:stringVal \"test-value\"";
Node componentNode = mockComponentNode(ComponentTakingConfig.class, configId);
@@ -79,7 +74,7 @@ public class ComponentGraphTest {
}
@Test
- public void all_created_components_are_returned_in_reverse_topological_order() {
+ void all_created_components_are_returned_in_reverse_topological_order() {
for (int i = 0; i < 10; i++) {
Node innerComponent = mockComponentNode(SimpleComponent.class);
Node middleComponent = mockComponentNode(ComponentTakingComponent.class);
@@ -96,12 +91,12 @@ public class ComponentGraphTest {
outerComponent.constructInstance();
assertEquals(List.of(outerComponent.constructedInstance().get(), middleComponent.constructedInstance().get(), innerComponent.constructedInstance().get()),
- componentGraph.allConstructedComponentsAndProviders());
+ componentGraph.allConstructedComponentsAndProviders());
}
}
@Test
- public void component_can_be_injected_into_another_component() {
+ void component_can_be_explicitly_injected_into_another_component() {
Node injectedComponent = mockComponentNode(SimpleComponent.class);
Node targetComponent = mockComponentNode(ComponentTakingComponent.class);
targetComponent.inject(injectedComponent);
@@ -116,10 +111,26 @@ public class ComponentGraphTest {
ComponentTakingComponent instance = componentGraph.getInstance(ComponentTakingComponent.class);
assertNotNull(instance);
+ assertSame(injectedComponent.instance.get(), instance.injectedComponent);
}
@Test
- public void interface_implementation_can_be_injected() {
+ void explicitly_injected_components_may_be_unused() {
+ Node notUsingInjected = mockComponentNode(SimpleComponent.class);
+ Node injectedComponent = mockComponentNode(SimpleComponent2.class);
+ notUsingInjected.inject(injectedComponent);
+
+ ComponentGraph componentGraph = new ComponentGraph();
+ componentGraph.add(injectedComponent);
+ componentGraph.add(notUsingInjected);
+ componentGraph.complete();
+
+ SimpleComponent instanceNotUsingInjected = componentGraph.getInstance(SimpleComponent.class);
+ assertNotNull(instanceNotUsingInjected);
+ }
+
+ @Test
+ void interface_implementation_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentImpl.class));
componentGraph.add(mockComponentNode(ComponentTakingInterface.class));
@@ -130,7 +141,7 @@ public class ComponentGraphTest {
}
@Test
- public void private_class_with_public_ctor_can_be_instantiated() {
+ void private_class_with_public_ctor_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(PrivateClassComponent.class));
componentGraph.complete();
@@ -140,7 +151,7 @@ public class ComponentGraphTest {
}
@Test
- public void all_components_of_a_type_can_be_injected() {
+ void all_components_of_a_type_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleComponent.class));
@@ -153,7 +164,7 @@ public class ComponentGraphTest {
}
@Test
- public void empty_component_registry_can_be_injected() {
+ void empty_component_registry_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingAllSimpleComponents.class));
componentGraph.complete();
@@ -163,7 +174,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_registry_with_wildcard_upper_bound_can_be_injected() {
+ void component_registry_with_wildcard_upper_bound_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
@@ -175,22 +186,24 @@ public class ComponentGraphTest {
assertEquals(2, instance.simpleComponents.allComponents().size());
}
- @Test(expected = RuntimeException.class)
- public void require_exception_when_injecting_registry_with_unknown_type_variable() {
- @SuppressWarnings("rawtypes")
- Class<ComponentTakingAllComponentsWithTypeVariable> clazz = ComponentTakingAllComponentsWithTypeVariable.class;
+ @Test
+ void require_exception_when_injecting_registry_with_unknown_type_variable() {
+ assertThrows(RuntimeException.class, () -> {
+ @SuppressWarnings("rawtypes")
+ Class<ComponentTakingAllComponentsWithTypeVariable> clazz = ComponentTakingAllComponentsWithTypeVariable.class;
- ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(SimpleComponent.class));
- componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
- componentGraph.add(mockComponentNode(clazz));
- componentGraph.complete();
+ ComponentGraph componentGraph = new ComponentGraph();
+ componentGraph.add(mockComponentNode(SimpleComponent.class));
+ componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
+ componentGraph.add(mockComponentNode(clazz));
+ componentGraph.complete();
- componentGraph.getInstance(clazz);
+ componentGraph.getInstance(clazz);
+ });
}
@Test
- public void components_are_shared() {
+ void components_are_shared() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.complete();
@@ -201,7 +214,7 @@ public class ComponentGraphTest {
}
@Test
- public void singleton_components_can_be_injected() {
+ void singleton_components_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
String configId = "raw:stringVal \"test-value\"";
@@ -216,17 +229,19 @@ public class ComponentGraphTest {
assertEquals("test-value", injected.config.stringVal());
}
- @Test(expected = RuntimeException.class)
- public void require_error_when_multiple_components_match_a_singleton_dependency() {
- ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
- componentGraph.add(mockComponentNode(SimpleComponent.class));
- componentGraph.add(mockComponentNode(ComponentTakingComponent.class));
- componentGraph.complete();
+ @Test
+ void require_error_when_multiple_components_match_a_singleton_dependency() {
+ assertThrows(RuntimeException.class, () -> {
+ ComponentGraph componentGraph = new ComponentGraph();
+ componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
+ componentGraph.add(mockComponentNode(SimpleComponent.class));
+ componentGraph.add(mockComponentNode(ComponentTakingComponent.class));
+ componentGraph.complete();
+ });
}
@Test
- public void named_component_can_be_injected() {
+ void named_component_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleComponent.class, Names.named("named-test")));
@@ -235,7 +250,7 @@ public class ComponentGraphTest {
}
@Test
- public void config_keys_can_be_retrieved() {
+ void config_keys_can_be_retrieved() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingConfig.class, "raw:stringVal \"component1\""));
componentGraph.add(mockComponentNode(ComponentTakingConfig.class, "raw:stringVal \"component2\""));
@@ -252,7 +267,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_instantiated() {
+ void providers_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ExecutorProvider.class));
componentGraph.complete();
@@ -261,7 +276,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_inherited() {
+ void providers_can_be_inherited() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(DerivedExecutorProvider.class));
componentGraph.complete();
@@ -270,7 +285,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_deliver_a_new_instance_for_each_component() {
+ void providers_can_deliver_a_new_instance_for_each_component() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(NewIntProvider.class));
componentGraph.complete();
@@ -282,7 +297,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_injected_explicitly() {
+ void providers_can_be_injected_explicitly() {
ComponentGraph componentGraph = new ComponentGraph();
Node componentTakingExecutor = mockComponentNode(ComponentTakingExecutor.class);
@@ -299,7 +314,7 @@ public class ComponentGraphTest {
}
@Test
- public void global_providers_can_be_injected() {
+ void global_providers_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
@@ -310,18 +325,20 @@ public class ComponentGraphTest {
assertNotNull(componentGraph.getInstance(ComponentTakingExecutor.class));
}
- @Test(expected = RuntimeException.class)
- public void throw_if_multiple_global_providers_exist() {
- ComponentGraph componentGraph = new ComponentGraph();
+ @Test
+ void throw_if_multiple_global_providers_exist() {
+ assertThrows(RuntimeException.class, () -> {
+ ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(ExecutorProvider.class));
- componentGraph.add(mockComponentNode(ExecutorProvider.class));
- componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
- componentGraph.complete();
+ componentGraph.add(mockComponentNode(ExecutorProvider.class));
+ componentGraph.add(mockComponentNode(ExecutorProvider.class));
+ componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
+ componentGraph.complete();
+ });
}
@Test
- public void provider_is_not_used_when_component_of_provided_class_exists() {
+ void provider_is_not_used_when_component_of_provided_class_exists() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
@@ -335,13 +352,13 @@ public class ComponentGraphTest {
//TODO: move
@Test
- public void check_if_annotation_is_a_binding_annotation() {
+ void check_if_annotation_is_a_binding_annotation() {
assertTrue(isBindingAnnotation(Names.named("name")));
assertFalse(isBindingAnnotation(Named.class.getAnnotations()[0]));
}
@Test
- public void cycles_gives_exception() {
+ void cycles_gives_exception() {
ComponentGraph componentGraph = new ComponentGraph();
Node node1 = mockComponentNode(ComponentCausingCycle.class);
@@ -362,18 +379,20 @@ public class ComponentGraphTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void abstract_classes_are_rejected() {
- new ComponentNode(ComponentId.fromString("Test"), "", AbstractClass.class);
+ @Test
+ void abstract_classes_are_rejected() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ComponentNode(ComponentId.fromString("Test"), "", AbstractClass.class);
+ });
}
@Test
- public void inject_constructor_is_preferred() {
+ void inject_constructor_is_preferred() {
assertThatComponentCanBeCreated(ComponentWithInjectConstructor.class);
}
@Test
- public void constructor_with_most_parameters_is_preferred() {
+ void constructor_with_most_parameters_is_preferred() {
assertThatComponentCanBeCreated(ComponentWithMultipleConstructors.class);
}
@@ -390,7 +409,7 @@ public class ComponentGraphTest {
}
@Test
- public void require_fallback_to_child_injector() {
+ void require_fallback_to_child_injector() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
@@ -400,7 +419,7 @@ public class ComponentGraphTest {
}
@Test
- public void child_injector_can_inject_multiple_instances_for_same_key() {
+ void child_injector_can_inject_multiple_instances_for_same_key() {
Pair<Integer, Pair<Executor, Executor>> graph = buildGraphWithChildInjector(Executors::newSingleThreadExecutor);
int graphSize = graph.getFirst();
Executor executorA = graph.getSecond().getFirst();
@@ -411,7 +430,7 @@ public class ComponentGraphTest {
}
@Test
- public void components_injected_via_child_injector_can_be_shared() {
+ void components_injected_via_child_injector_can_be_shared() {
Executor commonExecutor = Executors.newSingleThreadExecutor();
Pair<Integer, Pair<Executor, Executor>> graph = buildGraphWithChildInjector(() -> commonExecutor);
int graphSize = graph.getFirst();
@@ -445,7 +464,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_reused() {
+ void providers_can_be_reused() {
ComponentGraph oldGraph = createReusingGraph();
Executor executor = oldGraph.getInstance(Executor.class);
@@ -466,7 +485,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_id_can_be_injected() {
+ void component_id_can_be_injected() {
String componentId = "myId:1.2@namespace";
ComponentGraph componentGraph = new ComponentGraph();
@@ -513,7 +532,7 @@ public class ComponentGraphTest {
}
public static class ComponentTakingComponent extends AbstractComponent {
- private final SimpleComponent injectedComponent;
+ final SimpleComponent injectedComponent;
public ComponentTakingComponent(SimpleComponent injectedComponent) {
assertNotNull(injectedComponent);
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
index 1e3d67ed463..878c245a708 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
@@ -11,18 +11,15 @@ import com.yahoo.component.AbstractComponent;
import com.yahoo.component.ComponentId;
import com.yahoo.config.ConfigInstance;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -36,7 +33,7 @@ public class FallbackToGuiceInjectorTest {
private final Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> configs = new HashMap<>();
- @Before
+ @BeforeEach
public void createGraph() {
injector = Guice.createInjector();
componentGraph = new ComponentGraph(0);
@@ -70,7 +67,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_is_used_when_no_global_component_exists() {
+ void guice_injector_is_used_when_no_global_component_exists() {
setInjector(
Guice.createInjector(new AbstractModule() {
@Override
@@ -89,7 +86,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_creates_a_new_instance_with_default_ctor_when_no_explicit_binding_exists() {
+ void guice_injector_creates_a_new_instance_with_default_ctor_when_no_explicit_binding_exists() {
setInjector(emptyGuiceInjector());
register(ComponentTakingDefaultString.class);
complete();
@@ -99,7 +96,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_fails_when_no_explicit_binding_exists_and_class_has_no_default_ctor() {
+ void guice_injector_fails_when_no_explicit_binding_exists_and_class_has_no_default_ctor() {
setInjector(emptyGuiceInjector());
register(ComponentThatCannotBeConstructed.class);
try {
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
index 29452f7babe..edd06e37e64 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
@@ -14,16 +14,14 @@ import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.ExecutorPro
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent;
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent2;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -32,7 +30,7 @@ import static org.junit.Assert.assertSame;
*/
public class ReuseComponentsTest {
@Test
- public void require_that_component_is_reused_when_componentNode_is_unmodified() {
+ void require_that_component_is_reused_when_componentNode_is_unmodified() {
reuseAndTest(SimpleComponent.class, SimpleComponent.class);
reuseAndTest(ExecutorProvider.class, Executor.class);
}
@@ -48,22 +46,25 @@ public class ReuseComponentsTest {
assertSame(instance2, instance);
}
- @Test(expected = IllegalStateException.class)
- public void require_that_component_is_not_reused_when_class_is_changed() {
- ComponentGraph graph = buildGraphAndSetNoConfigs(SimpleComponent.class);
- SimpleComponent instance = getComponent(graph, SimpleComponent.class);
-
- ComponentGraph newGraph = buildGraphAndSetNoConfigs(SimpleComponent2.class);
- newGraph.reuseNodes(graph);
- SimpleComponent2 instance2 = getComponent(newGraph, SimpleComponent2.class);
-
- assertEquals(instance2.getId(),instance.getId());
- @SuppressWarnings("unused")
- SimpleComponent throwsException = getComponent(newGraph, SimpleComponent.class);
+ @Test
+ void require_that_component_is_not_reused_when_class_is_changed() {
+ assertThrows(IllegalStateException.class, () -> {
+ ComponentGraph graph = buildGraphAndSetNoConfigs(SimpleComponent.class);
+ SimpleComponent instance = getComponent(graph, SimpleComponent.class);
+
+ ComponentGraph newGraph = buildGraphAndSetNoConfigs(SimpleComponent2.class);
+ newGraph.reuseNodes(graph);
+ SimpleComponent2 instance2 = getComponent(newGraph, SimpleComponent2.class);
+
+ assertEquals(instance2.getId(), instance.getId());
+ @SuppressWarnings("unused")
+ SimpleComponent throwsException = getComponent(newGraph, SimpleComponent.class);
+ });
}
+ @SuppressWarnings("deprecation")
@Test
- public void require_that_component_is_not_reused_when_config_is_changed() {
+ void require_that_component_is_not_reused_when_config_is_changed() {
Class<ComponentTakingConfig> componentClass = ComponentTakingConfig.class;
ComponentGraph graph = buildGraph(componentClass);
@@ -80,8 +81,9 @@ public class ReuseComponentsTest {
assertNotSame(instance2, instance);
}
+ @SuppressWarnings("deprecation")
@Test
- public void require_that_component_is_not_reused_when_injected_component_is_changed() {
+ void require_that_component_is_not_reused_when_injected_component_is_changed() {
Function<String, ComponentGraph> buildGraph = config -> {
ComponentGraph graph = new ComponentGraph();
@@ -113,7 +115,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_component_is_not_reused_when_injected_component_registry_has_one_component_removed() {
+ void require_that_component_is_not_reused_when_injected_component_registry_has_one_component_removed() {
Function<Boolean, ComponentGraph> buildGraph = useBothInjectedComponents -> {
ComponentGraph graph = new ComponentGraph();
graph.add(mockComponentNode(ComponentTakingAllSimpleComponents.class, "root_component"));
@@ -144,8 +146,9 @@ public class ReuseComponentsTest {
assertNotSame(newSimpleComponentRegistry, oldSimpleComponentRegistry);
}
+ @SuppressWarnings("deprecation")
@Test
- public void require_that_injected_component_is_reused_even_when_dependent_component_is_changed() {
+ void require_that_injected_component_is_reused_even_when_dependent_component_is_changed() {
Function<String, ComponentGraph> buildGraph = config -> {
ComponentGraph graph = new ComponentGraph();
@@ -180,7 +183,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_node_depending_on_guice_node_is_reused() {
+ void require_that_node_depending_on_guice_node_is_reused() {
Supplier<ComponentGraph> makeGraph = () -> {
ComponentGraph graph = new ComponentGraph();
graph.add(mockComponentNode(ComponentTakingExecutor.class, "dummyId"));
@@ -199,7 +202,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_node_equals_only_checks_first_level_components_to_inject() {
+ void require_that_node_equals_only_checks_first_level_components_to_inject() {
Function<String, Node> createNodeWithInjectedNodeWithInjectedNode = indirectlyInjectedComponentId -> {
ComponentNode targetComponent = mockComponentNode(SimpleComponent.class, "target");
ComponentNode directlyInjectedComponent = mockComponentNode(SimpleComponent.class, "directlyInjected");
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
index 65fbdc578aa..b7ce61c2f1a 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
@@ -2,7 +2,7 @@
package com.yahoo.container.di.componentgraph.cycle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -10,7 +10,7 @@ import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertic
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.B;
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.C;
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.D;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -20,7 +20,7 @@ public class CycleFinderTest {
enum Vertices {A, B, C, D}
@Test
- public void graph_without_cycles_returns_no_cycle() {
+ void graph_without_cycles_returns_no_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -32,7 +32,7 @@ public class CycleFinderTest {
}
@Test
- public void graph_with_cycle_returns_cycle() {
+ void graph_with_cycle_returns_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -43,7 +43,7 @@ public class CycleFinderTest {
}
@Test
- public void graph_with_self_referencing_vertex_returns_cycle() {
+ void graph_with_self_referencing_vertex_returns_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
@@ -52,7 +52,7 @@ public class CycleFinderTest {
}
@Test
- public void leading_nodes_are_stripped_from_cycle() {
+ void leading_nodes_are_stripped_from_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -63,7 +63,7 @@ public class CycleFinderTest {
}
@Test
- public void findCycle_is_idempotent_with_cycle() {
+ void findCycle_is_idempotent_with_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
@@ -73,7 +73,7 @@ public class CycleFinderTest {
}
@Test
- public void findCycle_is_idempotent_without_cycle() {
+ void findCycle_is_idempotent_without_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
index 526e683ad46..d945b4f0544 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
@@ -2,16 +2,14 @@
package com.yahoo.container.di.componentgraph.cycle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.A;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.B;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.C;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -21,7 +19,7 @@ public class GraphTest {
enum Vertices {A, B, C}
@Test
- public void vertices_and_edges_are_added_and_can_be_retrieved() {
+ void vertices_and_edges_are_added_and_can_be_retrieved() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -34,7 +32,7 @@ public class GraphTest {
}
@Test
- public void null_vertices_are_not_allowed() {
+ void null_vertices_are_not_allowed() {
var graph = new Graph<Vertices>();
try {
@@ -46,7 +44,7 @@ public class GraphTest {
}
@Test
- public void duplicate_edges_are_ignored() {
+ void duplicate_edges_are_ignored() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(A, B);
@@ -55,7 +53,7 @@ public class GraphTest {
}
@Test
- public void self_edges_are_allowed() {
+ void self_edges_are_allowed() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
index 2eba4144b45..728118c38cc 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.handler;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.logging.CircularArrayAccessLogKeeper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.Executor;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class AccessLogRequestHandlerTest {
@@ -20,7 +20,7 @@ public class AccessLogRequestHandlerTest {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
@Test
- public void testOneLogLine() throws IOException {
+ void testOneLogLine() throws IOException {
keeper.addUri("foo");
HttpResponse response = handler.handle(null);
response.render(out);
@@ -28,14 +28,14 @@ public class AccessLogRequestHandlerTest {
}
@Test
- public void testEmpty() throws IOException {
+ void testEmpty() throws IOException {
HttpResponse response = handler.handle(null);
response.render(out);
assertEquals("{\"entries\":[]}", out.toString());
}
@Test
- public void testManyLogLines() throws IOException {
+ void testManyLogLines() throws IOException {
keeper.addUri("foo");
keeper.addUri("foo");
HttpResponse response = handler.handle(null);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
index 4c7cb5475dd..3d9a2360e77 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.container.jdisc.ContentChannelOutputStream;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.handler.ReadableContentChannel;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
@@ -15,13 +15,13 @@ import java.util.Optional;
import java.util.concurrent.Executor;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class LogHandlerTest {
@Test
- public void handleCorrectlyParsesQueryParameters() throws IOException {
+ void handleCorrectlyParsesQueryParameters() throws IOException {
MockLogReader mockLogReader = new MockLogReader();
LogHandler logHandler = new LogHandler(mock(Executor.class), mockLogReader);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java b/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
index e1bd0da457e..f49c127cb01 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
@@ -2,15 +2,14 @@
package com.yahoo.container.handler;
import com.yahoo.compress.ZstdCompressor;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.Rule;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
+import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
-import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
@@ -20,12 +19,12 @@ import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LogReaderTest {
- @Rule
- public TemporaryFolder folder = new TemporaryFolder();
+ @TempDir
+ public File folder;
private Path logDirectory;
private static final String logv11 = "3600.2\tnode1.com\t5480\tcontainer\tstdout\tinfo\tfourth\n";
@@ -35,9 +34,9 @@ public class LogReaderTest {
private static final String log110 = "3600.1\tnode1.com\t5480\tcontainer\tstderr\twarning\tthird\n";
private static final String log200 = "86400.1\tnode2.com\t5480\tcontainer\tstderr\twarning\tjava.lang.NullPointerException\\n\\tat org.apache.felix.framework.BundleRevisionImpl.calculateContentPath(BundleRevisionImpl.java:438)\\n\\tat org.apache.felix.framework.BundleRevisionImpl.initializeContentPath(BundleRevisionImpl.java:371)\n";
- @Before
+ @BeforeEach
public void setup() throws IOException {
- logDirectory = folder.newFolder("opt/vespa/logs").toPath();
+ logDirectory = newFolder(folder, "opt/vespa/logs").toPath();
// Log archive paths and file names indicate what hour they contain logs for, with the start of that hour.
// Multiple entries may exist for each hour.
Files.createDirectories(logDirectory.resolve("1970/01/01"));
@@ -55,7 +54,7 @@ public class LogReaderTest {
}
@Test
- public void testThatLogsOutsideRangeAreExcluded() {
+ void testThatLogsOutsideRangeAreExcluded() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(baos, Instant.ofEpochMilli(150), Instant.ofEpochMilli(3601050), Optional.empty());
@@ -64,7 +63,7 @@ public class LogReaderTest {
}
@Test
- public void testThatLogsNotMatchingRegexAreExcluded() {
+ void testThatLogsNotMatchingRegexAreExcluded() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*-1.*"));
logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.empty());
@@ -73,7 +72,7 @@ public class LogReaderTest {
}
@Test
- public void testZippedStreaming() {
+ void testZippedStreaming() {
ByteArrayOutputStream zippedBaos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(zippedBaos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.empty());
@@ -82,7 +81,7 @@ public class LogReaderTest {
}
@Test
- public void logsForSingeNodeIsRetrieved() {
+ void logsForSingeNodeIsRetrieved() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.of("node2.com"));
@@ -103,4 +102,13 @@ public class LogReaderTest {
return new ZstdCompressor().compress(data, 0, data.length);
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
index e78810db897..18eca0bc8bd 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
@@ -15,7 +15,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.File;
@@ -27,8 +27,8 @@ import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Check semantics of VIP status handler. Do note this handler does not need to
@@ -52,7 +52,7 @@ public class VipStatusHandlerTestCase {
Metric metric = Mockito.mock(Metric.class);
@Test
- public void testHandleRequest() {
+ void testHandleRequest() {
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(false));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -78,7 +78,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testFileNotFound() {
+ void testFileNotFound() {
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(true)
.statusfile("/VipStatusHandlerTestCaseFileThatReallyReallyShouldNotExist"));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric);
@@ -95,7 +95,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testFileFound() throws IOException {
+ void testFileFound() throws IOException {
File statusFile = File.createTempFile("VipStatusHandlerTestCase", null);
try {
FileWriter writer = new FileWriter(statusFile);
@@ -121,7 +121,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testExplicitlyRotationControl() {
+ void testExplicitlyRotationControl() {
VipStatus vipStatus = new VipStatus();
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(false));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric, vipStatus);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java b/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
index 168dd2cac7b..eed3c047b0a 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
@@ -5,13 +5,11 @@ import com.yahoo.container.QrSearchersConfig;
import com.yahoo.container.core.VipStatusConfig;
import com.yahoo.container.jdisc.state.StateMonitor;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -19,14 +17,14 @@ import static org.junit.Assert.assertTrue;
public class VipStatusTestCase {
@Test
- public void testInitializingOrDownRequireAllUp() {
+ void testInitializingOrDownRequireAllUp() {
String[] clusters = {"cluster1", "cluster2", "cluster3"};
verifyStatus(clusters, StateMonitor.Status.initializing);
verifyStatus(clusters, StateMonitor.Status.down);
}
@Test
- public void testUpRequireAllDown() {
+ void testUpRequireAllDown() {
String[] clusters = {"cluster1", "cluster2", "cluster3"};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, true, new ClustersStatus(), new MetricMock());
@@ -54,21 +52,21 @@ public class VipStatusTestCase {
}
@Test
- public void testNoClustersConfiguringInitiallyInRotationFalse() {
+ void testNoClustersConfiguringInitiallyInRotationFalse() {
String[] clusters = {};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, false, new ClustersStatus(), new MetricMock());
assertFalse(v.isInRotation());
}
@Test
- public void testNoClustersConfiguringInitiallyInRotationTrue() {
+ void testNoClustersConfiguringInitiallyInRotationTrue() {
String[] clusters = {};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, true, new ClustersStatus(), new MetricMock());
assertTrue(v.isInRotation());
}
@Test
- public void testInRotationMetricFollowsRotationState() {
+ void testInRotationMetricFollowsRotationState() {
MetricMock metric = new MetricMock();
String[] clusters = {"cluster1", "cluster2", "cluster3"};
@@ -81,17 +79,17 @@ public class VipStatusTestCase {
}
@Test
- public void testClusterRemovalRemovedIsDown() {
+ void testClusterRemovalRemovedIsDown() {
assertClusterRemoval(true, false);
}
@Test
- public void testClusterRemovalRemovedIsUp() {
+ void testClusterRemovalRemovedIsUp() {
assertClusterRemoval(false, false);
}
@Test
- public void testClusterRemovalAnotherIsDown() {
+ void testClusterRemovalAnotherIsDown() {
assertClusterRemoval(false, true);
}
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
index c6e3986e870..4743075a9a6 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler.metrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author gjoranv
@@ -11,13 +11,13 @@ import static org.junit.Assert.assertEquals;
public class ErrorResponseTest {
@Test
- public void error_message_is_wrapped_in_json_object() {
+ void error_message_is_wrapped_in_json_object() {
var json = ErrorResponse.asErrorJson("bad");
assertEquals("{\"error\":\"bad\"}", json);
}
@Test
- public void quotes_are_escaped() {
+ void quotes_are_escaped() {
var json = ErrorResponse.asErrorJson("Message \" with \" embedded quotes.");
assertEquals("{\"error\":\"Message \\\" with \\\" embedded quotes.\"}", json);
}
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
index 350aad8198b..ad5b1a49670 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
@@ -4,12 +4,12 @@ package com.yahoo.container.handler.metrics;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.BufferedReader;
import java.io.IOException;
@@ -26,9 +26,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options
import static com.yahoo.container.handler.metrics.MetricsV2Handler.V2_PATH;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.VALUES_PATH;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.consumerQuery;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -53,15 +51,15 @@ public class MetricsV2HandlerTest {
private static RequestHandlerTestDriver testDriver;
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());
+ @RegisterExtension
+ public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(options().dynamicPort()).build();
- @Before
+ @BeforeEach
public void setup() {
setupWireMock();
var handler = new MetricsV2Handler(Executors.newSingleThreadExecutor(),
new MetricsProxyApiConfig.Builder()
- .metricsPort(wireMockRule.port())
+ .metricsPort(wireMockRule.getPort())
.metricsApiPath(MOCK_METRICS_PATH)
.prometheusApiPath("Not/In/Use")
.build());
@@ -80,7 +78,7 @@ public class MetricsV2HandlerTest {
}
@Test
- public void v2_response_contains_values_uri() throws Exception {
+ void v2_response_contains_values_uri() throws Exception {
String response = testDriver.sendRequest(V2_URI).readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("resources"));
@@ -92,29 +90,29 @@ public class MetricsV2HandlerTest {
assertEquals(VALUES_URI, valuesUri.get("url").textValue());
}
- @Ignore
+ @Disabled
@Test
- public void visually_inspect_values_response() {
+ void visually_inspect_values_response() {
JsonNode responseJson = getResponseAsJson(null);
System.out.println(responseJson);
}
@Test
- public void invalid_path_yields_error_response() throws Exception {
+ void invalid_path_yields_error_response() throws Exception {
String response = testDriver.sendRequest(V2_URI + "/invalid").readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("error"));
- assertTrue(root.get("error" ).textValue().startsWith("No content"));
+ assertTrue(root.get("error").textValue().startsWith("No content"));
}
@Test
- public void values_response_is_equal_to_test_file() {
+ void values_response_is_equal_to_test_file() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
assertEquals(RESPONSE, response);
}
@Test
- public void consumer_is_propagated_to_metrics_proxy_api() {
+ void consumer_is_propagated_to_metrics_proxy_api() {
JsonNode responseJson = getResponseAsJson(CUSTOM_CONSUMER);
JsonNode firstNodeMetricsValues =
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
index 98920b895e0..5989ba4a202 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
@@ -4,12 +4,12 @@ package com.yahoo.container.handler.metrics;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.concurrent.Executors;
@@ -20,8 +20,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.consumerQuery;
import static com.yahoo.container.handler.metrics.MetricsV2HandlerTest.getFileContents;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -46,16 +46,16 @@ public class PrometheusV1HandlerTest {
private static RequestHandlerTestDriver testDriver;
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());
+ @RegisterExtension
+ public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(options().dynamicPort()).build();
- @Before
+ @BeforeEach
public void setup() {
setupWireMock();
var handler = new PrometheusV1Handler(Executors.newSingleThreadExecutor(),
new MetricsProxyApiConfig.Builder()
.prometheusApiPath(MOCK_METRICS_PATH)
- .metricsPort(wireMockRule.port())
+ .metricsPort(wireMockRule.getPort())
.metricsApiPath("/Not/In/Use")
.build());
testDriver = new RequestHandlerTestDriver(handler);
@@ -74,7 +74,7 @@ public class PrometheusV1HandlerTest {
}
@Test
- public void v1_response_contains_values_uri() throws Exception {
+ void v1_response_contains_values_uri() throws Exception {
String response = testDriver.sendRequest(V1_URI).readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("resources"));
@@ -86,29 +86,29 @@ public class PrometheusV1HandlerTest {
assertEquals(VALUES_URI, valuesUri.get("url").asText());
}
- @Ignore
+ @Disabled
@Test
- public void visually_inspect_values_response() {
+ void visually_inspect_values_response() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
System.out.println(response);
}
@Test
- public void invalid_path_yields_error_response() throws Exception {
+ void invalid_path_yields_error_response() throws Exception {
String response = testDriver.sendRequest(V1_URI + "/invalid").readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("error"));
- assertTrue(root.get("error" ).textValue().startsWith("No content"));
+ assertTrue(root.get("error").textValue().startsWith("No content"));
}
@Test
- public void values_response_is_equal_to_test_file() {
+ void values_response_is_equal_to_test_file() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
assertEquals(RESPONSE, response);
}
@Test
- public void consumer_is_propagated_to_metrics_proxy_api() {
+ void consumer_is_propagated_to_metrics_proxy_api() {
String response = testDriver.sendRequest(VALUES_URI + consumerQuery(CUSTOM_CONSUMER)).readAll();
assertTrue(response.contains(REPLACED_CPU_METRIC));
diff --git a/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java b/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
index 2efa717800d..eefcc43fcb7 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
@@ -4,7 +4,7 @@ package com.yahoo.container.handler.test;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -12,7 +12,8 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Executor;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -22,7 +23,7 @@ public class MockServiceTest {
private final File testFile = new File("src/test/java/com/yahoo/container/handler/test/test.txt");
@Test
- public void testHandlerTextFormat() throws InterruptedException, IOException {
+ void testHandlerTextFormat() throws InterruptedException, IOException {
HttpResponse response = runHandler(com.yahoo.jdisc.http.HttpRequest.Method.GET, "/foo/bar");
assertResponse(response, 200, "Hello\nThere!");
@@ -34,20 +35,24 @@ public class MockServiceTest {
}
@Test
- public void testNoHandlerFound() throws InterruptedException, IOException {
+ void testNoHandlerFound() throws InterruptedException, IOException {
HttpResponse response = runHandler(com.yahoo.jdisc.http.HttpRequest.Method.DELETE, "/foo/bar");
assertEquals(404, response.getStatus());
assertResponseContents(response, "DELETE:/foo/bar was not found");
}
- @Test(expected = IllegalArgumentException.class)
- public void testUnknownFileType() throws InterruptedException, IOException {
- runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant"));
+ @Test
+ void testUnknownFileType() throws InterruptedException, IOException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant"));
+ });
}
- @Test(expected = FileNotFoundException.class)
- public void testExceptionResponse() throws InterruptedException, IOException {
- runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant.txt"));
+ @Test
+ void testExceptionResponse() throws InterruptedException, IOException {
+ assertThrows(FileNotFoundException.class, () -> {
+ runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant.txt"));
+ });
}
private void assertResponse(HttpResponse response, int expectedCode, String expectedMessage) throws IOException {
diff --git a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
index c3f91000296..4639022d767 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
@@ -6,15 +6,15 @@ import com.yahoo.concurrent.Receiver;
import com.yahoo.container.protect.ProcessTerminator;
import com.yahoo.container.test.MetricMock;
import com.yahoo.jdisc.Metric;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Steinar Knutsen
@@ -25,14 +25,14 @@ public class ContainerThreadPoolImplTest {
private static final int CPUS = 16;
@Test
- public final void testThreadPool() throws InterruptedException {
+ final void testThreadPool() throws InterruptedException {
Metric metrics = new MetricMock();
ContainerThreadpoolConfig config = new ContainerThreadpoolConfig(new ContainerThreadpoolConfig.Builder().maxThreads(1));
ContainerThreadPool threadPool = new ContainerThreadpoolImpl(config, metrics);
Executor exec = threadPool.executor();
Tuple2<Receiver.MessageState, Boolean> reply;
FlipIt command = new FlipIt();
- for (boolean done = false; !done;) {
+ for (boolean done = false; !done; ) {
try {
exec.execute(command);
done = true;
@@ -74,7 +74,7 @@ public class ContainerThreadPoolImplTest {
}
@Test
- public void testThatThreadPoolSizeFollowsConfig() {
+ void testThatThreadPoolSizeFollowsConfig() {
MetricMock metrics = new MetricMock();
ThreadPoolExecutor executor = createPool(metrics, 3, 1200);
assertEquals(3, executor.getMaximumPoolSize());
@@ -86,11 +86,12 @@ public class ContainerThreadPoolImplTest {
assertEquals(1200L, metrics.innvocations().get("jdisc.thread_pool.work_queue.capacity").val);
assertEquals(0L, metrics.innvocations().get("jdisc.thread_pool.work_queue.size").val);
}
+
@Test
- public void testThatThreadPoolSizeAutoDetected() {
+ void testThatThreadPoolSizeAutoDetected() {
MetricMock metrics = new MetricMock();
ThreadPoolExecutor executor = createPool(metrics, 0, 0);
- assertEquals(CPUS*4, executor.getMaximumPoolSize());
+ assertEquals(CPUS * 4, executor.getMaximumPoolSize());
assertEquals(0, executor.getQueue().remainingCapacity());
assertEquals(7, metrics.innvocations().size());
assertEquals(64L, metrics.innvocations().get("serverThreadPoolSize").val);
@@ -99,17 +100,19 @@ public class ContainerThreadPoolImplTest {
assertEquals(64L, metrics.innvocations().get("jdisc.thread_pool.work_queue.capacity").val);
assertEquals(0L, metrics.innvocations().get("jdisc.thread_pool.work_queue.size").val);
}
+
@Test
- public void testThatQueueSizeAutoDetected() {
+ void testThatQueueSizeAutoDetected() {
ThreadPoolExecutor executor = createPool(24, -50);
assertEquals(24, executor.getMaximumPoolSize());
- assertEquals(24*50, executor.getQueue().remainingCapacity());
+ assertEquals(24 * 50, executor.getQueue().remainingCapacity());
}
+
@Test
- public void testThatThreadPoolSizeAndQueueSizeAutoDetected() {
+ void testThatThreadPoolSizeAndQueueSizeAutoDetected() {
ThreadPoolExecutor executor = createPool(0, -100);
- assertEquals(CPUS*4, executor.getMaximumPoolSize());
- assertEquals(CPUS*4*100, executor.getQueue().remainingCapacity());
+ assertEquals(CPUS * 4, executor.getMaximumPoolSize());
+ assertEquals(CPUS * 4 * 100, executor.getQueue().remainingCapacity());
}
private class FlipIt implements Runnable {
@@ -121,9 +124,10 @@ public class ContainerThreadPoolImplTest {
}
}
+ // Ignored because it depends on the system time and so is unstable on factory
@Test
- @Ignore // Ignored because it depends on the system time and so is unstable on factory
- public void testThreadPoolTerminationOnBreakdown() throws InterruptedException {
+ @Disabled
+ void testThreadPoolTerminationOnBreakdown() throws InterruptedException {
ContainerThreadpoolConfig config = new ContainerThreadpoolConfig(
new ContainerThreadpoolConfig.Builder()
.maxThreads(2)
@@ -138,10 +142,16 @@ public class ContainerThreadPoolImplTest {
assertEquals(0, terminator.dieRequests);
assertRejected(threadPool, new Hang(500)); // no more threads
assertEquals(0, terminator.dieRequests); // ... but not for long enough yet
- try { Thread.sleep(1500); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ }
threadPool.executor().execute(new Hang(1));
assertEquals(0, terminator.dieRequests);
- try { Thread.sleep(50); } catch (InterruptedException e) {} // Make sure both threads are available
+ try {
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ } // Make sure both threads are available
// Dying when hanging both thread pool threads for longer than max thread execution time
threadPool.executor().execute(new Hang(2000));
@@ -149,7 +159,10 @@ public class ContainerThreadPoolImplTest {
assertEquals(0, terminator.dieRequests);
assertRejected(threadPool, new Hang(2000)); // no more threads
assertEquals(0, terminator.dieRequests); // ... but not for long enough yet
- try { Thread.sleep(1500); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ }
assertRejected(threadPool, new Hang(2000)); // no more threads
assertEquals(1, terminator.dieRequests); // ... for longer than maxThreadExecutionTime
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
index 400697af2a8..1b0521177e0 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
@@ -48,18 +48,18 @@ public class ExtendedResponseTestCase {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
r = new TestResponse(Response.Status.OK);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testRenderOutputStreamContentChannelCompletionHandler() throws IOException {
+ final void testRenderOutputStreamContentChannelCompletionHandler() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
r.render(b, null, null);
assertEquals(COM_YAHOO_CONTAINER_JDISC_EXTENDED_RESPONSE_TEST_CASE, Utf8.toString(b.toByteArray()));
@@ -67,22 +67,22 @@ public class ExtendedResponseTestCase {
@Test
- public final void testGetParsedQuery() {
+ final void testGetParsedQuery() {
assertNull(r.getParsedQuery());
}
@Test
- public final void testGetTiming() {
+ final void testGetTiming() {
assertNull(r.getTiming());
}
@Test
- public final void testGetCoverage() {
+ final void testGetCoverage() {
assertNull(r.getCoverage());
}
@Test
- public final void testGetHitCounts() {
+ final void testGetHitCounts() {
assertNull(r.getHitCounts());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java
index 7fcca89b0d3..ca3c24113ff 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -10,10 +10,9 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.text.Utf8;
@@ -28,74 +27,74 @@ public class HttpRequestTestCase {
HttpRequest r;
InputStream requestData;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
requestData = new ByteArrayInputStream(Utf8.toBytes(X_RAY_YANKEE_ZULU));
r = HttpRequest.createTestRequest(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA, Method.GET, requestData, Collections.singletonMap("foxtrot", "golf"));
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testGetMethod() {
+ final void testGetMethod() {
assertSame(Method.GET, r.getMethod());
}
@Test
- public final void testGetUri() throws URISyntaxException {
+ final void testGetUri() throws URISyntaxException {
assertEquals(new URI(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA), r.getUri());
}
@Test
- public final void testGetJDiscRequest() throws URISyntaxException {
+ final void testGetJDiscRequest() throws URISyntaxException {
assertEquals(new URI(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA), r.getJDiscRequest().getUri());
}
@Test
- public final void testGetProperty() {
+ final void testGetProperty() {
assertEquals("charlie", r.getProperty("bravo"));
assertEquals("golf", r.getProperty("foxtrot"));
assertNull(r.getProperty("zulu"));
}
@Test
- public final void testPropertyMap() {
+ final void testPropertyMap() {
assertEquals(4, r.propertyMap().size());
}
@Test
- public final void testGetBooleanProperty() {
+ final void testGetBooleanProperty() {
assertTrue(r.getBooleanProperty("trueboolean"));
assertFalse(r.getBooleanProperty("falseboolean"));
assertFalse(r.getBooleanProperty("bravo"));
}
@Test
- public final void testHasProperty() {
+ final void testHasProperty() {
assertFalse(r.hasProperty("alpha"));
assertTrue(r.hasProperty("bravo"));
}
@Test
- public final void testGetHeader() {
+ final void testGetHeader() {
assertNull(r.getHeader("SyntheticHeaderFor-com.yahoo.container.jdisc.HttpRequestTestCase"));
}
@Test
- public final void testGetHost() {
+ final void testGetHost() {
assertEquals("mailhost", r.getHost());
}
@Test
- public final void testGetPort() {
+ final void testGetPort() {
assertEquals(25, r.getPort());
}
@Test
- public final void testGetData() throws IOException {
+ final void testGetData() throws IOException {
byte[] b = new byte[X_RAY_YANKEE_ZULU.length()];
r.getData().read(b);
assertEquals(X_RAY_YANKEE_ZULU, Utf8.toString(b));
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
index 8dfa9a83988..963c98c2469 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.Response;
import com.yahoo.text.Utf8;
@@ -37,45 +37,45 @@ public class HttpResponseTestCase {
HttpResponse r;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
r = new TestResponse(Response.Status.OK);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testRender() throws IOException {
+ final void testRender() throws IOException {
ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
r.render(o);
assertEquals(COM_YAHOO_CONTAINER_JDISC_HTTP_RESPONSE_TEST_CASE_TEST_RESPONSE, Utf8.toString(o.toByteArray()));
}
@Test
- public final void testGetStatus() {
+ final void testGetStatus() {
assertEquals(Response.Status.OK, r.getStatus());
}
@Test
- public final void testHeaders() {
+ final void testHeaders() {
assertNotNull(r.headers());
}
@Test
- public final void testGetJdiscResponse() {
+ final void testGetJdiscResponse() {
assertNotNull(r.getJdiscResponse());
}
@Test
- public final void testGetContentType() {
+ final void testGetContentType() {
assertEquals(HttpResponse.DEFAULT_MIME_TYPE, r.getContentType());
}
@Test
- public final void testGetCharacterEncoding() {
+ final void testGetCharacterEncoding() {
assertEquals(HttpResponse.DEFAULT_CHARACTER_ENCODING, r.getCharacterEncoding());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
index ae0f679771e..94158b277c4 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
@@ -13,8 +13,8 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.io.IOException;
import java.io.OutputStream;
@@ -26,7 +26,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test contracts in LoggingRequestHandler.
@@ -110,13 +110,13 @@ public class LoggingRequestHandlerTestCase {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
executor = Executors.newCachedThreadPool();
handler = new AccessLogTestHandler(executor);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
handler = null;
executor.shutdown();
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
index ee76b3c5321..e423d44dfa4 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
@@ -3,10 +3,9 @@ package com.yahoo.container.jdisc;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
-import java.util.logging.Level;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -17,8 +16,8 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Check error logging from ContentChannelOutputStream is sane.
@@ -72,7 +71,7 @@ public class LoggingTestCase {
ContentChannelOutputStream stream;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
stream = new ContentChannelOutputStream(new FailingContentChannel());
logger = Logger.getLogger(ContentChannelOutputStream.class.getName());
@@ -83,7 +82,7 @@ public class LoggingTestCase {
logger.addHandler(logChecker);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
logger.removeHandler(logChecker);
logger.setUseParentHandlers(initUseParentHandlers);
@@ -96,7 +95,7 @@ public class LoggingTestCase {
}
@Test
- public final void testFailed() throws IOException {
+ final void testFailed() throws IOException {
stream.send(createData());
stream.send(createData());
stream.send(createData());
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
index 9967ead052d..2a3adaff16e 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.http.HttpRequest.Method;
/**
@@ -17,26 +17,26 @@ import com.yahoo.jdisc.http.HttpRequest.Method;
public class RequestBuilderTestCase {
HttpRequest.Builder b;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
HttpRequest r = HttpRequest.createTestRequest("http://ssh:22/alpha?bravo=charlie", Method.GET);
b = new HttpRequest.Builder(r);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
b = null;
}
@Test
- public final void testBasic() {
+ final void testBasic() {
HttpRequest r = b.put("delta", "echo").createDirectRequest();
assertEquals("charlie", r.getProperty("bravo"));
assertEquals("echo", r.getProperty("delta"));
}
@Test
- public void testRemove() {
+ void testRemove() {
HttpRequest orig = b.put("delta", "echo").createDirectRequest();
HttpRequest child = new HttpRequest.Builder(orig).removeProperty("delta").createDirectRequest();
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
index 2592b587539..86b7f545762 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.container.jdisc;
import com.yahoo.container.test.MetricMock;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
@@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ThreadedHttpRequestHandlerTest {
@Test
- public void unhandled_exceptions_metric_is_incremented_if_subclassed_handler_throws_exception() {
+ void unhandled_exceptions_metric_is_incremented_if_subclassed_handler_throws_exception() {
MetricMock metricMock = new MetricMock();
ThreadedHttpRequestHandlerThrowingException handler = new ThreadedHttpRequestHandlerThrowingException(metricMock);
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
@@ -24,7 +24,7 @@ public class ThreadedHttpRequestHandlerTest {
String expectedMetricName = "jdisc.http.handler.unhandled_exceptions";
assertThat(metricMock.innvocations())
.containsKey(expectedMetricName);
- assertThat(((MetricMock.SimpleMetricContext)metricMock.innvocations().get(expectedMetricName).ctx).dimensions)
+ assertThat(((MetricMock.SimpleMetricContext) metricMock.innvocations().get(expectedMetricName).ctx).dimensions)
.containsEntry("exception", "DummyException");
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
index a9b16799aea..0fbe533fd99 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.handler.*;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -23,7 +23,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -31,7 +31,7 @@ import static org.junit.Assert.*;
public class ThreadedRequestHandlerTestCase {
@Test
- public void requireThatNullExecutorThrowsException() {
+ void requireThatNullExecutorThrowsException() {
try {
new ThreadedRequestHandler(null) {
@@ -47,7 +47,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
+ void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -69,7 +69,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatOverriddenRequestTimeoutIsUsed() throws InterruptedException {
+ void requireThatOverriddenRequestTimeoutIsUsed() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -82,7 +82,7 @@ public class ThreadedRequestHandlerTestCase {
requestHandler.entryLatch.countDown();
assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
- assertEquals(1, (long)requestHandler.request.getTimeout(TimeUnit.SECONDS));
+ assertEquals(1, (long) requestHandler.request.getTimeout(TimeUnit.SECONDS));
assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
assertNull(responseHandler.content.read());
@@ -90,7 +90,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
+ void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -119,7 +119,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRejectedExecutionIsHandledGracefully() throws Exception {
+ void requireThatRejectedExecutionIsHandledGracefully() throws Exception {
// Instrumentation.
final Executor executor = new Executor() {
@Override
@@ -150,14 +150,14 @@ public class ThreadedRequestHandlerTestCase {
}
// Verification.
- assertEquals("Response handler should be invoked synchronously in this case.", 0, responseHandler.latch.getCount());
+ assertEquals(0, responseHandler.latch.getCount(), "Response handler should be invoked synchronously in this case.");
assertEquals(Response.Status.SERVICE_UNAVAILABLE, responseHandler.response.getStatus());
assertNull(responseHandler.content.read());
assertTrue(driver.close());
}
@Test
- public void requireThatRequestContentIsClosedIfHandlerIgnoresIt() throws InterruptedException {
+ void requireThatRequestContentIsClosedIfHandlerIgnoresIt() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -186,7 +186,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatResponseIsDispatchedIfHandlerIgnoresIt() throws InterruptedException {
+ void requireThatResponseIsDispatchedIfHandlerIgnoresIt() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -207,7 +207,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt()
+ void requireThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt()
throws InterruptedException
{
Executor executor = Executors.newSingleThreadExecutor();
@@ -360,7 +360,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void testMaxPendingOutputStream() throws IOException, ExecutionException, InterruptedException {
+ void testMaxPendingOutputStream() throws IOException, ExecutionException, InterruptedException {
ReadableContentChannel buffer = new ReadableContentChannel();
MaxPendingContentChannelOutputStream limited = new MaxPendingContentChannelOutputStream(buffer, 2);
@@ -375,7 +375,8 @@ public class ThreadedRequestHandlerTestCase {
future.get(100, TimeUnit.MILLISECONDS);
fail("Should not be able to write now");
}
- catch (TimeoutException expected) { }
+ catch (TimeoutException expected) {
+ }
// Free buffer capacity, so write completes, then drain buffer.
assertEquals(2, buffer.read().capacity());
@@ -390,12 +391,14 @@ public class ThreadedRequestHandlerTestCase {
limited.send(ByteBuffer.allocate(3));
fail("Should throw");
}
- catch (IOException expected) { }
+ catch (IOException expected) {
+ }
try {
limited.send(ByteBuffer.allocate(3));
fail("Should throw");
}
- catch (IOException expected) { }
+ catch (IOException expected) {
+ }
}
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
index 1b075ace190..5cec6c471fe 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
@@ -2,12 +2,12 @@
package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertEquals;
public class CoredumpGathererTest {
@Test
- public void finds_one_coredump() {
- JsonNode packet = CoredumpGatherer.gatherCoredumpMetrics(new MockFileWrapper());
+ void finds_one_coredump() {
+ JsonNode packet = CoredumpGatherer.gatherCoredumpMetrics(new MockFileWrapper());
- assertEquals("system-coredumps-processing", packet.get("application").textValue());
- assertEquals(1, packet.get("status_code").intValue());
- assertEquals("Found 1 coredump(s)", packet.get("status_msg").textValue());
+ assertEquals("system-coredumps-processing", packet.get("application").textValue());
+ assertEquals(1, packet.get("status_code").intValue());
+ assertEquals("Found 1 coredump(s)", packet.get("status_msg").textValue());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
index 634f5321555..c394630cb40 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
@@ -2,11 +2,11 @@
package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Path;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals;
public class HostLifeGathererTest {
@Test
- public void host_is_alive() {
+ void host_is_alive() {
JsonNode packet = HostLifeGatherer.getHostLifePacket(new MockFileWrapper());
JsonNode metrics = packet.get("metrics");
assertEquals("host_life", packet.get("application").textValue());
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
index 82349dd6af9..1fd5e081fb0 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.state;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
public class MetricSnapshotTest {
@@ -19,16 +19,16 @@ public class MetricSnapshotTest {
* most likely be deprecated.
*/
@Test
- public void emptyMetricSetNotAddedToClonedSnapshot() {
+ void emptyMetricSetNotAddedToClonedSnapshot() {
StateMetricContext ctx = StateMetricContext.newInstance(null);
MetricSnapshot snapshot = new MetricSnapshot();
snapshot.add(ctx, "foo", 1234);
MetricSnapshot newSnapshot = snapshot.createSnapshot();
assertFalse(newSnapshot.iterator().hasNext());
}
-
+
@Test
- public void testEquality() {
+ void testEquality() {
assertEquals(Collections.unmodifiableMap(new HashMap(0)).hashCode(), Collections.emptyMap().hashCode());
assertEquals(Collections.unmodifiableMap(new HashMap(0)), Collections.emptyMap());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
index 99a31640429..019fc1e1e78 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
@@ -4,8 +4,8 @@ package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -18,8 +18,8 @@ import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.PACKET_SEPAR
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.STATUS_CODE_KEY;
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.STATUS_MSG_KEY;
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.TIMESTAMP_KEY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -27,32 +27,33 @@ import static org.junit.Assert.assertTrue;
public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
private static final String APPLICATION_NAME = "state-handler-test-base";
+ private static final String HOST_DIMENSION = "some-hostname";
private static MetricsPacketsHandler metricsPacketsHandler;
- @Before
+ @BeforeEach
public void setupHandler() {
metricsPacketsHandlerConfig = new MetricsPacketsHandlerConfig(new MetricsPacketsHandlerConfig.Builder()
- .application(APPLICATION_NAME));
+ .application(APPLICATION_NAME).hostname(HOST_DIMENSION));
metricsPacketsHandler = new MetricsPacketsHandler(monitor, timer, snapshotProviderRegistry, metricsPacketsHandlerConfig);
testDriver = new RequestHandlerTestDriver(metricsPacketsHandler);
}
@Test
- public void status_packet_is_returned_prior_to_first_snapshot() throws Exception {
+ void status_packet_is_returned_prior_to_first_snapshot() throws Exception {
String response = requestAsString("http://localhost/metrics-packets");
List<JsonNode> packets = toJsonPackets(response);
assertEquals(1, packets.size());
JsonNode statusPacket = packets.get(0);
- assertEquals(statusPacket.toString(), APPLICATION_NAME, statusPacket.get(APPLICATION_KEY).asText());
- assertEquals(statusPacket.toString(), 0, statusPacket.get(STATUS_CODE_KEY).asInt());
- assertEquals(statusPacket.toString(), "up", statusPacket.get(STATUS_MSG_KEY).asText());
+ assertEquals(APPLICATION_NAME, statusPacket.get(APPLICATION_KEY).asText(), statusPacket.toString());
+ assertEquals(0, statusPacket.get(STATUS_CODE_KEY).asInt(), statusPacket.toString());
+ assertEquals("up", statusPacket.get(STATUS_MSG_KEY).asText(), statusPacket.toString());
}
@Test
- public void metrics_are_included_after_snapshot() throws Exception {
+ void metrics_are_included_after_snapshot() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
assertEquals(2, packets.size());
@@ -62,7 +63,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metadata_is_included_in_each_metrics_packet() throws Exception {
+ void metadata_is_included_in_each_metrics_packet() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
JsonNode counterPacket = packets.get(1);
@@ -73,16 +74,16 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void timestamp_resolution_is_in_seconds() throws Exception {
+ void timestamp_resolution_is_in_seconds() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
JsonNode counterPacket = packets.get(1);
- assertEquals(SNAPSHOT_INTERVAL/1000L, counterPacket.get(TIMESTAMP_KEY).asLong());
+ assertEquals(SNAPSHOT_INTERVAL / 1000L, counterPacket.get(TIMESTAMP_KEY).asLong());
}
@Test
- public void expected_aggregators_are_output_for_gauge_metrics() throws Exception{
+ void expected_aggregators_are_output_for_gauge_metrics() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var snapshot = new MetricSnapshot();
snapshot.set(context, "gauge", 0.2);
@@ -97,7 +98,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void dimensions_from_context_are_included() throws Exception {
+ void dimensions_from_context_are_included() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
createSnapshotWithCountMetric("counter", 1, context);
@@ -110,7 +111,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metrics_with_identical_dimensions_are_contained_in_the_same_packet() throws Exception {
+ void metrics_with_identical_dimensions_are_contained_in_the_same_packet() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var snapshot = new MetricSnapshot();
snapshot.add(context, "counter1", 1);
@@ -127,7 +128,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metrics_with_different_dimensions_get_separate_packets() throws Exception {
+ void metrics_with_different_dimensions_get_separate_packets() throws Exception {
var context1 = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var context2 = StateMetricContext.newInstance(Map.of("dim2", "value2"));
var snapshot = new MetricSnapshot();
@@ -138,6 +139,26 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
assertEquals(3, packets.size());
}
+
+ @Test
+ void host_dimension_only_created_if_absent() throws Exception {
+ var context1 = StateMetricContext.newInstance(Map.of("dim1", "value1", "host", "foo.bar"));
+ var context2 = StateMetricContext.newInstance(Map.of("dim2", "value2"));
+ var snapshot = new MetricSnapshot();
+ snapshot.add(context1, "counter1", 1);
+ snapshot.add(context2, "counter2", 2);
+ snapshotProvider.setSnapshot(snapshot);
+
+ var packets = incrementTimeAndGetJsonPackets();
+ assertEquals(3, packets.size());
+
+ packets.forEach(packet -> {
+ if (!packet.has(DIMENSIONS_KEY)) return;
+ var dimensions = packet.get(DIMENSIONS_KEY);
+ if (dimensions.has("dim1")) assertDimension(packet, "host", "foo.bar");
+ if (dimensions.has("dim2")) assertDimension(packet, "host", HOST_DIMENSION);
+ });
+ }
private List<JsonNode> incrementTimeAndGetJsonPackets() throws Exception {
advanceToNextSnapshot();
@@ -163,6 +184,13 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
assertEquals(expected, counterMetrics.get(metricName).asLong());
}
+ private void assertDimension(JsonNode metricsPacket, String dimensionName, String expectedDimensionValue) {
+ assertTrue(metricsPacket.has(DIMENSIONS_KEY));
+ var dimensions = metricsPacket.get(DIMENSIONS_KEY);
+ assertTrue(dimensions.has(dimensionName));
+ assertEquals(expectedDimensionValue, dimensions.get(dimensionName).asText());
+ }
+
private void createSnapshotWithCountMetric(String name, Number value, MetricDimensions context) {
var snapshot = new MetricSnapshot();
snapshot.add(context, name, value);
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
index 8f800707f7a..63502a6b49f 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
@@ -5,15 +5,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.yahoo.component.Vtag;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.vespa.defaults.Defaults;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -23,47 +21,47 @@ public class StateHandlerTest extends StateHandlerTestBase {
private static final String V1_URI = URI_BASE + "/state/v1/";
private static StateHandler stateHandler;
- @Before
+ @BeforeEach
public void setupHandler() {
stateHandler = new StateHandler(monitor, timer, applicationMetadataConfig, snapshotProviderRegistry);
testDriver = new RequestHandlerTestDriver(stateHandler);
}
@Test
- public void testStatusReportPriorToFirstSnapshot() throws Exception {
+ void testStatusReportPriorToFirstSnapshot() throws Exception {
JsonNode json = requestAsJson(V1_URI + "/all");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertFalse(json.toString(), json.get("metrics").has("values"));
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertFalse(json.get("metrics").has("values"), json.toString());
}
@Test
- public void testReportIncludesMetricsAfterSnapshot() throws Exception {
+ void testReportIncludesMetricsAfterSnapshot() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.add(null, "foo", 1);
snapshot.set(null, "bar", 4);
snapshotProvider.setSnapshot(snapshot);
JsonNode json1 = requestAsJson(V1_URI + "metrics");
- assertEquals(json1.toString(), "up", json1.get("status").get("code").asText());
- assertEquals(json1.toString(), 2, json1.get("metrics").get("values").size());
+ assertEquals("up", json1.get("status").get("code").asText(), json1.toString());
+ assertEquals(2, json1.get("metrics").get("values").size(), json1.toString());
}
@Test
- public void testCountMetricCount() throws Exception {
+ void testCountMetricCount() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.add(null, "foo", 4);
snapshot.add(null, "foo", 2);
snapshotProvider.setSnapshot(snapshot);
JsonNode json = requestAsJson(V1_URI + "all");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
- assertEquals(json.toString(), 6,
- json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertEquals(1, json.get("metrics").get("values").size(), json.toString());
+ assertEquals(6,
+ json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001, json.toString());
}
@Test
- public void gaugeSnapshotsTracksCountMinMaxAvgPerPeriod() throws Exception {
+ void gaugeSnapshotsTracksCountMinMaxAvgPerPeriod() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.set(null, "bar", 20);
snapshot.set(null, "bar", 40);
@@ -71,23 +69,23 @@ public class StateHandlerTest extends StateHandlerTestBase {
JsonNode json = requestAsJson(V1_URI + "all");
JsonNode metricValues = getFirstMetricValueNode(json);
- assertEquals(json.toString(), 40, metricValues.get("last").asDouble(), 0.001);
+ assertEquals(40, metricValues.get("last").asDouble(), 0.001, json.toString());
// Last snapshot had explicit values set
- assertEquals(json.toString(), 30, metricValues.get("average").asDouble(), 0.001);
- assertEquals(json.toString(), 20, metricValues.get("min").asDouble(), 0.001);
- assertEquals(json.toString(), 40, metricValues.get("max").asDouble(), 0.001);
- assertEquals(json.toString(), 2, metricValues.get("count").asInt());
+ assertEquals(30, metricValues.get("average").asDouble(), 0.001, json.toString());
+ assertEquals(20, metricValues.get("min").asDouble(), 0.001, json.toString());
+ assertEquals(40, metricValues.get("max").asDouble(), 0.001, json.toString());
+ assertEquals(2, metricValues.get("count").asInt(), json.toString());
}
private JsonNode getFirstMetricValueNode(JsonNode root) {
- assertEquals(root.toString(), 1, root.get("metrics").get("values").size());
+ assertEquals(1, root.get("metrics").get("values").size(), root.toString());
JsonNode metricValues = root.get("metrics").get("values").get(0).get("values");
- assertTrue(root.toString(), metricValues.has("last"));
+ assertTrue(metricValues.has("last"), root.toString());
return metricValues;
}
@Test
- public void testReadabilityOfJsonReport() {
+ void testReadabilityOfJsonReport() {
var snapshot = new MetricSnapshot(0L, SNAPSHOT_INTERVAL, TimeUnit.MILLISECONDS);
snapshot.add(null, "foo", 1);
var ctx = StateMetricContext.newInstance(Map.of("component", "test"));
@@ -98,43 +96,43 @@ public class StateHandlerTest extends StateHandlerTestBase {
snapshotProvider.setSnapshot(snapshot);
advanceToNextSnapshot();
assertEquals("{\n" +
- " \"time\" : 300000,\n" +
- " \"status\" : {\n" +
- " \"code\" : \"up\"\n" +
- " },\n" +
- " \"metrics\" : {\n" +
- " \"snapshot\" : {\n" +
- " \"from\" : 0.0,\n" +
- " \"to\" : 300.0\n" +
- " },\n" +
- " \"values\" : [ {\n" +
- " \"name\" : \"foo\",\n" +
- " \"values\" : {\n" +
- " \"count\" : 1,\n" +
- " \"rate\" : 0.0033333333333333335\n" +
- " }\n" +
- " }, {\n" +
- " \"name\" : \"bar\",\n" +
- " \"values\" : {\n" +
- " \"average\" : 3.5,\n" +
- " \"sum\" : 14.0,\n" +
- " \"count\" : 4,\n" +
- " \"last\" : 5.0,\n" +
- " \"max\" : 5.0,\n" +
- " \"min\" : 2.0,\n" +
- " \"rate\" : 0.013333333333333334\n" +
- " },\n" +
- " \"dimensions\" : {\n" +
- " \"component\" : \"test\"\n" +
- " }\n" +
- " } ]\n" +
- " }\n" +
- "}",
- requestAsString(V1_URI + "all"));
+ " \"time\" : 300000,\n" +
+ " \"status\" : {\n" +
+ " \"code\" : \"up\"\n" +
+ " },\n" +
+ " \"metrics\" : {\n" +
+ " \"snapshot\" : {\n" +
+ " \"from\" : 0.0,\n" +
+ " \"to\" : 300.0\n" +
+ " },\n" +
+ " \"values\" : [ {\n" +
+ " \"name\" : \"foo\",\n" +
+ " \"values\" : {\n" +
+ " \"count\" : 1,\n" +
+ " \"rate\" : 0.0033333333333333335\n" +
+ " }\n" +
+ " }, {\n" +
+ " \"name\" : \"bar\",\n" +
+ " \"values\" : {\n" +
+ " \"average\" : 3.5,\n" +
+ " \"sum\" : 14.0,\n" +
+ " \"count\" : 4,\n" +
+ " \"last\" : 5.0,\n" +
+ " \"max\" : 5.0,\n" +
+ " \"min\" : 2.0,\n" +
+ " \"rate\" : 0.013333333333333334\n" +
+ " },\n" +
+ " \"dimensions\" : {\n" +
+ " \"component\" : \"test\"\n" +
+ " }\n" +
+ " } ]\n" +
+ " }\n" +
+ "}",
+ requestAsString(V1_URI + "all"));
}
@Test
- public void testHealthAggregation() throws Exception {
+ void testHealthAggregation() throws Exception {
var context1 = StateMetricContext.newInstance(Map.of("port", Defaults.getDefaults().vespaWebServicePort()));
var context2 = StateMetricContext.newInstance(Map.of("port", 80));
var snapshot = new MetricSnapshot();
@@ -146,20 +144,22 @@ public class StateHandlerTest extends StateHandlerTestBase {
snapshotProvider.setSnapshot(snapshot);
JsonNode json = requestAsJson(V1_URI + "health");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertEquals(json.toString(), 2, json.get("metrics").get("values").size());
- assertEquals(json.toString(), "requestsPerSecond",
- json.get("metrics").get("values").get(0).get("name").asText());
- assertEquals(json.toString(), 6,
- json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
- assertEquals(json.toString(), "latencySeconds",
- json.get("metrics").get("values").get(1).get("name").asText());
- assertEquals(json.toString(), 0.03,
- json.get("metrics").get("values").get(1).get("values").get("average").asDouble(), 0.001);
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertEquals(2, json.get("metrics").get("values").size(), json.toString());
+ assertEquals("requestsPerSecond",
+ json.get("metrics").get("values").get(0).get("name").asText(),
+ json.toString());
+ assertEquals(6,
+ json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001, json.toString());
+ assertEquals("latencySeconds",
+ json.get("metrics").get("values").get(1).get("name").asText(),
+ json.toString());
+ assertEquals(0.03,
+ json.get("metrics").get("values").get(1).get("values").get("average").asDouble(), 0.001, json.toString());
}
@Test
- public void testStateConfig() throws Exception {
+ void testStateConfig() throws Exception {
JsonNode root = requestAsJson(V1_URI + "config");
JsonNode config = root.get("config");
@@ -168,7 +168,7 @@ public class StateHandlerTest extends StateHandlerTestBase {
}
@Test
- public void testStateVersion() throws Exception {
+ void testStateVersion() throws Exception {
JsonNode root = requestAsJson(V1_URI + "version");
JsonNode version = root.get("version");
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
index b87a1179832..e3d01391a9c 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
@@ -9,8 +9,8 @@ import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.container.jdisc.config.HealthMonitorConfig;
import com.yahoo.jdisc.Timer;
-import org.junit.Before;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@@ -38,7 +38,7 @@ public class StateHandlerTestBase {
MockSnapshotProvider snapshotProvider;
ComponentRegistry<SnapshotProvider> snapshotProviderRegistry;
- @BeforeClass
+ @BeforeAll
public static void setupClass() {
healthMonitorConfig = new HealthMonitorConfig(new HealthMonitorConfig.Builder()
.initialStatus("up"));
@@ -46,7 +46,7 @@ public class StateHandlerTestBase {
.generation(META_GENERATION));
}
- @Before
+ @BeforeEach
public void setupSnapshotProvider() {
timer = currentTimeMillis::get;
snapshotProvider = new MockSnapshotProvider();
diff --git a/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java b/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java
index 451e6dc42bb..f942ee588be 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.logging;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.Matchers.contains;
@@ -14,11 +14,11 @@ public class CircularArrayAccessLogKeeperTest {
private CircularArrayAccessLogKeeper circularArrayAccessLogKeeper = new CircularArrayAccessLogKeeper();
@Test
- public void testSizeIsCroppedCorrectly() {
+ void testSizeIsCroppedCorrectly() {
for (int i = 0; i < CircularArrayAccessLogKeeper.SIZE - 1; i++) {
circularArrayAccessLogKeeper.addUri(String.valueOf(i));
}
- assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE -1));
+ assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE - 1));
circularArrayAccessLogKeeper.addUri("foo");
assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE));
circularArrayAccessLogKeeper.addUri("bar");
@@ -28,12 +28,12 @@ public class CircularArrayAccessLogKeeperTest {
}
@Test
- public void testEmpty() {
+ void testEmpty() {
assertThat(circularArrayAccessLogKeeper.getUris().size(), is(0));
}
@Test
- public void testSomeItems() {
+ void testSomeItems() {
circularArrayAccessLogKeeper.addUri("a");
circularArrayAccessLogKeeper.addUri("b");
circularArrayAccessLogKeeper.addUri("b");
diff --git a/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
index eb862d69b5b..1c66a1d805a 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.container.logging;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -41,35 +41,36 @@ public class JSONLogTestCase {
}
@Test
- public void test_json_log_entry() {
+ void test_json_log_entry() {
RequestLogEntry entry = newRequestLogEntry("test").build();
- String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ String expectedOutput =
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
+
@Test
- public void test_json_of_trace() {
+ void test_json_of_trace() {
TraceNode root = new TraceNode("root", 7);
RequestLogEntry entry = newRequestLogEntry("test")
.traceNode(root)
@@ -77,31 +78,32 @@ public class JSONLogTestCase {
String expectedOutput =
"{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"trace\":{\"timestamp\":0,\"message\":\"root\"}," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"trace\":{\"timestamp\":0,\"message\":\"root\"}," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
+
@Test
- public void test_with_keyvalues() {
+ void test_with_keyvalues() {
RequestLogEntry entry = newRequestLogEntry("test")
.addExtraAttribute("singlevalue", "value1")
.addExtraAttribute("multivalue", "value2")
@@ -109,62 +111,62 @@ public class JSONLogTestCase {
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}," +
- "\"attributes\":{" +
- "\"singlevalue\":\"value1\"," +
- "\"multivalue\":[\"value2\",\"value3\"]}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}," +
+ "\"attributes\":{" +
+ "\"singlevalue\":\"value1\"," +
+ "\"multivalue\":[\"value2\",\"value3\"]}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@Test
- public void test_with_remoteaddrport() throws Exception {
+ void test_with_remoteaddrport() throws Exception {
RequestLogEntry entry = newRequestLogEntry("test")
.remoteAddress("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
@@ -175,34 +177,34 @@ public class JSONLogTestCase {
.build();
expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
- "\"remoteport\":1234," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
+ "\"remoteport\":1234," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@Test
- public void test_remote_address_same_as_ip_address() throws Exception {
+ void test_remote_address_same_as_ip_address() throws Exception {
RequestLogEntry entry = newRequestLogEntry("test").build();
RequestLogEntry entrywithremote = newRequestLogEntry("test")
.remoteAddress(entry.peerAddress().get())
@@ -212,7 +214,7 @@ public class JSONLogTestCase {
}
@Test
- public void test_useragent_with_quotes() {
+ void test_useragent_with_quotes() {
RequestLogEntry entry = new RequestLogEntry.Builder()
.rawQuery("query=test")
.rawPath("")
@@ -231,26 +233,26 @@ public class JSONLogTestCase {
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I; \\\"Best Browser Ever\\\")\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I; \\\"Best Browser Ever\\\")\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@@ -280,15 +282,15 @@ public class JSONLogTestCase {
}
@Test
- public void test_with_coverage_degradation() {
+ void test_with_coverage_degradation() {
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,0)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 0)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"match-phase\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,1)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 1)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"timeout\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,2)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 2)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"adaptive-timeout\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,4)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 4)).build());
}
private String formatEntry(RequestLogEntry entry) {
diff --git a/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
index 2a3877100f5..b5c65733436 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.container.logging;
import com.yahoo.compress.ZstdCompressor;
import com.yahoo.container.logging.LogFileHandler.Compression;
import com.yahoo.io.IOUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
@@ -26,7 +26,7 @@ import java.util.zip.GZIPInputStream;
import static com.yahoo.yolean.Exceptions.uncheck;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author Bob Travis
@@ -35,26 +35,26 @@ import static org.junit.Assert.assertNotEquals;
public class LogFileHandlerTestCase {
private static final int BUFFER_SIZE = 0x10000;
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
@Test
- public void testIt() throws IOException {
- File root = temporaryFolder.newFolder("logfilehandlertest");
+ void testIt() throws IOException {
+ File root = newFolder(temporaryFolder, "logfilehandlertest");
String pattern = root.getAbsolutePath() + "/logfilehandlertest.%Y%m%d%H%M%S";
long[] rTimes = {1000, 2000, 10000};
LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, pattern, rTimes, null, 2048, "thread-name", new StringLogWriter());
long now = System.currentTimeMillis();
- long millisPerDay = 60*60*24*1000;
- long tomorrowDays = (now / millisPerDay) +1;
+ long millisPerDay = 60 * 60 * 24 * 1000;
+ long tomorrowDays = (now / millisPerDay) + 1;
long tomorrowMillis = tomorrowDays * millisPerDay;
- assertThat(tomorrowMillis+1000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis));
- assertThat(tomorrowMillis+10000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis+3000));
+ assertThat(tomorrowMillis + 1000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis));
+ assertThat(tomorrowMillis + 10000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis + 3000));
String message = "test";
h.publish(message);
- h.publish( "another test");
+ h.publish("another test");
h.rotateNow();
h.publish(message);
h.flush();
@@ -62,41 +62,42 @@ public class LogFileHandlerTestCase {
}
@Test
- public void testSimpleLogging() throws IOException {
- File logFile = temporaryFolder.newFile("testLogFileG1.txt");
+ void testSimpleLogging() throws IOException {
+ File logFile = File.createTempFile("testLogFileG1.txt", null, temporaryFolder);
- //create logfilehandler
- LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
+ //create logfilehandler
+ LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
- //write log
- h.publish("testDeleteFileFirst1");
- h.flush();
- h.shutdown();
+ //write log
+ h.publish("testDeleteFileFirst1");
+ h.flush();
+ h.shutdown();
}
@Test
- public void testDeleteFileDuringLogging() throws IOException {
- File logFile = temporaryFolder.newFile("testLogFileG2.txt");
+ void testDeleteFileDuringLogging() throws IOException {
+ File logFile = File.createTempFile("testLogFileG2.txt", null, temporaryFolder);
- //create logfilehandler
- LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
+ //create logfilehandler
+ LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
- //write log
- h.publish("testDeleteFileDuringLogging1");
- h.flush();
+ //write log
+ h.publish("testDeleteFileDuringLogging1");
+ h.flush();
- //delete log file
+ //delete log file
logFile.delete();
- //write log again
- h.publish("testDeleteFileDuringLogging2");
- h.flush();
- h.shutdown();
+ //write log again
+ h.publish("testDeleteFileDuringLogging2");
+ h.flush();
+ h.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testSymlink() throws IOException, InterruptedException {
- File root = temporaryFolder.newFolder("testlogforsymlinkchecking");
+ @Test
+ @Timeout(300_000)
+ void testSymlink() throws IOException, InterruptedException {
+ File root = newFolder(temporaryFolder, "testlogforsymlinkchecking");
Formatter formatter = new Formatter() {
public String format(LogRecord r) {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd:HH:mm:ss.SSS");
@@ -125,9 +126,10 @@ public class LogFileHandlerTestCase {
handler.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void compresses_previous_log_file() throws InterruptedException, IOException {
- File root = temporaryFolder.newFolder("compressespreviouslogfile");
+ @Test
+ @Timeout(300_000)
+ void compresses_previous_log_file() throws InterruptedException, IOException {
+ File root = newFolder(temporaryFolder, "compressespreviouslogfile");
LogFileHandler<String> firstHandler = new LogFileHandler<>(
Compression.ZSTD, BUFFER_SIZE, root.getAbsolutePath() + "/compressespreviouslogfile.%Y%m%d%H%M%S%s", new long[]{0}, "symlink", 2048, "thread-name", new StringLogWriter());
firstHandler.publishAndWait("test");
@@ -135,7 +137,7 @@ public class LogFileHandlerTestCase {
assertThat(Files.size(Paths.get(firstHandler.getFileName()))).isEqualTo(5);
assertThat(root.toPath().resolve("symlink").toRealPath().toString()).isEqualTo(
- Paths.get(firstHandler.getFileName()).toRealPath().toString());
+ Paths.get(firstHandler.getFileName()).toRealPath().toString());
LogFileHandler<String> secondHandler = new LogFileHandler<>(
Compression.ZSTD, BUFFER_SIZE, root.getAbsolutePath() + "/compressespreviouslogfile.%Y%m%d%H%M%S%s", new long[]{0}, "symlink", 2048, "thread-name", new StringLogWriter());
@@ -143,22 +145,24 @@ public class LogFileHandlerTestCase {
secondHandler.rotateNow();
assertThat(root.toPath().resolve("symlink").toRealPath().toString()).isEqualTo(
- Paths.get(secondHandler.getFileName()).toRealPath().toString());
+ Paths.get(secondHandler.getFileName()).toRealPath().toString());
while (Files.exists(root.toPath().resolve(firstHandler.getFileName()))) Thread.sleep(1);
assertThat(Files.exists(Paths.get(firstHandler.getFileName() + ".zst"))).isTrue();
secondHandler.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testcompression_gzip() throws InterruptedException, IOException {
+ @Test
+ @Timeout(300_000)
+ void testcompression_gzip() throws InterruptedException, IOException {
testcompression(
Compression.GZIP, "gz",
(compressedFile, __) -> uncheck(() -> new String(new GZIPInputStream(Files.newInputStream(compressedFile)).readAllBytes())));
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testcompression_zstd() throws InterruptedException, IOException {
+ @Test
+ @Timeout(300_000)
+ void testcompression_zstd() throws InterruptedException, IOException {
testcompression(
Compression.ZSTD, "zst",
(compressedFile, uncompressedSize) -> uncheck(() -> {
@@ -173,7 +177,7 @@ public class LogFileHandlerTestCase {
private void testcompression(Compression compression,
String fileExtension,
BiFunction<Path, Integer, String> decompressor) throws IOException, InterruptedException {
- File root = temporaryFolder.newFolder("testcompression" + compression.name());
+ File root = newFolder(temporaryFolder, "testcompression" + compression.name());
LogFileHandler<String> h = new LogFileHandler<>(
compression, BUFFER_SIZE, root.getAbsolutePath() + "/logfilehandlertest.%Y%m%d%H%M%S%s", new long[]{0}, null, 2048, "thread-name", new StringLogWriter());
@@ -206,5 +210,23 @@ public class LogFileHandlerTestCase {
public void write(String record, OutputStream outputStream) throws IOException {
outputStream.write(record.getBytes(StandardCharsets.UTF_8));
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+ }
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
}
}
diff --git a/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
index 382f17f072f..c3526b42f55 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.container.logging.test;
import com.yahoo.container.logging.LogFormatter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Date;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Bob Travis
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class LogFormatterTestCase {
@Test
- public void testIt() {
+ void testIt() {
java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("UTC"));
@SuppressWarnings("deprecation")
- long time = new Date(103,7,25,13,30,35).getTime();
- String result = LogFormatter.insertDate("test%Y%m%d%H%M%S%x",time);
- assertEquals("test20030825133035Aug",result);
- result = LogFormatter.insertDate("test%s%T",time);
- assertEquals("test000"+time, result);
+ long time = new Date(103, 7, 25, 13, 30, 35).getTime();
+ String result = LogFormatter.insertDate("test%Y%m%d%H%M%S%x", time);
+ assertEquals("test20030825133035Aug", result);
+ result = LogFormatter.insertDate("test%s%T", time);
+ assertEquals("test000" + time, result);
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java
index cf43a6470bc..3f18d41badd 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -9,9 +9,7 @@ import java.util.concurrent.TimeUnit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -20,19 +18,19 @@ import static org.junit.Assert.assertTrue;
public class CookieTestCase {
@Test
- public void requireThatDefaultValuesAreSane() {
+ void requireThatDefaultValuesAreSane() {
Cookie cookie = new Cookie("foo", "bar");
assertEquals("foo", cookie.getName());
assertEquals("bar", cookie.getValue());
- assertEquals(null, cookie.getDomain());
+ assertNull(cookie.getDomain());
assertEquals(Integer.MIN_VALUE, cookie.getMaxAge(TimeUnit.SECONDS));
- assertEquals(null, cookie.getPath());
+ assertNull(cookie.getPath());
assertEquals(false, cookie.isHttpOnly());
assertEquals(false, cookie.isSecure());
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
final Cookie cookie = new Cookie();
cookie.setName("foo");
assertEquals("foo", cookie.getName());
@@ -70,7 +68,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatCopyConstructorWorks() {
+ void requireThatCopyConstructorWorks() {
final Cookie lhs = newSetCookie("foo");
final Cookie rhs = new Cookie(lhs);
assertEquals(rhs.getName(), rhs.getName());
@@ -83,23 +81,23 @@ public class CookieTestCase {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
final Cookie cookie = newCookie("foo");
- assertFalse(cookie.hashCode() == new Cookie().hashCode());
+ assertNotNull(new Cookie().hashCode());
assertEquals(cookie.hashCode(), cookie.hashCode());
assertEquals(cookie.hashCode(), new Cookie(cookie).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
final Cookie cookie = newCookie("foo");
- assertFalse(cookie.equals(new Cookie()));
+ assertNotEquals(cookie, new Cookie());
assertEquals(cookie, cookie);
assertEquals(cookie, new Cookie(cookie));
}
@Test
- public void requireThatCookieCanBeEncoded() {
+ void requireThatCookieCanBeEncoded() {
assertEncodeCookie(
"foo.name=foo.value",
List.of(newCookie("foo")));
@@ -109,7 +107,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatSetCookieCanBeEncoded() {
+ void requireThatSetCookieCanBeEncoded() {
assertEncodeSetCookie(
List.of("foo.name=foo.value; Path=path; Domain=domain; Secure; HttpOnly",
"foo.name=foo.value; Path=path; Domain=domain; Secure; HttpOnly; SameSite=None"),
@@ -118,7 +116,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatCookieCanBeDecoded() {
+ void requireThatCookieCanBeDecoded() {
final Cookie foo = new Cookie();
foo.setName("foo.name");
foo.setValue("foo.value");
@@ -127,11 +125,11 @@ public class CookieTestCase {
final Cookie bar = new Cookie();
bar.setName("bar.name");
bar.setValue("bar.value");
- assertDecodeCookie(List.of(foo, bar),"foo.name=foo.value; bar.name=bar.value");
+ assertDecodeCookie(List.of(foo, bar), "foo.name=foo.value; bar.name=bar.value");
}
@Test
- public void requireThatSetCookieCanBeDecoded() {
+ void requireThatSetCookieCanBeDecoded() {
final Cookie foo = new Cookie();
foo.setName("foo.name");
foo.setValue("foo.value");
@@ -152,45 +150,45 @@ public class CookieTestCase {
}
@Test
- public void requireThatCookieDecoderWorksForGenericValidCookies() {
+ void requireThatCookieDecoderWorksForGenericValidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=8es5opih9ljtk&l=og0_iedeh0qqvqqr/o&p=m2g2rs6012000000&r=pv&lg=en-US&intl=" +
- "us&np=1; T=z=h.nzPBhSP4PBVd5JqacVnIbNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=YAE&sk=DAALShmNQ" +
- "vhoZV&ks=EAABsibvMK6ejwn0uUoS4rC9w--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
- "NU5nLS0BYQFZQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAWNOUnZIbEc3ZHZoVHlWZ" +
- "0NoXzEwYkxhOVdzcy0Bb2sBWlcwLQF0aXABWUhwTmVDAXp6AWgubnpQQkE3RQ--");
+ "us&np=1; T=z=h.nzPBhSP4PBVd5JqacVnIbNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=YAE&sk=DAALShmNQ" +
+ "vhoZV&ks=EAABsibvMK6ejwn0uUoS4rC9w--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
+ "NU5nLS0BYQFZQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAWNOUnZIbEc3ZHZoVHlWZ" +
+ "0NoXzEwYkxhOVdzcy0Bb2sBWlcwLQF0aXABWUhwTmVDAXp6AWgubnpQQkE3RQ--");
}
@Test
- public void requireThatCookieDecoderWorksForYInvalidCookies() {
+ void requireThatCookieDecoderWorksForYInvalidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=77nkr5t7o4nqn&l=og0_iedeh0qqvqqr/o&p=m2g2rs6012000000&r=pv&lg=en-US&intl=" +
- "us&np=1; T=z=05nzPB0NP4PBN/n0gwc1AWGNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=QAE&sk=DAA4R2svo" +
- "osjIa&ks=EAAj3nBQFkN4ZmuhqFxJdNoaQ--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
- "NU5nLS0BYQFRQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAUpPalRXOEVsUDZrR3RHT" +
- "VZkX29CWk53clJIQS0BdGlwAVlIcE5lQwF6egEwNW56UEJBN0U-");
+ "us&np=1; T=z=05nzPB0NP4PBN/n0gwc1AWGNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=QAE&sk=DAA4R2svo" +
+ "osjIa&ks=EAAj3nBQFkN4ZmuhqFxJdNoaQ--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
+ "NU5nLS0BYQFRQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAUpPalRXOEVsUDZrR3RHT" +
+ "VZkX29CWk53clJIQS0BdGlwAVlIcE5lQwF6egEwNW56UEJBN0U-");
}
@Test
- public void requireThatCookieDecoderWorksForYValidCookies() {
+ void requireThatCookieDecoderWorksForYValidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=3767k6te5aj2s&l=1v4u3001uw2ys00q0rw0qrw34q0x5s3u/o&p=030vvit012000000&iz=" +
- "&r=pu&lg=en-US,it-IT,it&intl=it&np=1; T=z=m38yPBmLk3PBWvehTPBhBHYNU5OBjQ3NE5ONU5P" +
- "NDY0NzU0M0&a=IAE&sk=DAAAx5URYgbhQ6&ks=EAA4rTgdlAGeMQmdYeM_VehGg--~E&d=c2wBTWprNUF" +
- "UTXdNems1TWprNE16RXpNREl6TkRneAFhAUlBRQFnAUVJSlNMSzVRM1pWNVNLQVBNRkszQTRaWDZBAXNj" +
- "aWQBSUlyZW5paXp4NS4zTUZMMDVlSVhuMjZKYUcwLQFvawFaVzAtAWFsAW1hcmlvYXByZWFAeW1haWwuY" +
- "29tAXp6AW0zOHlQQkE3RQF0aXABaXRZOFRE");
+ "&r=pu&lg=en-US,it-IT,it&intl=it&np=1; T=z=m38yPBmLk3PBWvehTPBhBHYNU5OBjQ3NE5ONU5P" +
+ "NDY0NzU0M0&a=IAE&sk=DAAAx5URYgbhQ6&ks=EAA4rTgdlAGeMQmdYeM_VehGg--~E&d=c2wBTWprNUF" +
+ "UTXdNems1TWprNE16RXpNREl6TkRneAFhAUlBRQFnAUVJSlNMSzVRM1pWNVNLQVBNRkszQTRaWDZBAXNj" +
+ "aWQBSUlyZW5paXp4NS4zTUZMMDVlSVhuMjZKYUcwLQFvawFaVzAtAWFsAW1hcmlvYXByZWFAeW1haWwuY" +
+ "29tAXp6AW0zOHlQQkE3RQF0aXABaXRZOFRE");
}
@Test
- public void requireThatCookieDecoderWorksForGenericInvalidCookies() {
+ void requireThatCookieDecoderWorksForGenericInvalidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=e92s5cq8qbs6h&l=3kdb0f.3@i126be10b.d4j/o&p=m1f2qgmb13000107&r=g5&lg=en-US" +
- "&intl=us; T=z=TXp3OBTrQ8OBFMcj3GBpFSyNk83TgY2MjMwN04zMDMw&a=YAE&sk=DAAVfaNwLeISrX" +
- "&ks=EAAOeNNgY8c5hV8YzPYmnrW7w--~E&d=c2wBTVRnd09RRXhOVFEzTURrME56UTMBYQFZQUUBZwFMQ" +
- "U5NT0Q2UjY2Q0I1STY0R0tKSUdVQVlRRQFvawFaVzAtAXRpcAFMTlRUdkMBenoBVFhwM09CQTdF&af=QU" +
- "FBQ0FDQURBd0FCMUNCOUFJQUJBQ0FEQU1IME1nTWhNbiZ0cz0xMzIzMjEwMTk1JnBzPVA1d3NYakh0aVk" +
- "2UDMuUGZ6WkdTT2ctLQ--");
+ "&intl=us; T=z=TXp3OBTrQ8OBFMcj3GBpFSyNk83TgY2MjMwN04zMDMw&a=YAE&sk=DAAVfaNwLeISrX" +
+ "&ks=EAAOeNNgY8c5hV8YzPYmnrW7w--~E&d=c2wBTVRnd09RRXhOVFEzTURrME56UTMBYQFZQUUBZwFMQ" +
+ "U5NT0Q2UjY2Q0I1STY0R0tKSUdVQVlRRQFvawFaVzAtAXRpcAFMTlRUdkMBenoBVFhwM09CQTdF&af=QU" +
+ "FBQ0FDQURBd0FCMUNCOUFJQUJBQ0FEQU1IME1nTWhNbiZ0cz0xMzIzMjEwMTk1JnBzPVA1d3NYakh0aVk" +
+ "2UDMuUGZ6WkdTT2ctLQ--");
}
@Test
- public void requireMappingBetweenSameSiteAndJettySameSite() {
+ void requireMappingBetweenSameSiteAndJettySameSite() {
for (var jdiscSameSite : Cookie.SameSite.values()) {
assertEquals(jdiscSameSite, Cookie.SameSite.fromJettySameSite(jdiscSameSite.jettySameSite()));
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
index 3ab4fb1078c..08f646c069e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class HttpHeadersTestCase {
@Test
- public void requireThatHeadersDoNotChange() {
+ void requireThatHeadersDoNotChange() {
assertEquals("X-JDisc-Disable-Chunking", HttpHeaders.Names.X_DISABLE_CHUNKING);
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
index 7f9e1e8bd64..30e58f6d2f5 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.http;
import com.yahoo.jdisc.Container;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -13,10 +13,7 @@ import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -27,7 +24,7 @@ import static org.mockito.Mockito.when;
public class HttpRequestTestCase {
@Test
- public void requireThatSimpleServerConstructorsUseReasonableDefaults() {
+ void requireThatSimpleServerConstructorsUseReasonableDefaults() {
URI uri = URI.create("http://localhost/");
HttpRequest request = HttpRequest.newServerRequest(mockContainer(), uri);
assertTrue(request.isServerRequest());
@@ -49,7 +46,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatSimpleClientConstructorsUseReasonableDefaults() {
+ void requireThatSimpleClientConstructorsUseReasonableDefaults() {
Request parent = new Request(mockContainer(), URI.create("http://localhost/"));
URI uri = URI.create("http://remotehost/");
@@ -73,11 +70,11 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://localhost/path?foo=bar&foo=baz&cox=69");
InetSocketAddress address = new InetSocketAddress("remotehost", 69);
final HttpRequest request = HttpRequest.newServerRequest(mockContainer(), uri, HttpRequest.Method.GET,
- HttpRequest.Version.HTTP_1_1, address, 1L);
+ HttpRequest.Version.HTTP_1_1, address, 1L);
assertEquals(uri, request.getUri());
assertEquals(HttpRequest.Method.GET, request.getMethod());
@@ -110,7 +107,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp10EncodingIsNeverChunked() throws Exception {
+ void requireThatHttp10EncodingIsNeverChunked() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.isChunked());
request.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
@@ -118,20 +115,20 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp11EncodingIsNotChunkedByDefault() throws Exception {
+ void requireThatHttp11EncodingIsNotChunkedByDefault() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertFalse(request.isChunked());
}
@Test
- public void requireThatHttp11EncodingCanBeChunked() throws Exception {
+ void requireThatHttp11EncodingCanBeChunked() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
request.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
assertTrue(request.isChunked());
}
@Test
- public void requireThatHttp10ConnectionIsAlwaysClose() throws Exception {
+ void requireThatHttp10ConnectionIsAlwaysClose() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.isKeepAlive());
request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
@@ -139,39 +136,39 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp11ConnectionIsKeepAliveByDefault() throws Exception {
+ void requireThatHttp11ConnectionIsKeepAliveByDefault() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertTrue(request.isKeepAlive());
}
@Test
- public void requireThatHttp11ConnectionCanBeClose() throws Exception {
+ void requireThatHttp11ConnectionCanBeClose() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
assertFalse(request.isKeepAlive());
}
@Test
- public void requireThatHttp10NeverHasChunkedResponse() throws Exception {
+ void requireThatHttp10NeverHasChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.hasChunkedResponse());
}
@Test
- public void requireThatHttp11HasDefaultChunkedResponse() throws Exception {
+ void requireThatHttp11HasDefaultChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertTrue(request.hasChunkedResponse());
}
@Test
- public void requireThatHttp11CanDisableChunkedResponse() throws Exception {
+ void requireThatHttp11CanDisableChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
request.headers().add(com.yahoo.jdisc.http.HttpHeaders.Names.X_DISABLE_CHUNKING, "true");
assertFalse(request.hasChunkedResponse());
}
@Test
- public void requireThatCookieHeaderCanBeEncoded() throws Exception {
+ void requireThatCookieHeaderCanBeEncoded() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
request.encodeCookieHeader(cookies);
@@ -181,7 +178,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatCookieHeaderCanBeDecoded() throws Exception {
+ void requireThatCookieHeaderCanBeDecoded() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
request.encodeCookieHeader(cookies);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
index c4cf1de0e4e..09682e73630 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
@@ -5,18 +5,14 @@ import com.yahoo.jdisc.Container;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -27,7 +23,7 @@ import static org.mockito.Mockito.when;
public class HttpResponseTestCase {
@Test
- public void requireThatAccessorsWork() throws Exception {
+ void requireThatAccessorsWork() throws Exception {
final HttpResponse response = newResponse(6, "foo");
assertEquals(6, response.getStatus());
assertEquals("foo", response.getMessage());
@@ -49,7 +45,7 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatStatusCodesDoNotChange() {
+ void requireThatStatusCodesDoNotChange() {
assertEquals(HttpResponse.Status.CREATED, 201);
assertEquals(HttpResponse.Status.ACCEPTED, 202);
assertEquals(HttpResponse.Status.NON_AUTHORITATIVE_INFORMATION, 203);
@@ -79,14 +75,14 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThat5xxIsServerError() {
+ void requireThat5xxIsServerError() {
for (int i = 0; i < 999; ++i) {
assertEquals(i >= 500 && i < 600, HttpResponse.isServerError(new Response(i)));
}
}
@Test
- public void requireThatCookieHeaderCanBeEncoded() throws Exception {
+ void requireThatCookieHeaderCanBeEncoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
response.encodeSetCookieHeader(cookies);
@@ -96,18 +92,18 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatMultipleCookieHeadersCanBeEncoded() throws Exception {
+ void requireThatMultipleCookieHeadersCanBeEncoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"));
response.encodeSetCookieHeader(cookies);
final List<String> headers = response.headers().get(HttpHeaders.Names.SET_COOKIE);
assertEquals(2, headers.size());
assertEquals(Cookie.toSetCookieHeaders(Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"))),
- headers);
+ headers);
}
@Test
- public void requireThatCookieHeaderCanBeDecoded() throws Exception {
+ void requireThatCookieHeaderCanBeDecoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
response.encodeSetCookieHeader(cookies);
@@ -115,7 +111,7 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatMultipleCookieHeadersCanBeDecoded() throws Exception {
+ void requireThatMultipleCookieHeadersCanBeDecoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"));
response.encodeSetCookieHeader(cookies);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
index 294e19aa2a1..0f5474cbf57 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
@@ -7,8 +7,7 @@ import com.yahoo.jdisc.http.HttpHeaders;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpRequest.Version;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -18,7 +17,7 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class DiscFilterRequestTest {
@@ -32,323 +31,323 @@ public class DiscFilterRequestTest {
return request;
}
- @Test
- public void testRequestConstruction(){
- URI uri = URI.create("http://localhost:8080/test?param1=abc");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
- httpReq.headers().add("X-Custom-Header", "custom_header");
- List<Cookie> cookies = new ArrayList<>();
- cookies.add(new Cookie("XYZ", "value"));
- cookies.add(new Cookie("ABC", "value"));
- httpReq.encodeCookieHeader(cookies);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getHeader("X-Custom-Header"),"custom_header");
- Assert.assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE),"text/html;charset=UTF-8");
-
- List<Cookie> c = request.getCookies();
- Assert.assertNotNull(c);
- Assert.assertEquals(c.size(), 2);
-
- Assert.assertEquals(request.getParameter("param1"),"abc");
- Assert.assertNull(request.getParameter("param2"));
- Assert.assertEquals(request.getVersion(),Version.HTTP_1_1);
- Assert.assertEquals(request.getProtocol(),Version.HTTP_1_1.name());
- Assert.assertNull(request.getRequestedSessionId());
- }
-
- @Test
- public void testRequestConstruction2() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add("some-header", "some-value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
-
- request.addHeader("some-header", "some-value");
- String value = request.getUntreatedHeaders().get("some-header").get(0);
- Assert.assertEquals(value,"some-value");
- }
-
- @Test
- public void testRequestAttributes() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setAttribute("some_attr", "some_value");
-
- Assert.assertTrue(request.containsAttribute("some_attr"));
-
- Assert.assertEquals(request.getAttribute("some_attr"),"some_value");
-
- }
-
- @Test
- public void testGetAttributeNames() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setAttribute("some_attr_1", "some_value1");
- request.setAttribute("some_attr_2", "some_value2");
-
- Enumeration<String> e = request.getAttributeNames();
- List<String> attrList = Collections.list(e);
- Assert.assertEquals(2, attrList.size());
- Assert.assertTrue(attrList.contains("some_attr_1"));
- Assert.assertTrue(attrList.contains("some_attr_2"));
-
- }
-
- @Test
- public void testRemoveAttribute() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ @Test
+ void testRequestConstruction() {
+ URI uri = URI.create("http://localhost:8080/test?param1=abc");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+ httpReq.headers().add("X-Custom-Header", "custom_header");
+ List<Cookie> cookies = new ArrayList<>();
+ cookies.add(new Cookie("XYZ", "value"));
+ cookies.add(new Cookie("ABC", "value"));
+ httpReq.encodeCookieHeader(cookies);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getHeader("X-Custom-Header"), "custom_header");
+ assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE), "text/html;charset=UTF-8");
+
+ List<Cookie> c = request.getCookies();
+ assertNotNull(c);
+ assertEquals(c.size(), 2);
+
+ assertEquals(request.getParameter("param1"), "abc");
+ assertNull(request.getParameter("param2"));
+ assertEquals(request.getVersion(), Version.HTTP_1_1);
+ assertEquals(request.getProtocol(), Version.HTTP_1_1.name());
+ assertNull(request.getRequestedSessionId());
+ }
+
+ @Test
+ void testRequestConstruction2() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add("some-header", "some-value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+
+ request.addHeader("some-header", "some-value");
+ String value = request.getUntreatedHeaders().get("some-header").get(0);
+ assertEquals(value, "some-value");
+ }
+
+ @Test
+ void testRequestAttributes() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
request.setAttribute("some_attr", "some_value");
- Assert.assertTrue(request.containsAttribute("some_attr"));
+ assertTrue(request.containsAttribute("some_attr"));
- request.removeAttribute("some_attr");
+ assertEquals(request.getAttribute("some_attr"), "some_value");
- Assert.assertFalse(request.containsAttribute("some_attr"));
- }
+ }
- @Test
- public void testGetIntHeader() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ @Test
+ void testGetAttributeNames() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setAttribute("some_attr_1", "some_value1");
+ request.setAttribute("some_attr_2", "some_value2");
- Assert.assertEquals(-1, request.getIntHeader("int_header"));
+ Enumeration<String> e = request.getAttributeNames();
+ List<String> attrList = Collections.list(e);
+ assertEquals(2, attrList.size());
+ assertTrue(attrList.contains("some_attr_1"));
+ assertTrue(attrList.contains("some_attr_2"));
- request.addHeader("int_header", String.valueOf(5));
+ }
- Assert.assertEquals(5, request.getIntHeader("int_header"));
- }
+ @Test
+ void testRemoveAttribute() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setAttribute("some_attr", "some_value");
+
+ assertTrue(request.containsAttribute("some_attr"));
+
+ request.removeAttribute("some_attr");
+
+ assertFalse(request.containsAttribute("some_attr"));
+ }
+
+ @Test
+ void testGetIntHeader() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+
+ assertEquals(-1, request.getIntHeader("int_header"));
- @Test
- public void testDateHeader() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.addHeader("int_header", String.valueOf(5));
+ assertEquals(5, request.getIntHeader("int_header"));
+ }
+
+ @Test
+ void testDateHeader() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(-1, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- request.addHeader(HttpHeaders.Names.IF_MODIFIED_SINCE, "Sat, 29 Oct 1994 19:43:31 GMT");
+ assertEquals(-1, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- Assert.assertEquals(783459811000L, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- }
+ request.addHeader(HttpHeaders.Names.IF_MODIFIED_SINCE, "Sat, 29 Oct 1994 19:43:31 GMT");
- @Test
- public void testParameterAPIsAsList() {
+ assertEquals(783459811000L, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
+ }
+
+ @Test
+ void testParameterAPIsAsList() {
URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getParameter("param1"),"abc");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getParameter("param1"), "abc");
List<String> values = request.getParameterValuesAsList("param2");
- Assert.assertEquals(values.get(0),"xyz");
- Assert.assertEquals(values.get(1),"pqr");
+ assertEquals(values.get(0), "xyz");
+ assertEquals(values.get(1), "pqr");
List<String> paramNames = request.getParameterNamesAsList();
- Assert.assertEquals(paramNames.size(), 2);
+ assertEquals(paramNames.size(), 2);
- }
+ }
- @Test
- public void testParameterAPI(){
- URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
+ @Test
+ void testParameterAPI() {
+ URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getParameter("param1"),"abc");
+ assertEquals(request.getParameter("param1"), "abc");
Enumeration<String> values = request.getParameterValues("param2");
List<String> valuesList = Collections.list(values);
- Assert.assertEquals(valuesList.get(0),"xyz");
- Assert.assertEquals(valuesList.get(1),"pqr");
+ assertEquals(valuesList.get(0), "xyz");
+ assertEquals(valuesList.get(1), "pqr");
Enumeration<String> paramNames = request.getParameterNames();
List<String> paramNamesList = Collections.list(paramNames);
- Assert.assertEquals(paramNamesList.size(), 2);
- }
+ assertEquals(paramNamesList.size(), 2);
+ }
- @Test
- public void testGetHeaderNamesAsList() {
- URI uri = URI.create("http://localhost:8080/test");
+ @Test
+ void testGetHeaderNamesAsList() {
+ URI uri = URI.create("http://localhost:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
httpReq.headers().add("header_1", "value1");
httpReq.headers().add("header_2", "value2");
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNotNull(request.getHeaderNamesAsList());
- Assert.assertEquals(request.getHeaderNamesAsList().size(), 3);
- }
+ assertNotNull(request.getHeaderNamesAsList());
+ assertEquals(request.getHeaderNamesAsList().size(), 3);
+ }
- @Test
- public void testGetHeadersAsList() {
+ @Test
+ void testGetHeadersAsList() {
URI uri = URI.create("http://localhost:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNotNull(request.getHeaderNamesAsList());
- Assert.assertEquals(request.getHeaderNamesAsList().size(), 0);
+ assertNotNull(request.getHeaderNamesAsList());
+ assertEquals(request.getHeaderNamesAsList().size(), 0);
httpReq.headers().add("header_1", "value1");
httpReq.headers().add("header_1", "value2");
- Assert.assertEquals(request.getHeadersAsList("header_1").size(), 2);
+ assertEquals(request.getHeadersAsList("header_1").size(), 2);
}
- @Test
- public void testIsMultipart() {
+ @Test
+ void testIsMultipart() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertTrue(DiscFilterRequest.isMultipart(request));
+ assertTrue(DiscFilterRequest.isMultipart(request));
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
- request = new DiscFilterRequest(httpReq);
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+ request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(DiscFilterRequest.isMultipart(request));
+ assertFalse(DiscFilterRequest.isMultipart(request));
- Assert.assertFalse(DiscFilterRequest.isMultipart(null));
+ assertFalse(DiscFilterRequest.isMultipart(null));
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(DiscFilterRequest.isMultipart(request));
- }
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ request = new DiscFilterRequest(httpReq);
+ assertFalse(DiscFilterRequest.isMultipart(request));
+ }
- @Test
- public void testGetRemotePortLocalPort() {
+ @Test
+ void testGetRemotePortLocalPort() {
URI uri = URI.create("http://example.yahoo.com:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(69, request.getRemotePort());
- Assert.assertEquals(8080, request.getLocalPort());
+ assertEquals(69, request.getRemotePort());
+ assertEquals(8080, request.getLocalPort());
- if (request.getRemoteHost() != null) // if we have network
- Assert.assertEquals("example.yahoo.com", request.getRemoteHost());
+ if (request.getRemoteHost() != null) // if we have network
+ assertEquals("example.yahoo.com", request.getRemoteHost());
request.setRemoteAddr("1.1.1.1");
- Assert.assertEquals("1.1.1.1",request.getRemoteAddr());
- }
-
- @Test
- public void testCharacterEncoding() {
- URI uri = URI.create("http://example.yahoo.com:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
-
- Assert.assertEquals(request.getCharacterEncoding(), "UTF-8");
-
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- request = new DiscFilterRequest(httpReq);
- request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html");
- request.setCharacterEncoding("UTF-8");
-
- Assert.assertEquals(request.getCharacterEncoding(),"UTF-8");
-
- Assert.assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE),"text/html;charset=UTF-8");
- }
-
- @Test
- public void testGetServerPort() {
- {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getServerPort(), 80);
-
- }
- {
- URI uri = URI.create("https://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getServerPort(), 443);
- }
- }
-
- @Test
- public void testIsSecure() {
- {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(request.isSecure());
- }
- {
- URI uri = URI.create("https://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertTrue(request.isSecure());
- }
- }
+ assertEquals("1.1.1.1", request.getRemoteAddr());
+ }
+
+ @Test
+ void testCharacterEncoding() {
+ URI uri = URI.create("http://example.yahoo.com:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+
+ assertEquals(request.getCharacterEncoding(), "UTF-8");
+
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ request = new DiscFilterRequest(httpReq);
+ request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html");
+ request.setCharacterEncoding("UTF-8");
+
+ assertEquals(request.getCharacterEncoding(), "UTF-8");
+
+ assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE), "text/html;charset=UTF-8");
+ }
+
+ @Test
+ void testGetServerPort() {
+ {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getServerPort(), 80);
+
+ }
+ {
+ URI uri = URI.create("https://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getServerPort(), 443);
+ }
+ }
@Test
- public void requireThatUnresolvableRemoteAddressesAreSupported() {
+ void testIsSecure() {
+ {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertFalse(request.isSecure());
+ }
+ {
+ URI uri = URI.create("https://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertTrue(request.isSecure());
+ }
+ }
+
+ @Test
+ void requireThatUnresolvableRemoteAddressesAreSupported() {
URI uri = URI.create("http://doesnotresolve.zzz:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNull(request.getLocalAddr());
+ assertNull(request.getLocalAddr());
}
@Test
- public void testGetUntreatedHeaders() {
- URI uri = URI.create("http://example.yahoo.com/test");
+ void testGetUntreatedHeaders() {
+ URI uri = URI.create("http://example.yahoo.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().add("key1", "value1");
- httpReq.headers().add("key2", Arrays.asList("value1","value2"));
+ httpReq.headers().add("key2", Arrays.asList("value1", "value2"));
DiscFilterRequest request = new DiscFilterRequest(httpReq);
HeaderFields headers = request.getUntreatedHeaders();
- Assert.assertEquals(headers.keySet().size(), 2);
- Assert.assertEquals(headers.get("key1").get(0), "value1" );
- Assert.assertEquals(headers.get("key2").get(0), "value1" );
- Assert.assertEquals(headers.get("key2").get(1), "value2" );
+ assertEquals(headers.keySet().size(), 2);
+ assertEquals(headers.get("key1").get(0), "value1");
+ assertEquals(headers.get("key2").get(0), "value1");
+ assertEquals(headers.get("key2").get(1), "value2");
+ }
+
+ @Test
+ void testClearCookies() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.clearCookies();
+ assertNull(request.getHeader(HttpHeaders.Names.COOKIE));
+ }
+
+ @Test
+ void testGetWrapedCookies() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ JDiscCookieWrapper[] wrappers = request.getWrappedCookies();
+ assertEquals(wrappers.length, 1);
+ assertEquals(wrappers[0].getName(), "XYZ");
+ assertEquals(wrappers[0].getValue(), "value");
}
- @Test
- public void testClearCookies() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.clearCookies();
- Assert.assertNull(request.getHeader(HttpHeaders.Names.COOKIE));
- }
-
- @Test
- public void testGetWrapedCookies() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- JDiscCookieWrapper[] wrappers = request.getWrappedCookies();
- Assert.assertEquals(wrappers.length ,1);
- Assert.assertEquals(wrappers[0].getName(), "XYZ");
- Assert.assertEquals(wrappers[0].getValue(), "value");
- }
-
- @Test
- public void testAddCookie() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
-
- List<Cookie> cookies = request.getCookies();
- Assert.assertEquals(cookies.size(), 1);
- Assert.assertEquals(cookies.get(0).getName(), "name");
- Assert.assertEquals(cookies.get(0).getValue(), "value");
- }
+ @Test
+ void testAddCookie() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
+
+ List<Cookie> cookies = request.getCookies();
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
+ assertEquals(cookies.get(0).getValue(), "value");
+ }
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
index ace41473eb4..73498e27892 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
@@ -6,15 +6,14 @@ import com.yahoo.jdisc.http.Cookie;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class DiscFilterResponseTest {
@@ -33,40 +32,40 @@ public class DiscFilterResponseTest {
}
@Test
- public void testGetSetStatus() {
+ void testGetSetStatus() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
- Assert.assertEquals(response.getStatus(), HttpResponse.Status.OK);
+ assertEquals(response.getStatus(), HttpResponse.Status.OK);
response.setStatus(HttpResponse.Status.REQUEST_TIMEOUT);
- Assert.assertEquals(response.getStatus(), HttpResponse.Status.REQUEST_TIMEOUT);
+ assertEquals(response.getStatus(), HttpResponse.Status.REQUEST_TIMEOUT);
}
@Test
- public void testAttributes() {
+ void testAttributes() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
response.setAttribute("attr_1", "value1");
- Assert.assertEquals(response.getAttribute("attr_1"), "value1");
+ assertEquals(response.getAttribute("attr_1"), "value1");
List<String> list = Collections.list(response.getAttributeNames());
- Assert.assertEquals(list.get(0), "attr_1");
+ assertEquals(list.get(0), "attr_1");
response.removeAttribute("attr_1");
- Assert.assertNull(response.getAttribute("attr_1"));
+ assertNull(response.getAttribute("attr_1"));
}
@Test
- public void testAddHeader() {
+ void testAddHeader() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
response.addHeader("header1", "value1");
- Assert.assertEquals(response.getHeader("header1"), "value1");
+ assertEquals(response.getHeader("header1"), "value1");
}
@Test
- public void testAddCookie() {
+ void testAddCookie() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
@@ -74,31 +73,31 @@ public class DiscFilterResponseTest {
response.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
List<Cookie> cookies = response.getCookies();
- Assert.assertEquals(cookies.size(),1);
- Assert.assertEquals(cookies.get(0).getName(),"name");
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
}
@Test
- public void testSetCookie() {
+ void testSetCookie() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
DiscFilterResponse response = new DiscFilterResponse(httpResp);
response.setCookie("name", "value");
List<Cookie> cookies = response.getCookies();
- Assert.assertEquals(cookies.size(),1);
- Assert.assertEquals(cookies.get(0).getName(),"name");
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
}
@Test
- public void testSetHeader() {
+ void testSetHeader() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
DiscFilterResponse response = new DiscFilterResponse(httpResp);
response.setHeader("name", "value");
- Assert.assertEquals(response.getHeader("name"), "value");
+ assertEquals(response.getHeader("name"), "value");
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
index 214ee6b91cc..dc263bb08a6 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.filter.chain.EmptyRequestFilter;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import static com.yahoo.jdisc.http.HttpRequest.Method;
import static com.yahoo.jdisc.http.HttpRequest.Version;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ import static org.mockito.Mockito.when;
public class EmptyRequestFilterTestCase {
@Test
- public void requireThatEmptyFilterDoesNothing() throws Exception {
+ void requireThatEmptyFilterDoesNothing() throws Exception {
final HttpRequest lhs = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
final HttpRequest rhs = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
index 91bc0b1aa4c..53e794cef29 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.http.filter.chain.EmptyResponseFilter;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import static com.yahoo.jdisc.http.HttpRequest.Method;
import static com.yahoo.jdisc.http.HttpRequest.Version;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ import static org.mockito.Mockito.when;
public class EmptyResponseFilterTestCase {
@Test
- public void requireThatEmptyFilterDoesNothing() throws Exception {
+ void requireThatEmptyFilterDoesNothing() throws Exception {
final HttpRequest request = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
final HttpResponse lhs = HttpResponse.newInstance(Response.Status.OK);
final HttpResponse rhs = HttpResponse.newInstance(Response.Status.OK);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
index 36217012fb0..41d80d16c54 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
@@ -2,15 +2,16 @@
package com.yahoo.jdisc.http.filter;
import com.yahoo.jdisc.http.Cookie;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class JDiscCookieWrapperTest {
@Test
- public void requireThatWrapWorks() {
+ void requireThatWrapWorks() {
Cookie cookie = new Cookie("name", "value");
JDiscCookieWrapper wrapper = JDiscCookieWrapper.wrap(cookie);
@@ -18,12 +19,12 @@ public class JDiscCookieWrapperTest {
wrapper.setMaxAge(10);
wrapper.setPath("/path");
- Assert.assertEquals(wrapper.getName(), cookie.getName());
- Assert.assertEquals(wrapper.getValue(), cookie.getValue());
- Assert.assertEquals(wrapper.getDomain(), cookie.getDomain());
- Assert.assertEquals(wrapper.getMaxAge(), cookie.getMaxAge(TimeUnit.SECONDS));
- Assert.assertEquals(wrapper.getPath(), cookie.getPath());
- Assert.assertEquals(wrapper.getSecure(), cookie.isSecure());
+ assertEquals(wrapper.getName(), cookie.getName());
+ assertEquals(wrapper.getValue(), cookie.getValue());
+ assertEquals(wrapper.getDomain(), cookie.getDomain());
+ assertEquals(wrapper.getMaxAge(), cookie.getMaxAge(TimeUnit.SECONDS));
+ assertEquals(wrapper.getPath(), cookie.getPath());
+ assertEquals(wrapper.getSecure(), cookie.isSecure());
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
index ab682ea9059..840a5537042 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
@@ -5,9 +5,9 @@ import com.google.common.collect.Lists;
import com.yahoo.jdisc.HeaderFields;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.http.filter.SecurityResponseFilterChain.RequestViewImpl;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -17,7 +17,7 @@ import static org.mockito.Mockito.when;
public class RequestViewImplTest {
@Test
- public void header_from_the_parent_request_is_available() throws Exception {
+ void header_from_the_parent_request_is_available() throws Exception {
final String HEADER = "single-header";
HeaderFields parentHeaders = new HeaderFields();
@@ -32,7 +32,7 @@ public class RequestViewImplTest {
@Test
- public void multi_value_header_from_the_parent_request_is_available() throws Exception {
+ void multi_value_header_from_the_parent_request_is_available() throws Exception {
final String HEADER = "list-header";
HeaderFields parentHeaders = new HeaderFields();
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
index 46d6be2e73b..645e523c155 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
@@ -9,8 +9,7 @@ import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -18,7 +17,7 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -32,40 +31,40 @@ public class SecurityRequestFilterChainTest {
driver.activateContainer(driver.newContainerBuilder());
HttpRequest request = HttpRequest.newServerRequest(driver, uri, method, version, address);
request.release();
- Assert.assertTrue(driver.close());
+ assertTrue(driver.close());
return request;
}
@Test
- public void testFilterChainConstruction() {
- SecurityRequestFilterChain chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance();
- assertEquals(chain.getFilters().size(),0);
+ void testFilterChainConstruction() {
+ SecurityRequestFilterChain chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance();
+ assertEquals(chain.getFilters().size(), 0);
List<SecurityRequestFilter> requestFilters = new ArrayList<SecurityRequestFilter>();
- chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance();
+ chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance();
- chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
- new RequestHeaderFilter("pqr", "def"));
+ chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
+ new RequestHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityRequestFilterChain, true);
}
@Test
- public void testFilterChainRun() {
+ void testFilterChainRun() {
RequestFilter chain = SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
- new RequestHeaderFilter("pqr", "def"));
+ new RequestHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityRequestFilterChain, true);
ResponseHandler handler = newResponseHandler();
HttpRequest request = newRequest(URI.create("http://test/test"), HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
chain.filter(request, handler);
- Assert.assertTrue(request.headers().contains("abc", "xyz"));
- Assert.assertTrue(request.headers().contains("pqr", "def"));
+ assertTrue(request.headers().contains("abc", "xyz"));
+ assertTrue(request.headers().contains("pqr", "def"));
}
@Test
- public void testFilterChainResponds() {
+ void testFilterChainResponds() {
RequestFilter chain = SecurityRequestFilterChain.newInstance(
new MyFilter(),
new RequestHeaderFilter("abc", "xyz"),
@@ -76,9 +75,9 @@ public class SecurityRequestFilterChainTest {
HttpRequest request = newRequest(URI.create("http://test/test"), HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
chain.filter(request, handler);
Response response = getResponse(handler);
- Assert.assertNotNull(response);
- Assert.assertTrue(!request.headers().contains("abc", "xyz"));
- Assert.assertTrue(!request.headers().contains("pqr", "def"));
+ assertNotNull(response);
+ assertFalse(request.headers().contains("abc", "xyz"));
+ assertFalse(request.headers().contains("pqr", "def"));
}
private class RequestHeaderFilter extends AbstractResource implements SecurityRequestFilter {
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
index d44fdbfd39b..3f04154e3f8 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
@@ -6,13 +6,13 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -29,24 +29,24 @@ public class SecurityResponseFilterChainTest {
}
@Test
- public void testFilterChainConstruction() {
- SecurityResponseFilterChain chain = (SecurityResponseFilterChain)SecurityResponseFilterChain.newInstance();
- assertEquals(chain.getFilters().size(),0);
+ void testFilterChainConstruction() {
+ SecurityResponseFilterChain chain = (SecurityResponseFilterChain) SecurityResponseFilterChain.newInstance();
+ assertEquals(chain.getFilters().size(), 0);
- chain = (SecurityResponseFilterChain)SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
- new ResponseHeaderFilter("pqr", "def"));
+ chain = (SecurityResponseFilterChain) SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
+ new ResponseHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityResponseFilterChain, true);
}
@Test
- public void testFilterChainRun() {
+ void testFilterChainRun() {
URI uri = URI.create("http://localhost:8080/echo");
HttpRequest request = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
Response response = HttpResponse.newInstance(Response.Status.OK);
ResponseFilter chain = SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
- new ResponseHeaderFilter("pqr", "def"));
+ new ResponseHeaderFilter("pqr", "def"));
chain.filter(response, null);
assertTrue(response.headers().contains("abc", "xyz"));
assertTrue(response.headers().contains("pqr", "def"));
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
index 16883f1a48e..b53479abdd8 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
@@ -4,14 +4,14 @@ package com.yahoo.jdisc.http.filter.util;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.Cookie;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.yahoo.jdisc.http.filter.util.FilterUtils.sendMessageResponse;
import static com.yahoo.jdisc.http.filter.util.FilterUtils.sendRedirectResponse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author valerijf
@@ -21,7 +21,7 @@ public class FilterUtilsTest {
private static final List<Cookie> cookies = List.of(new Cookie("my-cookie", "value1"), new Cookie("second-cookie", "value2"));
@Test
- public void redirect_test() {
+ void redirect_test() {
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
String location = "http://domain.tld/path?query";
@@ -31,7 +31,7 @@ public class FilterUtilsTest {
}
@Test
- public void message_response() {
+ void message_response() {
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
sendMessageResponse(responseHandler, List.of(), 404, "Not found");
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
index 65f871e47ea..766c7918882 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
@@ -7,7 +7,7 @@ import com.yahoo.container.logging.RequestLogEntry;
import com.yahoo.jdisc.http.ServerConfig;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
@@ -16,8 +16,8 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Oyvind Bakksjo
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
*/
public class AccessLogRequestLogTest {
@Test
- public void requireThatQueryWithUnquotedSpecialCharactersIsHandled() {
+ void requireThatQueryWithUnquotedSpecialCharactersIsHandled() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "/search/", "query=year:>2010")
.build();
@@ -39,7 +39,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void requireThatDoubleQuotingIsNotPerformed() {
+ void requireThatDoubleQuotingIsNotPerformed() {
String path = "/search/";
String query = "query=year%252010+%3B&customParameter=something";
Request jettyRequest = createRequestBuilder()
@@ -56,7 +56,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void raw_path_and_query_are_set_from_request() {
+ void raw_path_and_query_are_set_from_request() {
String rawPath = "//search/";
String rawQuery = "q=%%2";
Request jettyRequest = createRequestBuilder()
@@ -73,7 +73,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void verify_x_forwarded_for_precedence () {
+ void verify_x_forwarded_for_precedence() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "//search/", "q=%%2")
.header("x-forwarded-for", List.of("1.2.3.4"))
@@ -87,7 +87,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void verify_x_forwarded_port_precedence () {
+ void verify_x_forwarded_port_precedence() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "//search/", "q=%%2")
.header("X-Forwarded-Port", List.of("80"))
@@ -101,7 +101,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void defaults_to_peer_port_if_remote_port_header_is_invalid() {
+ void defaults_to_peer_port_if_remote_port_header_is_invalid() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "/search/", null)
.header("X-Forwarded-Port", List.of("8o8o"))
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
index add7e458fbd..a65231db2b7 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
@@ -6,11 +6,11 @@ import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.statistic.RateStatistic;
import org.eclipse.jetty.util.thread.Scheduler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -23,14 +23,14 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
public class ConnectionThrottlerTest {
@Test
- public void throttles_when_any_resource_check_exceeds_configured_threshold() {
+ void throttles_when_any_resource_check_exceeds_configured_threshold() {
Runtime runtime = mock(Runtime.class);
when(runtime.maxMemory()).thenReturn(100l);
RateStatistic rateStatistic = new RateStatistic(1, TimeUnit.HOURS);
MockScheduler scheduler = new MockScheduler();
ConnectorConfig.Throttling config = new ConnectorConfig.Throttling(new ConnectorConfig.Throttling.Builder()
- .maxHeapUtilization(0.8)
- .maxAcceptRate(1));
+ .maxHeapUtilization(0.8)
+ .maxAcceptRate(1));
AbstractConnector connector = mock(AbstractConnector.class);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
index b47df9d5931..1ff2783cc53 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
@@ -8,9 +8,9 @@ import com.yahoo.jdisc.http.ssl.impl.ConfiguredSslContextFactoryProvider;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -18,7 +18,7 @@ import java.io.IOException;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Einar M R Rosenvinge
@@ -28,12 +28,12 @@ public class ConnectorFactoryTest {
private Server server;
- @Before
+ @BeforeEach
public void createServer() {
server = new Server();
}
- @After
+ @AfterEach
public void stopServer() {
try {
server.stop();
@@ -44,7 +44,7 @@ public class ConnectorFactoryTest {
}
@Test
- public void requireThatServerCanBindChannel() throws Exception {
+ void requireThatServerCanBindChannel() throws Exception {
ConnectorConfig config = new ConnectorConfig(new ConnectorConfig.Builder());
ConnectorFactory factory = createConnectorFactory(config);
JDiscServerConnector connector = createConnectorFromFactory(factory);
@@ -59,7 +59,7 @@ public class ConnectorFactoryTest {
}
@Test
- public void constructed_connector_is_based_on_jdisc_connector_config() {
+ void constructed_connector_is_based_on_jdisc_connector_config() {
ConnectorConfig config = new ConnectorConfig.Builder()
.idleTimeout(25)
.name("my-server-name")
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
index 796adebb5e8..8b18c8cf09d 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
@@ -2,12 +2,12 @@
package com.yahoo.jdisc.http.server.jetty;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -16,20 +16,20 @@ import static org.junit.Assert.assertEquals;
public class ErrorResponseContentCreatorTest {
@Test
- public void response_content_matches_expected_string() {
+ void response_content_matches_expected_string() {
String expectedHtml =
"<html>\n" +
- "<head>\n" +
- "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" +
- "<title>Error 200</title>\n" +
- "</head>\n" +
- "<body>\n" +
- "<h2>HTTP ERROR: 200</h2>\n" +
- "<p>Problem accessing http://foo.bar. Reason:\n" +
- "<pre> My custom error message</pre></p>\n" +
- "<hr/>\n" +
- "</body>\n" +
- "</html>\n";
+ "<head>\n" +
+ "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" +
+ "<title>Error 200</title>\n" +
+ "</head>\n" +
+ "<body>\n" +
+ "<h2>HTTP ERROR: 200</h2>\n" +
+ "<p>Problem accessing http://foo.bar. Reason:\n" +
+ "<pre> My custom error message</pre></p>\n" +
+ "<hr/>\n" +
+ "</body>\n" +
+ "</html>\n";
ErrorResponseContentCreator c = new ErrorResponseContentCreator();
byte[] rawContent = c.createErrorContent(
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java
index 153d3f34899..9512dc22a93 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.server.jetty;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -15,7 +15,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class ExceptionWrapperTest {
@Test
- public final void requireNoMessageIsOK() {
+ final void requireNoMessageIsOK() {
final Throwable t = new Throwable();
final ExceptionWrapper e = new ExceptionWrapper(t);
final String expected = "Throwable() at com.yahoo.jdisc.http.server.jetty.ExceptionWrapperTest(ExceptionWrapperTest.java:19)";
@@ -24,7 +24,7 @@ public class ExceptionWrapperTest {
}
@Test
- public final void requireAllWrappedLevelsShowUp() {
+ final void requireAllWrappedLevelsShowUp() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable("t1", t0);
final Throwable t2 = new Throwable("t2", t1);
@@ -37,7 +37,7 @@ public class ExceptionWrapperTest {
}
@Test
- public final void requireMixOfMessageAndNoMessageWorks() {
+ final void requireMixOfMessageAndNoMessageWorks() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable(t0);
final Throwable t2 = new Throwable("t2", t1);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
index c975f7c17c3..ce49926c58b 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
@@ -29,7 +29,7 @@ import com.yahoo.jdisc.http.filter.chain.RequestFilterChain;
import com.yahoo.jdisc.http.filter.chain.ResponseFilterChain;
import com.yahoo.jdisc.http.server.jetty.testutils.ConnectorFactoryRegistryModule;
import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
@@ -58,7 +58,7 @@ import static org.mockito.Mockito.when;
*/
public class FilterTestCase {
@Test
- public void requireThatRequestFilterIsNotRunOnUnboundPath() throws Exception {
+ void requireThatRequestFilterIsNotRunOnUnboundPath() throws Exception {
RequestFilterMockBase filter = mock(RequestFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -76,7 +76,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterIsRunOnBoundPath() throws Exception {
+ void requireThatRequestFilterIsRunOnBoundPath() throws Exception {
final RequestFilter filter = mock(RequestFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -94,7 +94,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChangesAreSeenByRequestHandler() throws Exception {
+ void requireThatRequestFilterChangesAreSeenByRequestHandler() throws Exception {
final RequestFilter filter = new HeaderRequestFilter("foo", "bar");
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -112,7 +112,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterCanRespond() throws Exception {
+ void requireThatRequestFilterCanRespond() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new RespondForbiddenFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -128,7 +128,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatFilterCanHaveNullCompletionHandler() throws Exception {
+ void requireThatFilterCanHaveNullCompletionHandler() throws Exception {
final int responseStatus = Response.Status.OK;
final String responseMessage = "Excellent";
FilterBindings filterBindings = new FilterBindings.Builder()
@@ -148,7 +148,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterExecutionIsExceptionSafe() throws Exception {
+ void requireThatRequestFilterExecutionIsExceptionSafe() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new ThrowingRequestFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -164,7 +164,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterIsNotRunOnUnboundPath() throws Exception {
+ void requireThatResponseFilterIsNotRunOnUnboundPath() throws Exception {
final ResponseFilter filter = mock(ResponseFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", filter)
@@ -182,7 +182,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterIsRunOnBoundPath() throws Exception {
+ void requireThatResponseFilterIsRunOnBoundPath() throws Exception {
final ResponseFilter filter = mock(ResponseFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", filter)
@@ -200,7 +200,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChangesAreWrittenToResponse() throws Exception {
+ void requireThatResponseFilterChangesAreWrittenToResponse() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", new HeaderResponseFilter("foo", "bar"))
.addResponseFilterBinding("my-response-filter", "http://*/*")
@@ -217,7 +217,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterExecutionIsExceptionSafe() throws Exception {
+ void requireThatResponseFilterExecutionIsExceptionSafe() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", new ThrowingResponseFilter())
.addResponseFilterBinding("my-response-filter", "http://*/*")
@@ -233,7 +233,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterAndResponseFilterCanBindToSamePath() throws Exception {
+ void requireThatRequestFilterAndResponseFilterCanBindToSamePath() throws Exception {
final RequestFilter requestFilter = mock(RequestFilterMockBase.class);
final ResponseFilter responseFilter = mock(ResponseFilterMockBase.class);
final String uriPattern = "http://*/*";
@@ -256,7 +256,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFromRequestFilterGoesThroughResponseFilter() throws Exception {
+ void requireThatResponseFromRequestFilterGoesThroughResponseFilter() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new RespondForbiddenFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -276,7 +276,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainRetainsFilters() {
+ void requireThatRequestFilterChainRetainsFilters() {
final RequestFilter requestFilter1 = mock(RequestFilter.class);
final RequestFilter requestFilter2 = mock(RequestFilter.class);
@@ -296,7 +296,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainIsRun() throws Exception {
+ void requireThatRequestFilterChainIsRun() throws Exception {
final RequestFilter requestFilter1 = mock(RequestFilter.class);
final RequestFilter requestFilter2 = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter1, requestFilter2);
@@ -308,7 +308,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainCallsFilterWithOriginalRequest() throws Exception {
+ void requireThatRequestFilterChainCallsFilterWithOriginalRequest() throws Exception {
final RequestFilter requestFilter = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter);
final HttpRequest request = mock(HttpRequest.class);
@@ -325,7 +325,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainCallsFilterWithOriginalResponseHandler() throws Exception {
+ void requireThatRequestFilterChainCallsFilterWithOriginalResponseHandler() throws Exception {
final RequestFilter requestFilter = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter);
final HttpRequest request = null;
@@ -342,7 +342,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterCanTerminateChain() throws Exception {
+ void requireThatRequestFilterCanTerminateChain() throws Exception {
final RequestFilter requestFilter1 = new RespondForbiddenFilter();
final RequestFilter requestFilter2 = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter1, requestFilter2);
@@ -360,7 +360,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChainRetainsFilters() {
+ void requireThatResponseFilterChainRetainsFilters() {
final ResponseFilter responseFilter1 = mock(ResponseFilter.class);
final ResponseFilter responseFilter2 = mock(ResponseFilter.class);
@@ -380,7 +380,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChainIsRun() {
+ void requireThatResponseFilterChainIsRun() {
final ResponseFilter responseFilter1 = new ResponseHeaderFilter("foo", "bar");
final ResponseFilter responseFilter2 = mock(ResponseFilter.class);
final int statusCode = Response.Status.BAD_GATEWAY;
@@ -399,7 +399,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatDefaultRequestFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
+ void requireThatDefaultRequestFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
RequestFilter filterWithBinding = mock(RequestFilter.class);
RequestFilter defaultFilter = mock(RequestFilter.class);
String defaultFilterId = "default-request-filter";
@@ -422,7 +422,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatDefaultResponseFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
+ void requireThatDefaultResponseFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
ResponseFilter filterWithBinding = mock(ResponseFilter.class);
ResponseFilter defaultFilter = mock(ResponseFilter.class);
String defaultFilterId = "default-response-filter";
@@ -445,7 +445,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
+ void requireThatRequestFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
RequestFilterMockBase filterWithBinding = mock(RequestFilterMockBase.class);
RequestFilterMockBase defaultFilter = mock(RequestFilterMockBase.class);
String defaultFilterId = "default-request-filter";
@@ -468,7 +468,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
+ void requireThatResponseFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
ResponseFilter filterWithBinding = mock(ResponseFilter.class);
ResponseFilter defaultFilter = mock(ResponseFilter.class);
String defaultFilterId = "default-response-filter";
@@ -491,7 +491,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatMetricAreReported() throws IOException, InterruptedException {
+ void requireThatMetricAreReported() throws IOException, InterruptedException {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", mock(RequestFilter.class))
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -514,7 +514,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatStrictFilteringRejectsRequestsNotMatchingFilterChains() throws IOException {
+ void requireThatStrictFilteringRejectsRequestsNotMatchingFilterChains() throws IOException {
RequestFilter filter = mock(RequestFilter.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -531,7 +531,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestHandlerSpecIsAvailableThroughDelegate() throws IOException, InterruptedException {
+ void requireThatRequestHandlerSpecIsAvailableThroughDelegate() throws IOException, InterruptedException {
MyRequestHandler requestHandler = new MyHttpRequestHandler();
MyDelegatedHandler delegateHandler1 = new MyDelegatedHandler(requestHandler);
MyDelegatedHandler delegateHandler2 = new MyDelegatedHandler(delegateHandler1);
@@ -539,7 +539,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestHandlerSpecIsAvailable() throws IOException, InterruptedException {
+ void requireThatRequestHandlerSpecIsAvailable() throws IOException, InterruptedException {
MyRequestHandler requestHandler = new MyHttpRequestHandler();
requestHandlerSpecTest(requestHandler);
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
index d1ba4a4d190..a23a3505bcb 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
@@ -8,7 +8,7 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
@@ -16,9 +16,7 @@ import java.net.URI;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Steinar Knutsen
@@ -29,7 +27,7 @@ public class HttpRequestFactoryTest {
private static final int LOCAL_PORT = 80;
@Test
- public void testLegalURIs() {
+ void testLegalURIs() {
{
URI uri = HttpRequestFactory.getUri(createMockRequest("https", "host", null, null));
assertEquals("https", uri.getScheme());
@@ -68,7 +66,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public void testIllegalQuery() {
+ void testIllegalQuery() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -80,7 +78,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception1() {
+ final void illegal_host_throws_requestexception1() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -92,7 +90,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception2() {
+ final void illegal_host_throws_requestexception2() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -104,7 +102,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception3() {
+ final void illegal_host_throws_requestexception3() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -116,7 +114,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_unicode_in_query_throws_requestexception() {
+ final void illegal_unicode_in_query_throws_requestexception() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -129,7 +127,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public void request_uri_uses_local_port() {
+ void request_uri_uses_local_port() {
HttpRequest request = HttpRequestFactory.newJDiscRequest(
new MockContainer(),
createMockRequest("https", "example.com", "/search", "query=value"));
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
index 89908e6d56b..1f65bc4f582 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
@@ -16,8 +16,8 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Callback;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -42,7 +42,7 @@ public class HttpResponseStatisticsCollectorTest {
private int httpResponseCode = 500;
@Test
- public void statistics_are_aggregated_by_category() {
+ void statistics_are_aggregated_by_category() {
testRequest("http", 300, "GET");
testRequest("http", 301, "GET");
testRequest("http", 200, "GET");
@@ -54,7 +54,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void statistics_are_grouped_by_http_method_and_scheme() {
+ void statistics_are_grouped_by_http_method_and_scheme() {
testRequest("http", 200, "GET");
testRequest("http", 200, "PUT");
testRequest("http", 200, "POST");
@@ -77,7 +77,7 @@ public class HttpResponseStatisticsCollectorTest {
@Test
@SuppressWarnings("removal")
- public void statistics_include_grouped_and_single_statuscodes() {
+ void statistics_include_grouped_and_single_statuscodes() {
testRequest("http", 401, "GET");
testRequest("http", 404, "GET");
testRequest("http", 403, "GET");
@@ -90,7 +90,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void retrieving_statistics_resets_the_counters() {
+ void retrieving_statistics_resets_the_counters() {
testRequest("http", 200, "GET");
testRequest("http", 200, "GET");
@@ -104,7 +104,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void statistics_include_request_type_dimension() {
+ void statistics_include_request_type_dimension() {
testRequest("http", 200, "GET", "/search");
testRequest("http", 200, "POST", "/search");
testRequest("http", 200, "POST", "/feed");
@@ -123,14 +123,14 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void request_type_can_be_set_explicitly() {
+ void request_type_can_be_set_explicitly() {
testRequest("http", 200, "GET", "/search", com.yahoo.jdisc.Request.RequestType.WRITE);
var stats = collector.takeStatistics();
assertStatisticsEntry(stats, "http", "GET", MetricDefinitions.RESPONSES_2XX, "write", 200, 1L);
}
- @Before
+ @BeforeEach
public void initializeCollector() throws Exception {
Server server = new Server();
connector = new AbstractConnector(server, null, null, null, 0) {
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
index baf198dde5d..7cce9f2a9ff 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
@@ -21,9 +21,9 @@ import org.apache.http.util.EntityUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -71,7 +71,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
* Reduce logging of every stack trace for {@link ServerProviderConformanceTest.ConformanceException} thrown.
* This makes the log more readable and the test faster as well.
*/
- @BeforeClass
+ @BeforeAll
public static void reduceExcessiveLogging() {
httpRequestDispatchLoggerOriginalLevel = httpRequestDispatchLogger.getLevel();
httpRequestDispatchLogger.setLevel(Level.SEVERE);
@@ -79,7 +79,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
executorService = Executors.newSingleThreadExecutor();
}
- @AfterClass
+ @AfterAll
public static void restoreExcessiveLogging() throws IOException, InterruptedException {
httpRequestDispatchLogger.setLevel(httpRequestDispatchLoggerOriginalLevel);
httpClient.close();
@@ -87,7 +87,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
executorService.awaitTermination(30, TimeUnit.SECONDS);
}
- @AfterClass
+ @AfterAll
public static void reportDiagnostics() {
System.out.println(
"After " + HttpServerConformanceTest.class.getSimpleName()
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
index 3f84bd3d632..5814ab230bd 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
@@ -38,12 +38,13 @@ import org.apache.hc.core5.http.ConnectionClosedException;
import org.apache.hc.core5.http.ContentType;
import org.assertj.core.api.Assertions;
import org.eclipse.jetty.server.handler.AbstractHandlerContainer;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLContext;
+
+import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.URI;
@@ -88,9 +89,7 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
@@ -104,18 +103,18 @@ import static org.mockito.Mockito.when;
*/
public class HttpServerTest {
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void requireThatServerCanListenToRandomPort() {
+ void requireThatServerCanListenToRandomPort() {
final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler());
assertNotEquals(0, driver.server().getListenPort());
assertTrue(driver.close());
}
@Test
- public void requireThatServerCanNotListenToBoundPort() {
+ void requireThatServerCanNotListenToBoundPort() {
final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler());
try {
JettyTestDriver.newConfiguredInstance(
@@ -131,7 +130,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatBindingSetNotFoundReturns404() throws Exception {
+ void requireThatBindingSetNotFoundReturns404() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
new ServerConfig.Builder()
@@ -139,28 +138,28 @@ public class HttpServerTest {
new ConnectorConfig.Builder(),
newBindingSetSelector("unknown"));
driver.client().get("/status.html")
- .expectStatusCode(is(NOT_FOUND))
- .expectContent(containsPattern(Pattern.compile(
- Pattern.quote(BindingSetNotFoundException.class.getName()) +
- ": No binding set named &apos;unknown&apos;\\.\n\tat .+",
- Pattern.DOTALL | Pattern.MULTILINE)));
+ .expectStatusCode(is(NOT_FOUND))
+ .expectContent(containsPattern(Pattern.compile(
+ Pattern.quote(BindingSetNotFoundException.class.getName()) +
+ ": No binding set named &apos;unknown&apos;\\.\n\tat .+",
+ Pattern.DOTALL | Pattern.MULTILINE)));
assertTrue(driver.close());
}
@Test
- public void requireThatTooLongInitLineReturns414() throws Exception {
+ void requireThatTooLongInitLineReturns414() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
new ServerConfig.Builder(),
new ConnectorConfig.Builder()
.requestHeaderSize(1));
driver.client().get("/status.html")
- .expectStatusCode(is(REQUEST_URI_TOO_LONG));
+ .expectStatusCode(is(REQUEST_URI_TOO_LONG));
assertTrue(driver.close());
}
@Test
- public void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception {
+ void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception {
BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog();
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
@@ -175,15 +174,15 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanEcho() throws Exception {
+ void requireThatServerCanEcho() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatServerCanEchoCompressed() throws Exception {
+ void requireThatServerCanEchoCompressed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
SimpleHttpClient client = driver.newClient(true);
client.get("/status.html")
@@ -192,31 +191,31 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanHandleMultipleRequests() throws Exception {
+ void requireThatServerCanHandleMultipleRequests() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatFormPostWorks() throws Exception {
+ void requireThatFormPostWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final String requestContent = generateContent('a', 30);
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent(requestContent)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception {
+ void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -229,7 +228,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception {
+ void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), false);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -242,7 +241,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception {
+ void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -255,72 +254,72 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception {
+ void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final String requestContent = generateContent('a', 30);
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(X_DISABLE_CHUNKING, "true")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8")
- .setContent(requestContent)
- .execute();
+ .addHeader(X_DISABLE_CHUNKING, "true")
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8")
+ .setContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatEmptyFormPostWorks() throws Exception {
+ void requireThatEmptyFormPostWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(is("{}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormParametersAreParsed() throws Exception {
+ void requireThatFormParametersAreParsed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent("a=b&c=d")
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent("a=b&c=d")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith("{a=[b], c=[d]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatUriParametersAreParsed() throws Exception {
+ void requireThatUriParametersAreParsed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html?a=b&c=d")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(is("{a=[b], c=[d]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormAndUriParametersAreMerged() throws Exception {
+ void requireThatFormAndUriParametersAreMerged() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html?a=b&c=d1")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent("c=d2&e=f")
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent("c=d2&e=f")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith("{a=[b], c=[d1, d2], e=[f]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormCharsetIsHonored() throws Exception {
+ void requireThatFormCharsetIsHonored() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -333,7 +332,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception {
+ void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -343,9 +342,9 @@ public class HttpServerTest {
response.expectStatusCode(is(UNSUPPORTED_MEDIA_TYPE));
assertTrue(driver.close());
}
-
+
@Test
- public void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception {
+ void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -358,7 +357,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception {
+ void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ThrowingHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -370,7 +369,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatMultiPostWorks() throws Exception {
+ void requireThatMultiPostWorks() throws Exception {
// This is taken from tcpdump of bug 5433352 and reassembled here to see that httpserver passes things on.
final String startTxtContent = "this is a test for POST.";
final String updaterConfContent
@@ -389,19 +388,19 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestCookiesAreReceived() throws Exception {
+ void requireThatRequestCookiesAreReceived() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new CookiePrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(COOKIE, "foo=bar")
- .execute();
+ .addHeader(COOKIE, "foo=bar")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(containsString("[foo=bar]"));
assertTrue(driver.close());
}
@Test
- public void requireThatSetCookieHeaderIsCorrect() throws Exception {
+ void requireThatSetCookieHeaderIsCorrect() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new CookieSetterRequestHandler(
new Cookie("foo", "bar")
.setDomain(".localhost")
@@ -409,18 +408,18 @@ public class HttpServerTest {
.setPath("/foopath")
.setSecure(true)));
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectHeader("Set-Cookie",
- is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly"));
+ .expectStatusCode(is(OK))
+ .expectHeader("Set-Cookie",
+ is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly"));
assertTrue(driver.close());
}
@Test
- public void requireThatTimeoutWorks() throws Exception {
+ void requireThatTimeoutWorks() throws Exception {
final UnresponsiveHandler requestHandler = new UnresponsiveHandler();
final JettyTestDriver driver = JettyTestDriver.newInstance(requestHandler);
driver.client().get("/status.html")
- .expectStatusCode(is(GATEWAY_TIMEOUT));
+ .expectStatusCode(is(GATEWAY_TIMEOUT));
ResponseDispatch.newInstance(OK).dispatch(requestHandler.responseHandler);
assertTrue(driver.close());
}
@@ -428,18 +427,18 @@ public class HttpServerTest {
// Header with no value is disallowed by https://tools.ietf.org/html/rfc7230#section-3.2
// Details in https://github.com/eclipse/jetty.project/issues/1116
@Test
- public void requireThatHeaderWithNullValueIsOmitted() throws Exception {
+ void requireThatHeaderWithNullValueIsOmitted() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", null));
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectNoHeader("X-Foo");
+ .expectStatusCode(is(OK))
+ .expectNoHeader("X-Foo");
assertTrue(driver.close());
}
// Header with empty value is allowed by https://tools.ietf.org/html/rfc7230#section-3.2
// Details in https://github.com/eclipse/jetty.project/issues/1116
@Test
- public void requireThatHeaderWithEmptyValueIsAllowed() throws Exception {
+ void requireThatHeaderWithEmptyValueIsAllowed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", ""));
driver.client().get("/status.html")
.expectStatusCode(is(OK))
@@ -448,19 +447,19 @@ public class HttpServerTest {
}
@Test
- public void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception {
+ void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler(CONNECTION, CLOSE));
driver.client().get("/status.html")
- .expectHeader(CONNECTION, is(CLOSE));
+ .expectHeader(CONNECTION, is(CLOSE));
assertThat(driver.close(), is(true));
}
@Test
- @Ignore("Temporarily ignore until stabilized")
- public void requireThatConnectionIsClosedAfterXRequests() throws Exception {
+ @Disabled("Temporarily ignore until stabilized")
+ void requireThatConnectionIsClosedAfterXRequests() throws Exception {
final int MAX_REQUESTS = 10;
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder()
.maxRequestsPerConnection(MAX_REQUESTS)
@@ -490,7 +489,7 @@ public class HttpServerTest {
// HTTP/2
try (CloseableHttpAsyncClient client = createHttp2Client(driver)) {
String uri = "https://localhost:" + driver.server().getListenPort() + "/status.html";
- for (int i = 0; i < 2*MAX_REQUESTS; i++) {
+ for (int i = 0; i < 2 * MAX_REQUESTS; i++) {
try {
client.execute(SimpleRequestBuilder.get(uri).build(), null).get();
} catch (ExecutionException e) {
@@ -508,22 +507,22 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanRespondToSslRequest() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatServerCanRespondToSslRequest() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
final JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT);
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
JettyTestDriver driver = createSslWithTlsClientAuthenticationEnforcer(certificateFile, privateKeyFile);
@@ -539,9 +538,9 @@ public class HttpServerTest {
}
@Test
- public void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT);
@@ -557,33 +556,33 @@ public class HttpServerTest {
}
@Test
- public void requireThatConnectedAtReturnsNonZero() throws Exception {
+ void requireThatConnectedAtReturnsNonZero() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ConnectedAtRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectContent(matchesPattern("\\d{13,}"));
+ .expectStatusCode(is(OK))
+ .expectContent(matchesPattern("\\d{13,}"));
assertThat(driver.close(), is(true));
}
@Test
- public void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception {
+ void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception {
JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
String requestContent = generateContent('a', 30);
ResponseValidator response = driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setGzipContent(requestContent)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setGzipContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatResponseStatsAreCollected() throws Exception {
+ void requireThatResponseStatsAreCollected() throws Exception {
RequestTypeHandler handler = new RequestTypeHandler();
JettyTestDriver driver = JettyTestDriver.newInstance(handler);
HttpResponseStatisticsCollector statisticsCollector = ((AbstractHandlerContainer) driver.server().server().getHandler())
- .getChildHandlerByClass(HttpResponseStatisticsCollector.class);
+ .getChildHandlerByClass(HttpResponseStatisticsCollector.class);
{
List<HttpResponseStatisticsCollector.StatisticsEntry> stats = statisticsCollector.takeStatistics();
@@ -614,7 +613,7 @@ public class HttpServerTest {
handler.setRequestType(Request.RequestType.READ);
driver.client().newPost("/status.html").execute();
var entry = waitForStatistics(statisticsCollector);
- assertEquals("Handler overrides request type", "read", entry.dimensions.requestType);
+ assertEquals("read", entry.dimensions.requestType, "Handler overrides request type");
}
assertTrue(driver.close());
@@ -635,25 +634,25 @@ public class HttpServerTest {
}
@Test
- public void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception {
+ void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception {
JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
new EchoRequestHandler(),
new ServerConfig.Builder(),
new ConnectorConfig.Builder()
.throttling(new Throttling.Builder()
- .enabled(true)
- .maxAcceptRate(10)
- .maxHeapUtilization(1.0)
- .maxConnections(10)));
+ .enabled(true)
+ .maxAcceptRate(10)
+ .maxHeapUtilization(1.0)
+ .maxConnections(10)));
driver.client().get("/status.html")
.expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatConnectionIsTrackedInConnectionLog() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatConnectionIsTrackedInConnectionLog() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
Module overrideModule = binder -> binder.bind(ConnectionLog.class).toInstance(connectionLog);
@@ -690,7 +689,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException {
+ void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException {
BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog();
JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
new EchoRequestHandler(),
@@ -705,9 +704,9 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestsPerConnectionMetricIsAggregated() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatRequestsPerConnectionMetricIsAggregated() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
var metricConsumer = new MetricConsumerMock();
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
@@ -719,9 +718,9 @@ public class HttpServerTest {
}
@Test
- public void uriWithEmptyPathSegmentIsAllowed() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void uriWithEmptyPathSegmentIsAllowed() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
MetricConsumerMock metricConsumer = new MetricConsumerMock();
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
index 494f33ca04b..348bfd6183e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
@@ -16,7 +16,7 @@ import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.HttpTrace;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -32,30 +32,30 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class JDiscHttpServletTest {
@Test
- public void requireThatServerRespondsToAllMethods() throws Exception {
+ void requireThatServerRespondsToAllMethods() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(newEchoHandler());
final URI uri = driver.client().newUri("/status.html");
driver.client().execute(new HttpGet(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPost(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpHead(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPut(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpDelete(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpOptions(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpTrace(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPatch(uri))
.expectStatusCode(is(OK));
assertThat(driver.close(), is(true));
}
@Test
- public void requireThatServerResponds405ToUnknownMethods() throws IOException {
+ void requireThatServerResponds405ToUnknownMethods() throws IOException {
JettyTestDriver driver = JettyTestDriver.newInstance(newEchoHandler());
final URI uri = driver.client().newUri("/status.html");
driver.client().execute(new UnknownMethodHttpRequest(uri))
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
index c2a6e0326e2..298f0feb9e6 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
@@ -24,7 +24,6 @@ import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.hamcrest.Matcher;
-import org.hamcrest.MatcherAssert;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@@ -38,7 +37,7 @@ import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* A simple http client for testing
@@ -186,14 +185,14 @@ public class SimpleHttpClient implements AutoCloseable {
}
public ResponseValidator expectStatusCode(Matcher<Integer> matcher) {
- MatcherAssert.assertThat(response.getCode(), matcher);
+ assertThat(response.getCode(), matcher);
return this;
}
public ResponseValidator expectHeader(String headerName, Matcher<String> matcher) {
Header firstHeader = response.getFirstHeader(headerName);
String headerValue = firstHeader != null ? firstHeader.getValue() : null;
- MatcherAssert.assertThat(headerValue, matcher);
+ assertThat(headerValue, matcher);
assertNotNull(firstHeader);
return this;
}
@@ -205,7 +204,7 @@ public class SimpleHttpClient implements AutoCloseable {
}
public ResponseValidator expectContent(final Matcher<String> matcher) {
- MatcherAssert.assertThat(content, matcher);
+ assertThat(content, matcher);
return this;
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
index cf7e1de4381..3858d6b9e4e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.jdisc.http.server.jetty;
import com.yahoo.jdisc.Metric;
import org.eclipse.jetty.io.ssl.SslHandshakeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
@@ -23,13 +23,13 @@ public class SslHandshakeFailedListenerTest {
SslHandshakeFailedListener listener = new SslHandshakeFailedListener(metrics, "connector", 1234);
@Test
- public void includes_client_ip_dimension_present_when_peer_available() {
+ void includes_client_ip_dimension_present_when_peer_available() {
listener.handshakeFailed(handshakeEvent(true), new SSLHandshakeException("Empty server certificate chain"));
verify(metrics).createContext(eq(Map.of("clientIp", "127.0.0.1", "serverName", "connector", "serverPort", 1234)));
}
@Test
- public void does_not_include_client_ip_dimension_present_when_peer_unavailable() {
+ void does_not_include_client_ip_dimension_present_when_peer_unavailable() {
listener.handshakeFailed(handshakeEvent(false), new SSLHandshakeException("Empty server certificate chain"));
verify(metrics).createContext(eq(Map.of("serverName", "connector", "serverPort", 1234)));
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
index fce4d6ee74e..a192c49aeb9 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.http.ssl.impl;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.tls.AuthorizationMode;
+import com.yahoo.security.tls.AuthorizedPeers;
import com.yahoo.security.tls.DefaultTlsContext;
import com.yahoo.security.tls.HostnameVerification;
import com.yahoo.security.tls.PeerAuthentication;
import com.yahoo.security.tls.TlsContext;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -22,7 +22,7 @@ import java.util.Set;
import static com.yahoo.security.KeyAlgorithm.EC;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* @author bjorncs
@@ -30,7 +30,7 @@ import static org.junit.Assert.assertArrayEquals;
public class TlsContextBasedProviderTest {
@Test
- public void creates_sslcontextfactory_from_tlscontext() {
+ void creates_sslcontextfactory_from_tlscontext() {
TlsContext tlsContext = createTlsContext();
var provider = new SimpleTlsContextBasedProvider(tlsContext);
DefaultConnectorSsl ssl = new DefaultConnectorSsl();
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
index cc5d110d423..11cc8b86a09 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.List;
@@ -12,10 +13,9 @@ import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.Set;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
@@ -28,18 +28,18 @@ import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
public class BucketTest {
private Bucket bucket;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
bucket = new Bucket();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
bucket = null;
}
@Test
- public final void testEntrySet() {
+ final void testEntrySet() {
assertEquals(0, bucket.entrySet().size());
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle_" + i, null), AssumedType.GAUGE));
@@ -47,7 +47,7 @@ public class BucketTest {
assertEquals(4, bucket.entrySet().size());
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle",
- new Point(new ImmutableMap.Builder<String, Integer>().put("dim", Integer.valueOf(i)).build())),
+ new Point(new ImmutableMap.Builder<String, Integer>().put("dim", Integer.valueOf(i)).build())),
AssumedType.GAUGE));
}
assertEquals(8, bucket.entrySet().size());
@@ -55,23 +55,23 @@ public class BucketTest {
for (Entry<Identifier, UntypedMetric> x : bucket.entrySet()) {
String metricName = x.getKey().getName();
switch (metricName) {
- case "nalle":
- ++nalle;
- break;
- case "nalle_0":
- ++nalle0;
- break;
- case "nalle_1":
- ++nalle1;
- break;
- case "nalle_2":
- ++nalle2;
- break;
- case "nalle_3":
- ++nalle3;
- break;
- default:
- throw new IllegalStateException();
+ case "nalle":
+ ++nalle;
+ break;
+ case "nalle_0":
+ ++nalle0;
+ break;
+ case "nalle_1":
+ ++nalle1;
+ break;
+ case "nalle_2":
+ ++nalle2;
+ break;
+ case "nalle_3":
+ ++nalle3;
+ break;
+ default:
+ throw new IllegalStateException();
}
}
assertEquals(4, nalle);
@@ -82,7 +82,7 @@ public class BucketTest {
}
@Test
- public final void testPutSampleWithUnsupportedType() {
+ final void testPutSampleWithUnsupportedType() {
boolean caughtIt = false;
try {
bucket.put(new Sample(new Measurement(1), new Identifier("nalle", null), AssumedType.NONE));
@@ -93,7 +93,7 @@ public class BucketTest {
}
@Test
- public final void testPutIdentifierUntypedValue() {
+ final void testPutIdentifierUntypedValue() {
UntypedMetric v = new UntypedMetric(null);
v.add(2);
bucket.put(new Sample(new Measurement(3), new Identifier("nalle", null), AssumedType.GAUGE));
@@ -106,10 +106,10 @@ public class BucketTest {
}
@Test
- public final void testHasIdentifier() {
+ final void testHasIdentifier() {
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle_" + i, new Point(
- new ImmutableMap.Builder<String, Integer>().put(String.valueOf(i), Integer.valueOf(i)).build())),
+ new ImmutableMap.Builder<String, Integer>().put(String.valueOf(i), Integer.valueOf(i)).build())),
AssumedType.GAUGE));
}
for (int i = 0; i < 4; ++i) {
@@ -119,7 +119,7 @@ public class BucketTest {
}
@Test
- public final void testOkMerge() {
+ final void testOkMerge() {
bucket.put(new Sample(new Measurement(2), new Identifier("nalle", null), AssumedType.GAUGE));
Bucket otherNew = new Bucket();
otherNew.put(new Sample(new Measurement(3), new Identifier("nalle", null), AssumedType.GAUGE));
@@ -138,7 +138,7 @@ public class BucketTest {
}
@Test
- public final void testMergeDifferentMetrics() {
+ final void testMergeDifferentMetrics() {
bucket.put(new Sample(new Measurement(2), new Identifier("nalle", null), AssumedType.GAUGE));
Bucket otherNew = new Bucket();
otherNew.put(new Sample(new Measurement(3), new Identifier("other", null), AssumedType.GAUGE));
@@ -188,7 +188,7 @@ public class BucketTest {
}
@Test
- public final void testMismatchedMerge() {
+ final void testMismatchedMerge() {
Logger log = Logger.getLogger(Bucket.class.getName());
boolean[] loggingMarker = new boolean[1];
loggingMarker[0] = false;
@@ -205,7 +205,7 @@ public class BucketTest {
}
@Test
- public final void testGetAllMetricNames() {
+ final void testGetAllMetricNames() {
twoMetricsUniqueDimensions();
Collection<String> names = bucket.getAllMetricNames();
assertEquals(2, names.size());
@@ -214,7 +214,7 @@ public class BucketTest {
}
@Test
- public final void testGetValuesForMetric() {
+ final void testGetValuesForMetric() {
twoMetricsUniqueDimensions();
Collection<Entry<Point, UntypedMetric>> values = bucket.getValuesForMetric("nalle");
assertEquals(4, values.size());
@@ -231,7 +231,7 @@ public class BucketTest {
}
@Test
- public final void testGetValuesByMetricName() {
+ final void testGetValuesByMetricName() {
twoMetricsUniqueDimensions();
Map<String, List<Entry<Point, UntypedMetric>>> values = bucket.getValuesByMetricName();
assertEquals(2, values.size());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
index f579b1584aa..45a76078619 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -10,9 +8,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Functional tests for counters.
@@ -23,18 +22,18 @@ public class CounterTest {
MetricReceiver receiver;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
receiver = new MetricReceiver.MockReceiver();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
receiver = null;
}
@Test
- public final void testAdd() throws InterruptedException {
+ final void testAdd() throws InterruptedException {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
c.add();
@@ -48,7 +47,7 @@ public class CounterTest {
}
@Test
- public final void testAddLong() throws InterruptedException {
+ final void testAddLong() throws InterruptedException {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
final long twoToThePowerOfFourtyeight = 65536L * 65536L * 65536L;
@@ -63,7 +62,7 @@ public class CounterTest {
}
@Test
- public final void testAddPoint() throws InterruptedException {
+ final void testAddPoint() throws InterruptedException {
final String metricName = "unitTestCounter";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Counter c = receiver.declareCounter(metricName, p);
@@ -75,10 +74,10 @@ public class CounterTest {
assertEquals(1, x.size());
assertEquals(p, x.get(0).getKey());
assertEquals(1, x.get(0).getValue().getCount());
- }
+ }
@Test
- public final void testAddLongPoint() throws InterruptedException {
+ final void testAddLongPoint() throws InterruptedException {
final String metricName = "unitTestCounter";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Counter c = receiver.declareCounter(metricName, p);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
index b1b1ff28aeb..267ca1d575d 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
@@ -1,17 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
/**
@@ -24,18 +24,18 @@ public class DimensionsCacheTest {
private static final int POINTS_TO_KEEP = 3;
DimensionCache cache;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
cache = new DimensionCache(POINTS_TO_KEEP);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
cache = null;
}
@Test
- public final void smokeTest() {
+ final void smokeTest() {
String metricName = "testMetric";
Bucket first = new Bucket();
for (int i = 0; i < 4; ++i) {
@@ -53,11 +53,11 @@ public class DimensionsCacheTest {
newestFound = true;
}
}
- assertTrue("Kept newest measurement when padding points.", newestFound);
+ assertTrue(newestFound, "Kept newest measurement when padding points.");
}
@Test
- public final void testNoBoomWithEmptyBuckets() {
+ final void testNoBoomWithEmptyBuckets() {
Bucket check = new Bucket();
cache.updateDimensionPersistence(null, new Bucket());
cache.updateDimensionPersistence(null, new Bucket());
@@ -66,7 +66,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void testUpdateWithNullThenDataThenData() {
+ final void testUpdateWithNullThenDataThenData() {
Bucket first = new Bucket();
populateDimensionLessValue("one", first, 2);
cache.updateDimensionPersistence(null, first);
@@ -80,7 +80,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void requireThatOldDataIsForgotten() {
+ final void requireThatOldDataIsForgotten() {
Bucket first = new Bucket(); // "now" as timestamp
populateDimensionLessValue("one", first, 2);
cache.updateDimensionPersistence(first, new Bucket());
@@ -96,7 +96,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void testUpdateWithNullThenDataThenNoDataThenData() {
+ final void testUpdateWithNullThenDataThenNoDataThenData() {
Bucket first = new Bucket();
Bucket second = new Bucket();
populateDimensionLessValue("first", first, 1.0d);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
index 0d4d6360f20..8147f9a53cc 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -10,10 +8,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.ManagerConfig;
/**
@@ -25,18 +23,18 @@ public class GaugeTest {
MetricReceiver receiver;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
receiver = new MetricReceiver.MockReceiver();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
receiver = null;
}
@Test
- public final void testSampleDouble() throws InterruptedException {
+ final void testSampleDouble() throws InterruptedException {
final String metricName = "unitTestGauge";
Gauge g = receiver.declareGauge(metricName);
g.sample(1.0d);
@@ -51,7 +49,7 @@ public class GaugeTest {
}
@Test
- public final void testSampleDoublePoint() throws InterruptedException {
+ final void testSampleDoublePoint() throws InterruptedException {
final String metricName = "unitTestGauge";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Gauge g = receiver.declareGauge(metricName, p);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
index c8a5f17fdfb..f64998f0be4 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
@@ -1,17 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.simple.jdisc.JdiscMetricsFactory;
import com.yahoo.metrics.simple.jdisc.SimpleMetricConsumer;
@@ -23,19 +22,19 @@ import com.yahoo.metrics.simple.jdisc.SimpleMetricConsumer;
public class MetricsTest extends UnitTestSetup {
SimpleMetricConsumer metricApi;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
super.init();
metricApi = (SimpleMetricConsumer) new JdiscMetricsFactory(metricManager.get()).newInstance();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
super.fini();
}
@Test
- public final void smokeTest() throws InterruptedException {
+ final void smokeTest() throws InterruptedException {
final String metricName = "testMetric";
metricApi.set(metricName, Double.valueOf(1.0d), null);
updater.gotData.await(10, TimeUnit.SECONDS);
@@ -49,7 +48,7 @@ public class MetricsTest extends UnitTestSetup {
}
@Test
- public final void testRedefinition() {
+ final void testRedefinition() {
MetricReceiver r = metricManager.get();
final String metricName = "gah";
r.addMetricDefinition(metricName, new MetricSettings.Builder().build());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
index ca680c805ef..e6cb70db07a 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
@@ -1,20 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
*/
public class PointTest {
-
+
@Test
- public void testPointEquality() {
+ void testPointEquality() {
Point a = new Point(Collections.emptyMap());
Point b = new Point(new HashMap<>(0));
assertEquals(a.hashCode(), b.hashCode());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
index 4d4229e8369..7981e5904f3 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
@@ -12,14 +12,14 @@ import com.yahoo.metrics.simple.Identifier;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.metrics.simple.Point;
import com.yahoo.metrics.simple.UntypedMetric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -27,10 +27,10 @@ import static org.junit.Assert.assertTrue;
public class SnapshotConverterTest {
@Test
- public void testPointConversion() {
+ void testPointConversion() {
MetricDimensions a = SnapshotConverter.convert(new Point(Collections.emptyMap()));
MetricDimensions b = SnapshotConverter.convert(new Point(new HashMap<>(0)));
- MetricDimensions c = SnapshotConverter.convert((Point)null);
+ MetricDimensions c = SnapshotConverter.convert((Point) null);
assertEquals(a.hashCode(), b.hashCode());
assertEquals(a, b);
assertEquals(a.hashCode(), c.hashCode());
@@ -40,11 +40,11 @@ public class SnapshotConverterTest {
}
@Test
- public void testConversion() {
+ void testConversion() {
MetricReceiver mock = new MetricReceiver.MockReceiver();
mock.declareCounter("foo").add(1);
mock.declareGauge("quuux").sample(42.25);
- mock.declareCounter("bar", new Point(new HashMap<String,String>())).add(4);
+ mock.declareCounter("bar", new Point(new HashMap<String, String>())).add(4);
MetricSnapshot snapshot = new SnapshotConverter(mock.getSnapshot()).convert();
@@ -58,14 +58,14 @@ public class SnapshotConverterTest {
++cnt;
if ("foo".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof CountMetric);
- assertEquals(1, ((CountMetric)mv.getValue()).getCount());
+ assertEquals(1, ((CountMetric) mv.getValue()).getCount());
} else if ("bar".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof CountMetric);
- assertEquals(4, ((CountMetric)mv.getValue()).getCount());
+ assertEquals(4, ((CountMetric) mv.getValue()).getCount());
} else if ("quuux".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof GaugeMetric);
- assertEquals(42.25, ((GaugeMetric)mv.getValue()).getLast(), 0.001);
- assertEquals(1, ((GaugeMetric)mv.getValue()).getCount());
+ assertEquals(42.25, ((GaugeMetric) mv.getValue()).getLast(), 0.001);
+ assertEquals(1, ((GaugeMetric) mv.getValue()).getCount());
} else {
assertTrue(false);
}
diff --git a/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java b/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
index 4433b78c807..c1f4991cfcc 100644
--- a/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
+++ b/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
@@ -2,9 +2,10 @@
package com.yahoo.osgi.provider.model;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author gjoranv
@@ -12,27 +13,29 @@ import static org.junit.Assert.assertEquals;
public class ComponentModelTest {
@Test
- public void create_from_instantiation_spec() {
+ void create_from_instantiation_spec() {
ComponentModel model = new ComponentModel(
- BundleInstantiationSpecification.getFromStrings("id", "class", "bundle"));
+ BundleInstantiationSpecification.fromStrings("id", "class", "bundle"));
verifyBundleSpec(model);
}
- @Test(expected = IllegalArgumentException.class)
- public void require_exception_upon_null_instantiation_spec() throws Exception {
- ComponentModel model = new ComponentModel(null);
+ @Test
+ void require_exception_upon_null_instantiation_spec() throws Exception {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ComponentModel model = new ComponentModel(null);
+ });
}
@Test
- public void create_from_instantiation_spec_and_config_id() throws Exception {
+ void create_from_instantiation_spec_and_config_id() throws Exception {
ComponentModel model = new ComponentModel(
- BundleInstantiationSpecification.getFromStrings("id", "class", "bundle"), "configId");
+ BundleInstantiationSpecification.fromStrings("id", "class", "bundle"), "configId");
verifyBundleSpec(model);
assertEquals("configId", model.configId);
}
@Test
- public void create_from_strings() throws Exception {
+ void create_from_strings() throws Exception {
ComponentModel model = new ComponentModel("id", "class", "bundle", "configId");
verifyBundleSpec(model);
assertEquals("configId", model.configId);
diff --git a/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java b/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
index f8cd646909d..274bd2050f2 100644
--- a/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
@@ -5,11 +5,11 @@ import com.yahoo.processing.response.ArrayDataList;
import com.yahoo.processing.response.DataList;
import com.yahoo.processing.test.ProcessorLibrary;
import com.yahoo.processing.test.Responses;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -24,7 +24,7 @@ public class ResponseTestCase {
*/
@SuppressWarnings({"unchecked"})
@Test
- public void testRecursiveCompletionAndToString() throws InterruptedException, ExecutionException {
+ void testRecursiveCompletionAndToString() throws InterruptedException, ExecutionException {
// create lists
Request request = new Request();
DataList list1 = ArrayDataList.create(request);
@@ -48,22 +48,22 @@ public class ResponseTestCase {
list123.add(list1231);
list123.add(list1232);
// add sync data elements
- list1.add(new ProcessorLibrary.StringData(request,"list1"));
- list12.add(new ProcessorLibrary.StringData(request,"list12"));
- list14.add(new ProcessorLibrary.StringData(request,"list14"));
- list122.add(new ProcessorLibrary.StringData(request,"list122"));
- list1231.add(new ProcessorLibrary.StringData(request,"list1231"));
+ list1.add(new ProcessorLibrary.StringData(request, "list1"));
+ list12.add(new ProcessorLibrary.StringData(request, "list12"));
+ list14.add(new ProcessorLibrary.StringData(request, "list14"));
+ list122.add(new ProcessorLibrary.StringData(request, "list122"));
+ list1231.add(new ProcessorLibrary.StringData(request, "list1231"));
- assertEqualsIgnoreObjectNumbers("Uncompleted tree, no incoming",uncompletedTreeUncompletedIncoming,Responses.recursiveToString(list1));
+ assertEqualsIgnoreObjectNumbers("Uncompleted tree, no incoming", uncompletedTreeUncompletedIncoming, Responses.recursiveToString(list1));
// provide all async incoming data
list12.incoming().markComplete();
- list121.incoming().addLast(new ProcessorLibrary.StringData(request,"list121async1"));
+ list121.incoming().addLast(new ProcessorLibrary.StringData(request, "list121async1"));
list123.incoming().markComplete();
- list1231.incoming().add(new ProcessorLibrary.StringData(request,"list13231async1"));
- list1231.incoming().addLast(new ProcessorLibrary.StringData(request,"list1231async2"));
- list13.incoming().add(new ProcessorLibrary.StringData(request,"list13async1"));
- list13.incoming().addLast(new ProcessorLibrary.StringData(request,"list13async2"));
+ list1231.incoming().add(new ProcessorLibrary.StringData(request, "list13231async1"));
+ list1231.incoming().addLast(new ProcessorLibrary.StringData(request, "list1231async2"));
+ list13.incoming().add(new ProcessorLibrary.StringData(request, "list13async1"));
+ list13.incoming().addLast(new ProcessorLibrary.StringData(request, "list13async2"));
assertEqualsIgnoreObjectNumbers("Uncompleted tree, incoming complete", uncompletedTreeCompletedIncoming, Responses.recursiveToString(list1));
@@ -73,7 +73,7 @@ public class ResponseTestCase {
}
private void assertEqualsIgnoreObjectNumbers(String explanation,String expected,String actual) {
- assertEquals(explanation,expected,removeObjectNumbers(actual));
+ assertEquals(expected,removeObjectNumbers(actual),explanation);
}
/** Removes all object numbers (occurrences of @hexnumber) */
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
index 22f69a87bc3..fb469c36e14 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -18,29 +18,29 @@ public class AsyncExecutionTestCase {
/** Execute a processing chain which forks off into multiple threads */
@Test
- public void testAsyncExecution() {
+ void testAsyncExecution() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new CombineData(),new BlockingSplitter(2),new Get6DataItems(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new CombineData(), new BlockingSplitter(2), new Get6DataItems(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result
- assertEquals(6*2-1,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.3",response.data().get(2).toString());
- assertEquals("second.3",response.data().get(3).toString());
- assertEquals("third.3",response.data().get(4).toString());
+ assertEquals(6 * 2 - 1, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.3", response.data().get(2).toString());
+ assertEquals("second.3", response.data().get(3).toString());
+ assertEquals("third.3", response.data().get(4).toString());
// from the parallel execution
- assertEquals("first.2",response.data().get(5).toString());
- assertEquals("second.2",response.data().get(6).toString());
- assertEquals("third.2",response.data().get(7).toString());
- assertEquals("first.3",response.data().get(8).toString());
- assertEquals("second.3",response.data().get(9).toString());
- assertEquals("third.3",response.data().get(10).toString());
+ assertEquals("first.2", response.data().get(5).toString());
+ assertEquals("second.2", response.data().get(6).toString());
+ assertEquals("third.2", response.data().get(7).toString());
+ assertEquals("first.3", response.data().get(8).toString());
+ assertEquals("second.3", response.data().get(9).toString());
+ assertEquals("third.3", response.data().get(10).toString());
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
index c8c489b2f9d..ce7a747d676 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
@@ -5,16 +5,13 @@ import com.yahoo.component.chain.Chain;
import com.yahoo.processing.Processor;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,53 +22,53 @@ public class ExecutionContextTestCase {
/** Tests combined use of trace messages, context values and access log entries */
@Test
- public void testtrace() {
- Execution execution1=Execution.createRoot(chain,2,Execution.Environment.createEmpty());
- execution1.trace().setProperty("a","a1");
- execution1.trace().logValue("a","a1");
+ void testtrace() {
+ Execution execution1 = Execution.createRoot(chain, 2, Execution.Environment.createEmpty());
+ execution1.trace().setProperty("a", "a1");
+ execution1.trace().logValue("a", "a1");
execution1.trace().trace("root 1", 2);
- execution1.trace().setProperty("a","a2");
- execution1.trace().setProperty("b","b1");
- execution1.trace().logValue("a","a2");
- execution1.trace().logValue("b","b1");
-
- Execution execution2=new Execution(chain,execution1);
- execution2.trace().setProperty("b","b2");
- execution2.trace().logValue("b","b2");
+ execution1.trace().setProperty("a", "a2");
+ execution1.trace().setProperty("b", "b1");
+ execution1.trace().logValue("a", "a2");
+ execution1.trace().logValue("b", "b1");
+
+ Execution execution2 = new Execution(chain, execution1);
+ execution2.trace().setProperty("b", "b2");
+ execution2.trace().logValue("b", "b2");
execution2.trace().trace(" child-1 1", 2);
execution2.trace().setProperty("b", "b3");
- execution2.trace().logValue("b","b3");
+ execution2.trace().logValue("b", "b3");
- execution1.trace().setProperty("b","b4");
- execution1.trace().logValue("b","b4");
+ execution1.trace().setProperty("b", "b4");
+ execution1.trace().logValue("b", "b4");
- Execution execution3=new Execution(chain,execution1);
- execution3.trace().setProperty("b","b5");
- execution3.trace().setProperty("c","c1");
- execution3.trace().logValue("b","b5");
- execution3.trace().logValue("c","c1");
+ Execution execution3 = new Execution(chain, execution1);
+ execution3.trace().setProperty("b", "b5");
+ execution3.trace().setProperty("c", "c1");
+ execution3.trace().logValue("b", "b5");
+ execution3.trace().logValue("c", "c1");
execution3.trace().trace(" child-2 1", 2);
- execution2.trace().setProperty("c","c2");
- execution2.trace().logValue("c","c2");
+ execution2.trace().setProperty("c", "c2");
+ execution2.trace().logValue("c", "c2");
execution1.trace().trace("root 2", 2);
execution3.trace().setProperty("d", "d1");
- execution1.trace().logValue("d","d1");
+ execution1.trace().logValue("d", "d1");
execution2.trace().trace(" child-1 2", 2);
execution2.trace().setProperty("c", "c3");
- execution2.trace().logValue("c","c3");
+ execution2.trace().logValue("c", "c3");
- execution1.trace().setProperty("c","c4");
- execution1.trace().logValue("c","c4");
+ execution1.trace().setProperty("c", "c4");
+ execution1.trace().logValue("c", "c4");
- Iterator<String> traceIterator=execution1.trace().traceNode().root().descendants(String.class).iterator();
- assertEquals("root 1",traceIterator.next());
- assertEquals(" child-1 1",traceIterator.next());
- assertEquals(" child-1 2",traceIterator.next());
- assertEquals(" child-2 1",traceIterator.next());
- assertEquals("root 2",traceIterator.next());
+ Iterator<String> traceIterator = execution1.trace().traceNode().root().descendants(String.class).iterator();
+ assertEquals("root 1", traceIterator.next());
+ assertEquals(" child-1 1", traceIterator.next());
+ assertEquals(" child-1 2", traceIterator.next());
+ assertEquals(" child-2 1", traceIterator.next());
+ assertEquals("root 2", traceIterator.next());
assertFalse(traceIterator.hasNext());
// Verify context variables
@@ -82,10 +79,10 @@ public class ExecutionContextTestCase {
assertNull(execution1.trace().getProperty("e"));
// Verify access log
- Set<String> logValues=new HashSet<>();
- for (Iterator<Execution.Trace.LogValue> logValueIterator=execution1.trace().logValueIterator(); logValueIterator.hasNext(); )
+ Set<String> logValues = new HashSet<>();
+ for (Iterator<Execution.Trace.LogValue> logValueIterator = execution1.trace().logValueIterator(); logValueIterator.hasNext(); )
logValues.add(logValueIterator.next().toString());
- assertEquals(12,logValues.size());
+ assertEquals(12, logValues.size());
assertTrue(logValues.contains("a=a1"));
assertTrue(logValues.contains("a=a2"));
assertTrue(logValues.contains("b=b1"));
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
index 7dd043383a1..e346628452c 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
@@ -7,14 +7,14 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.response.DataList;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests scenarios where a data producer returns a promise of some future data rather than the data itself.
@@ -27,92 +27,92 @@ public class FutureDataTestCase {
/** Run a chain which ends in a processor which returns a response containing future data. */
@SuppressWarnings({"unchecked"})
@Test
- public void testFutureDataPassThrough() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFutureDataPassThrough() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> chain=new Chain<>(new DataCounter(),futureDataSource);
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> chain = new Chain<>(new DataCounter(), futureDataSource);
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request); // Urk ...
+ Request request = new Request();
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request); // Urk ...
// Verify the result prior to completion of delayed data
- assertEquals(1,response.data().asList().size());
- assertEquals("Data count: 0",response.data().get(0).toString());
+ assertEquals(1, response.data().asList().size());
+ assertEquals("Data count: 0", response.data().get(0).toString());
// complete delayed data
- assertEquals("Delayed data was requested once", 1, futureDataSource.incomingData.size());
+ assertEquals(1, futureDataSource.incomingData.size(), "Delayed data was requested once");
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("New data is not visible because we haven't asked for it", 1, response.data().asList().size());
+ assertEquals(1, response.data().asList().size(), "New data is not visible because we haven't asked for it");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data is available", 3, response.data().asList().size());
- assertEquals("d1",response.data().get(1).toString().toString());
- assertEquals("d2",response.data().get(2).toString().toString());
+ assertEquals(3, response.data().asList().size(), "Now the data is available");
+ assertEquals("d1", response.data().get(1).toString().toString());
+ assertEquals("d2", response.data().get(2).toString().toString());
}
/** Federate to one source which returns data immediately and one who return future data */
@SuppressWarnings({"unchecked"})
@Test
- public void testFederateSyncAndAsyncData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFederateSyncAndAsyncData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> chain=new Chain<>(new DataCounter(),new Federator(new Chain<>(new DataSource()),new Chain<>(futureDataSource)));
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> chain = new Chain<>(new DataCounter(), new Federator(new Chain<>(new DataSource()), new Chain<>(futureDataSource)));
// Execute
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals(3,response.data().asList().size()); // The sync data list + the (currently empty) future data list) + the data count
- DataList syncData=(DataList)response.data().get(0);
- DataList asyncData=(DataList)response.data().get(1);
- StringData countData=(StringData)response.data().get(2);
+ assertEquals(3, response.data().asList().size()); // The sync data list + the (currently empty) future data list) + the data count
+ DataList syncData = (DataList) response.data().get(0);
+ DataList asyncData = (DataList) response.data().get(1);
+ StringData countData = (StringData) response.data().get(2);
- assertEquals("The sync data is available",3,syncData.asList().size());
- assertEquals( "first.1",syncData.get(0).toString());
+ assertEquals(3, syncData.asList().size(), "The sync data is available");
+ assertEquals("first.1", syncData.get(0).toString());
assertEquals("second.1", syncData.get(1).toString());
- assertEquals( "third.1",syncData.get(2).toString());
- assertEquals("No async data yet",0,asyncData.asList().size());
- assertEquals("The data counter has run and accessed the sync data","Data count: 3",countData.toString());
+ assertEquals("third.1", syncData.get(2).toString());
+ assertEquals(0, asyncData.asList().size(), "No async data yet");
+ assertEquals("Data count: 3", countData.toString(), "The data counter has run and accessed the sync data");
// complete async data
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("New data is not visible because we haven't asked for it", 0, asyncData.asList().size());
+ assertEquals(0, asyncData.asList().size(), "New data is not visible because we haven't asked for it");
asyncData.completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data is available", 2, asyncData.asList().size());
- assertEquals("d1",asyncData.get(0).toString().toString());
+ assertEquals(2, asyncData.asList().size(), "Now the data is available");
+ assertEquals("d1", asyncData.get(0).toString().toString());
assertEquals("d2", asyncData.get(1).toString().toString());
}
/** Register a chain which will be called when some async data is available */
@SuppressWarnings({"unchecked", "removal"})
@Test
- public void testAsyncDataProcessing() throws InterruptedException, ExecutionException, TimeoutException {
+ void testAsyncDataProcessing() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> asyncChain=new Chain<Processor>(new DataCounter());
- Chain<Processor> chain=new Chain<>(new AsyncDataProcessingInitiator(asyncChain),futureDataSource);
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> asyncChain = new Chain<Processor>(new DataCounter());
+ Chain<Processor> chain = new Chain<>(new AsyncDataProcessingInitiator(asyncChain), futureDataSource);
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals("No data yet",0,response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "No data yet");
// complete async data
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
- assertEquals("New data is not visible because it is not complete", 0, response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "New data is not visible because it is not complete");
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("Not visible because it has not been synced yet", 0, response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "Not visible because it has not been synced yet");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data as well as the count is available", 3, response.data().asList().size());
- assertEquals("d1",response.data().get(0).toString().toString());
- assertEquals("d2",response.data().get(1).toString().toString());
- assertEquals("Data count: 2",response.data().get(2).toString());
+ assertEquals(3, response.data().asList().size(), "Now the data as well as the count is available");
+ assertEquals("d1", response.data().get(0).toString().toString());
+ assertEquals("d2", response.data().get(1).toString().toString());
+ assertEquals("Data count: 2", response.data().get(2).toString());
}
/**
@@ -122,52 +122,51 @@ public class FutureDataTestCase {
*/
@SuppressWarnings({"unchecked"})
@Test
- public void testAsyncDataProcessingOfFederatedResult() throws InterruptedException, ExecutionException, TimeoutException {
+ void testAsyncDataProcessingOfFederatedResult() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
// Source 1 (async with completion chain)
- FutureDataSource futureSource1=new FutureDataSource();
- Chain<Processor> asyncChainSource1=new Chain<Processor>(new DataCounter("source1"));
- Chain<Processor> chainSource1=new Chain<>(new AsyncDataProcessingInitiator(asyncChainSource1),futureSource1);
+ FutureDataSource futureSource1 = new FutureDataSource();
+ Chain<Processor> asyncChainSource1 = new Chain<Processor>(new DataCounter("source1"));
+ Chain<Processor> chainSource1 = new Chain<>(new AsyncDataProcessingInitiator(asyncChainSource1), futureSource1);
// Source 2 (async source)
- FutureDataSource futureSource2=new FutureDataSource();
- Chain<Processor> chainSource2=new Chain<Processor>(futureSource2);
+ FutureDataSource futureSource2 = new FutureDataSource();
+ Chain<Processor> chainSource2 = new Chain<Processor>(futureSource2);
// Source 3 (sync source)
- Chain<Processor> chainSource3=new Chain<Processor>(new DataSource());
+ Chain<Processor> chainSource3 = new Chain<Processor>(new DataSource());
// Main chain federating to the above - not waiting for source 1 and 2 but invoking asyncMain when both are complete
- Chain<Processor> asyncMain=new Chain<Processor>(new DataCounter("main"));
- Chain<Processor> main=new Chain<>(new AsyncDataProcessingInitiator(asyncMain),new Federator(chainSource1,chainSource2,chainSource3));
+ Chain<Processor> asyncMain = new Chain<Processor>(new DataCounter("main"));
+ Chain<Processor> main = new Chain<>(new AsyncDataProcessingInitiator(asyncMain), new Federator(chainSource1, chainSource2, chainSource3));
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(main,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals("We have the sync data plus placeholders for the async lists",3,response.data().asList().size());
- DataList source1Data=((DataList)response.data().get(0));
- DataList source2Data=((DataList)response.data().get(1));
- DataList source3Data=((DataList)response.data().get(2));
+ assertEquals(3, response.data().asList().size(), "We have the sync data plus placeholders for the async lists");
+ DataList source1Data = ((DataList) response.data().get(0));
+ DataList source2Data = ((DataList) response.data().get(1));
+ DataList source3Data = ((DataList) response.data().get(2));
- assertEquals("No data yet",0,source1Data.asList().size());
- assertEquals("No data yet",0,source2Data.asList().size());
- assertEquals(3,source3Data.asList().size());
+ assertEquals(0, source1Data.asList().size(), "No data yet");
+ assertEquals(0, source2Data.asList().size(), "No data yet");
+ assertEquals(3, source3Data.asList().size());
// complete async data in source1
- futureSource1.incomingData.get(0).addLast(new StringData(request,"source1Data"));
- assertEquals("Not visible yet", 0, source1Data.asList().size());
+ futureSource1.incomingData.get(0).addLast(new StringData(request, "source1Data"));
+ assertEquals(0, source1Data.asList().size(), "Not visible yet");
source1Data.completeFuture().get(1000, TimeUnit.MILLISECONDS);
assertEquals(2, source1Data.asList().size());
- assertEquals("source1Data",source1Data.get(0).toString());
- assertEquals("Completion listener chain on this has run", "[source1] Data count: 1", source1Data.get(1).toString());
+ assertEquals("source1Data", source1Data.get(0).toString());
+ assertEquals("[source1] Data count: 1", source1Data.get(1).toString(), "Completion listener chain on this has run");
// source2 & main completion
- assertEquals("Main completion listener has not run", 3, response.data().asList().size());
+ assertEquals(3, response.data().asList().size(), "Main completion listener has not run");
futureSource2.incomingData.get(0).addLast(new StringData(request, "source2Data"));
- assertEquals("Main completion listener has not run", 3, response.data().asList().size());
+ assertEquals(3, response.data().asList().size(), "Main completion listener has not run");
Response.recursiveFuture(response.data()).get();
- assertEquals("Main completion listener has run", 4, response.data().asList().size());
- assertEquals("The main data counter saw all sync data, but not source2 data as it executes after this",
- "[main] Data count: " + (2 + 0 + 3), response.data().get(3).toString());
+ assertEquals(4, response.data().asList().size(), "Main completion listener has run");
+ assertEquals("[main] Data count: " + (2 + 0 + 3), response.data().get(3).toString(), "The main data counter saw all sync data, but not source2 data as it executes after this");
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
index d494e774f8e..557bef39276 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
@@ -10,13 +10,13 @@ import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.response.Data;
import com.yahoo.processing.response.IncomingData;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests listening on every available new piece of data in a response
@@ -28,48 +28,48 @@ public class StreamingTestCase {
/** Tests adding a chain which is called every time new data is added to a data list */
@SuppressWarnings({"unchecked"})
@Test
- public void testStreamingData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testStreamingData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
StreamProcessor streamProcessor = new StreamProcessor();
Chain<Processor> streamProcessing = new Chain<Processor>(streamProcessor);
- ProcessorLibrary.FutureDataSource futureDataSource=new ProcessorLibrary.FutureDataSource();
- Chain<Processor> main=new Chain<>(new ProcessorLibrary.DataCounter(),
- new ProcessorLibrary.StreamProcessingInitiator(streamProcessing),
- futureDataSource);
+ ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
+ Chain<Processor> main = new Chain<>(new ProcessorLibrary.DataCounter(),
+ new ProcessorLibrary.StreamProcessingInitiator(streamProcessing),
+ futureDataSource);
// Execute
- Request request=new Request();
- Response response= Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
IncomingData incomingData = futureDataSource.incomingData.get(0);
// State prior to receiving any additional data
- assertEquals(1,response.data().asList().size());
- assertEquals("Data count: 0",response.data().get(0).toString());
- assertEquals("Add data listener invoked also for DataCounter", 1, streamProcessor.invocationCount);
- assertEquals("Initial data count", 1, response.data().asList().size());
+ assertEquals(1, response.data().asList().size());
+ assertEquals("Data count: 0", response.data().get(0).toString());
+ assertEquals(1, streamProcessor.invocationCount, "Add data listener invoked also for DataCounter");
+ assertEquals(1, response.data().asList().size(), "Initial data count");
// add first data - we have no listener so the data is held in the incoming buffer
incomingData.add(new ProcessorLibrary.StringData(request, "d1"));
- assertEquals("Data add listener not invoked as we are not listening on new data yet",1, streamProcessor.invocationCount);
- assertEquals("New data is not consumed", 1, response.data().asList().size());
+ assertEquals(1, streamProcessor.invocationCount, "Data add listener not invoked as we are not listening on new data yet");
+ assertEquals(1, response.data().asList().size(), "New data is not consumed");
// start listening on incoming data - this is what a renderer will do
incomingData.addNewDataListener(new MockNewDataListener(incomingData), MoreExecutors.directExecutor());
- assertEquals("We got a data add event for the data which was already added", 2, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 2, response.data().asList().size());
+ assertEquals(2, streamProcessor.invocationCount, "We got a data add event for the data which was already added");
+ assertEquals(2, response.data().asList().size(), "New data is consumed");
incomingData.add(new ProcessorLibrary.StringData(request, "d2"));
- assertEquals("We are now getting data add events each time", 3, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 3, response.data().asList().size());
+ assertEquals(3, streamProcessor.invocationCount, "We are now getting data add events each time");
+ assertEquals(3, response.data().asList().size(), "New data is consumed");
incomingData.addLast(new ProcessorLibrary.StringData(request, "d3"));
- assertEquals("We are getting data add events also the last time", 4, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 4, response.data().asList().size());
+ assertEquals(4, streamProcessor.invocationCount, "We are getting data add events also the last time");
+ assertEquals(4, response.data().asList().size(), "New data is consumed");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS); // no-op here
- assertEquals("d1",response.data().get(1).toString().toString());
- assertEquals("d2",response.data().get(2).toString().toString());
- assertEquals("d3",response.data().get(3).toString().toString());
+ assertEquals("d1", response.data().get(1).toString().toString());
+ assertEquals("d2", response.data().get(2).toString().toString());
+ assertEquals("d3", response.data().get(3).toString().toString());
}
private static class MockNewDataListener implements Runnable {
diff --git a/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java b/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
index baed2ccdcc8..70bae6c97b1 100644
--- a/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
@@ -21,9 +21,9 @@ import com.yahoo.processing.rendering.Renderer;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.processing.response.Data;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.After;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -39,12 +39,7 @@ import java.util.concurrent.ExecutionException;
import static com.yahoo.jdisc.http.server.jetty.AccessLoggingRequestHandler.CONTEXT_KEY_ACCESS_LOG_ENTRY;
import static com.yahoo.processing.test.ProcessorLibrary.MapData;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests processing handler scenarios end to end.
@@ -74,13 +69,13 @@ public class ProcessingHandlerTestCase {
new Chain<>("log-value",
new ProcessorLibrary.LogValueAdder(LOG_KEY, LOG_VALUE));
- @After
+ @AfterEach
public void shutDown() {
driver.close();
}
@Test
- public void processing_handler_stores_trace_log_values_in_the_access_log_entry() {
+ void processing_handler_stores_trace_log_values_in_the_access_log_entry() {
driver = new ProcessingTestDriver(logValueChain);
Request request = HttpRequest.newServerRequest(driver.jDiscDriver(), URI.create("http://localhost/?chain=log-value"), HttpRequest.Method.GET);
AccessLogEntry entry = new AccessLogEntry();
@@ -95,7 +90,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerResolvesChains() {
+ void testProcessingHandlerResolvesChains() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(defaultChain);
chains.add(simpleChain);
@@ -106,16 +101,16 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerPropagatesRequestParametersAndContext() {
+ void testProcessingHandlerPropagatesRequestParametersAndContext() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(new Chain<>("default", new RequestPropertyTracer()));
driver = new ProcessingTestDriver(chains);
- assertTrue("JDisc request context is propagated to properties()",
- driver.sendRequest("http://localhost/?chain=default&tracelevel=4").readAll().contains("context.contextVariable: '37'"));
+ assertTrue(driver.sendRequest("http://localhost/?chain=default&tracelevel=4").readAll().contains("context.contextVariable: '37'"),
+ "JDisc request context is propagated to properties()");
}
@Test
- public void testProcessingHandlerOutputsTrace() {
+ void testProcessingHandlerOutputsTrace() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(defaultChain);
driver = new ProcessingTestDriver(chains);
@@ -128,28 +123,28 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerTransfersErrorsToHttpStatusCodesNoData() {
+ void testProcessingHandlerTransfersErrorsToHttpStatusCodesNoData() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(simpleChain);
- chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.ErrorAdder(new ErrorMessage(301,"Message"))));
- chains.add(new Chain<>("unauthorized", new ProcessorLibrary.ErrorAdder(new ErrorMessage(401,"Message"))));
- chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code,"Message"))));
- chains.add(new Chain<>("forbidden", new ProcessorLibrary.ErrorAdder(new ErrorMessage(403,"Message"))));
- chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
- chains.add(new Chain<>("not_found", new ProcessorLibrary.ErrorAdder(new ErrorMessage(404,"Message"))));
- chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code,"Message"))));
- chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.ErrorAdder(new ErrorMessage(429,"Message"))));
- chains.add(new Chain<>("bad_request", new ProcessorLibrary.ErrorAdder(new ErrorMessage(400,"Message"))));
- chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code,"Message"))));
- chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.ErrorAdder(new ErrorMessage(500,"Message"))));
- chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code,"Message"))));
- chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.ErrorAdder(new ErrorMessage(503,"Message"))));
- chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code,"Message"))));
- chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.ErrorAdder(new ErrorMessage(504,"Message"))));
- chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code,"Message"))));
- chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.ErrorAdder(new ErrorMessage(502,"Message"))));
- chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code,"Message"))));
- chains.add(new Chain<>("unknown_code", new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567,"Message"))));
+ chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.ErrorAdder(new ErrorMessage(301, "Message"))));
+ chains.add(new Chain<>("unauthorized", new ProcessorLibrary.ErrorAdder(new ErrorMessage(401, "Message"))));
+ chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code, "Message"))));
+ chains.add(new Chain<>("forbidden", new ProcessorLibrary.ErrorAdder(new ErrorMessage(403, "Message"))));
+ chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
+ chains.add(new Chain<>("not_found", new ProcessorLibrary.ErrorAdder(new ErrorMessage(404, "Message"))));
+ chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code, "Message"))));
+ chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.ErrorAdder(new ErrorMessage(429, "Message"))));
+ chains.add(new Chain<>("bad_request", new ProcessorLibrary.ErrorAdder(new ErrorMessage(400, "Message"))));
+ chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code, "Message"))));
+ chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.ErrorAdder(new ErrorMessage(500, "Message"))));
+ chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code, "Message"))));
+ chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.ErrorAdder(new ErrorMessage(503, "Message"))));
+ chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code, "Message"))));
+ chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.ErrorAdder(new ErrorMessage(504, "Message"))));
+ chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code, "Message"))));
+ chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.ErrorAdder(new ErrorMessage(502, "Message"))));
+ chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code, "Message"))));
+ chains.add(new Chain<>("unknown_code", new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567, "Message"))));
driver = new ProcessingTestDriver(chains);
assertEqualStatus(200, "http://localhost/?chain=simple");
assertEqualStatus(301, "http://localhost/?chain=moved_permanently");
@@ -174,28 +169,28 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerTransfersErrorsToHttpStatusCodesWithData() {
+ void testProcessingHandlerTransfersErrorsToHttpStatusCodesWithData() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(simpleChain);
- chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(301,"Message"))));
- chains.add(new Chain<>("unauthorized", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(401,"Message"))));
- chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code,"Message"))));
- chains.add(new Chain<>("forbidden", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(403,"Message"))));
- chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
- chains.add(new Chain<>("not_found", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(404,"Message"))));
- chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code,"Message"))));
- chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(429,"Message"))));
- chains.add(new Chain<>("bad_request", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(400,"Message"))));
- chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code,"Message"))));
- chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(500,"Message"))));
- chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code,"Message"))));
- chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(503,"Message"))));
- chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code,"Message"))));
- chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(504,"Message"))));
- chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code,"Message"))));
- chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(502,"Message"))));
- chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code,"Message"))));
- chains.add(new Chain<>("unknown_code", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567,"Message"))));
+ chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(301, "Message"))));
+ chains.add(new Chain<>("unauthorized", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(401, "Message"))));
+ chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code, "Message"))));
+ chains.add(new Chain<>("forbidden", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(403, "Message"))));
+ chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
+ chains.add(new Chain<>("not_found", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(404, "Message"))));
+ chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code, "Message"))));
+ chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(429, "Message"))));
+ chains.add(new Chain<>("bad_request", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(400, "Message"))));
+ chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code, "Message"))));
+ chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(500, "Message"))));
+ chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code, "Message"))));
+ chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(503, "Message"))));
+ chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code, "Message"))));
+ chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(504, "Message"))));
+ chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code, "Message"))));
+ chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(502, "Message"))));
+ chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code, "Message"))));
+ chains.add(new Chain<>("unknown_code", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567, "Message"))));
driver = new ProcessingTestDriver(chains);
assertEqualStatus(200, "http://localhost/?chain=simple");
assertEqualStatus(301, "http://localhost/?chain=moved_permanently");
@@ -220,27 +215,27 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessorSetsResponseHeaders() throws InterruptedException {
+ void testProcessorSetsResponseHeaders() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
- Map<String,List<String>> responseHeaders = new HashMap<>();
+ Map<String, List<String>> responseHeaders = new HashMap<>();
responseHeaders.put("foo", List.of("fooValue"));
responseHeaders.put("bar", List.of("barValue", "bazValue"));
- Map<String,List<String>> otherResponseHeaders = new HashMap<>();
+ Map<String, List<String>> otherResponseHeaders = new HashMap<>();
otherResponseHeaders.put("foo", List.of("fooValue2"));
otherResponseHeaders.put("bax", List.of("baxValue"));
List<Chain<Processor>> chains = new ArrayList<>();
- chains.add(new Chain<>("default",new ResponseHeaderSetter(responseHeaders),
- new ResponseHeaderSetter(otherResponseHeaders)));
+ chains.add(new Chain<>("default", new ResponseHeaderSetter(responseHeaders),
+ new ResponseHeaderSetter(otherResponseHeaders)));
driver = new ProcessingTestDriver(chains);
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
- assertEquals("[fooValue2, fooValue]",response.headers().get("foo").toString());
+ assertEquals("[fooValue2, fooValue]", response.headers().get("foo").toString());
assertEquals("[barValue, bazValue]", response.headers().get("bar").toString());
assertEquals("[baxValue]", response.headers().get("bax").toString());
- assertEquals("ResponseHeaders are not rendered", "{\"datalist\":[]}", responseHandler.read());
+ assertEquals("{\"datalist\":[]}", responseHandler.read(), "ResponseHeaders are not rendered");
}
finally {
if (responseHandler != null)
@@ -249,7 +244,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testResponseDataStatus() throws InterruptedException {
+ void testResponseDataStatus() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
List<Chain<Processor>> chains = new ArrayList<>();
@@ -258,7 +253,7 @@ public class ProcessingHandlerTestCase {
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
assertEquals(429, response.getStatus());
- assertEquals("ResponseHeaders are not rendered", "{\"datalist\":[]}", responseHandler.read());
+ assertEquals("{\"datalist\":[]}", responseHandler.read(), "ResponseHeaders are not rendered");
}
finally {
if (responseHandler != null)
@@ -268,13 +263,13 @@ public class ProcessingHandlerTestCase {
/** Tests that the ResponseStatus takes precedence over errors */
@Test
- public void testResponseDataStatusOverridesErrors() throws InterruptedException {
+ void testResponseDataStatusOverridesErrors() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(new Chain<>("default", new ResponseStatusSetter(200),
- new ProcessorLibrary.StringDataAdder("Hello"),
- new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
+ new ProcessorLibrary.StringDataAdder("Hello"),
+ new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
driver = new ProcessingTestDriver(chains);
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
@@ -304,14 +299,14 @@ public class ProcessingHandlerTestCase {
@SuppressWarnings("unchecked")
@Test
- public void testProcessingHandlerSupportsAsyncRendering() {
+ void testProcessingHandlerSupportsAsyncRendering() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
Chain<Processor> asyncCompletionChain = new Chain<>("asyncCompletion", new ProcessorLibrary.DataCounter("async"));
Chain<Processor> chain =
new Chain<>("federation", new ProcessorLibrary.DataCounter("sync"),
- new ProcessorLibrary.Federator(new Chain<Processor>(new ProcessorLibrary.DataSource()),
- new Chain<>(new ProcessorLibrary.AsyncDataProcessingInitiator(asyncCompletionChain),futureDataSource)));
+ new ProcessorLibrary.Federator(new Chain<Processor>(new ProcessorLibrary.DataSource()),
+ new Chain<>(new ProcessorLibrary.AsyncDataProcessingInitiator(asyncCompletionChain), futureDataSource)));
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(chain);
driver = new ProcessingTestDriver(chains);
@@ -320,46 +315,46 @@ public class ProcessingHandlerTestCase {
String synchronousResponse = responseHandler.read();
assertEquals(
"{\"datalist\":[" +
- "{\"datalist\":[" +
- "{\"data\":\"first.null\"}," +
- "{\"data\":\"second.null\"}," +
- "{\"data\":\"third.null\"}" +
- "]}",
+ "{\"datalist\":[" +
+ "{\"data\":\"first.null\"}," +
+ "{\"data\":\"second.null\"}," +
+ "{\"data\":\"third.null\"}" +
+ "]}",
synchronousResponse);
- assertEquals("No more data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No more data is available at this point");
// Now, complete async data
futureDataSource.incomingData.get(0).add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "," +
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}",
- responseHandler.read());
+ "," +
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}",
+ responseHandler.read());
futureDataSource.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d2"));
// ... which leads to the rest of the response becoming available
assertEquals(
- "," +
- "{\"data\":\"d2\"}," +
- "{\"data\":\"[async] Data count: 2\"}" +
- "]}",
+ "," +
+ "{\"data\":\"d2\"}," +
+ "{\"data\":\"[async] Data count: 2\"}" +
+ "]}",
responseHandler.read());
assertEquals(",{\"data\":\"[sync] Data count: 3\"}" + // Async items not counted as they arrive after chain completion
- "]}",
- responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ "]}",
+ responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testProcessingHandlerSupportsAsyncUnorderedRendering() {
+ void testProcessingHandlerSupportsAsyncUnorderedRendering() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource1 = new ProcessorLibrary.FutureDataSource();
ProcessorLibrary.FutureDataSource futureDataSource2 = new ProcessorLibrary.FutureDataSource();
Chain<Processor> chain =
new Chain<>("federation",
- new ProcessorLibrary.Federator(false,new Chain<Processor>(futureDataSource1),
- new Chain<Processor>(futureDataSource2)));
+ new ProcessorLibrary.Federator(false, new Chain<Processor>(futureDataSource1),
+ new Chain<Processor>(futureDataSource2)));
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(chain);
driver = new ProcessingTestDriver(chains);
@@ -368,69 +363,69 @@ public class ProcessingHandlerTestCase {
assertEquals(
"{\"datalist\":[",
responseHandler.read());
- assertEquals("No more data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No more data is available at this point");
// Complete second async data first
futureDataSource2.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(
- "{\"datalist\":[" +
- "{\"data\":\"d2\"}"+
- "]}",
- responseHandler.read());
+ "{\"datalist\":[" +
+ "{\"data\":\"d2\"}" +
+ "]}",
+ responseHandler.read());
// Now complete first async data (which is therefore rendered last)
futureDataSource1.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "," +
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}"+
- "]}",
- responseHandler.read());
+ "," +
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}" +
+ "]}",
+ responseHandler.read());
assertEquals(
- "]}",
- responseHandler.read());
+ "]}",
+ responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncOnlyRendering() throws Exception {
+ void testAsyncOnlyRendering() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
Chain<Processor> chain = new Chain<>("main", List.of(futureDataSource));
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}",
- responseHandler.read());
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}",
+ responseHandler.read());
futureDataSource.incomingData.get().addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(
"," +
- "{\"data\":\"d2\"}" +
- "]}",
+ "{\"data\":\"d2\"}" +
+ "]}",
responseHandler.read());
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncRenderingWithClientClose() throws Exception {
+ void testAsyncRenderingWithClientClose() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
Chain<Processor> chain = new Chain<>("main", List.of(futureDataSource));
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
@@ -443,24 +438,24 @@ public class ProcessingHandlerTestCase {
assertNull(responseHandler.read());
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncOnlyRenderingWithAsyncPostData() throws Exception {
+ void testAsyncOnlyRenderingWithAsyncPostData() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
PostReader postReader = new PostReader();
Chain<Processor> chain = new Chain<>("main",
- new ProcessorLibrary.AsyncDataProcessingInitiator(new Chain<>(postReader)),
- futureDataSource);
+ new ProcessorLibrary.AsyncDataProcessingInitiator(new Chain<>(postReader)),
+ futureDataSource);
driver = new ProcessingTestDriver(chain);
RequestHandlerTestDriver.MockResponseHandler responseHandler =
driver.sendRequest("http://localhost/?chain=main", HttpRequest.Method.POST, "Hello, world!");
- assertFalse("Post data is read later, on async completion", postReader.bodyDataFuture.isDone());
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertFalse(postReader.bodyDataFuture.isDone(), "Post data is read later, on async completion");
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
@@ -476,10 +471,10 @@ public class ProcessingHandlerTestCase {
"]}",
responseHandler.read()
);
- assertEquals("Data is completed, so post data is read", "Hello, world!", postReader.bodyDataFuture.get().trim());
+ assertEquals("Hello, world!", postReader.bodyDataFuture.get().trim(), "Data is completed, so post data is read");
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
private static class PostReader extends Processor {
@@ -506,8 +501,8 @@ public class ProcessingHandlerTestCase {
@SuppressWarnings("unchecked")
@Test
- public void testStatusAndHeadersCanBeSetAsynchronously() throws Exception {
- Map<String,List<String>> responseHeaders = new HashMap<>();
+ void testStatusAndHeadersCanBeSetAsynchronously() throws Exception {
+ Map<String, List<String>> responseHeaders = new HashMap<>();
responseHeaders.put("foo", List.of("fooValue"));
responseHeaders.put("bar", List.of("barValue", "bazValue"));
@@ -517,7 +512,7 @@ public class ProcessingHandlerTestCase {
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
com.yahoo.processing.Request request = futureDataSource.incomingData.get().getOwner().request();
futureDataSource.incomingData.get().addLast(new ProcessorLibrary.StringData(request, "d1"));
@@ -527,12 +522,12 @@ public class ProcessingHandlerTestCase {
assertEquals(500, responseHandler.getStatus());
assertEquals("[fooValue]", responseHandler.getResponse().headers().get("foo").toString());
assertEquals("[barValue, bazValue]", responseHandler.getResponse().headers().get("bar").toString());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncRenderingDoesNotHoldThreads() {
+ void testAsyncRenderingDoesNotHoldThreads() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
// Add some sync data as well to cause rendering to start before async data is added.
@@ -545,11 +540,11 @@ public class ProcessingHandlerTestCase {
ProcessingTestDriver.MockResponseHandler[] responseHandler = new ProcessingTestDriver.MockResponseHandler[requestCount];
for (int i = 0; i < requestCount; i++) {
responseHandler[i] = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("Sync data is available",
- "{\"datalist\":[{\"datalist\":[{\"data\":\"first.null\"},{\"data\":\"second.null\"},{\"data\":\"third.null\"}]}",
- responseHandler[i].read());
+ assertEquals("{\"datalist\":[{\"datalist\":[{\"data\":\"first.null\"},{\"data\":\"second.null\"},{\"data\":\"third.null\"}]}",
+ responseHandler[i].read(),
+ "Sync data is available");
}
- assertEquals("All requests was processed", requestCount, futureDataSource.incomingData.size());
+ assertEquals(requestCount, futureDataSource.incomingData.size(), "All requests was processed");
// Complete all
for (int i = 0; i < requestCount; i++) {
@@ -558,13 +553,13 @@ public class ProcessingHandlerTestCase {
futureDataSource.incomingData.get(i).addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(",{\"data\":\"d2\"}]}", responseHandler[i].read());
assertEquals("]}", responseHandler[i].read());
- assertNull("Transmission completed", responseHandler[i].read());
+ assertNull(responseHandler[i].read(), "Transmission completed");
}
}
@SuppressWarnings("unchecked")
@Test
- public void testStreamedRendering() throws Exception {
+ void testStreamedRendering() throws Exception {
// Set up
Chain<Processor> streamChain = new Chain<>(new StreamProcessor());
@@ -593,26 +588,27 @@ public class ProcessingHandlerTestCase {
",{\"data\":\"map data: {streamProcessed=true}\"}]}",
responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@Test
- public void testEagerStreamedRenderingOnFreeze() {
+ void testEagerStreamedRenderingOnFreeze() {
FreezingDataSource source = new FreezingDataSource();
Chain<Processor> mainChain = new Chain<>("main", source);
driver = new ProcessingTestDriver(mainChain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
source.freeze.set(true);
assertEquals("{\"datalist\":[{\"data\":\"d1\"}", responseHandler.read());
source.addLastData.set(true); // signal completion
assertEquals(",{\"data\":\"d2\"}]}", responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
+ // TODO
@Test
- @Ignore // TODO
- public void testNestedEagerStreamedRenderingOnFreeze() {
+ @Disabled
+ void testNestedEagerStreamedRenderingOnFreeze() {
try {
FreezingDataSource source1 = new FreezingDataSource("s1");
FreezingDataSource source2 = new FreezingDataSource("s2");
@@ -625,16 +621,15 @@ public class ProcessingHandlerTestCase {
new Chain<Processor>(source3)));
driver = new ProcessingTestDriver(mainChain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
source1.freeze.set(true);
- assertEquals("Received because the parent list and source1 list is frozen",
- "{\"datalist\":[{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read());
+ assertEquals("{\"datalist\":[{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read(), "Received because the parent list and source1 list is frozen");
source2.addLastData.set(true); // No effect as we are working on source1, which is not completed yet
assertEquals("{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read());
source1.addLastData.set(true); // Make source 1 and 2 available
assertEquals(",{\"data\":\"d2\"}]}", responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
catch (Throwable t) {
t.printStackTrace();
@@ -642,14 +637,16 @@ public class ProcessingHandlerTestCase {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void testRetrievingNonExistingRendererThrows() {
- driver = new ProcessingTestDriver(List.of());
- driver.processingHandler().getRendererCopy(ComponentSpecification.fromString("non-existent"));
+ @Test
+ void testRetrievingNonExistingRendererThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ driver = new ProcessingTestDriver(List.of());
+ driver.processingHandler().getRendererCopy(ComponentSpecification.fromString("non-existent"));
+ });
}
@Test
- public void testDefaultRendererIsAddedToRegistryWhenNoneIsGivenByUser() {
+ void testDefaultRendererIsAddedToRegistryWhenNoneIsGivenByUser() {
String defaultId = AbstractProcessingHandler.DEFAULT_RENDERER_ID;
driver = new ProcessingTestDriver(List.of());
@@ -659,7 +656,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testUserSpecifiedDefaultRendererIsNotReplacedInRegistry() {
+ void testUserSpecifiedDefaultRendererIsNotReplacedInRegistry() {
String defaultId = AbstractProcessingHandler.DEFAULT_RENDERER_ID;
Renderer myDefaultRenderer = new ProcessingRenderer();
ComponentRegistry<Renderer> renderers = new ComponentRegistry<>();
diff --git a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
index 8de08189f7a..58a490b8e80 100644
--- a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
+++ b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
@@ -11,30 +11,29 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.execution.chain.ChainRegistry;
-import org.junit.After;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class MockUserDatabaseClientTest {
private TestDriver driver;
@Test
- public void testClientExampleProcessor() {
- Request request=null;
+ void testClientExampleProcessor() {
+ Request request = null;
try {
- Chain<Processor> chain = new Chain<>("default",new MockUserDatabaseClient());
+ Chain<Processor> chain = new Chain<>("default", new MockUserDatabaseClient());
setupJDisc(Collections.singletonList(chain));
request = createRequest();
Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
- MockUserDatabaseClient.User user = (MockUserDatabaseClient.User)response.data().request().properties().get("User");
+ MockUserDatabaseClient.User user = (MockUserDatabaseClient.User) response.data().request().properties().get("User");
assertNotNull(user);
assertEquals("foo", user.getId());
}
@@ -71,7 +70,7 @@ public class MockUserDatabaseClientTest {
driver.activateContainer(builder);
}
- @After
+ @AfterEach
public void shutDownDisc() {
assertTrue(driver.close());
}
diff --git a/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java b/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
index 5dfe29dd4a1..fb8aca95d9a 100644
--- a/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
+++ b/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
@@ -13,7 +13,7 @@ import com.yahoo.processing.response.Data;
import com.yahoo.processing.response.DataList;
import com.yahoo.processing.response.IncomingData;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
@@ -23,9 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
@@ -35,27 +33,27 @@ public class AsynchronousSectionedRendererTest {
private static final Charset CHARSET = Utf8.getCharset();
@Test
- public void testRenderersOfTheSamePrototypeUseTheSameExecutor() {
+ void testRenderersOfTheSamePrototypeUseTheSameExecutor() {
TestRenderer rendererPrototype = new TestRenderer();
- TestRenderer rendererCopy1 = (TestRenderer)rendererPrototype.clone();
+ TestRenderer rendererCopy1 = (TestRenderer) rendererPrototype.clone();
rendererCopy1.init();
assertSame(rendererPrototype.getRenderingExecutor(), rendererCopy1.getRenderingExecutor());
}
@Test
- public void testRenderersOfDifferentPrototypesUseDifferentExecutors() {
+ void testRenderersOfDifferentPrototypesUseDifferentExecutors() {
TestRenderer rendererPrototype1 = new TestRenderer();
- TestRenderer rendererCopy1 = (TestRenderer)rendererPrototype1.clone();
+ TestRenderer rendererCopy1 = (TestRenderer) rendererPrototype1.clone();
rendererCopy1.init();
TestRenderer rendererPrototype2 = new TestRenderer();
- TestRenderer rendererCopy2 = (TestRenderer)rendererPrototype2.clone();
+ TestRenderer rendererCopy2 = (TestRenderer) rendererPrototype2.clone();
rendererCopy2.init();
assertNotSame(rendererPrototype1.getRenderingExecutor(), rendererCopy2.getRenderingExecutor());
}
@Test
- public void testAsyncSectionedRenderer() throws IOException, InterruptedException {
+ void testAsyncSectionedRenderer() throws IOException, InterruptedException {
StringDataList dataList = createDataListWithStrangeStrings();
TestRenderer renderer = new TestRenderer();
@@ -69,7 +67,7 @@ public class AsynchronousSectionedRendererTest {
}
@Test
- public void testEmptyProcessingRendering() throws IOException, InterruptedException {
+ void testEmptyProcessingRendering() throws IOException, InterruptedException {
Request request = new Request();
DataList dataList = ArrayDataList.create(request);
@@ -77,117 +75,117 @@ public class AsynchronousSectionedRendererTest {
}
@Test
- public void testProcessingRendering() throws IOException, InterruptedException {
+ void testProcessingRendering() throws IOException, InterruptedException {
StringDataList dataList = createDataListWithStrangeStrings();
assertEquals("{\"datalist\":[" +
- "{\"data\":\"f\\\\o\\\"o\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"b/a\\br\"}," +
- "{\"data\":\"f\\f\\no\\ro\\tbar\\u0005\"}" +
- "]}" +
- "]}",
+ "{\"data\":\"f\\\\o\\\"o\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"b/a\\br\"}," +
+ "{\"data\":\"f\\f\\no\\ro\\tbar\\u0005\"}" +
+ "]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithErrors() throws IOException, InterruptedException {
+ void testProcessingRenderingWithErrors() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithStackTraces() throws IOException, InterruptedException {
+ void testProcessingRenderingWithStackTraces() throws IOException, InterruptedException {
Exception exception;
// Create thrown exception
try {
throw new RuntimeException("Thrown");
}
catch (RuntimeException e) {
- exception=e;
+ exception = e;
}
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1",exception));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1", exception));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
assertEquals(
"{\"errors\":[" +
- "{" +
- "\"error\":\"m1: d1: Thrown\"," +
- "\"stacktrace\":\"java.lang.RuntimeException: Thrown\\n\\tat com.yahoo.processing.rendering.AsynchronousSectionedRendererTest.",
- render(dataList).substring(0,157));
+ "{" +
+ "\"error\":\"m1: d1: Thrown\"," +
+ "\"stacktrace\":\"java.lang.RuntimeException: Thrown\\n\\tat com.yahoo.processing.rendering.AsynchronousSectionedRendererTest.",
+ render(dataList).substring(0, 157));
}
@Test
- public void testProcessingRenderingWithClonedErrorRequest() throws IOException, InterruptedException {
+ void testProcessingRenderingWithClonedErrorRequest() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
dataList.add(new StringDataList(dataList.request().clone())); // Cloning a request which contains errors
// ... should not cause repetition of those errors
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}," +
- "{\"datalist\":[]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}," +
+ "{\"datalist\":[]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithClonedErrorRequestContainingNewErrors() throws IOException, InterruptedException {
+ void testProcessingRenderingWithClonedErrorRequestContainingNewErrors() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
dataList.add(new StringDataList(dataList.request().clone())); // Cloning a request containing errors
// and adding new errors to it
- dataList.asList().get(2).request().errors().add(new ErrorMessage("m3","d3"));
+ dataList.asList().get(2).request().errors().add(new ErrorMessage("m3", "d3"));
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}," +
- "{\"errors\":[" +
- "\"m3: d3\"" +
- "]," +
- "\"datalist\":[]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}," +
+ "{\"errors\":[" +
+ "\"m3: d3\"" +
+ "]," +
+ "\"datalist\":[]}" +
+ "]}",
render(dataList));
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
index 841866f1e83..055dbf77371 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
@@ -1,17 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.processing.request;
-
-import static org.junit.Assert.*;
+import com.google.common.base.Splitter;
+import com.yahoo.text.Lowercase;
import java.util.Iterator;
import java.util.List;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import com.google.common.base.Splitter;
-import com.yahoo.text.Lowercase;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Module local test of the basic property name building block.
@@ -21,44 +18,43 @@ import com.yahoo.text.Lowercase;
public class CompoundNameTestCase {
private static final String NAME = "com.yahoo.processing.request.CompoundNameTestCase";
- private CompoundName cn;
+ private final CompoundName cn = new CompoundName(NAME);
- @Before
- public void setUp() throws Exception {
- cn = new CompoundName(NAME);
+ void verifyStrict(CompoundName expected, CompoundName actual) {
+ assertEquals(expected, actual);
+ assertEquals(expected.asList(), actual.asList());
}
-
- @After
- public void tearDown() throws Exception {
+ void verifyStrict(String expected, CompoundName actual) {
+ verifyStrict(new CompoundName(expected), actual);
}
@Test
- public final void testLast() {
+ final void testLast() {
assertEquals(NAME.substring(NAME.lastIndexOf('.') + 1), cn.last());
}
@Test
- public final void testFirst() {
+ final void testFirst() {
assertEquals(NAME.substring(0, NAME.indexOf('.')), cn.first());
}
@Test
- public final void testRest() {
- assertEquals(NAME.substring(NAME.indexOf('.') + 1), cn.rest().toString());
+ final void testRest() {
+ verifyStrict(NAME.substring(NAME.indexOf('.') + 1), cn.rest());
}
@Test
- public final void testRestN() {
- assertEquals("a.b.c.d.e", new CompoundName("a.b.c.d.e").rest(0).toString());
- assertEquals("b.c.d.e", new CompoundName("a.b.c.d.e").rest(1).toString());
- assertEquals("c.d.e", new CompoundName("a.b.c.d.e").rest(2).toString());
- assertEquals("d.e", new CompoundName("a.b.c.d.e").rest(3).toString());
- assertEquals("e", new CompoundName("a.b.c.d.e").rest(4).toString());
- assertEquals("", new CompoundName("a.b.c.d.e").rest(5).toString());
+ final void testRestN() {
+ verifyStrict("a.b.c.d.e", new CompoundName("a.b.c.d.e").rest(0));
+ verifyStrict("b.c.d.e", new CompoundName("a.b.c.d.e").rest(1));
+ verifyStrict("c.d.e", new CompoundName("a.b.c.d.e").rest(2));
+ verifyStrict("d.e", new CompoundName("a.b.c.d.e").rest(3));
+ verifyStrict("e", new CompoundName("a.b.c.d.e").rest(4));
+ verifyStrict(CompoundName.empty, new CompoundName("a.b.c.d.e").rest(5));
}
@Test
- public final void testPrefix() {
+ final void testPrefix() {
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("")));
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("a")));
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("a.b")));
@@ -69,7 +65,13 @@ public class CompoundNameTestCase {
}
@Test
- public final void testSize() {
+ void testFromComponents() {
+ verifyStrict("a", CompoundName.fromComponents("a"));
+ verifyStrict("a.b", CompoundName.fromComponents("a", "b"));
+ }
+
+ @Test
+ final void testSize() {
Splitter s = Splitter.on('.');
Iterable<String> i = s.split(NAME);
int n = 0;
@@ -80,23 +82,23 @@ public class CompoundNameTestCase {
}
@Test
- public final void testGet() {
+ final void testGet() {
String s = cn.get(0);
assertEquals(NAME.substring(0, NAME.indexOf('.')), s);
}
@Test
- public final void testIsCompound() {
+ final void testIsCompound() {
assertTrue(cn.isCompound());
}
@Test
- public final void testIsEmpty() {
+ final void testIsEmpty() {
assertFalse(cn.isEmpty());
}
@Test
- public final void testAsList() {
+ final void testAsList() {
List<String> l = cn.asList();
Splitter peoplesFront = Splitter.on('.');
Iterable<String> answer = peoplesFront.split(NAME);
@@ -108,40 +110,40 @@ public class CompoundNameTestCase {
}
@Test
- public final void testEqualsObject() {
- assertFalse(cn.equals(NAME));
- assertFalse(cn.equals(null));
- assertTrue(cn.equals(cn));
- assertTrue(cn.equals(new CompoundName(NAME)));
+ final void testEqualsObject() {
+ assertNotEquals(cn, NAME);
+ assertNotEquals(cn, null);
+ verifyStrict(cn, cn);
+ verifyStrict(cn, new CompoundName(NAME));
}
@Test
- public final void testEmptyNonEmpty() {
+ final void testEmptyNonEmpty() {
assertTrue(new CompoundName("").isEmpty());
assertEquals(0, new CompoundName("").size());
assertFalse(new CompoundName("a").isEmpty());
assertEquals(1, new CompoundName("a").size());
CompoundName empty = new CompoundName("a.b.c");
- assertTrue(empty == empty.rest(0));
- assertFalse(empty == empty.rest(1));
+ verifyStrict(empty, empty.rest(0));
+ assertNotEquals(empty, empty.rest(1));
}
@Test
- public final void testGetLowerCasedName() {
+ final void testGetLowerCasedName() {
assertEquals(Lowercase.toLowerCase(NAME), cn.getLowerCasedName());
}
@Test
- public void testAppend() {
- assertEquals(new CompoundName("a.b.c.d"), new CompoundName("").append(new CompoundName("a.b.c.d")));
- assertEquals(new CompoundName("a.b.c.d"), new CompoundName("a").append(new CompoundName("b.c.d")));
- assertEquals(new CompoundName("a.b.c.d"), new CompoundName("a.b").append(new CompoundName("c.d")));
- assertEquals(new CompoundName("a.b.c.d"), new CompoundName("a.b.c").append(new CompoundName("d")));
- assertEquals(new CompoundName("a.b.c.d"), new CompoundName("a.b.c.d").append(new CompoundName("")));
+ void testAppendCompound() {
+ verifyStrict("a.b.c.d", new CompoundName("").append(new CompoundName("a.b.c.d")));
+ verifyStrict("a.b.c.d", new CompoundName("a").append(new CompoundName("b.c.d")));
+ verifyStrict("a.b.c.d", new CompoundName("a.b").append(new CompoundName("c.d")));
+ verifyStrict("a.b.c.d", new CompoundName("a.b.c").append(new CompoundName("d")));
+ verifyStrict("a.b.c.d", new CompoundName("a.b.c.d").append(new CompoundName("")));
}
@Test
- public void empty_CompoundName_is_prefix_of_any_CompoundName() {
+ void empty_CompoundName_is_prefix_of_any_CompoundName() {
CompoundName empty = new CompoundName("");
assertTrue(empty.hasPrefix(empty));
@@ -149,10 +151,65 @@ public class CompoundNameTestCase {
}
@Test
- public void whole_components_must_match_to_be_prefix() {
+ void whole_components_must_match_to_be_prefix() {
CompoundName stringPrefix = new CompoundName("a");
CompoundName name = new CompoundName("aa");
assertFalse(name.hasPrefix(stringPrefix));
}
+
+ @Test
+ void testFirstRest() {
+ verifyStrict(CompoundName.empty, CompoundName.empty.rest());
+
+ CompoundName n = new CompoundName("on.two.three");
+ assertEquals("on", n.first());
+ verifyStrict("two.three", n.rest());
+ n = n.rest();
+ assertEquals("two", n.first());
+ verifyStrict("three", n.rest());
+ n = n.rest();
+ assertEquals("three", n.first());
+ verifyStrict("", n.rest());
+ n = n.rest();
+ assertEquals("", n.first());
+ verifyStrict("", n.rest());
+ n = n.rest();
+ assertEquals("", n.first());
+ verifyStrict("", n.rest());
+ }
+
+ @Test
+ void testHashCodeAndEquals() {
+ CompoundName n1 = new CompoundName("venn.d.a");
+ CompoundName n2 = new CompoundName(n1.asList());
+ assertEquals(n1.hashCode(), n2.hashCode());
+ verifyStrict(n1, n2);
+ }
+
+ @Test
+ void testAppendString() {
+ verifyStrict("a", new CompoundName("a").append(""));
+ verifyStrict("a", new CompoundName("").append("a"));
+ verifyStrict("a.b", new CompoundName("a").append("b"));
+ verifyStrict("a.b.c.d", new CompoundName("a.b").append("c.d"));
+
+ CompoundName name = new CompoundName("a.b");
+ verifyStrict("a.b.c", name.append("c"));
+ verifyStrict("a.b.d", name.append("d"));
+ verifyStrict("a.b.d.e", name.append("d.e"));
+ }
+
+ @Test
+ void testEmpty() {
+ CompoundName empty = new CompoundName("");
+ assertEquals("", empty.toString());
+ assertEquals(0, empty.asList().size());
+ }
+
+ @Test
+ void testAsList2() {
+ assertEquals("[one]", new CompoundName("one").asList().toString());
+ assertEquals("[one, two, three]", new CompoundName("one.two.three").asList().toString());
+ }
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameBenchmark.java b/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameBenchmark.java
index 81ddc42f6c3..144c3cf736e 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameBenchmark.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameBenchmark.java
@@ -9,34 +9,37 @@ import com.yahoo.processing.request.CompoundName;
public class CompoundNameBenchmark {
public void run() {
long result=0;
- String strings[] = createStrings(1000);
+ String [] strings = createStrings(1000);
// Warm-up
out("Warming up...");
- for (int i=0; i<10*1000; i++)
+ for (int i=0; i<2*1000; i++)
result+=createCompundName(strings);
long startTime=System.currentTimeMillis();
out("Running...");
- for (int i=0; i<100*1000; i++)
+ for (int i=0; i<10*1000; i++)
result+=createCompundName(strings);
out("Ignore this: " + result); // Make sure we are not fooled by optimization by creating an observable result
long endTime=System.currentTimeMillis();
out("Compoundification 1000 strings 100.000 times took " + (endTime-startTime) + " ms");
}
- private final String [] createStrings(int num) {
- String strings [] = new String [num];
+ private String [] createStrings(int num) {
+ String [] strings = new String [num];
for(int i=0; i < strings.length; i++) {
strings[i] = "this.is.a.short.compound.name." + i;
}
return strings;
}
- private final int createCompundName(String [] strings) {
+ private int createCompundName(String [] strings) {
int retval = 0;
- for (int i=0; i < strings.length; i++) {
- CompoundName n = new CompoundName(strings[i]);
+ CompoundName toAppend = new CompoundName("appended.twice");
+ for (String s : strings) {
+ CompoundName n = new CompoundName(s);
retval += n.size();
+ CompoundName a = n.append(toAppend);
+ retval += a.size();
}
return retval;
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameTestCase.java
deleted file mode 100644
index df9e77938a6..00000000000
--- a/container-core/src/test/java/com/yahoo/processing/request/test/CompoundNameTestCase.java
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.processing.request.test;
-
-import com.yahoo.processing.request.CompoundName;
-import static org.junit.Assert.assertEquals;
-import org.junit.Test;
-
-/**
- * @author bratseth
- */
-public class CompoundNameTestCase {
-
- @Test
- public void testFirstRest() {
- assertEquals(CompoundName.empty, CompoundName.empty.rest());
-
- CompoundName n=new CompoundName("on.two.three");
- assertEquals("on", n.first());
- assertEquals("two.three", n.rest().toString());
- n=n.rest();
- assertEquals("two", n.first());
- assertEquals("three", n.rest().toString());
- n=n.rest();
- assertEquals("three", n.first());
- assertEquals("", n.rest().toString());
- n=n.rest();
- assertEquals("", n.first());
- assertEquals("", n.rest().toString());
- n=n.rest();
- assertEquals("", n.first());
- assertEquals("", n.rest().toString());
- }
-
- @Test
- public void testHashCodeAndEquals() {
- CompoundName n1 = new CompoundName("venn.d.a");
- CompoundName n2 = new CompoundName(n1.asList());
- assertEquals(n1.hashCode(), n2.hashCode());
- assertEquals(n1, n2);
- }
-
- @Test
- public void testAppend() {
- assertEquals("a",new CompoundName("a").append("").toString());
- assertEquals("a",new CompoundName("").append("a").toString());
- assertEquals("a.b",new CompoundName("a").append("b").toString());
-
- CompoundName name = new CompoundName("a.b");
- assertEquals("a.b.c",name.append("c").toString());
- assertEquals("a.b.d",name.append("d").toString());
- }
-
- @Test
- public void testEmpty() {
- CompoundName empty=new CompoundName("");
- assertEquals("", empty.toString());
- assertEquals(0, empty.asList().size());
- }
-
- @Test
- public void testAsList() {
- assertEquals("[one]", new CompoundName("one").asList().toString());
- assertEquals("[one, two, three]", new CompoundName("one.two.three").asList().toString());
- }
-
-}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
index fd152dccb96..1d4208fd356 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.processing.request.test;
import com.yahoo.processing.request.ErrorMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author bratseth
@@ -13,49 +13,49 @@ import static org.junit.Assert.assertNotEquals;
public class ErrorMessageTestCase {
@Test
- public void testToString() {
- assertEquals("message",new ErrorMessage("message").toString());
- assertEquals("message: hello",new ErrorMessage("message",new Exception("hello")).toString());
- assertEquals("message: detail",new ErrorMessage("message","detail").toString());
- assertEquals("37: message: detail",new ErrorMessage(37,"message","detail").toString());
- assertEquals("message: detail: hello",new ErrorMessage("message","detail",new Exception("hello")).toString());
- assertEquals("message: detail: hello: world",new ErrorMessage("message","detail",new Exception("hello",new Exception("world"))).toString());
- assertEquals("message: detail: hello: Exception",new ErrorMessage("message","detail",new Exception("hello",new Exception())).toString());
- assertEquals("message: detail: hello",new ErrorMessage("message","detail",new Exception(new Exception("hello"))).toString());
- assertEquals("message: detail: java.lang.Exception: Exception",new ErrorMessage("message","detail",new Exception(new Exception())).toString());
+ void testToString() {
+ assertEquals("message", new ErrorMessage("message").toString());
+ assertEquals("message: hello", new ErrorMessage("message", new Exception("hello")).toString());
+ assertEquals("message: detail", new ErrorMessage("message", "detail").toString());
+ assertEquals("37: message: detail", new ErrorMessage(37, "message", "detail").toString());
+ assertEquals("message: detail: hello", new ErrorMessage("message", "detail", new Exception("hello")).toString());
+ assertEquals("message: detail: hello: world", new ErrorMessage("message", "detail", new Exception("hello", new Exception("world"))).toString());
+ assertEquals("message: detail: hello: Exception", new ErrorMessage("message", "detail", new Exception("hello", new Exception())).toString());
+ assertEquals("message: detail: hello", new ErrorMessage("message", "detail", new Exception(new Exception("hello"))).toString());
+ assertEquals("message: detail: java.lang.Exception: Exception", new ErrorMessage("message", "detail", new Exception(new Exception())).toString());
}
@Test
- public void testAccessors() {
- ErrorMessage m = new ErrorMessage(37,"message","detail",new Exception("hello"));
- assertEquals(37,m.getCode());
- assertEquals("message",m.getMessage());
- assertEquals("detail",m.getDetailedMessage());
- assertEquals("hello",m.getCause().getMessage());
+ void testAccessors() {
+ ErrorMessage m = new ErrorMessage(37, "message", "detail", new Exception("hello"));
+ assertEquals(37, m.getCode());
+ assertEquals("message", m.getMessage());
+ assertEquals("detail", m.getDetailedMessage());
+ assertEquals("hello", m.getCause().getMessage());
}
@Test
- public void testEquality() {
- assertEquals(new ErrorMessage(37,"message","detail",new Exception("hello")),
- new ErrorMessage(37,"message","detail",new Exception("hello")));
- assertEquals(new ErrorMessage("message","detail",new Exception("hello")),
- new ErrorMessage("message","detail",new Exception("hello")));
- assertEquals(new ErrorMessage("message",new Exception("hello")),
- new ErrorMessage("message",new Exception("hello")));
+ void testEquality() {
+ assertEquals(new ErrorMessage(37, "message", "detail", new Exception("hello")),
+ new ErrorMessage(37, "message", "detail", new Exception("hello")));
+ assertEquals(new ErrorMessage("message", "detail", new Exception("hello")),
+ new ErrorMessage("message", "detail", new Exception("hello")));
+ assertEquals(new ErrorMessage("message", new Exception("hello")),
+ new ErrorMessage("message", new Exception("hello")));
assertEquals(new ErrorMessage("message"),
- new ErrorMessage("message"));
- assertEquals(new ErrorMessage("message",new Exception()),
- new ErrorMessage("message"));
+ new ErrorMessage("message"));
+ assertEquals(new ErrorMessage("message", new Exception()),
+ new ErrorMessage("message"));
assertNotEquals(new ErrorMessage("message"),
- new ErrorMessage("message","detail"));
- assertNotEquals(new ErrorMessage(37,"message"),
- new ErrorMessage("message"));
- assertNotEquals(new ErrorMessage(37,"message"),
- new ErrorMessage(38,"message"));
- assertNotEquals(new ErrorMessage("message","detail1"),
- new ErrorMessage("message","detail2"));
+ new ErrorMessage("message", "detail"));
+ assertNotEquals(new ErrorMessage(37, "message"),
+ new ErrorMessage("message"));
+ assertNotEquals(new ErrorMessage(37, "message"),
+ new ErrorMessage(38, "message"));
+ assertNotEquals(new ErrorMessage("message", "detail1"),
+ new ErrorMessage("message", "detail2"));
assertNotEquals(new ErrorMessage("message1"),
- new ErrorMessage("message2"));
+ new ErrorMessage("message2"));
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
index 5d7d1e63b21..de5437ab658 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
@@ -3,15 +3,13 @@ package com.yahoo.processing.request.test;
import com.yahoo.processing.request.properties.PropertyMap;
import com.yahoo.processing.request.properties.PublicCloneable;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -19,40 +17,40 @@ import static org.junit.Assert.assertTrue;
public class PropertyMapTestCase {
@Test
- public void testObjectCloning() {
+ void testObjectCloning() {
PropertyMap map = new PropertyMap();
map.set("clonable", new ClonableObject());
map.set("publicClonable", new PublicClonableObject());
map.set("nonclonable", new NonClonableObject());
- map.set("clonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("publicClonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("nonclonableArray", new NonClonableObject[] {new NonClonableObject()});
+ map.set("clonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("publicClonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()});
map.set("clonableList", Collections.singletonList(new ClonableObject()));
map.set("nonclonableList", Collections.singletonList(new NonClonableObject()));
assertNotNull(map.get("clonable"));
assertNotNull(map.get("nonclonable"));
- PropertyMap mapClone=map.clone();
+ PropertyMap mapClone = map.clone();
assertTrue(map.get("clonable") != mapClone.get("clonable"));
- assertTrue(map.get("publicClonable")!= mapClone.get("publicClonable"));
- assertTrue(map.get("nonclonable") == mapClone.get("nonclonable"));
+ assertTrue(map.get("publicClonable") != mapClone.get("publicClonable"));
+ assertEquals(map.get("nonclonable"), mapClone.get("nonclonable"));
assertTrue(map.get("clonableArray") != mapClone.get("clonableArray"));
assertTrue(first(map.get("clonableArray")) != first(mapClone.get("clonableArray")));
assertTrue(map.get("publicClonableArray") != mapClone.get("publicClonableArray"));
assertTrue(first(map.get("publicClonableArray")) != first(mapClone.get("publicClonableArray")));
- assertTrue(first(map.get("nonclonableArray")) == first(mapClone.get("nonclonableArray")));
+ assertEquals(first(map.get("nonclonableArray")), first(mapClone.get("nonclonableArray")));
}
-
+
@Test
- public void testArrayCloning() {
+ void testArrayCloning() {
PropertyMap map = new PropertyMap();
- byte[] byteArray = new byte[] {2, 4, 7};
+ byte[] byteArray = new byte[]{2, 4, 7};
map.set("byteArray", byteArray);
PropertyMap mapClone = map.clone();
- assertArrayEquals(byteArray, (byte[])mapClone.get("byteArray"));
- assertTrue("Array was cloned", mapClone.get("byteArray") != byteArray);
+ assertArrayEquals(byteArray, (byte[]) mapClone.get("byteArray"));
+ assertTrue(mapClone.get("byteArray") != byteArray, "Array was cloned");
}
private Object first(Object object) {
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
index a791c535b5d..c82b85d84d9 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.request.CompoundName;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.processing.request.Properties;
import com.yahoo.processing.request.properties.PropertyMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests using requests
@@ -21,7 +21,7 @@ public class RequestTestCase {
private static final double delta = 0.0000000001;
@Test
- public void testProperties() {
+ void testProperties() {
Properties p = new PropertyMap();
p.set("a", "a1");
Request r = new Request(p);
@@ -39,52 +39,52 @@ public class RequestTestCase {
assertNull(r.properties().get(new CompoundName("c")));
assertEquals("b1", r.properties().getString("b"));
- assertEquals("b1", r.properties().getString("b","default"));
- assertEquals("default", r.properties().getString("c","default"));
- assertEquals(null, r.properties().getString("c"));
+ assertEquals("b1", r.properties().getString("b", "default"));
+ assertEquals("default", r.properties().getString("c", "default"));
+ assertNull(r.properties().getString("c"));
assertEquals("b1", r.properties().getString(new CompoundName("b")));
- assertEquals("b1", r.properties().getString(new CompoundName("b"),"default"));
- assertEquals("default", r.properties().getString(new CompoundName("c"),"default"));
- assertEquals(null, r.properties().getString(new CompoundName("c")));
-
- r.properties().set("i",7);
- assertEquals(7, (int)r.properties().getInteger("i"));
- assertEquals(7, (int)r.properties().getInteger("i",3));
- assertEquals(3, (int)r.properties().getInteger("n",3));
+ assertEquals("b1", r.properties().getString(new CompoundName("b"), "default"));
+ assertEquals("default", r.properties().getString(new CompoundName("c"), "default"));
+ assertNull(r.properties().getString(new CompoundName("c")));
+
+ r.properties().set("i", 7);
+ assertEquals(7, (int) r.properties().getInteger("i"));
+ assertEquals(7, (int) r.properties().getInteger("i", 3));
+ assertEquals(3, (int) r.properties().getInteger("n", 3));
assertNull(r.properties().getInteger("n"));
- assertEquals(7, (int)r.properties().getInteger(new CompoundName("i")));
- assertEquals(7, (int)r.properties().getInteger(new CompoundName("i"),3));
- assertEquals(3, (int)r.properties().getInteger(new CompoundName("n"),3));
+ assertEquals(7, (int) r.properties().getInteger(new CompoundName("i")));
+ assertEquals(7, (int) r.properties().getInteger(new CompoundName("i"), 3));
+ assertEquals(3, (int) r.properties().getInteger(new CompoundName("n"), 3));
assertNull(r.properties().getInteger("n"));
r.properties().set(new CompoundName("l"), 7);
assertEquals(7, (long) r.properties().getLong("l"));
- assertEquals(7, (long)r.properties().getLong("l",3l));
- assertEquals(3, (long)r.properties().getLong("m",3l));
+ assertEquals(7, (long) r.properties().getLong("l", 3l));
+ assertEquals(3, (long) r.properties().getLong("m", 3l));
assertNull(r.properties().getInteger("m"));
- assertEquals(7, (long)r.properties().getLong(new CompoundName("l")));
- assertEquals(7, (long)r.properties().getLong(new CompoundName("l"),3l));
- assertEquals(3, (long)r.properties().getLong(new CompoundName("m"),3l));
+ assertEquals(7, (long) r.properties().getLong(new CompoundName("l")));
+ assertEquals(7, (long) r.properties().getLong(new CompoundName("l"), 3l));
+ assertEquals(3, (long) r.properties().getLong(new CompoundName("m"), 3l));
assertNull(r.properties().getInteger("m"));
r.properties().set("d", 7.3);
assertEquals(7.3, r.properties().getDouble("d"), delta);
- assertEquals(7.3, r.properties().getDouble("d",3.4d), delta);
- assertEquals(3.4, r.properties().getDouble("f",3.4d), delta);
+ assertEquals(7.3, r.properties().getDouble("d", 3.4d), delta);
+ assertEquals(3.4, r.properties().getDouble("f", 3.4d), delta);
assertNull(r.properties().getDouble("f"));
assertEquals(7.3, r.properties().getDouble(new CompoundName("d")), delta);
- assertEquals(7.3, r.properties().getDouble(new CompoundName("d"),3.4d), delta);
- assertEquals(3.4, r.properties().getDouble(new CompoundName("f"),3.4d), delta);
+ assertEquals(7.3, r.properties().getDouble(new CompoundName("d"), 3.4d), delta);
+ assertEquals(3.4, r.properties().getDouble(new CompoundName("f"), 3.4d), delta);
assertNull(r.properties().getDouble("f"));
- r.properties().set("o",true);
+ r.properties().set("o", true);
assertEquals(true, r.properties().getBoolean("o"));
- assertEquals(true, r.properties().getBoolean("o",true));
- assertEquals(true, r.properties().getBoolean("g",true));
+ assertEquals(true, r.properties().getBoolean("o", true));
+ assertEquals(true, r.properties().getBoolean("g", true));
assertEquals(false, r.properties().getBoolean("g"));
assertEquals(true, r.properties().getBoolean(new CompoundName("o")));
- assertEquals(true, r.properties().getBoolean(new CompoundName("o"),true));
- assertEquals(true, r.properties().getBoolean(new CompoundName("g"),true));
+ assertEquals(true, r.properties().getBoolean(new CompoundName("o"), true));
+ assertEquals(true, r.properties().getBoolean(new CompoundName("g"), true));
assertEquals(false, r.properties().getBoolean("g"));
r.properties().set(new CompoundName("x.y"), "x1.y1");
@@ -99,20 +99,20 @@ public class RequestTestCase {
}
@Test
- public void testErrorMessages() {
+ void testErrorMessages() {
Request r = new Request();
r.errors().add(new ErrorMessage("foo"));
r.errors().add(new ErrorMessage("bar"));
- assertEquals(2,r.errors().size());
+ assertEquals(2, r.errors().size());
assertEquals("foo", r.errors().get(0).getMessage());
assertEquals("bar", r.errors().get(1).getMessage());
}
@Test
- public void testCloning() {
+ void testCloning() {
Request request = new Request();
- request.properties().set("a","a1");
- request.properties().set("b","b1");
+ request.properties().set("a", "a1");
+ request.properties().set("b", "b1");
request.errors().add(new ErrorMessage("foo"));
request.errors().add(new ErrorMessage("bar"));
Request rcloned = request.clone();
@@ -125,17 +125,17 @@ public class RequestTestCase {
assertEquals("a1", rcloned.properties().get("a"));
assertEquals("b1", request.properties().get("b"));
assertEquals("b1", rcloned.properties().get("b"));
- assertEquals(null, request.properties().get("c"));
+ assertNull(request.properties().get("c"));
assertEquals("c1", rcloned.properties().get("c"));
assertEquals("d1", request.properties().get("d"));
- assertEquals(null, rcloned.properties().get("d"));
+ assertNull(rcloned.properties().get("d"));
assertEquals(3, request.errors().size());
assertEquals(1, rcloned.errors().size());
- assertEquals("foo",request.errors().get(0).getMessage());
- assertEquals("bar",request.errors().get(1).getMessage());
- assertEquals("boz",request.errors().get(2).getMessage());
- assertEquals("baz",rcloned.errors().get(0).getMessage());
+ assertEquals("foo", request.errors().get(0).getMessage());
+ assertEquals("bar", request.errors().get(1).getMessage());
+ assertEquals("boz", request.errors().get(2).getMessage());
+ assertEquals("baz", rcloned.errors().get(0).getMessage());
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java b/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java
index 2028d39f973..8716b858696 100644
--- a/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java
@@ -1,11 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.processing.test;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
@@ -24,7 +23,7 @@ public class DocumentationTestCase {
@SuppressWarnings("unchecked")
@Test
- public final void test() {
+ final void test() {
Processor p = new ExampleProcessor();
Chain<Processor> basic = new Chain<>(p);
Processor initiator = new AsyncDataProcessingInitiator(basic);
diff --git a/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java b/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
index 3f11663a1d7..da1b406927f 100644
--- a/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the basic of the processing framework
@@ -18,43 +18,43 @@ public class ProcessingTestCase {
/** Execute three simple processors doing some phony processing */
@Test
- public void testChainedProcessing1() {
+ void testChainedProcessing1() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new CombineData(),new Get6DataItems(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new CombineData(), new Get6DataItems(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result
- assertEquals(6-1,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.3",response.data().get(2).toString());
- assertEquals("second.3",response.data().get(3).toString());
- assertEquals("third.3",response.data().get(4).toString());
+ assertEquals(6 - 1, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.3", response.data().get(2).toString());
+ assertEquals("second.3", response.data().get(3).toString());
+ assertEquals("third.3", response.data().get(4).toString());
}
/** Execute the same processors in a different order */
@Test
- public void testChainedProcessing2() {
+ void testChainedProcessing2() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new Get6DataItems(),new CombineData(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new Get6DataItems(), new CombineData(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Check the result
- assertEquals(6,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.4, third.4",response.data().get(2).toString());
- assertEquals("second.4",response.data().get(3).toString());
- assertEquals("first.6, third.6",response.data().get(4).toString());
- assertEquals("second.6",response.data().get(5).toString());
+ assertEquals(6, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.4, third.4", response.data().get(2).toString());
+ assertEquals("second.4", response.data().get(3).toString());
+ assertEquals("first.6, third.6", response.data().get(4).toString());
+ assertEquals("second.6", response.data().get(5).toString());
}
}
diff --git a/container-core/src/test/java/com/yahoo/restapi/PathTest.java b/container-core/src/test/java/com/yahoo/restapi/PathTest.java
index b0392c16e2e..60d4f3b9831 100644
--- a/container-core/src/test/java/com/yahoo/restapi/PathTest.java
+++ b/container-core/src/test/java/com/yahoo/restapi/PathTest.java
@@ -1,16 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -18,7 +14,7 @@ import static org.junit.Assert.fail;
public class PathTest {
@Test
- public void testPath() {
+ void testPath() {
assertFalse(new Path(URI.create("")).matches("/a/{foo}/bar/{b}"));
assertFalse(new Path(URI.create("///")).matches("/a/{foo}/bar/{b}"));
assertFalse(new Path(URI.create("///foo")).matches("/a/{foo}/bar/{b}"));
@@ -30,7 +26,7 @@ public class PathTest {
}
@Test
- public void testPathWithRest() {
+ void testPathWithRest() {
{
Path path = new Path(URI.create("/a/1/bar/fuz/"));
assertTrue(path.matches("/a/{foo}/bar/{b}/{*}"));
@@ -65,21 +61,23 @@ public class PathTest {
}
@Test
- public void testUrlEncodedPath() {
+ void testUrlEncodedPath() {
assertTrue(new Path(URI.create("/a/%62/c")).matches("/a/b/c"));
- assertFalse(new Path(URI.create("/a/b%2fc"), __ -> { }).matches("/a/b/c"));
+ assertFalse(new Path(URI.create("/a/b%2fc"), __ -> {
+ }).matches("/a/b/c"));
assertEquals("path segments cannot be \"\", \".\", or \"..\", but got: '..'",
- assertThrows(IllegalArgumentException.class,
- () -> new Path(URI.create("/foo")).matches("/foo/bar/%2e%2e")).getMessage());
+ assertThrows(IllegalArgumentException.class,
+ () -> new Path(URI.create("/foo")).matches("/foo/bar/%2e%2e")).getMessage());
- Path path = new Path(URI.create("/%61/%2f/%63"), __ -> { });
+ Path path = new Path(URI.create("/%61/%2f/%63"), __ -> {
+ });
assertTrue(path.matches("/a/{slash}/{c}"));
assertEquals("/", path.get("slash"));
assertEquals("c", path.get("c"));
}
@Test
- public void testInvalidPaths() {
+ void testInvalidPaths() {
assertInvalid(URI.create("/foo/../bar"));
assertInvalid(URI.create("/foo/%2e%2e/bar"));
assertInvalidPathSpec(URI.create("/foo/bar"), "/foo/bar/..");
diff --git a/container-dependency-versions/pom.xml b/container-dependency-versions/pom.xml
index 709f9dc333a..695ee72df5c 100644
--- a/container-dependency-versions/pom.xml
+++ b/container-dependency-versions/pom.xml
@@ -242,7 +242,6 @@
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<javax.ws.rs-api.version>2.0.1</javax.ws.rs-api.version>
<jaxb.version>2.3.0</jaxb.version>
- <org.json.version>20090211</org.json.version>
<slf4j.version>1.7.32</slf4j.version> <!-- WARNING: when updated, also update c.y.v.tenant:base pom -->
<xml-apis.version>1.4.01</xml-apis.version>
diff --git a/container-disc/pom.xml b/container-disc/pom.xml
index 95f54e5d932..273270b208b 100644
--- a/container-disc/pom.xml
+++ b/container-disc/pom.xml
@@ -16,25 +16,29 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
@@ -185,31 +189,16 @@
<discApplicationClass>com.yahoo.container.jdisc.ConfiguredApplication</discApplicationClass>
<buildLegacyVespaPlatformBundle>true</buildLegacyVespaPlatformBundle>
<discPreInstallBundle>
- <!-- Vespa bundles -->
+ <!-- BEGIN Bundles needed to retrieve config, or used by container-disc -->
config-bundle-jar-with-dependencies.jar,
configdefinitions-jar-with-dependencies.jar,
- container-search-and-docproc-jar-with-dependencies.jar,
- container-search-gui-jar-with-dependencies.jar,
- docprocs-jar-with-dependencies.jar,
hosted-zone-api-jar-with-dependencies.jar,
- jdisc-security-filters-jar-with-dependencies.jar,
- linguistics-components-jar-with-dependencies.jar,
- vespaclient-container-plugin-jar-with-dependencies.jar,
- vespa-athenz-jar-with-dependencies.jar,
-
- <!-- Apache http client repackaged as bundle -->
container-apache-http-client-bundle-jar-with-dependencies.jar,
-
- <!-- Vespa security utils with necessary 3rd party bundles -->
security-utils.jar,
- bcpkix-jdk15on-${bouncycastle.version}.jar,
- bcprov-jdk15on-${bouncycastle.version}.jar,
-
- <!-- TODO Vespa 9 Stop providing servlet-api 3.x -->
- javax.servlet-api-3.1.0.jar,
+ bcprov-jdk15on-${bouncycastle.version}.jar, <!-- Used by security-utils -->
+ <!-- END Bundles needed to retrieve config, or used by container-disc -->
- <!-- Aries SPIFly repackaged -->
- container-spifly.jar,
+ bcpkix-jdk15on-${bouncycastle.version}.jar, <!-- Used by security-utils -->
jackson-annotations-${jackson2.version}.jar,
jackson-core-${jackson2.version}.jar,
diff --git a/container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java b/container-disc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java
index 09b5a6ff85e..67862533259 100644
--- a/container-search-and-docproc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java
+++ b/container-disc/src/main/java/com/yahoo/container/handler/observability/ApplicationStatusHandler.java
@@ -6,18 +6,15 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.yahoo.component.annotation.Inject;
-import com.yahoo.component.AbstractComponent;
+import com.yahoo.component.Component;
import com.yahoo.component.ComponentId;
import com.yahoo.component.Vtag;
+import com.yahoo.component.annotation.Inject;
import com.yahoo.component.chain.Chain;
import com.yahoo.component.provider.ComponentRegistry;
import com.yahoo.container.Container;
import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.jdisc.JdiscBindingsConfig;
-import com.yahoo.docproc.Call;
-import com.yahoo.docproc.impl.DocprocService;
-import com.yahoo.docproc.jdisc.DocumentProcessingHandler;
import com.yahoo.jdisc.handler.AbstractRequestHandler;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
@@ -32,15 +29,13 @@ import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.processing.Processor;
import com.yahoo.processing.execution.chain.ChainRegistry;
import com.yahoo.processing.handler.ProcessingHandler;
-import com.yahoo.search.handler.SearchHandler;
-import com.yahoo.search.searchchain.SearchChainRegistry;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import java.nio.ByteBuffer;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Date;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -49,9 +44,14 @@ import java.util.Map;
*
* @author gjoranv
* @author Einar M R Rosenvinge
+ * @author bjorncs
*/
public class ApplicationStatusHandler extends AbstractRequestHandler {
+ public interface Extension {
+ Map<String, ? extends JsonNode> produceExtraFields(ApplicationStatusHandler handler);
+ }
+
private static final ObjectMapper jsonMapper = new ObjectMapper();
private final JsonNode applicationJson;
@@ -60,6 +60,7 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
private final JsonNode requestFiltersJson;
private final JsonNode responseFiltersJson;
private final JdiscBindingsConfig bindingsConfig;
+ private final Collection<Extension> extensions;
@Inject
public ApplicationStatusHandler(ApplicationMetadataConfig metaConfig,
@@ -68,8 +69,8 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
ComponentRegistry<ClientProvider> clientProviderRegistry,
ComponentRegistry<ServerProvider> serverProviderRegistry,
ComponentRegistry<RequestFilterBase> requestFilterRegistry,
- ComponentRegistry<ResponseFilterBase> responseFilterRegistry) {
-
+ ComponentRegistry<ResponseFilterBase> responseFilterRegistry,
+ ComponentRegistry<Extension> extensions) {
applicationJson = renderApplicationConfigs(metaConfig, userConfig);
clientsJson = renderRequestHandlers(bindingsConfig, clientProviderRegistry.allComponentsById());
serversJson = renderObjectComponents(serverProviderRegistry.allComponentsById());
@@ -77,14 +78,11 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
responseFiltersJson = renderObjectComponents(responseFilterRegistry.allComponentsById());
this.bindingsConfig = bindingsConfig;
+ this.extensions = extensions.allComponents();
}
@Override
public ContentChannel handleRequest(com.yahoo.jdisc.Request request, ResponseHandler handler) {
- JsonNode json = new StatusResponse(applicationJson, clientsJson, serversJson,
- requestFiltersJson, responseFiltersJson, bindingsConfig)
- .render();
-
FastContentWriter writer = new FastContentWriter(new ResponseDispatch() {
@Override
protected com.yahoo.jdisc.Response newResponse() {
@@ -95,7 +93,7 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
}.connect(handler));
try {
- writer.write(jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(json));
+ writer.write(jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(render()));
} catch (JsonProcessingException e) {
throw new RuntimeException("Invalid JSON: " + e.getMessage(), e);
}
@@ -104,8 +102,18 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
return new IgnoredContent();
}
+ public ObjectMapper jsonMapper() { return jsonMapper; }
+
+ public Collection<RequestHandler> requestHandlers() { return container().getRequestHandlerRegistry().allComponents(); }
+
+ private Map<ComponentId, RequestHandler> requestHandlersById() { return container().getRequestHandlerRegistry().allComponentsById(); }
+
+ private List<? extends Component> components() { return container().getComponentRegistry().allComponents(); }
+
+ private static Container container() { return Container.get(); }
+
static JsonNode renderApplicationConfigs(ApplicationMetadataConfig metaConfig,
- ApplicationUserdataConfig userConfig) {
+ ApplicationUserdataConfig userConfig) {
ObjectNode vespa = jsonMapper.createObjectNode();
vespa.put("version", Vtag.currentVersion.toString());
@@ -139,7 +147,7 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
}
static JsonNode renderRequestHandlers(JdiscBindingsConfig bindingsConfig,
- Map<ComponentId, ? extends RequestHandler> handlersById) {
+ Map<ComponentId, ? extends RequestHandler> handlersById) {
ArrayNode ret = jsonMapper.createArrayNode();
for (Map.Entry<ComponentId, ? extends RequestHandler> handlerEntry : handlersById.entrySet()) {
@@ -175,17 +183,17 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
return ret;
}
- private static JsonNode renderAbstractComponents(List<? extends AbstractComponent> components) {
+ private static JsonNode renderAbstractComponents(List<? extends Component> components) {
ArrayNode ret = jsonMapper.createArrayNode();
- for (AbstractComponent c : components) {
+ for (Component c : components) {
JsonNode jc = renderComponent(c, c.getId());
ret.add(jc);
}
return ret;
}
- private static ObjectNode renderComponent(Object component, ComponentId id) {
+ public static ObjectNode renderComponent(Object component, ComponentId id) {
ObjectNode jc = jsonMapper.createObjectNode();
jc.put("id", id.stringValue());
addBundleInfo(jc, component);
@@ -221,102 +229,48 @@ public class ApplicationStatusHandler extends AbstractRequestHandler {
}
}
- static final class StatusResponse {
- private final JsonNode applicationJson;
- private final JsonNode clientsJson;
- private final JsonNode serversJson;
- private final JsonNode requestFiltersJson;
- private final JsonNode responseFiltersJson;
- private final JdiscBindingsConfig bindingsConfig;
-
- StatusResponse(JsonNode applicationJson,
- JsonNode clientsJson,
- JsonNode serversJson,
- JsonNode requestFiltersJson,
- JsonNode responseFiltersJson,
- JdiscBindingsConfig bindingsConfig) {
- this.applicationJson = applicationJson;
- this.clientsJson = clientsJson;
- this.serversJson = serversJson;
- this.requestFiltersJson = requestFiltersJson;
- this.responseFiltersJson = responseFiltersJson;
- this.bindingsConfig = bindingsConfig;
- }
-
- public JsonNode render() {
- ObjectNode root = jsonMapper.createObjectNode();
-
- root.set("application", applicationJson);
- root.set("abstractComponents",
- renderAbstractComponents(Container.get().getComponentRegistry().allComponents()));
+ JsonNode render() {
+ ObjectNode root = jsonMapper.createObjectNode();
- root.set("handlers",
- renderRequestHandlers(bindingsConfig, Container.get().getRequestHandlerRegistry().allComponentsById()));
- root.set("clients", clientsJson);
- root.set("servers", serversJson);
- root.set("httpRequestFilters", requestFiltersJson);
- root.set("httpResponseFilters", responseFiltersJson);
+ root.set("application", applicationJson);
+ root.set("abstractComponents",
+ renderAbstractComponents(components()));
- root.set("searchChains", renderSearchChains(Container.get()));
- root.set("docprocChains", renderDocprocChains(Container.get()));
- root.set("processingChains", renderProcessingChains(Container.get()));
+ root.set("handlers", renderRequestHandlers(bindingsConfig, requestHandlersById()));
+ root.set("clients", clientsJson);
+ root.set("servers", serversJson);
+ root.set("httpRequestFilters", requestFiltersJson);
+ root.set("httpResponseFilters", responseFiltersJson);
- return root;
- }
-
- private static JsonNode renderSearchChains(Container container) {
- for (RequestHandler h : container.getRequestHandlerRegistry().allComponents()) {
- if (h instanceof SearchHandler) {
- SearchChainRegistry scReg = ((SearchHandler) h).getSearchChainRegistry();
- return renderChains(scReg);
- }
- }
- return jsonMapper.createObjectNode();
- }
-
- private static JsonNode renderDocprocChains(Container container) {
- ObjectNode ret = jsonMapper.createObjectNode();
- for (RequestHandler h : container.getRequestHandlerRegistry().allComponents()) {
- if (h instanceof DocumentProcessingHandler) {
- ComponentRegistry<DocprocService> registry = ((DocumentProcessingHandler) h).getDocprocServiceRegistry();
- for (DocprocService service : registry.allComponents()) {
- ret.set(service.getId().stringValue(), renderCalls(service.getCallStack().iterator()));
- }
- }
- }
- return ret;
- }
+ root.set("processingChains", renderProcessingChains());
+ for (Extension extension : extensions) {
+ extension.produceExtraFields(this).forEach((field, json) -> {
+ if (root.has(field)) throw new IllegalArgumentException("Field '" + field + "' already defined");
+ root.set(field, json);
+ });
- private static JsonNode renderProcessingChains(Container container) {
- JsonNode ret = jsonMapper.createObjectNode();
- for (RequestHandler h : container.getRequestHandlerRegistry().allComponents()) {
- if (h instanceof ProcessingHandler) {
- ChainRegistry<Processor> registry = ((ProcessingHandler) h).getChainRegistry();
- return renderChains(registry);
- }
- }
- return ret;
}
+ return root;
+ }
- // Note the generic param here! The key to make this work is '? extends Chain', but why?
- static JsonNode renderChains(ComponentRegistry<? extends Chain<?>> chains) {
- ObjectNode ret = jsonMapper.createObjectNode();
- for (Chain<?> chain : chains.allComponents()) {
- ret.set(chain.getId().stringValue(), renderAbstractComponents(chain.components()));
+ private JsonNode renderProcessingChains() {
+ JsonNode ret = jsonMapper.createObjectNode();
+ for (RequestHandler h : requestHandlers()) {
+ if (h instanceof ProcessingHandler) {
+ ChainRegistry<Processor> registry = ((ProcessingHandler) h).getChainRegistry();
+ return renderChains(registry);
}
- return ret;
}
+ return ret;
+ }
- private static JsonNode renderCalls(Iterator<Call> components) {
- ArrayNode ret = jsonMapper.createArrayNode();
- while (components.hasNext()) {
- Call c = components.next();
- JsonNode jc = renderComponent(c.getDocumentProcessor(), c.getDocumentProcessor().getId());
- ret.add(jc);
- }
- return ret;
+ // Note the generic param here! The key to make this work is '? extends Chain', but why?
+ public static JsonNode renderChains(ComponentRegistry<? extends Chain<?>> chains) {
+ ObjectNode ret = jsonMapper.createObjectNode();
+ for (Chain<?> chain : chains.allComponents()) {
+ ret.set(chain.getId().stringValue(), renderAbstractComponents(chain.components()));
}
-
+ return ret;
}
private class IgnoredContent implements ContentChannel {
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java b/container-disc/src/main/java/com/yahoo/container/handler/observability/package-info.java
index 73313c2c86d..1a669b176d0 100644
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java
+++ b/container-disc/src/main/java/com/yahoo/container/handler/observability/package-info.java
@@ -3,6 +3,6 @@
* @author bjorncs
*/
@ExportPackage
-package com.yahoo.jdisc.http.filter.security.rule;
+package com.yahoo.container.handler.observability;
import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/container-disc/src/main/java/com/yahoo/container/jdisc/SystemInfoProvider.java b/container-disc/src/main/java/com/yahoo/container/jdisc/SystemInfoProvider.java
index 280e10f7022..d98ea0ffc25 100644
--- a/container-disc/src/main/java/com/yahoo/container/jdisc/SystemInfoProvider.java
+++ b/container-disc/src/main/java/com/yahoo/container/jdisc/SystemInfoProvider.java
@@ -2,6 +2,7 @@
package com.yahoo.container.jdisc;
import ai.vespa.cloud.ApplicationId;
+import ai.vespa.cloud.Cloud;
import ai.vespa.cloud.Cluster;
import ai.vespa.cloud.Environment;
import ai.vespa.cloud.Node;
@@ -34,6 +35,7 @@ public class SystemInfoProvider extends AbstractComponent implements Provider<Sy
applicationIdConfig.application(),
applicationIdConfig.instance()),
new Zone(Environment.valueOf(csConfig.environment()), csConfig.region()),
+ new Cloud(csConfig.cloud()),
new Cluster(ciConfig.nodeCount(), ciConfig.nodeIndices()),
new Node(qrConfig.nodeIndex()));
}
diff --git a/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java b/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
index 4b75bc233d6..3f7990288f5 100644
--- a/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
+++ b/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
@@ -9,6 +9,7 @@ import com.yahoo.nativec.NativeHeap;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -39,6 +40,7 @@ public class MetricUpdater extends AbstractComponent {
private static final String DIRECT_COUNT = "mem.direct.count";
private static final String MEMORY_MAPPINGS_COUNT = "jdisc.memory_mappings";
private static final String OPEN_FILE_DESCRIPTORS = "jdisc.open_file_descriptors";
+ private static final String TOTAL_THREADS = "jdisc.threads.total";
private final Scheduler scheduler;
@@ -99,6 +101,7 @@ public class MetricUpdater extends AbstractComponent {
private final ContainerWatchdogMetrics containerWatchdogMetrics;
private final GarbageCollectionMetrics garbageCollectionMetrics;
private final JrtMetrics jrtMetrics;
+ private final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
public UpdaterTask(Metric metric, ContainerWatchdogMetrics containerWatchdogMetrics) {
this.metric = metric;
@@ -148,6 +151,7 @@ public class MetricUpdater extends AbstractComponent {
metric.set(HEAP_TOTAL_MEMORY_BYTES, totalMemory, null);
metric.set(MEMORY_MAPPINGS_COUNT, count_mappings(), null);
metric.set(OPEN_FILE_DESCRIPTORS, count_open_files(), null);
+ metric.set(TOTAL_THREADS, threadMXBean.getThreadCount(), null);
directMemoryUsed();
nativeHeapUsed();
diff --git a/container-search-and-docproc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def b/container-disc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def
index cde92df9ef4..cde92df9ef4 100644
--- a/container-search-and-docproc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def
+++ b/container-disc/src/main/resources/configdefinitions/container.handler.observability.application-userdata.def
diff --git a/container-disc/src/main/sh/vespa-start-container-daemon.sh b/container-disc/src/main/sh/vespa-start-container-daemon.sh
index b27e02b6c23..b4ce6a03ba8 100755
--- a/container-disc/src/main/sh/vespa-start-container-daemon.sh
+++ b/container-disc/src/main/sh/vespa-start-container-daemon.sh
@@ -27,14 +27,10 @@ else
fi
CONTAINER_HOME="${VESPA_HOME}/var/jdisc_container/${DISCRIMINATOR}/"
-if [[ "$VESPA_SERVICE_NAME" = "container" || "$VESPA_SERVICE_NAME" = "container-clustercontroller" || "$VESPA_SERVICE_NAME" = "qrserver" ]]; then
+if [[ "$VESPA_SERVICE_NAME" = "container" || "$VESPA_SERVICE_NAME" = "container-clustercontroller" ]]; then
ZOOKEEPER_LOG_FILE_PREFIX="${VESPA_HOME}/logs/vespa/zookeeper.${VESPA_SERVICE_NAME}"
rm -f $ZOOKEEPER_LOG_FILE_PREFIX*lck
zookeeper_log_file_property="-Dzookeeper_log_file_prefix=${ZOOKEEPER_LOG_FILE_PREFIX}"
-# TODO: Temporary, remove else clause after 2022-05-20
-else
- ZOOKEEPER_LOG_FILE_PREFIX="${VESPA_HOME}/logs/vespa/zookeeper.${VESPA_SERVICE_NAME}"
- rm -f $ZOOKEEPER_LOG_FILE_PREFIX*
fi
# common setup
@@ -192,7 +188,6 @@ configure_cpu() {
configure_numactl() {
numactlcmd=$(get_numa_ctl_cmd)
- log_message debug "starting ${VESPA_SERVICE_NAME} for ${VESPA_CONFIG_ID} with numactl command : $numactlcmd"
}
configure_gcopts() {
diff --git a/container-search-and-docproc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java b/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
index 317f5fc1329..30c31a64a29 100644
--- a/container-search-and-docproc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
@@ -12,22 +12,21 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.execution.chain.ChainRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import static com.yahoo.container.jdisc.JdiscBindingsConfig.Handlers;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
- * @since 5.1.10
*/
public class ApplicationStatusHandlerTest {
@Test
- public void application_configs_are_rendered() {
+ void application_configs_are_rendered() {
ApplicationMetadataConfig metaConfig = new ApplicationMetadataConfig(
new ApplicationMetadataConfig.Builder()
.checksum("abc")
@@ -53,7 +52,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void object_components_are_rendered() {
+ void object_components_are_rendered() {
HashMap<ComponentId, Object> id2object = new HashMap<>();
id2object.put(new ComponentId("myComponent"), new Object());
@@ -62,7 +61,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void request_handlers_are_rendered() {
+ void request_handlers_are_rendered() {
final String id = "myHandler";
final String serverBinding1 = "http://*/serverBinding";
final String serverBinding2 = "http://*/anotherServerBinding";
@@ -85,7 +84,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void client_providers_are_rendered() {
+ void client_providers_are_rendered() {
final String id = "myClient";
final String clientBinding = "http://*/clientBinding";
final String clientBinding2 = "http://*/anotherClientBinding";
@@ -109,12 +108,12 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void chains_are_rendered() {
+ void chains_are_rendered() {
ChainRegistry<Processor> chains = new ChainRegistry<>();
Chain<Processor> chain = new Chain<>("myChain", new VoidProcessor(new ComponentId("voidProcessor")));
chains.register(new ComponentId("myChain"), chain);
- String json = ApplicationStatusHandler.StatusResponse.renderChains(chains).toString();
+ String json = ApplicationStatusHandler.renderChains(chains).toString();
assertTrue(json.contains("myChain"));
assertTrue(json.contains("voidProcessor"));
}
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
index ec727c506b5..d55bf18c823 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc;
import com.yahoo.container.jdisc.metric.MetricConsumerProvider;
import com.yahoo.jdisc.application.ContainerThread;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.ThreadFactory;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class ContainerThreadFactoryTest {
@Test
- public void requireThatMetricConsumerProviderCanNotBeNull() {
+ void requireThatMetricConsumerProviderCanNotBeNull() {
try {
new ContainerThreadFactory(null);
fail();
@@ -27,15 +27,15 @@ public class ContainerThreadFactoryTest {
}
@Test
- public void requireThatThreadsCreatedAreJDiscContainerThreads() {
+ void requireThatThreadsCreatedAreJDiscContainerThreads() {
assertEquals(ContainerThread.class,
- new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class))
- .newThread(Mockito.mock(Runnable.class))
- .getClass());
+ new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class))
+ .newThread(Mockito.mock(Runnable.class))
+ .getClass());
}
@Test
- public void requireThatThreadFactoryCallsProvider() {
+ void requireThatThreadFactoryCallsProvider() {
MetricConsumerProvider provider = Mockito.mock(MetricConsumerProvider.class);
ThreadFactory factory = new ContainerThreadFactory(provider);
factory.newThread(Mockito.mock(Runnable.class));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
index 46acd5ce2b8..f6b2424e0e1 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
@@ -1,47 +1,63 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleException;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* @author Ulf Lilleengen
*/
public class DisableOsgiFrameworkTest {
- @Test(expected = RuntimeException.class)
- public void require_that_installBundle_throws_exception() throws BundleException {
- new DisableOsgiFramework().installBundle("foo");
+ @Test
+ void require_that_installBundle_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().installBundle("foo");
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_startBundles_throws_exception() throws BundleException {
- new DisableOsgiFramework().startBundles(null, true);
+ @Test
+ void require_that_startBundles_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().startBundles(null, true);
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_bundleContext_throws_exception() throws BundleException {
- new DisableOsgiFramework().bundleContext();
+ @Test
+ void require_that_bundleContext_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().bundleContext();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_refreshPackages_throws_exception() {
- new DisableOsgiFramework().refreshPackages();
+ @Test
+ void require_that_refreshPackages_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().refreshPackages();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_bundles_throws_exception() {
- new DisableOsgiFramework().bundles();
+ @Test
+ void require_that_bundles_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().bundles();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_start_throws_exception() throws BundleException {
- new DisableOsgiFramework().start();
+ @Test
+ void require_that_start_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().start();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_stop_throws_exception() throws BundleException {
- new DisableOsgiFramework().stop();
+ @Test
+ void require_that_stop_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().stop();
+ });
}
}
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
index 70e956480ed..fe18206b5af 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
@@ -9,15 +9,15 @@ import com.yahoo.jdisc.http.ServerConfig;
import com.yahoo.jdisc.http.filter.RequestFilter;
import com.yahoo.jdisc.http.filter.ResponseFilter;
import com.yahoo.jdisc.http.server.jetty.FilterBindings;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
/**
@@ -28,7 +28,7 @@ public class FilterBindingsProviderTest {
final ServerConfig.Builder configBuilder = new ServerConfig.Builder();
@Test
- public void requireThatEmptyInputGivesEmptyOutput() {
+ void requireThatEmptyInputGivesEmptyOutput() {
final FilterChainRepository filterChainRepository = new FilterChainRepository(
new ChainsConfig(new ChainsConfig.Builder()),
new ComponentRegistry<>(),
@@ -50,7 +50,7 @@ public class FilterBindingsProviderTest {
}
@Test
- public void requireThatCorrectlyConfiguredFiltersAreIncluded() {
+ void requireThatCorrectlyConfiguredFiltersAreIncluded() {
final String requestFilter1Id = "requestFilter1";
final String requestFilter2Id = "requestFilter2";
final String requestFilter3Id = "requestFilter3";
@@ -107,7 +107,7 @@ public class FilterBindingsProviderTest {
private interface DualRoleFilter extends RequestFilter, ResponseFilter {}
@Test
- public void requireThatInstanceCanNotBeBothRequestAndResponseFilter() {
+ void requireThatInstanceCanNotBeBothRequestAndResponseFilter() {
final String filterId = "filter";
// Set up config.
@@ -137,7 +137,7 @@ public class FilterBindingsProviderTest {
}
@Test
- public void requireThatConfigWithUnknownReferenceFails() {
+ void requireThatConfigWithUnknownReferenceFails() {
// Set up config.
configBuilder.filter(new ServerConfig.Filter.Builder().id("someFilter").binding("http://*/*"));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
index 715c2759aa6..76b4d7701ea 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
@@ -6,8 +6,8 @@ import com.yahoo.container.bundle.MockBundle;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.SharedResource;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
@@ -15,7 +15,7 @@ import java.util.function.Supplier;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -23,13 +23,13 @@ import static org.junit.Assert.assertTrue;
public class DeconstructorTest {
public static Deconstructor deconstructor;
- @Before
+ @BeforeEach
public void init() {
deconstructor = new Deconstructor();
}
@Test
- public void deconstructor_waits_for_completion_on_shutdown() {
+ void deconstructor_waits_for_completion_on_shutdown() {
deconstructor = new Deconstructor();
var slowDeconstructComponent = new SlowDeconstructComponent();
@@ -39,7 +39,7 @@ public class DeconstructorTest {
}
@Test
- public void require_abstract_component_destructed() throws InterruptedException {
+ void require_abstract_component_destructed() throws InterruptedException {
TestAbstractComponent abstractComponent = new TestAbstractComponent();
deconstructor.deconstruct(0, List.of(abstractComponent), emptyList());
@@ -48,7 +48,7 @@ public class DeconstructorTest {
}
@Test
- public void require_provider_destructed() throws InterruptedException {
+ void require_provider_destructed() throws InterruptedException {
TestProvider provider = new TestProvider();
deconstructor.deconstruct(0, List.of(provider), emptyList());
@@ -57,7 +57,7 @@ public class DeconstructorTest {
}
@Test
- public void require_shared_resource_released() throws InterruptedException {
+ void require_shared_resource_released() throws InterruptedException {
TestSharedResource sharedResource = new TestSharedResource();
deconstructor.deconstruct(0, List.of(sharedResource), emptyList());
waitForDeconstructToComplete(() -> sharedResource.released);
@@ -65,7 +65,7 @@ public class DeconstructorTest {
}
@Test
- public void bundles_are_uninstalled() throws InterruptedException {
+ void bundles_are_uninstalled() throws InterruptedException {
var bundle = new UninstallableMockBundle();
// Done by executor, so it takes some time even with a 0 delay.
deconstructor.deconstruct(0, emptyList(), singleton(bundle));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
index 95b179c207f..982ad4389c2 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull;
public class ForwardingMetricConsumerTest {
@Test
- public void requireThatAllMethodsAreForwarded() {
+ void requireThatAllMethodsAreForwarded() {
MetricConsumer fooConsumer = Mockito.mock(MetricConsumer.class);
Metric.Context fooCtx = Mockito.mock(Metric.Context.class);
Mockito.when(fooConsumer.createContext(Mockito.<Map<String, ?>>any())).thenReturn(fooCtx);
@@ -26,7 +26,7 @@ public class ForwardingMetricConsumerTest {
Metric.Context barCtx = Mockito.mock(Metric.Context.class);
Mockito.when(barConsumer.createContext(Mockito.<Map<String, ?>>any())).thenReturn(barCtx);
- MetricConsumer fwdConsumer = new ForwardingMetricConsumer(new MetricConsumer[] { fooConsumer, barConsumer });
+ MetricConsumer fwdConsumer = new ForwardingMetricConsumer(new MetricConsumer[]{fooConsumer, barConsumer});
Map<String, ?> properties = new HashMap<>();
Metric.Context ctx = fwdConsumer.createContext(properties);
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
index e4f8c6d76ed..8e38420b872 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -21,7 +21,7 @@ import static org.mockito.Mockito.verify;
*/
public class GarbageCollectionMetricsTest {
@Test
- public void gc_metrics_are_collected_in_a_sliding_window() {
+ void gc_metrics_are_collected_in_a_sliding_window() {
ManualClock clock = new ManualClock();
Metric metric = mock(Metric.class);
int garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans().size();
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
index e0650ad3d0c..5a67b7189c4 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
@@ -2,12 +2,11 @@
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -15,14 +14,14 @@ import static org.junit.Assert.assertSame;
public class MetricConsumerProviderTest {
@Test
- public void requireThatSingleConsumerIsNotDelegated() {
+ void requireThatSingleConsumerIsNotDelegated() {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricConsumerProvider provider = MetricConsumerProviders.newSingletonFactories(consumer);
assertSame(consumer, provider.newInstance());
}
@Test
- public void requireThatMultipleConsumersAreDelegated() {
+ void requireThatMultipleConsumersAreDelegated() {
MetricConsumer foo = Mockito.mock(MetricConsumer.class);
MetricConsumer bar = Mockito.mock(MetricConsumer.class);
MetricConsumerProvider provider = MetricConsumerProviders.newSingletonFactories(foo, bar);
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
index eac3ad2f060..5ad7d5767a6 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
@@ -4,7 +4,7 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.Callable;
@@ -13,9 +13,9 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class MetricProviderTest {
@Test
- public void requireThatMetricProviderDelegatesToConsumerFactory() {
+ void requireThatMetricProviderDelegatesToConsumerFactory() {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricProvider provider = MetricProviders.newInstance(consumer);
@@ -38,7 +38,7 @@ public class MetricProviderTest {
}
@Test
- public void requireThatThreadLocalConsumersAreProvided() throws Exception {
+ void requireThatThreadLocalConsumersAreProvided() throws Exception {
AtomicInteger cnt = new AtomicInteger(0);
final MetricProvider metricProvider = MetricProviders.newInstance(MetricConsumerFactories.newCounter(cnt));
assertEquals(0, cnt.get());
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
index 0652f35a5d1..bc196b08ab9 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
@@ -3,7 +3,7 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
@@ -18,16 +18,16 @@ import static org.mockito.Mockito.verify;
* @author bjorncs
*/
public class MetricUpdaterTest {
-
+
@Test
- public void metrics_are_updated_in_scheduler_cycle() {
+ void metrics_are_updated_in_scheduler_cycle() {
int gcCount = ManagementFactory.getGarbageCollectorMXBeans().size();
Metric metric = mock(Metric.class);
ContainerWatchdogMetrics containerWatchdogMetrics = mock(ContainerWatchdogMetrics.class);
new MetricUpdater(new MockScheduler(), metric, containerWatchdogMetrics);
verify(containerWatchdogMetrics, times(1)).emitMetrics(any());
- verify(metric, times(13 + 2 * gcCount)).set(anyString(), any(), any());
+ verify(metric, times(14 + 2 * gcCount)).set(anyString(), any(), any());
}
private static class MockScheduler implements MetricUpdater.Scheduler {
diff --git a/container-messagebus/src/main/java/com/yahoo/messagebus/shared/SharedMessageBus.java b/container-messagebus/src/main/java/com/yahoo/messagebus/shared/SharedMessageBus.java
index e3042310ad0..cf50eeb2c8d 100644
--- a/container-messagebus/src/main/java/com/yahoo/messagebus/shared/SharedMessageBus.java
+++ b/container-messagebus/src/main/java/com/yahoo/messagebus/shared/SharedMessageBus.java
@@ -1,12 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.shared;
+import com.yahoo.cloud.config.SlobroksConfig;
import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.jdisc.AbstractResource;
-
-import java.util.Objects;
-import java.util.logging.Level;
-
import com.yahoo.messagebus.DestinationSessionParams;
import com.yahoo.messagebus.IntermediateSessionParams;
import com.yahoo.messagebus.MessageBus;
@@ -15,8 +12,8 @@ import com.yahoo.messagebus.SourceSessionParams;
import com.yahoo.messagebus.network.Network;
import com.yahoo.messagebus.network.rpc.RPCNetwork;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
-import com.yahoo.cloud.config.SlobroksConfig;
-
+import java.util.Objects;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -57,6 +54,7 @@ public class SharedMessageBus extends AbstractResource {
return new SharedMessageBus(new MessageBus(newNetwork(netParams), mbusParams));
}
+ @SuppressWarnings("deprecation")
private static Network newNetwork(RPCNetworkParams params) {
SlobroksConfig cfg = params.getSlobroksConfig();
if (cfg == null) {
diff --git a/container-messagebus/src/main/resources/configdefinitions/container.jdisc.container-mbus.def b/container-messagebus/src/main/resources/configdefinitions/container.jdisc.container-mbus.def
index 143e02a30ef..bd43c13aba3 100644
--- a/container-messagebus/src/main/resources/configdefinitions/container.jdisc.container-mbus.def
+++ b/container-messagebus/src/main/resources/configdefinitions/container.jdisc.container-mbus.def
@@ -22,10 +22,6 @@ transport_events_before_wakeup int default=1
# Dynamic throttling is used, and works better than anything else.
maxpendingcount int default=2048
-enabled bool default=false
-#maxpendingsize is set in megabytes!
-maxpendingsize int default=100
-
#The amount of input data that the service can process concurrently
maxConcurrentFactor double default=0.2 range=[0.0-1.0]
diff --git a/container-search-gui/pom.xml b/container-search-gui/pom.xml
index d0c6706189d..74a854ce4a3 100644
--- a/container-search-gui/pom.xml
+++ b/container-search-gui/pom.xml
@@ -16,43 +16,13 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>com.google.inject</groupId>
- <artifactId>guice</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>jdisc_core</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>container-core</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>container-search-and-docproc</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>configdefinitions</artifactId>
+ <artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
-
<plugins>
<!-- TODO: alternative solution. For now, don't call out during build.
<plugin>
diff --git a/container-search/abi-spec.json b/container-search/abi-spec.json
index f53856d465a..b7374ecb81d 100644
--- a/container-search/abi-spec.json
+++ b/container-search/abi-spec.json
@@ -2319,7 +2319,9 @@
],
"methods": [
"public void <init>()",
- "public com.yahoo.search.Result search(com.yahoo.search.Query, com.yahoo.search.searchchain.Execution)"
+ "public com.yahoo.search.Result search(com.yahoo.search.Query, com.yahoo.search.searchchain.Execution)",
+ "public static void validate(com.yahoo.search.Query)",
+ "public static void createGroupingRequestIn(com.yahoo.search.Query, com.yahoo.search.grouping.request.GroupingOperation, java.util.List)"
],
"fields": [
"public static final java.lang.String SELECT_PARAMETER_PARSING",
diff --git a/container-search/pom.xml b/container-search/pom.xml
index ccec1330d68..1c3e7e71497 100644
--- a/container-search/pom.xml
+++ b/container-search/pom.xml
@@ -16,11 +16,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>test</scope>
@@ -73,6 +68,12 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>container-disc</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<exclusions>
@@ -146,12 +147,36 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/container-search/src/main/java/com/yahoo/prelude/query/parser/StructuredParser.java b/container-search/src/main/java/com/yahoo/prelude/query/parser/StructuredParser.java
index 54a6e5b6e90..f993c7a9e02 100644
--- a/container-search/src/main/java/com/yahoo/prelude/query/parser/StructuredParser.java
+++ b/container-search/src/main/java/com/yahoo/prelude/query/parser/StructuredParser.java
@@ -333,6 +333,7 @@ abstract class StructuredParser extends AbstractParser {
if (tokens.currentIs(NUMBER)) {
rangeEnd = (negative ? "-" : "") + tokens.next().toString() + decimalPart();
}
+ if (rangeStart.isBlank() && rangeEnd.isBlank()) return null;
String range = "[" + rangeStart + ";" + rangeEnd;
diff --git a/container-search/src/main/java/com/yahoo/search/Query.java b/container-search/src/main/java/com/yahoo/search/Query.java
index 48885e4b3da..3a2bccf017e 100644
--- a/container-search/src/main/java/com/yahoo/search/Query.java
+++ b/container-search/src/main/java/com/yahoo/search/Query.java
@@ -438,7 +438,7 @@ public class Query extends com.yahoo.processing.Request implements Cloneable {
for (FieldDescription field : arguments.fields().values()) {
if (field.getType() == FieldType.genericQueryProfileType) { // Generic map
- CompoundName fullName = prefix.append(field.getName());
+ CompoundName fullName = prefix.append(field.getCompoundName());
for (Map.Entry<String, Object> entry : originalProperties.listProperties(fullName, context).entrySet()) {
properties().set(fullName.append(entry.getKey()), entry.getValue(), context);
}
@@ -447,7 +447,7 @@ public class Query extends com.yahoo.processing.Request implements Cloneable {
setFrom(prefix, originalProperties, ((QueryProfileFieldType)field.getType()).getQueryProfileType(), context);
}
else {
- CompoundName fullName = prefix.append(field.getName());
+ CompoundName fullName = prefix.append(field.getCompoundName());
Object value = originalProperties.get(fullName, context);
if (value != null) {
properties().set(fullName, value, context);
diff --git a/container-search/src/main/java/com/yahoo/search/dispatch/searchcluster/Group.java b/container-search/src/main/java/com/yahoo/search/dispatch/searchcluster/Group.java
index af9834e282a..d30abd1d047 100644
--- a/container-search/src/main/java/com/yahoo/search/dispatch/searchcluster/Group.java
+++ b/container-search/src/main/java/com/yahoo/search/dispatch/searchcluster/Group.java
@@ -74,7 +74,7 @@ public class Group {
long average = activeDocs / numWorkingNodes;
long skew = nodes.stream().filter(node -> node.isWorking() == Boolean.TRUE).mapToLong(node -> Math.abs(node.getActiveDocuments() - average)).sum();
boolean balanced = skew <= activeDocs * maxContentSkew;
- if (!isBalanced.get() || balanced != isBalanced.get()) {
+ if (balanced != isBalanced.get()) {
if (!isSparse())
log.info("Content in " + this + ", with " + numWorkingNodes + "/" + nodes.size() + " working nodes, is " +
(balanced ? "" : "not ") + "well balanced. Current deviation: " + skew * 100 / activeDocs +
diff --git a/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java b/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java
index 36a8b7812ba..54194221958 100644
--- a/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java
+++ b/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java
@@ -50,25 +50,14 @@ public class GroupingQueryParser extends Searcher {
@Override
public Result search(Query query, Execution execution) {
try {
- if (query.getHttpRequest().getProperty(GROUPING_GLOBAL_MAX_GROUPS.toString()) != null) {
- throw new IllegalInputException(GROUPING_GLOBAL_MAX_GROUPS + " must be specified in a query profile.");
- }
+ validate(query);
String reqParam = query.properties().getString(PARAM_REQUEST);
if (reqParam == null) return execution.search(query);
List<Continuation> continuations = getContinuations(query.properties().getString(PARAM_CONTINUE));
- TimeZone zone = getTimeZone(query.properties().getString(PARAM_TIMEZONE, "utc"));
- for (GroupingOperation op : GroupingOperation.fromStringAsList(reqParam)) {
- GroupingRequest grpRequest = GroupingRequest.newInstance(query);
- grpRequest.setRootOperation(op);
- grpRequest.setTimeZone(zone);
- grpRequest.continuations().addAll(continuations);
- intProperty(query, PARAM_DEFAULT_MAX_GROUPS).ifPresent(grpRequest::setDefaultMaxGroups);
- intProperty(query, PARAM_DEFAULT_MAX_HITS).ifPresent(grpRequest::setDefaultMaxHits);
- longProperty(query, GROUPING_GLOBAL_MAX_GROUPS).ifPresent(grpRequest::setGlobalMaxGroups);
- doubleProperty(query, PARAM_DEFAULT_PRECISION_FACTOR).ifPresent(grpRequest::setDefaultPrecisionFactor);
- }
+ for (GroupingOperation operation : GroupingOperation.fromStringAsList(reqParam))
+ createGroupingRequestIn(query, operation, continuations);
return execution.search(query);
}
catch (IllegalArgumentException e) {
@@ -76,6 +65,22 @@ public class GroupingQueryParser extends Searcher {
}
}
+ public static void validate(Query query) {
+ if (query.getHttpRequest().getProperty(GROUPING_GLOBAL_MAX_GROUPS.toString()) != null)
+ throw new IllegalInputException(GROUPING_GLOBAL_MAX_GROUPS + " must be specified in a query profile.");
+ }
+
+ public static void createGroupingRequestIn(Query query, GroupingOperation operation, List<Continuation> continuations) {
+ GroupingRequest request = GroupingRequest.newInstance(query);
+ request.setRootOperation(operation);
+ request.setTimeZone(getTimeZone(query.properties().getString(PARAM_TIMEZONE, "utc")));
+ request.continuations().addAll(continuations);
+ intProperty(query, PARAM_DEFAULT_MAX_GROUPS).ifPresent(request::setDefaultMaxGroups);
+ intProperty(query, PARAM_DEFAULT_MAX_HITS).ifPresent(request::setDefaultMaxHits);
+ longProperty(query, GROUPING_GLOBAL_MAX_GROUPS).ifPresent(request::setGlobalMaxGroups);
+ doubleProperty(query, PARAM_DEFAULT_PRECISION_FACTOR).ifPresent(request::setDefaultPrecisionFactor);
+ }
+
private List<Continuation> getContinuations(String param) {
if (param == null) {
return Collections.emptyList();
@@ -87,7 +92,7 @@ public class GroupingQueryParser extends Searcher {
return ret;
}
- private TimeZone getTimeZone(String name) {
+ private static TimeZone getTimeZone(String name) {
ZoneCache cache = zoneCache.get();
if (cache == null) {
cache = new ZoneCache();
diff --git a/container-search/src/main/java/com/yahoo/search/grouping/vespa/RequestBuilder.java b/container-search/src/main/java/com/yahoo/search/grouping/vespa/RequestBuilder.java
index e43067ade62..2280ea01263 100644
--- a/container-search/src/main/java/com/yahoo/search/grouping/vespa/RequestBuilder.java
+++ b/container-search/src/main/java/com/yahoo/search/grouping/vespa/RequestBuilder.java
@@ -406,8 +406,9 @@ class RequestBuilder {
}
private void validateGlobalMax() {
- this.totalGroupsAndSummaries = -1;
if (globalMaxGroups < 0) return;
+
+ this.totalGroupsAndSummaries = -1;
int totalGroupsAndSummaries = 0;
for (Grouping grp : requestList) {
int levelMultiplier = 1;
diff --git a/container-search/src/main/java/com/yahoo/search/handler/Json2SingleLevelMap.java b/container-search/src/main/java/com/yahoo/search/handler/Json2SingleLevelMap.java
index 5b8c99506c5..bf0272f4f66 100644
--- a/container-search/src/main/java/com/yahoo/search/handler/Json2SingleLevelMap.java
+++ b/container-search/src/main/java/com/yahoo/search/handler/Json2SingleLevelMap.java
@@ -22,7 +22,7 @@ import java.util.Map;
* @author baldersheim
*/
class Json2SingleLevelMap {
- private static final ObjectMapper jsonMapper = new ObjectMapper();
+ private static final ObjectMapper jsonMapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
private final byte [] buf;
private final JsonParser parser;
Json2SingleLevelMap(InputStream data) {
diff --git a/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java b/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java
index 76702a1d4e0..3da3f57cb21 100644
--- a/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java
+++ b/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java
@@ -41,7 +41,6 @@ import com.yahoo.search.searchchain.ExecutionFactory;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.statistics.ElapsedTime;
import com.yahoo.slime.Inspector;
-import com.yahoo.slime.ObjectTraverser;
import com.yahoo.yolean.Exceptions;
import com.yahoo.yolean.trace.TraceNode;
diff --git a/container-search/src/main/java/com/yahoo/search/handler/observability/SearchStatusExtension.java b/container-search/src/main/java/com/yahoo/search/handler/observability/SearchStatusExtension.java
new file mode 100644
index 00000000000..836bb1b8354
--- /dev/null
+++ b/container-search/src/main/java/com/yahoo/search/handler/observability/SearchStatusExtension.java
@@ -0,0 +1,32 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.search.handler.observability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.yahoo.container.handler.observability.ApplicationStatusHandler;
+import com.yahoo.jdisc.handler.RequestHandler;
+import com.yahoo.search.handler.SearchHandler;
+import com.yahoo.search.searchchain.SearchChainRegistry;
+
+import java.util.Map;
+
+/**
+ * @author bjorncs
+ */
+public class SearchStatusExtension implements ApplicationStatusHandler.Extension {
+
+ @Override
+ public Map<String, ? extends JsonNode> produceExtraFields(ApplicationStatusHandler statusHandler) {
+ return Map.of("searchChains", renderSearchChains(statusHandler));
+ }
+
+ private static JsonNode renderSearchChains(ApplicationStatusHandler statusHandler) {
+ for (RequestHandler h : statusHandler.requestHandlers()) {
+ if (h instanceof SearchHandler) {
+ SearchChainRegistry scReg = ((SearchHandler) h).getSearchChainRegistry();
+ return ApplicationStatusHandler.renderChains(scReg);
+ }
+ }
+ return statusHandler.jsonMapper().createObjectNode();
+ }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/https/package-info.java b/container-search/src/main/java/com/yahoo/search/handler/observability/package-info.java
index 91a1672e19f..baf24b4a94d 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/https/package-info.java
+++ b/container-search/src/main/java/com/yahoo/search/handler/observability/package-info.java
@@ -3,6 +3,6 @@
* @author bjorncs
*/
@ExportPackage
-package com.yahoo.security.tls.https;
+package com.yahoo.search.handler.observability;
import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/ChainedMap.java b/container-search/src/main/java/com/yahoo/search/query/profile/ChainedMap.java
new file mode 100644
index 00000000000..3ec9a3c41b8
--- /dev/null
+++ b/container-search/src/main/java/com/yahoo/search/query/profile/ChainedMap.java
@@ -0,0 +1,107 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.search.query.profile;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A read-only map which forwards lookups to a primary map, and then a secondary for
+ * keys not existing in the primary.
+ *
+ * @author bratseth
+ */
+class ChainedMap<K, V> implements Map<K, V> {
+
+ private final Map<K, V> primary, secondary;
+
+ ChainedMap(Map<K, V> primary, Map<K, V> secondary) {
+ this.primary = primary;
+ this.secondary = secondary;
+ }
+
+ @Override
+ public int size() {
+ return (primary.size() >= secondary.size())
+ ? countUnique(primary, secondary)
+ : countUnique(secondary, primary);
+ }
+
+ private int countUnique(Map<K, V> large, Map<K,V> small) {
+ int size = large.size();
+ for (K key : small.keySet()) {
+ if ( ! large.containsKey(key)) size++;
+ }
+ return size;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return primary.isEmpty() && secondary.isEmpty();
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ return primary.containsKey(key) || secondary.containsKey(key);
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ return primary.containsValue(value) || secondary.containsValue(value);
+ }
+
+ @Override
+ public V get(Object key) {
+ V value = primary.get(key);
+ return value != null ? value : secondary.get(key);
+ }
+
+ @Override
+ public V put(K key, V value) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public V remove(Object key) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void clear() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Set<K> keySet() {
+ var keys = new HashSet<>(secondary.keySet());
+ keys.addAll(primary.keySet());
+ return keys;
+ }
+
+ @Override
+ public Collection<V> values() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Set<Entry<K, V>> entrySet() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException();
+ }
+
+}
diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java
index 7f5df94d020..224f75e7034 100644
--- a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java
+++ b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java
@@ -300,13 +300,7 @@ public class QueryProfileProperties extends Properties {
if (zoneInfo == ZoneInfo.defaultInfo()) return context;
if (context == null || context.isEmpty()) return zoneContext;
if (context == zoneContext) return context;
- if (context.containsKey(ENVIRONMENT) && context.containsKey(REGION) && context.containsKey(INSTANCE)) return context;
-
- Map<String, String> contextWithZoneInfo = new HashMap<>(context);
- contextWithZoneInfo.putIfAbsent(ENVIRONMENT, zoneInfo.zone().environment().name());
- contextWithZoneInfo.putIfAbsent(REGION, zoneInfo.zone().region());
- contextWithZoneInfo.putIfAbsent(INSTANCE, zoneInfo.application().instance());
- return Collections.unmodifiableMap(contextWithZoneInfo);
+ return new ChainedMap(context, zoneContext);
}
private boolean reachableTypesAreComplete(CompoundName prefix, CompiledQueryProfile profile, StringBuilder firstMissingName, Map<String,String> context) {
diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileConfigurer.java b/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileConfigurer.java
index 31278af9579..5b30e3c383d 100644
--- a/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileConfigurer.java
+++ b/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileConfigurer.java
@@ -21,6 +21,7 @@ import java.util.Set;
*/
public class QueryProfileConfigurer {
+ @SuppressWarnings("deprecation")
public static QueryProfileRegistry createFromConfigId(String configId) {
return createFromConfig(ConfigGetter.getConfig(QueryProfilesConfig.class, configId));
}
diff --git a/container-search/src/main/java/com/yahoo/search/query/ranking/RankFeatures.java b/container-search/src/main/java/com/yahoo/search/query/ranking/RankFeatures.java
index 5fed5f13c64..51be79f8c2e 100644
--- a/container-search/src/main/java/com/yahoo/search/query/ranking/RankFeatures.java
+++ b/container-search/src/main/java/com/yahoo/search/query/ranking/RankFeatures.java
@@ -75,7 +75,9 @@ public class RankFeatures implements Cloneable {
Object feature = features.get(name);
if (feature == null) return OptionalDouble.empty();
if (feature instanceof Double) return OptionalDouble.of((Double)feature);
- throw new IllegalArgumentException("Expected a double value of '" + name + "' but has " + feature);
+ throw new IllegalArgumentException("Expected '" + name + "' to be a double, but it is " +
+ (feature instanceof Tensor ? "the tensor " + ((Tensor)feature).toAbbreviatedString() :
+ "the string '" + feature + "'"));
}
/**
@@ -88,7 +90,7 @@ public class RankFeatures implements Cloneable {
if (feature == null) return Optional.empty();
if (feature instanceof Tensor) return Optional.of((Tensor)feature);
if (feature instanceof Double) return Optional.of(Tensor.from((Double)feature));
- throw new IllegalArgumentException("Expected a tensor value of '" + name + "' but has " + feature);
+ throw new IllegalArgumentException("Expected '" + name + "' to be a tensor, but it is the string '" + feature + "'");
}
/**
@@ -100,9 +102,9 @@ public class RankFeatures implements Cloneable {
Object feature = features.get(name);
if (feature == null) return Optional.empty();
if (feature instanceof String) return Optional.of((String)feature);
- // TODO: Use toShortString for tensors below
- throw new IllegalArgumentException("Expected a string value of '" + name + "' but has " +
- (feature instanceof Tensor ? ((Tensor)feature).toString() : feature));
+ throw new IllegalArgumentException("Expected '" + name + "' to be a string, but it is " +
+ (feature instanceof Tensor ? "the tensor " + ((Tensor)feature).toAbbreviatedString() :
+ "the double " + feature));
}
diff --git a/container-search/src/main/java/com/yahoo/search/querytransform/WeakAndReplacementSearcher.java b/container-search/src/main/java/com/yahoo/search/querytransform/WeakAndReplacementSearcher.java
index b47b54bc362..898e348db92 100644
--- a/container-search/src/main/java/com/yahoo/search/querytransform/WeakAndReplacementSearcher.java
+++ b/container-search/src/main/java/com/yahoo/search/querytransform/WeakAndReplacementSearcher.java
@@ -1,7 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.querytransform;
-import com.yahoo.prelude.query.*;
+import com.yahoo.prelude.query.CompositeItem;
+import com.yahoo.prelude.query.Item;
+import com.yahoo.prelude.query.OrItem;
+import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
@@ -15,7 +18,8 @@ import com.yahoo.search.searchchain.Execution;
* @author karowan
*/
public class WeakAndReplacementSearcher extends Searcher {
- private static final CompoundName WEAKAND_REPLACE = new CompoundName("weakAnd.replace");
+ static final CompoundName WEAKAND_REPLACE = new CompoundName("weakAnd.replace");
+ static final CompoundName WAND_HITS = new CompoundName("wand.hits");
@Override public Result search(Query query, Execution execution) {
if (!query.properties().getBoolean(WEAKAND_REPLACE)) {
@@ -31,7 +35,7 @@ public class WeakAndReplacementSearcher extends Searcher {
*/
private void replaceOrItems(Query query) {
Item root = query.getModel().getQueryTree().getRoot();
- int hits = query.properties().getInteger("wand.hits", WeakAndItem.defaultN);
+ int hits = query.properties().getInteger(WAND_HITS, WeakAndItem.defaultN);
query.getModel().getQueryTree().setRoot(replaceOrItems(root, hits));
if (root != query.getModel().getQueryTree().getRoot())
query.trace("Replaced OR by WeakAnd", true, 2);
@@ -45,10 +49,9 @@ public class WeakAndReplacementSearcher extends Searcher {
* @return the original item or a WeakAndItem replacement of an OrItem
*/
private Item replaceOrItems(Item item, int hits) {
- if (!(item instanceof CompositeItem)) {
+ if (!(item instanceof CompositeItem compositeItem)) {
return item;
}
- CompositeItem compositeItem = (CompositeItem) item;
if (compositeItem instanceof OrItem) {
WeakAndItem newItem = new WeakAndItem(hits);
newItem.setWeight(compositeItem.getWeight());
diff --git a/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java b/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java
index 85b8a563a9e..110f69c19ca 100644
--- a/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java
+++ b/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java
@@ -78,7 +78,7 @@ public class VespaSearchers {
for (Class c : searchers) {
searcherModels.add(
new ChainedComponentModel(
- BundleInstantiationSpecification.getInternalSearcherSpecificationFromStrings(c.getName(), null),
+ BundleInstantiationSpecification.fromSearchAndDocproc(c.getName()),
Dependencies.emptyDependencies()));
}
return searcherModels;
diff --git a/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/FederationSearcherModel.java b/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/FederationSearcherModel.java
index ea8275760dc..8acac776ae8 100644
--- a/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/FederationSearcherModel.java
+++ b/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/FederationSearcherModel.java
@@ -24,9 +24,11 @@ public class FederationSearcherModel extends ChainedComponentModel {
public final List<TargetSpec> targets;
public final boolean inheritDefaultSources;
- public FederationSearcherModel(ComponentSpecification componentId, Dependencies dependencies,
- List<TargetSpec> targets, boolean inheritDefaultSources) {
- super(BundleInstantiationSpecification.getInternalSearcherSpecification(componentId, federationSearcherComponentSpecification),
+ public FederationSearcherModel(ComponentSpecification componentId,
+ Dependencies dependencies,
+ List<TargetSpec> targets,
+ boolean inheritDefaultSources) {
+ super(BundleInstantiationSpecification.fromSearchAndDocproc(componentId, federationSearcherComponentSpecification),
dependencies);
this.inheritDefaultSources = inheritDefaultSources;
this.targets = ImmutableList.copyOf(targets);
diff --git a/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/LocalProviderSpec.java b/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/LocalProviderSpec.java
index 3c2767430c7..c4e5f26a3eb 100644
--- a/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/LocalProviderSpec.java
+++ b/container-search/src/main/java/com/yahoo/search/searchchain/model/federation/LocalProviderSpec.java
@@ -63,9 +63,7 @@ public class LocalProviderSpec {
for (Class<? extends Searcher> c : searchers) {
searcherModels.add(
new ChainedComponentModel(
- BundleInstantiationSpecification.getInternalSearcherSpecificationFromStrings(
- c.getName(),
- null),
+ BundleInstantiationSpecification.fromSearchAndDocproc(c.getName()),
Dependencies.emptyDependencies()));
}
diff --git a/container-search/src/main/java/com/yahoo/search/yql/MinimalQueryInserter.java b/container-search/src/main/java/com/yahoo/search/yql/MinimalQueryInserter.java
index 48c48748563..e844bac21e8 100644
--- a/container-search/src/main/java/com/yahoo/search/yql/MinimalQueryInserter.java
+++ b/container-search/src/main/java/com/yahoo/search/yql/MinimalQueryInserter.java
@@ -10,7 +10,7 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.processing.request.CompoundName;
-import com.yahoo.search.grouping.GroupingRequest;
+import com.yahoo.search.grouping.GroupingQueryParser;
import com.yahoo.search.query.QueryTree;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
@@ -116,11 +116,11 @@ public class MinimalQueryInserter extends Searcher {
}
query.getModel().getQueryTree().setRoot(newTree.getRoot());
query.getPresentation().getSummaryFields().addAll(parser.getYqlSummaryFields());
- for (VespaGroupingStep step : parser.getGroupingSteps()) {
- GroupingRequest.newInstance(query)
- .setRootOperation(step.getOperation())
- .continuations().addAll(step.continuations());
- }
+
+ GroupingQueryParser.validate(query);
+ for (VespaGroupingStep step : parser.getGroupingSteps())
+ GroupingQueryParser.createGroupingRequestIn(query, step.getOperation(), step.continuations());
+
if (parser.getYqlSources().size() == 0) {
query.getModel().getSources().clear();
} else {
diff --git a/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java b/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java
index a149ae9323a..384be7798fa 100644
--- a/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java
+++ b/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java
@@ -106,7 +106,7 @@ public class YqlParser implements Parser {
public static final String ASCENDING_HITS_ORDER = "ascending";
private enum SegmentWhen {
- NEVER, POSSIBLY, ALWAYS;
+ NEVER, POSSIBLY, ALWAYS
}
private static class IndexNameExpander {
@@ -290,7 +290,7 @@ public class YqlParser implements Parser {
Preconditions.checkArgument(filterPart.getArguments().length == 2,
"Expected 2 arguments to filter, got %s.",
filterPart.getArguments().length);
- populateYqlSources(filterPart.<OperatorNode<?>> getArgument(0));
+ populateYqlSources(filterPart.getArgument(0));
OperatorNode<ExpressionOperator> filterExpression = filterPart.getArgument(1);
Item root = convertExpression(filterExpression);
connectItems();
@@ -617,6 +617,8 @@ public class YqlParser implements Parser {
// All terms below sameElement are relative to this.
IndexNameExpander prev = swapIndexCreator(new PrefixExpander(field));
for (OperatorNode<ExpressionOperator> term : ast.<List<OperatorNode<ExpressionOperator>>> getArgument(1)) {
+ // TODO getIndex that is called once every term is rather expensive as it does sanity checking
+ // that is not necessary. This is an issue when having many elements
sameElement.addItem(convertExpression(term));
}
swapIndexCreator(prev);
@@ -838,7 +840,7 @@ public class YqlParser implements Parser {
OperatorNode<?> ast = toScan;
while (ast.getOperator() == SequenceOperator.PIPE) {
OperatorNode<ExpressionOperator> groupingAst = ast.<List<OperatorNode<ExpressionOperator>>> getArgument(2).get(0);
- GroupingOperation groupingOperation = GroupingOperation.fromString(groupingAst.<String> getArgument(0));
+ GroupingOperation groupingOperation = GroupingOperation.fromString(groupingAst.getArgument(0));
VespaGroupingStep groupingStep = new VespaGroupingStep(groupingOperation);
List<Object> continuations = getAnnotation(groupingAst, "continuations", List.class,
Collections.emptyList(), "grouping continuations");
@@ -854,8 +856,7 @@ public class YqlParser implements Parser {
}
private String dereference(Object constantOrVarref) {
- if (constantOrVarref instanceof OperatorNode) {
- OperatorNode<?> varref = (OperatorNode<?>)constantOrVarref;
+ if (constantOrVarref instanceof OperatorNode<?> varref) {
Preconditions.checkState(userQuery != null,
"properties must be available when trying to fetch user input");
return userQuery.properties().getString(varref.getArgument(0, String.class));
@@ -871,7 +872,7 @@ public class YqlParser implements Parser {
List<FieldOrder> sortingInit = new ArrayList<>();
List<OperatorNode<?>> sortArguments = ast.getArgument(1);
for (OperatorNode<?> op : sortArguments) {
- OperatorNode<ExpressionOperator> fieldNode = op.<OperatorNode<ExpressionOperator>> getArgument(0);
+ OperatorNode<ExpressionOperator> fieldNode = op.getArgument(0);
String field = fetchFieldRead(fieldNode);
String locale = getAnnotation(fieldNode, SORTING_LOCALE, String.class, null,
"locale used by sorting function");
@@ -963,7 +964,7 @@ public class YqlParser implements Parser {
Preconditions.checkArgument(ast.getArguments().length == 2,
"Expected 2 arguments to PROJECT, got %s.",
ast.getArguments().length);
- populateYqlSummaryFields(ast.<List<OperatorNode<ProjectOperator>>> getArgument(1));
+ populateYqlSummaryFields(ast.getArgument(1));
return ast.getArgument(0);
}
@@ -1127,7 +1128,6 @@ public class YqlParser implements Parser {
return convertVarArgs(spec, 0, new OrItem());
}
- @SuppressWarnings("deprecation")
private CompositeItem buildWeakAnd(OperatorNode<ExpressionOperator> spec) {
WeakAndItem weakAnd = new WeakAndItem();
Integer targetNumHits = getAnnotation(spec, TARGET_HITS,
@@ -1175,7 +1175,7 @@ public class YqlParser implements Parser {
if (userQuery != null && indexFactsSession.getIndex(field).isAttribute()) {
userQuery.trace("Field '" + field + "' is an attribute, 'contains' will only match exactly (unless fuzzy is used)", 2);
}
- return instantiateLeafItem(field, ast.<OperatorNode<ExpressionOperator>> getArgument(1));
+ return instantiateLeafItem(field, ast.getArgument(1));
}
private Item buildRegExpSearch(OperatorNode<ExpressionOperator> ast) {
@@ -1468,7 +1468,7 @@ public class YqlParser implements Parser {
wordItem = new WordItem(wordData, fromQuery);
break;
case POSSIBLY:
- if (shouldSegment(field, ast, fromQuery) && ! grammar.equals(USER_INPUT_RAW)) {
+ if (shouldSegment(field, fromQuery) && ! grammar.equals(USER_INPUT_RAW)) {
wordItem = segment(field, ast, wordData, fromQuery, parent, language);
} else {
wordItem = new WordItem(wordData, fromQuery);
@@ -1489,7 +1489,7 @@ public class YqlParser implements Parser {
return (Item) leafStyleSettings(ast, wordItem);
}
- private boolean shouldSegment(String field, OperatorNode<ExpressionOperator> ast, boolean fromQuery) {
+ private boolean shouldSegment(String field, boolean fromQuery) {
return fromQuery && ! indexFactsSession.getIndex(indexNameExpander.expand(field)).isAttribute();
}
@@ -1584,8 +1584,7 @@ public class YqlParser implements Parser {
leaf.setWeight(weight);
}
}
- if (out instanceof IntItem) {
- IntItem number = (IntItem) out;
+ if (out instanceof IntItem number) {
Integer hitLimit = getCappedRangeSearchParameter(ast);
if (hitLimit != null) {
number.setHitLimit(hitLimit);
@@ -1822,7 +1821,7 @@ public class YqlParser implements Parser {
Object value = ast.getAnnotation(key);
for (Iterator<OperatorNode<?>> i = annotationStack.iterator(); value == null
&& considerParents && i.hasNext();) {
- OperatorNode node = i.next();
+ OperatorNode<?> node = i.next();
if (node.getOperator() == ExpressionOperator.VARREF) {
Preconditions.checkState(userQuery != null,
"properties must be available when trying to fetch user input");
@@ -1886,8 +1885,7 @@ public class YqlParser implements Parser {
@Override
public boolean visit(Item item) {
- if (item instanceof WordItem) {
- WordItem w = (WordItem) item;
+ if (item instanceof WordItem w) {
if (usePositionData != null) {
w.setPositionData(usePositionData);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/IndexFactsFactory.java b/container-search/src/test/java/com/yahoo/prelude/IndexFactsFactory.java
index 88cc066b665..482c9e3c6ba 100644
--- a/container-search/src/test/java/com/yahoo/prelude/IndexFactsFactory.java
+++ b/container-search/src/test/java/com/yahoo/prelude/IndexFactsFactory.java
@@ -23,6 +23,7 @@ public abstract class IndexFactsFactory {
}
+ @SuppressWarnings("deprecation")
private static <T extends ConfigInstance> T resolveConfig(Class<T> configClass, String configId) {
if (configId == null) return null;
return ConfigGetter.getConfig(configClass, configId);
diff --git a/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
index a09c2ff9b79..2b560713c57 100644
--- a/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
@@ -26,7 +26,7 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.vespa.config.search.DispatchConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -38,10 +38,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests cluster monitoring
@@ -53,7 +50,7 @@ public class ClusterSearcherTestCase {
private static final double DELTA = 0.0000000000000001;
@Test
- public void testNoBackends() {
+ void testNoBackends() {
ClusterSearcher cluster = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("dummy")));
try {
Execution execution = new Execution(cluster, Execution.Context.createContextStub());
@@ -87,7 +84,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatDocumentTypesAreResolved() {
+ void testThatDocumentTypesAreResolved() {
ClusterSearcher cluster1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type1", "type2", "type3")));
try {
ClusterSearcher type1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type6")));
@@ -126,12 +123,12 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatDocumentTypesAreResolvedTODO_REMOVE() {
- ClusterSearcher cluster1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type1", "type2", "type3")));
+ void testThatDocumentTypesAreResolvedTODO_REMOVE() {
+ ClusterSearcher cluster1 = new ClusterSearcher(new LinkedHashSet<>(List.of("type1", "type2", "type3")));
try {
- ClusterSearcher type1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type6")));
+ ClusterSearcher type1 = new ClusterSearcher(new LinkedHashSet<>(List.of("type6")));
try {
- assertEquals(new LinkedHashSet<>(Arrays.asList()), resolve(cluster1, "&sources=cluster2"));
+ assertEquals(new LinkedHashSet<>(List.of()), resolve(cluster1, "&sources=cluster2"));
} finally {
type1.deconstruct();
}
@@ -284,7 +281,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatSingleDocumentTypeCanBeSearched() {
+ void testThatSingleDocumentTypeCanBeSearched() {
{ // Explicit 1 type in restrict set
Execution execution = createExecution();
Query query = new Query("?query=hello&restrict=type1");
@@ -311,7 +308,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatSubsetOfDocumentTypesCanBeSearched() {
+ void testThatSubsetOfDocumentTypesCanBeSearched() {
Execution execution = createExecution();
Query query = new Query("?query=hello&restrict=type1,type3");
@@ -328,7 +325,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatMultipleDocumentTypesCanBeSearchedAndFilled() {
+ void testThatMultipleDocumentTypesCanBeSearchedAndFilled() {
Execution execution = createExecution();
Query query = new Query("?query=hello");
@@ -386,7 +383,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatWeCanSpecifyNumHitsAndHitOffset() {
+ void testThatWeCanSpecifyNumHitsAndHitOffset() {
Execution ex = createExecution();
// all types
@@ -411,7 +408,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatWeCanSpecifyNumHitsAndHitOffsetWhenSorting() {
+ void testThatWeCanSpecifyNumHitsAndHitOffsetWhenSorting() {
Execution ex = createExecution(true);
String extra = "&restrict=type1,type2&sorting=%2Basc-score";
@@ -485,7 +482,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatVipStatusIsSetUpForStreamingSearch() {
+ void testThatVipStatusIsSetUpForStreamingSearch() {
String clusterName = "test-cluster";
VipStatus vipStatus = new VipStatus(new QrSearchersConfig.Builder().searchcluster(new QrSearchersConfig.Searchcluster.Builder().name(clusterName)).build(), new ClustersStatus());
assertFalse(vipStatus.isInRotation());
@@ -494,7 +491,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsCappedWithDefaultMax() {
+ void testThatQueryTimeoutIsCappedWithDefaultMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(600001);
f.search();
@@ -502,7 +499,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsNotCapped() {
+ void testThatQueryTimeoutIsNotCapped() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(599999);
f.search();
@@ -510,7 +507,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsCappedWithSpecifiedMax() {
+ void testThatQueryTimeoutIsCappedWithSpecifiedMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(70.0, null);
f.query.setTimeout(70001);
f.search();
@@ -518,7 +515,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanMax() {
+ void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(10001);
f.query.getRanking().setQueryCache(true);
@@ -527,7 +524,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsNotDisabledIfTimeoutIsOk() {
+ void testThatQueryCacheIsNotDisabledIfTimeoutIsOk() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(10000);
f.query.getRanking().setQueryCache(true);
@@ -536,7 +533,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanConfiguredMax() {
+ void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanConfiguredMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, 5.0);
f.query.setTimeout(5001);
f.query.getRanking().setQueryCache(true);
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
index c39efe21e70..74874c28452 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
@@ -16,7 +16,7 @@ import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -27,12 +27,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class SlimeSummaryTestCase {
@@ -43,7 +38,7 @@ public class SlimeSummaryTestCase {
private static final String partial_summary3_cf = cf_pre + "partial-summary3.cfg";
@Test
- public void testDecodingEmpty() {
+ void testDecodingEmpty() {
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertNull(docsum.lazyDecode("default", emptySummary(), hit));
@@ -69,23 +64,23 @@ public class SlimeSummaryTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertEquals("Hit hit index:null/0/000000000000000000000000 (relevance 0.0) [fasthit, globalid: 0 0 0 0 0 0 0 0 0 0 0 0, partId: 0, distributionkey: 0] failed: Timed out....",
- docsum.lazyDecode("default", timeoutSummary(), hit));
+ docsum.lazyDecode("default", timeoutSummary(), hit));
}
@Test
- public void testDecoding() {
+ void testDecoding() {
Tensor tensor1 = Tensor.from("tensor(x{},y{}):{{x:foo,y:bar}:0.1}");
Tensor tensor2 = Tensor.from("tensor(x[1],y[1]):{{x:0,y:0}:-0.3}");
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertNull(docsum.lazyDecode("default", fullSummary(tensor1, tensor2), hit));
assertEquals(4, hit.getField("integer_field"));
- assertEquals((short)2, hit.getField("short_field"));
- assertEquals((byte)1, hit.getField("byte_field"));
+ assertEquals((short) 2, hit.getField("short_field"));
+ assertEquals((byte) 1, hit.getField("byte_field"));
assertEquals(4.5F, hit.getField("float_field"));
assertEquals(8.75, hit.getField("double_field"));
assertEquals(8L, hit.getField("int64_field"));
@@ -117,7 +112,7 @@ public class SlimeSummaryTestCase {
assertEquals(tensor2, hit.getField("tensor_field2"));
FeatureData featureData = hit.features();
assertEquals("double_feature,rankingExpression(tensor1_feature),tensor2_feature",
- featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
+ featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
assertEquals(0.5, featureData.getDouble("double_feature"), 0.00000001);
assertEquals(tensor1, featureData.getTensor("tensor1_feature"));
assertEquals(tensor1, featureData.getTensor("rankingExpression(tensor1_feature)"));
@@ -125,7 +120,7 @@ public class SlimeSummaryTestCase {
}
@Test
- public void testFieldAccessAPI() {
+ void testFieldAccessAPI() {
DocsumDefinitionSet partialDocsum1 = createPartialDocsumDefinitionSet1();
DocsumDefinitionSet partialDocsum2 = createPartialDocsumDefinitionSet2();
DocsumDefinitionSet partialDocsum3 = createPartialDocsumDefinitionSet3();
@@ -253,8 +248,8 @@ public class SlimeSummaryTestCase {
Tensor tensor2 = Tensor.from("tensor(x[1],y[1]):{{x:0,y:0}:-0.3}");
assertNull(fullDocsum.lazyDecode("default", fullishSummary(tensor1, tensor2), hit));
expected.put("integer_field", 4);
- expected.put("short_field", (short)2);
- expected.put("byte_field", (byte)1);
+ expected.put("short_field", (short) 2);
+ expected.put("byte_field", (byte) 1);
expected.put("float_field", 4.5f);
expected.put("double_field", 8.75d);
expected.put("int64_field", 8L);
@@ -303,7 +298,7 @@ public class SlimeSummaryTestCase {
for (Iterator<String> i = hit.fieldKeys().iterator(); i.hasNext(); ) {
fieldNameIteratorFieldCount++;
String name = i.next();
- assertTrue("Expected field " + name, expected.containsKey(name));
+ assertTrue(expected.containsKey(name), "Expected field " + name);
}
assertEquals(expected.size(), fieldNameIteratorFieldCount);
// fieldKeys
@@ -324,11 +319,10 @@ public class SlimeSummaryTestCase {
}
private void assertEqualMaps(Map<String, Object> expected, Map<String, Object> actual) {
- assertEquals("Map sizes", expected.size(), actual.size());
- assertEquals("Keys", expected.keySet(), actual.keySet());
+ assertEquals(expected.size(), actual.size(), "Map sizes");
+ assertEquals(expected.keySet(), actual.keySet(), "Keys");
for (var expectedEntry : expected.entrySet()) {
- assertEquals("Key '" + expectedEntry.getKey() + "'",
- expectedEntry.getValue(), actual.get(expectedEntry.getKey()));
+ assertEquals(expectedEntry.getValue(), actual.get(expectedEntry.getKey()), "Key '" + expectedEntry.getKey() + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
index da9d849db90..f07ef0f733b 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
@@ -15,15 +15,12 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.slime.BinaryFormat;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests docsum class functionality
@@ -33,7 +30,7 @@ import static org.junit.Assert.assertTrue;
public class DocsumDefinitionTestCase {
@Test
- public void testDecoding() {
+ void testDecoding() {
DocsumDefinitionSet set = createDocsumDefinitionSet();
FastHit hit = new FastHit();
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
index d5630063f4b..dbc827ea5c2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
@@ -30,7 +30,7 @@ import com.yahoo.search.schema.RankProfile;
import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -39,11 +39,7 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -54,20 +50,20 @@ import static org.junit.Assert.assertTrue;
public class FastSearcherTestCase {
@Test
- public void testNullQuery() {
+ void testNullQuery() {
Logger.getLogger(FastSearcher.class.getName()).setLevel(Level.ALL);
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(Collections.emptyList()),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(Collections.emptyList()),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
String query = "?junkparam=ignored";
Result result = doSearch(fastSearcher, new Query(query), 0, 10);
ErrorMessage message = result.hits().getError();
- assertNotNull("Got error", message);
+ assertNotNull(message, "Got error");
assertEquals("Null query", message.getMessage());
assertEquals(query, message.getDetailedMessage());
assertEquals(Error.NULL_QUERY.code, message.getCode());
@@ -90,13 +86,13 @@ public class FastSearcherTestCase {
}
@Test
- public void testSinglePassGroupingIsForcedWithSingleNodeGroups() {
+ void testSinglePassGroupingIsForcedWithSingleNodeGroups() {
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(List.of(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(List.of(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
Query q = new Query("?query=foo");
GroupingRequest request1 = GroupingRequest.newInstance(q);
request1.setRootOperation(new AllOperation());
@@ -113,32 +109,32 @@ public class FastSearcherTestCase {
}
@Test
- public void testRankProfileValidation() {
+ void testRankProfileValidation() {
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(List.of(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(List.of(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
assertFalse(searchError("?query=q", fastSearcher).contains("does not contain requested rank profile"));
assertFalse(searchError("?query=q&ranking.profile=default", fastSearcher).contains("does not contain requested rank profile"));
assertTrue(searchError("?query=q&ranking.profile=nosuch", fastSearcher).contains("does not contain requested rank profile"));
}
@Test
- public void testSummaryNeedsQuery() {
+ void testSummaryNeedsQuery() {
var documentDb = new DocumentdbInfoConfig(new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")));
var schema = new Schema.Builder("test")
- .add(new DocumentSummary.Builder("default").build())
- .add(new RankProfile.Builder("default").setHasRankFeatures(false)
- .setHasSummaryFeatures(false)
- .build());
+ .add(new DocumentSummary.Builder("default").build())
+ .add(new RankProfile.Builder("default").setHasRankFeatures(false)
+ .setHasSummaryFeatures(false)
+ .build());
FastSearcher backend = new FastSearcher("container.0",
- MockDispatcher.create(Collections.singletonList(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentDb,
- new SchemaInfo(List.of(schema.build()), Map.of()));
+ MockDispatcher.create(Collections.singletonList(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentDb,
+ new SchemaInfo(List.of(schema.build()), Map.of()));
Query q = new Query("?query=foo");
Result result = doSearch(backend, q, 0, 10);
assertFalse(backend.summaryNeedsQuery(q));
@@ -150,15 +146,15 @@ public class FastSearcherTestCase {
}
@Test
- public void testSinglePassGroupingIsNotForcedWithSingleNodeGroups() {
+ void testSinglePassGroupingIsNotForcedWithSingleNodeGroups() {
MockDispatcher dispatcher = MockDispatcher.create(ImmutableList.of(new Node(0, "host0", 0), new Node(2, "host1", 0)));
FastSearcher fastSearcher = new FastSearcher("container.0",
- dispatcher,
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ dispatcher,
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
Query q = new Query("?query=foo");
GroupingRequest request1 = GroupingRequest.newInstance(q);
request1.setRootOperation(new AllOperation());
@@ -180,14 +176,13 @@ public class FastSearcherTestCase {
}
private void assertForceSinglePassIs(boolean expected, GroupingOperation operation) {
- assertEquals("Force single pass is " + expected + " in " + operation,
- expected, operation.getForceSinglePass());
+ assertEquals(expected, operation.getForceSinglePass(), "Force single pass is " + expected + " in " + operation);
for (GroupingOperation child : operation.getChildren())
assertForceSinglePassIs(expected, child);
}
@Test
- public void testDispatchReconfig() {
+ void testDispatchReconfig() {
String clusterName = "a";
var b = new QrSearchersConfig.Builder();
var searchClusterB = new QrSearchersConfig.Searchcluster.Builder();
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
index 45ae8241696..f73edfec4c5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
@@ -12,16 +12,13 @@ import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author havardpe
@@ -50,7 +47,7 @@ public class PartialFillTestCase {
}
@Test
- public void testPartitioning() {
+ void testPartitioning() {
FS4 fs4 = new FS4();
Query a = new Query("/?query=foo");
Query b = new Query("/?query=bar");
@@ -107,7 +104,7 @@ public class PartialFillTestCase {
}
@Test
- public void testMergeErrors() {
+ void testMergeErrors() {
BadFS4 fs4 = new BadFS4();
Query a = new Query("/?query=foo");
Query b = new Query("/?query=bar");
@@ -129,17 +126,17 @@ public class PartialFillTestCase {
assertNotNull(eh);
ErrorMessage exp_sub = ErrorMessage.createUnspecifiedError("error");
int n = 0;
- for (Iterator<? extends com.yahoo.search.result.ErrorMessage> i = eh.errorIterator(); i.hasNext();) {
+ for (Iterator<? extends com.yahoo.search.result.ErrorMessage> i = eh.errorIterator(); i.hasNext(); ) {
com.yahoo.search.result.ErrorMessage error = i.next();
switch (n) {
- case 0:
- assertEquals(exp_sub, error);
- break;
- case 1:
- assertEquals(exp_sub, error);
- break;
- default:
- assertTrue(false);
+ case 0:
+ assertEquals(exp_sub, error);
+ break;
+ case 1:
+ assertEquals(exp_sub, error);
+ break;
+ default:
+ assertTrue(false);
}
n++;
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
index f35c45e7ad6..bf020b5ca84 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
@@ -2,71 +2,71 @@
package com.yahoo.prelude.hitfield;
import com.yahoo.data.access.simple.Value;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class XmlRendererTestCase {
@Test
- public void testWeightedSet1() {
+ void testWeightedSet1() {
Value.ArrayValue top = new Value.ArrayValue();
top
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("paal"))
- .add(new Value.LongValue(20)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("espen"))
- .add(new Value.LongValue(30)));
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.LongValue(10)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("paal"))
+ .add(new Value.LongValue(20)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("espen"))
+ .add(new Value.LongValue(30)));
String rendered = XmlRenderer.render(new StringBuilder(), top).toString();
String correct = "\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " ";
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " ";
assertEquals(correct, rendered);
}
@Test
- public void testWeightedSet2() {
+ void testWeightedSet2() {
Value.ObjectValue top = new Value.ObjectValue();
top
- .put("foo", new Value.ArrayValue()
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("paal"))
- .add(new Value.LongValue(20)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("espen"))
- .add(new Value.LongValue(30))))
- .put("bar", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("item",new Value.StringValue("per"))
- .put("weight",new Value.LongValue(10)))
- .add(new Value.ObjectValue()
- .put("item",new Value.StringValue("paal"))
- .put("weight",new Value.LongValue(20)))
- .add(new Value.ObjectValue()
- .put("weight",new Value.LongValue(30))
- .put("item",new Value.StringValue("espen"))));
+ .put("foo", new Value.ArrayValue()
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.LongValue(10)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("paal"))
+ .add(new Value.LongValue(20)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("espen"))
+ .add(new Value.LongValue(30))))
+ .put("bar", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("item", new Value.StringValue("per"))
+ .put("weight", new Value.LongValue(10)))
+ .add(new Value.ObjectValue()
+ .put("item", new Value.StringValue("paal"))
+ .put("weight", new Value.LongValue(20)))
+ .add(new Value.ObjectValue()
+ .put("weight", new Value.LongValue(30))
+ .put("item", new Value.StringValue("espen"))));
String rendered = XmlRenderer.render(new StringBuilder(), top).toString();
String correct = "\n"
- + " <struct-field name=\"foo\">\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"bar\">\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " </struct-field>\n"
- + " ";
+ + " <struct-field name=\"foo\">\n"
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"bar\">\n"
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " </struct-field>\n"
+ + " ";
assertEquals(correct, rendered);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
index 7c264f40388..f6b3ee65d12 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
@@ -5,10 +5,10 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.prelude.hitfield.HitField;
-import com.yahoo.prelude.hitfield.StringFieldPart;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import com.yahoo.prelude.hitfield.StringFieldPart;
+import org.junit.jupiter.api.Test;
/**
* Tests the HitField class
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class HitFieldTestCase {
@Test
- public void testHitField() {
+ void testHitField() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
List l = new ArrayList();
@@ -32,7 +32,7 @@ public class HitFieldTestCase {
}
@Test
- public void testCjk() {
+ void testCjk() {
HitField hf = new HitField("boo", "hmm\u001fgr");
assertEquals(2, hf.getTokenizedContent().size());
assertEquals("hmmgr", hf.getContent());
@@ -44,7 +44,7 @@ public class HitFieldTestCase {
}
@Test
- public void testAnnotateField() {
+ void testAnnotateField() {
HitField hf = new HitField("boo", "The <hi>Eclipse</hi> SDK \uFFF9include\uFFFAincludes\uFFFB the <hi>Eclipse</hi> Platform");
assertEquals(11, hf.getTokenizedContent().size());
hf = new HitField("boo", "\uFFF9include\uFFFAincludes\uFFFB the <hi>Eclipse</hi> Platform");
@@ -72,7 +72,7 @@ public class HitFieldTestCase {
}
@Test
- public void testEmptyField() {
+ void testEmptyField() {
HitField hf = new HitField("boo", "");
assertEquals(0, hf.getTokenizedContent().size());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
index 256014b7df4..944e1e0a02f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
@@ -8,10 +8,10 @@ import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.Type;
import com.yahoo.slime.Slime;
import com.yahoo.slime.Cursor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the JSONString XML rendering.
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class JSONStringTestCase {
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
String json = "[[{\"as1\":[\"per\",\"paal\"],\"l1\":1122334455667788997,\"d1\":87.790001,\"i1\":7,\"al1\":[11223344556677881,11223344556677883],\"s1\":\"string\\n"
+ "espa\u00F1a\\n"
+ "wssf1.s1[0]\"},10],"
@@ -44,7 +44,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n" + "españa\n"
- + "wssf1.s1[0]</struct-field>\n" };
+ + "wssf1.s1[0]</struct-field>\n"};
String o2 = " <item weight=\"20\">\n";
String[] o2Fields = {
" <struct-field name=\"l1\">1122334455667788998</struct-field>\n",
@@ -59,7 +59,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n"
- + "españa wssf1.s1[1]</struct-field>\n" };
+ + "españa wssf1.s1[1]</struct-field>\n"};
String rendered = js.toString();
int o1Offset = rendered.indexOf(o1);
assertTrue(-1 < o1Offset);
@@ -72,88 +72,88 @@ public class JSONStringTestCase {
}
@Test
- public void testWeightedSetFromInspector() {
+ void testWeightedSetFromInspector() {
Value.ArrayValue top = new Value.ArrayValue();
top.add(new Value.ArrayValue()
.add(new Value.ObjectValue()
- .put("d1", new Value.DoubleValue(87.790001))
- .put("s1", new Value.StringValue("string\n" + "espa\u00F1a\n" + "wssf1.s1[0]"))
- .put("al1", new Value.ArrayValue()
- .add(new Value.LongValue(11223344556677881L))
- .add(new Value.LongValue(11223344556677883L)))
- .put("l1", new Value.LongValue(1122334455667788997L))
- .put("as1", new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.StringValue("paal")))
- .put("i1", new Value.LongValue(7)))
+ .put("d1", new Value.DoubleValue(87.790001))
+ .put("s1", new Value.StringValue("string\n" + "espa\u00F1a\n" + "wssf1.s1[0]"))
+ .put("al1", new Value.ArrayValue()
+ .add(new Value.LongValue(11223344556677881L))
+ .add(new Value.LongValue(11223344556677883L)))
+ .put("l1", new Value.LongValue(1122334455667788997L))
+ .put("as1", new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.StringValue("paal")))
+ .put("i1", new Value.LongValue(7)))
.add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("d1", new Value.DoubleValue(88.790001))
- .put("s1", new Value.StringValue("string\n" + "espa\u00F1a wssf1.s1[1]"))
- .put("al1", new Value.ArrayValue()
- .add(new Value.LongValue(11223344556677881L))
- .add(new Value.LongValue(11223344556677883L)))
- .put("l1", new Value.LongValue(1122334455667788998L))
- .put("as1", new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.StringValue("paal")))
- .put("i1", new Value.LongValue(8)))
- .add(new Value.LongValue(20)));
+ .add(new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("d1", new Value.DoubleValue(88.790001))
+ .put("s1", new Value.StringValue("string\n" + "espa\u00F1a wssf1.s1[1]"))
+ .put("al1", new Value.ArrayValue()
+ .add(new Value.LongValue(11223344556677881L))
+ .add(new Value.LongValue(11223344556677883L)))
+ .put("l1", new Value.LongValue(1122334455667788998L))
+ .put("as1", new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.StringValue("paal")))
+ .put("i1", new Value.LongValue(8)))
+ .add(new Value.LongValue(20)));
JSONString js = new JSONString(top);
String correct = "\n"
- + " <item weight=\"10\">\n"
- + " <struct-field name=\"d1\">87.790001</struct-field>\n"
- + " <struct-field name=\"s1\">string\n"
- + "espa\u00F1a\n"
- + "wssf1.s1[0]</struct-field>\n"
- + " <struct-field name=\"al1\">\n"
- + " <item>11223344556677881</item>\n"
- + " <item>11223344556677883</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"l1\">1122334455667788997</struct-field>\n"
- + " <struct-field name=\"as1\">\n"
- + " <item>per</item>\n"
- + " <item>paal</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"i1\">7</struct-field>\n"
- + " </item>\n"
- + " <item weight=\"20\">\n"
- + " <struct-field name=\"d1\">88.790001</struct-field>\n"
- + " <struct-field name=\"s1\">string\n"
- + "espa\u00F1a wssf1.s1[1]</struct-field>\n"
- + " <struct-field name=\"al1\">\n"
- + " <item>11223344556677881</item>\n"
- + " <item>11223344556677883</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"l1\">1122334455667788998</struct-field>\n"
- + " <struct-field name=\"as1\">\n"
- + " <item>per</item>\n"
- + " <item>paal</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"i1\">8</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item weight=\"10\">\n"
+ + " <struct-field name=\"d1\">87.790001</struct-field>\n"
+ + " <struct-field name=\"s1\">string\n"
+ + "espa\u00F1a\n"
+ + "wssf1.s1[0]</struct-field>\n"
+ + " <struct-field name=\"al1\">\n"
+ + " <item>11223344556677881</item>\n"
+ + " <item>11223344556677883</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"l1\">1122334455667788997</struct-field>\n"
+ + " <struct-field name=\"as1\">\n"
+ + " <item>per</item>\n"
+ + " <item>paal</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"i1\">7</struct-field>\n"
+ + " </item>\n"
+ + " <item weight=\"20\">\n"
+ + " <struct-field name=\"d1\">88.790001</struct-field>\n"
+ + " <struct-field name=\"s1\">string\n"
+ + "espa\u00F1a wssf1.s1[1]</struct-field>\n"
+ + " <struct-field name=\"al1\">\n"
+ + " <item>11223344556677881</item>\n"
+ + " <item>11223344556677883</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"l1\">1122334455667788998</struct-field>\n"
+ + " <struct-field name=\"as1\">\n"
+ + " <item>per</item>\n"
+ + " <item>paal</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"i1\">8</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.renderFromInspector());
top = new Value.ArrayValue();
top.add(new Value.ArrayValue()
.add(new Value.StringValue("s1"))
.add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("s2"))
- .add(new Value.LongValue(20)));
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("s2"))
+ .add(new Value.LongValue(20)));
js = new JSONString(top);
correct = "\n" +
- " <item weight=\"10\">s1</item>\n" +
- " <item weight=\"20\">s2</item>\n" +
- " ";
+ " <item weight=\"10\">s1</item>\n" +
+ " <item weight=\"20\">s2</item>\n" +
+ " ";
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testStruct() {
+ void testStruct() {
{
Value.ObjectValue top = new Value.ObjectValue();
top.put("d1", new Value.DoubleValue(81.790001))
@@ -184,7 +184,7 @@ public class JSONStringTestCase {
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
+ " </struct-field>\n",
- " <struct-field name=\"i1\">1</struct-field>\n" };
+ " <struct-field name=\"i1\">1</struct-field>\n"};
String rendered = js.renderFromInspector();
checkSubstrings(renderedFields, rendered);
@@ -213,7 +213,7 @@ public class JSONStringTestCase {
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
+ " </struct-field>\n",
- " <struct-field name=\"i1\">4</struct-field>\n " };
+ " <struct-field name=\"i1\">4</struct-field>\n "};
String rendered = js.renderFromInspector();
checkSubstrings(renderedFields, rendered);
@@ -299,7 +299,7 @@ public class JSONStringTestCase {
String[] renderedFields = {
" <struct-field name=\"nss1\">\n",
" <struct-field name=\"s2\">string españa\n"
- + "ssf8.s2</struct-field>\n " };
+ + "ssf8.s2</struct-field>\n "};
String nss1Fields[] = {
" <struct-field name=\"al1\">\n"
+ " <item>11223344556677881</item>\n"
@@ -310,7 +310,7 @@ public class JSONStringTestCase {
" <struct-field name=\"as1\">\n"
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
- + " </struct-field>\n" };
+ + " </struct-field>\n"};
checkSubstrings(renderedFields, rendered);
int nss1Offset = rendered.indexOf(renderedFields[0])
@@ -321,58 +321,58 @@ public class JSONStringTestCase {
}
@Test
- public void testMap() {
+ void testMap() {
String json = "[{\"key\":\"k1\",\"value\":\"v1\"},{\"key\":\"k2\",\"value\":\"v2\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item><key>k1</key><value>v1</value></item>\n"
- + " <item><key>k2</key><value>v2</value></item>\n ";
- assertEquals(correct,js.toString());
+ + " <item><key>k1</key><value>v1</value></item>\n"
+ + " <item><key>k2</key><value>v2</value></item>\n ";
+ assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "k1")
- .put("value", "v1"))
- .add(new Value.ObjectValue()
- .put("key", "k2")
- .put("value", "v2"));
+ .add(new Value.ObjectValue()
+ .put("key", "k1")
+ .put("value", "v1"))
+ .add(new Value.ObjectValue()
+ .put("key", "k2")
+ .put("value", "v2"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testWithData() {
- byte[] d1 = { (byte)0x41, (byte)0x42, (byte)0x43 };
- byte[] d2 = { (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x02 };
- byte[] d3 = { (byte)0x12, (byte)0x34 };
- byte[] d4 = { (byte)0xff, (byte)0x80, (byte)0x7f };
+ void testWithData() {
+ byte[] d1 = {(byte) 0x41, (byte) 0x42, (byte) 0x43};
+ byte[] d2 = {(byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x02};
+ byte[] d3 = {(byte) 0x12, (byte) 0x34};
+ byte[] d4 = {(byte) 0xff, (byte) 0x80, (byte) 0x7f};
Inspector top = new Value.ObjectValue()
- .put("simple", new Value.DataValue(d1))
- .put("array", new Value.ArrayValue()
- .add(new Value.DataValue(d2))
- .add(new Value.DataValue(d3))
- .add(new Value.DataValue(d4)));
+ .put("simple", new Value.DataValue(d1))
+ .put("array", new Value.ArrayValue()
+ .add(new Value.DataValue(d2))
+ .add(new Value.DataValue(d3))
+ .add(new Value.DataValue(d4)));
JSONString js = new JSONString(top);
String correct = "\n"
- + " <struct-field name=\"simple\">"
- + "<data length=\"3\" encoding=\"hex\">414243</data>"
- + "</struct-field>\n"
- + " <struct-field name=\"array\">\n"
- + " <item>"
- + "<data length=\"4\" encoding=\"hex\">00010002</data>"
- + "</item>\n"
- + " <item>"
- + "<data length=\"2\" encoding=\"hex\">1234</data>"
- + "</item>\n"
- + " <item>"
- + "<data length=\"3\" encoding=\"hex\">FF807F</data>"
- + "</item>\n"
- + " </struct-field>\n ";
+ + " <struct-field name=\"simple\">"
+ + "<data length=\"3\" encoding=\"hex\">414243</data>"
+ + "</struct-field>\n"
+ + " <struct-field name=\"array\">\n"
+ + " <item>"
+ + "<data length=\"4\" encoding=\"hex\">00010002</data>"
+ + "</item>\n"
+ + " <item>"
+ + "<data length=\"2\" encoding=\"hex\">1234</data>"
+ + "</item>\n"
+ + " <item>"
+ + "<data length=\"3\" encoding=\"hex\">FF807F</data>"
+ + "</item>\n"
+ + " </struct-field>\n ";
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfArray() {
+ void testArrayOfArray() {
String json = "[[\"c1\", 0], [\"c2\", 2, 3], [\"c3\", 3, 4, 5], [\"c4\", 4,5,6,7]]";
JSONString js = new JSONString(json);
Inspector outer = js.inspect();
@@ -402,48 +402,48 @@ public class JSONStringTestCase {
}
@Test
- public void testSimpleArrays() {
+ void testSimpleArrays() {
String json = "[1, 2, 3]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>1</item>\n"
- + " <item>2</item>\n"
- + " <item>3</item>\n ";
+ + " <item>1</item>\n"
+ + " <item>2</item>\n"
+ + " <item>3</item>\n ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(1).add(2).add(3);
+ .add(1).add(2).add(3);
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
json = "[1.0, 2.0, 3.0]";
js = new JSONString(json);
correct = "\n"
- + " <item>1.0</item>\n"
- + " <item>2.0</item>\n"
- + " <item>3.0</item>\n ";
+ + " <item>1.0</item>\n"
+ + " <item>2.0</item>\n"
+ + " <item>3.0</item>\n ";
assertEquals(correct, js.toString());
top = new Value.ArrayValue()
- .add(1.0).add(2.0).add(3.0);
+ .add(1.0).add(2.0).add(3.0);
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
json = "[\"a\", \"b\", \"c\"]";
correct = "\n"
- + " <item>a</item>\n"
- + " <item>b</item>\n"
- + " <item>c</item>\n ";
+ + " <item>a</item>\n"
+ + " <item>b</item>\n"
+ + " <item>c</item>\n ";
js = new JSONString(json);
assertEquals(correct, js.toString());
top = new Value.ArrayValue()
- .add("a").add("b").add("c");
+ .add("a").add("b").add("c");
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfStruct() {
+ void testArrayOfStruct() {
String json = "[{\"as1\":[\"per\",\"paal\"],"
+ "\"l1\":1122334455667788994,\"d1\":74.790001,"
+ "\"i1\":14,\"al1\":[11223344556677881,11223344556677883],\"s1\":\"string\\n"
@@ -465,7 +465,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n" + "españa\n"
- + "asf1[0].s1</struct-field>\n" };
+ + "asf1[0].s1</struct-field>\n"};
String separator = " </item>\n" + " <item>\n";
String[] o2Fields = {
" <struct-field name=\"l1\">1122334455667788995</struct-field>\n",
@@ -480,7 +480,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n"
- + "españa asf1[1].s1</struct-field>\n" };
+ + "españa asf1[1].s1</struct-field>\n"};
String rendered = js.toString();
int o2Offset = rendered.indexOf(separator);
@@ -535,153 +535,153 @@ public class JSONStringTestCase {
}
}
-/*** here is some json for you
-
- [{"asf":"here is 1st simple string field",
- "map":[{"key":"one key string","value":["one value string","embedded array"]},
- {"key":"two key string","value":["two value string","embedded array"]}],
- "sf2":"here is 2nd simple string field"},
- {"asf":"here is 3rd simple string field",
- "map":[{"key":"three key string","value":["three value string","embedded array"]},
- {"key":"four key string","value":["four value string","embedded array"]}],
- "sf2":"here is 4th simple string field"},
- ]
-
-***/
-
-/*** and here is some corresponding XML
-
- <item>
- <struct-field name="asf">here is 1st simple string field</struct-field>
- <struct-field name="map">
- <item><key>one key string</key><value>
- <item>one value string</item>
- <item>embedded array</item>
- </value></item>
- <item><key>two key string</key><value>
- <item>two value string</item>
- <item>embedded array</item>
- </value></item>
- </struct-field>
- <struct-field name="sf2">here is 2nd simple string field</struct-field>
- </item>
- <item>
- <struct-field name="asf">here is 3rd simple string field</struct-field>
- <struct-field name="map">
- <item><key>three key string</key><value>
- <item>three value string</item>
- <item>embedded array</item>
- </value></item>
- <item><key>four key string</key><value>
- <item>four value string</item>
- <item>embedded array</item>
- </value></item>
- </struct-field>
- <struct-field name="sf2">here is 4th simple string field</struct-field>
- </item>
-
-***/
+ /*** here is some json for you
+
+ [{"asf":"here is 1st simple string field",
+ "map":[{"key":"one key string","value":["one value string","embedded array"]},
+ {"key":"two key string","value":["two value string","embedded array"]}],
+ "sf2":"here is 2nd simple string field"},
+ {"asf":"here is 3rd simple string field",
+ "map":[{"key":"three key string","value":["three value string","embedded array"]},
+ {"key":"four key string","value":["four value string","embedded array"]}],
+ "sf2":"here is 4th simple string field"},
+ ]
+
+ ***/
+
+ /*** and here is some corresponding XML
+
+ <item>
+ <struct-field name="asf">here is 1st simple string field</struct-field>
+ <struct-field name="map">
+ <item><key>one key string</key><value>
+ <item>one value string</item>
+ <item>embedded array</item>
+ </value></item>
+ <item><key>two key string</key><value>
+ <item>two value string</item>
+ <item>embedded array</item>
+ </value></item>
+ </struct-field>
+ <struct-field name="sf2">here is 2nd simple string field</struct-field>
+ </item>
+ <item>
+ <struct-field name="asf">here is 3rd simple string field</struct-field>
+ <struct-field name="map">
+ <item><key>three key string</key><value>
+ <item>three value string</item>
+ <item>embedded array</item>
+ </value></item>
+ <item><key>four key string</key><value>
+ <item>four value string</item>
+ <item>embedded array</item>
+ </value></item>
+ </struct-field>
+ <struct-field name="sf2">here is 4th simple string field</struct-field>
+ </item>
+
+ ***/
@Test
- public void testArrayOfStructWithMap() {
+ void testArrayOfStructWithMap() {
String json = "[{\"asf\":\"here is 1st simple string field\",\"map\":[{\"key\":\"one key string\",\"value\":[\"one value string\",\"embedded array\"]},{\"key\":\"two key string\",\"value\":[\"two value string\",\"embedded array\"]}],\"sf2\":\"here is 2nd simple string field\"},{\"asf\":\"here is 3rd simple string field\",\"map\":[{\"key\":\"three key string\",\"value\":[\"three value string\",\"embedded array\"]},{\"key\":\"four key string\",\"value\":[\"four value string\",\"embedded array\"]}],\"sf2\":\"here is 4th simple string field\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
- + " <struct-field name=\"map\">\n"
- + " <item><key>one key string</key><value>\n"
- + " <item>one value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " <item><key>two key string</key><value>\n"
- + " <item>two value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
- + " </item>\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
- + " <struct-field name=\"map\">\n"
- + " <item><key>three key string</key><value>\n"
- + " <item>three value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " <item><key>four key string</key><value>\n"
- + " <item>four value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
+ + " <struct-field name=\"map\">\n"
+ + " <item><key>one key string</key><value>\n"
+ + " <item>one value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " <item><key>two key string</key><value>\n"
+ + " <item>two value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
+ + " </item>\n"
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
+ + " <struct-field name=\"map\">\n"
+ + " <item><key>three key string</key><value>\n"
+ + " <item>three value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " <item><key>four key string</key><value>\n"
+ + " <item>four value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("asf", "here is 1st simple string field")
- .put("map", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "one key string")
- .put("value", new Value.ArrayValue()
- .add("one value string")
- .add("embedded array")))
- .add(new Value.ObjectValue()
- .put("key", "two key string")
- .put("value", new Value.ArrayValue()
- .add("two value string")
- .add("embedded array"))))
- .put("sf2", "here is 2nd simple string field"))
- .add(new Value.ObjectValue()
- .put("asf", "here is 3rd simple string field")
- .put("map", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "three key string")
- .put("value", new Value.ArrayValue()
- .add("three value string")
- .add("embedded array")))
- .add(new Value.ObjectValue()
- .put("key", "four key string")
- .put("value", new Value.ArrayValue()
- .add("four value string")
- .add("embedded array"))))
- .put("sf2", "here is 4th simple string field"));
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 1st simple string field")
+ .put("map", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("key", "one key string")
+ .put("value", new Value.ArrayValue()
+ .add("one value string")
+ .add("embedded array")))
+ .add(new Value.ObjectValue()
+ .put("key", "two key string")
+ .put("value", new Value.ArrayValue()
+ .add("two value string")
+ .add("embedded array"))))
+ .put("sf2", "here is 2nd simple string field"))
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 3rd simple string field")
+ .put("map", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("key", "three key string")
+ .put("value", new Value.ArrayValue()
+ .add("three value string")
+ .add("embedded array")))
+ .add(new Value.ObjectValue()
+ .put("key", "four key string")
+ .put("value", new Value.ArrayValue()
+ .add("four value string")
+ .add("embedded array"))))
+ .put("sf2", "here is 4th simple string field"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfStructWithEmptyMap() {
+ void testArrayOfStructWithEmptyMap() {
String json = "[{\"asf\":\"here is 1st simple string field\",\"map\":[],\"sf2\":\"here is 2nd simple string field\"},{\"asf\":\"here is 3rd simple string field\",\"map\":[],\"sf2\":\"here is 4th simple string field\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
- + " <struct-field name=\"map\"></struct-field>\n"
- + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
- + " </item>\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
- + " <struct-field name=\"map\"></struct-field>\n"
- + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
+ + " <struct-field name=\"map\"></struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
+ + " </item>\n"
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
+ + " <struct-field name=\"map\"></struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("asf", "here is 1st simple string field")
- .put("map", new Value.ArrayValue())
- .put("sf2", "here is 2nd simple string field"))
- .add(new Value.ObjectValue()
- .put("asf", "here is 3rd simple string field")
- .put("map", new Value.ArrayValue())
- .put("sf2", "here is 4th simple string field"));
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 1st simple string field")
+ .put("map", new Value.ArrayValue())
+ .put("sf2", "here is 2nd simple string field"))
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 3rd simple string field")
+ .put("map", new Value.ArrayValue())
+ .put("sf2", "here is 4th simple string field"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
@@ -718,7 +718,7 @@ public class JSONStringTestCase {
}
@Test
- public void testInspectorToContentMapping() {
+ void testInspectorToContentMapping() {
String content1 = new JSONString(getSlime1()).getContent();
String content2 = new JSONString(getSlime2()).getContent();
String content3 = new JSONString(getSlime3()).getContent();
@@ -732,7 +732,7 @@ public class JSONStringTestCase {
}
@Test
- public void testContentToInspectorMapping() {
+ void testContentToInspectorMapping() {
Inspector value1 = new JSONString("").inspect();
Inspector value2 = new JSONString("foo").inspect();
Inspector value3 = new JSONString("\"foo\"").inspect();
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
index 4b59a31785a..1e689d95cee 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.prelude.hitfield.test;
import java.util.ListIterator;
import com.yahoo.prelude.hitfield.FieldPart;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.hitfield.HitField;
import com.yahoo.prelude.hitfield.StringFieldPart;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Tests the FieldTokenIterator class
@@ -18,35 +18,35 @@ import static org.junit.Assert.assertEquals;
public class TokenFieldIteratorTestCase {
@Test
- public void testTokenIteratorNext() {
+ void testTokenIteratorNext() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<?> l = hf.tokenIterator();
- FieldPart p = (FieldPart)l.next();
+ FieldPart p = (FieldPart) l.next();
assertEquals("hei", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("deg", p.getContent());
assertEquals(false, l.hasNext());
}
@Test
- public void testTokenIteratorPrevious() {
+ void testTokenIteratorPrevious() {
HitField hf = new HitField("boo", "hei paa");
ListIterator<?> l = hf.tokenIterator();
- FieldPart p = (FieldPart)l.next();
+ FieldPart p = (FieldPart) l.next();
assertEquals("hei", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.previous();
+ p = (FieldPart) l.previous();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.previous();
+ p = (FieldPart) l.previous();
assertEquals("hei", p.getContent());
}
@Test
- public void testTokenIteratorSet() {
+ void testTokenIteratorSet() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<FieldPart> l = hf.tokenIterator();
@@ -61,7 +61,7 @@ public class TokenFieldIteratorTestCase {
}
@Test
- public void testTokenIteratorAdd() {
+ void testTokenIteratorAdd() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<FieldPart> l = hf.tokenIterator();
@@ -76,7 +76,7 @@ public class TokenFieldIteratorTestCase {
}
@Test
- public void testTokenIteratorRemove() {
+ void testTokenIteratorRemove() {
HitField hf = new HitField("boo", "hei paa deg");
ListIterator<FieldPart> l = hf.tokenIterator();
l.next();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
index 657d7fb30bc..dccf471fb04 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -9,8 +10,7 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.search.Query;
@@ -23,14 +23,14 @@ import com.yahoo.search.Query;
public class ItemHelperTestCase {
@Test
- public final void testGetNumTerms() {
+ final void testGetNumTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c"));
assertEquals(3, helper.getNumTerms(q.getModel().getQueryTree().getRoot()));
}
@Test
- public final void testGetPositiveTerms() {
+ final void testGetPositiveTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c \"d e\" -f"));
List<IndexedItem> l = new ArrayList<>();
@@ -52,7 +52,7 @@ public class ItemHelperTestCase {
c = true;
}
}
- assertFalse("An item is missing.", (a & b & c & d) == false);
+ assertNotNull(false);
}
private String enc(String s) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
index 06808d2c8d5..17a4ce400ff 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.prelude.query;
import java.lang.reflect.Modifier;
-import static org.junit.Assert.*;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
import com.yahoo.search.Query;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
@@ -27,13 +27,13 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelVisibility() throws Exception {
+ final void testLabelVisibility() throws Exception {
assertTrue(Modifier.isPublic(Item.class.getMethod("setLabel", String.class).getModifiers()));
assertTrue(Modifier.isPublic(Item.class.getMethod("getLabel").getModifiers()));
}
@Test
- public final void testLabelAccess() {
+ final void testLabelAccess() {
Item item = new WordItem("word");
assertFalse(item.hasUniqueID());
assertNull(item.getLabel());
@@ -43,7 +43,7 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelDisclose() {
+ final void testLabelDisclose() {
LabelCatcher catcher = new LabelCatcher();
Item item = new WordItem("word");
item.disclose(catcher);
@@ -54,7 +54,7 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelEncode() {
+ final void testLabelEncode() {
Item w1 = new WordItem("w1");
Item w2 = new WordItem("w2");
Item w3 = new WordItem("w3");
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java
index 418d7121769..f25c858a6a4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -9,8 +9,7 @@ import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.regex.PatternSyntaxException;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.Item.ItemType;
/**
@@ -21,7 +20,7 @@ import com.yahoo.prelude.query.Item.ItemType;
public class ItemsCommonStuffTestCase {
@Test
- public void testLoops() {
+ void testLoops() {
AndSegmentItem as = new AndSegmentItem("farmyards", false, false);
boolean caught = false;
try {
@@ -58,7 +57,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIndexName() {
+ void testIndexName() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
a.addItem(w);
@@ -68,7 +67,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testBoundaries() {
+ void testBoundaries() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
boolean caught = false;
@@ -102,7 +101,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testRemoving() {
+ void testRemoving() {
AndItem other = new AndItem();
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
@@ -117,7 +116,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testGeneralMutability() {
+ void testGeneralMutability() {
AndItem a = new AndItem();
assertFalse(a.isLocked());
a.lock();
@@ -125,7 +124,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testCounting() {
+ void testCounting() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
WordItem v = new WordItem("bamse");
@@ -139,7 +138,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIteratorJuggling() {
+ void testIteratorJuggling() {
AndItem a = new AndItem();
WordItem w0 = new WordItem("nalle");
WordItem w1 = new WordItem("bamse");
@@ -168,7 +167,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIdStuff() {
+ void testIdStuff() {
Item i;
String expected = "i";
i = new ExactStringItem(expected);
@@ -187,7 +186,7 @@ public class ItemsCommonStuffTestCase {
i = new WeightedSetItem("nalle");
assertEquals(ItemType.WEIGHTEDSET, i.getItemType());
assertEquals("WEIGHTEDSET", i.getName());
- i = new AndSegmentItem("",false, false);
+ i = new AndSegmentItem("", false, false);
assertEquals(ItemType.AND, i.getItemType());
assertEquals("SAND", i.getName());
i = new WeakAndItem();
@@ -196,7 +195,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testEquivBuilding() {
+ void testEquivBuilding() {
WordItem w = new WordItem("nalle");
WordItem v = new WordItem("bamse");
w.setConnectivity(v, 1.0);
@@ -206,7 +205,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public final void testEquivBuildingFromCollection() {
+ final void testEquivBuildingFromCollection() {
WordItem w = new WordItem("nalle");
WordItem v = new WordItem("bamse");
w.setConnectivity(v, 1.0);
@@ -220,7 +219,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testSegment() {
+ void testSegment() {
AndSegmentItem as = new AndSegmentItem("farmyards", false, false);
assertFalse(as.isLocked());
WordItem firstItem = new WordItem("nalle");
@@ -253,20 +252,20 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testMarkersVsWords() {
+ void testMarkersVsWords() {
WordItem mw0 = MarkerWordItem.createEndOfHost();
WordItem mw1 = MarkerWordItem.createStartOfHost();
WordItem w0 = new WordItem("$");
WordItem w1 = new WordItem("^");
assertEquals(w0.getWord(), mw0.getWord());
assertEquals(w1.getWord(), mw1.getWord());
- assertFalse(mw0.equals(w0));
- assertTrue(mw0.equals(MarkerWordItem.createEndOfHost()));
- assertFalse(w1.hashCode() == mw1.hashCode());
+ assertNotEquals(mw0, w0);
+ assertEquals(mw0, MarkerWordItem.createEndOfHost());
+ assertNotNull(mw1.hashCode());
}
@Test
- public void testNumberBasics() {
+ void testNumberBasics() {
String expected = "12";
IntItem i = new IntItem(expected, "num");
assertEquals(expected, i.stringValue());
@@ -279,12 +278,12 @@ public class ItemsCommonStuffTestCase {
assertTrue(i.isStemmed());
assertFalse(i.isWords());
assertEquals(1, i.getNumWords());
- assertFalse(i.equals(new IntItem(expected3)));
- assertTrue(i.equals(new IntItem(expected3, "num")));
+ assertNotEquals(i, new IntItem(expected3));
+ assertEquals(i, new IntItem(expected3, "num"));
}
@Test
- public void testNullItemFailsProperly() {
+ void testNullItemFailsProperly() {
NullItem n = new NullItem();
n.setIndexName("nalle");
boolean caught = false;
@@ -311,7 +310,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testNearisNotAnd() {
+ void testNearisNotAnd() {
AndItem a = new AndItem();
NearItem n = new NearItem();
n.setDistance(2);
@@ -323,14 +322,14 @@ public class ItemsCommonStuffTestCase {
fill(n);
fill(n2);
fill(n3);
- assertFalse(a.hashCode() == n.hashCode());
- assertFalse(n.equals(a));
- assertTrue(n.equals(n2));
- assertFalse(n.equals(n3));
+ assertNotNull(n.hashCode());
+ assertNotEquals(n, a);
+ assertEquals(n, n2);
+ assertNotEquals(n, n3);
}
@Test
- public void testPhraseSegmentBasics() {
+ void testPhraseSegmentBasics() {
AndSegmentItem a = new AndSegmentItem("gnurk", "gurk", false, false);
fill(a);
a.lock();
@@ -352,7 +351,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testPhraseConnectivity() {
+ void testPhraseConnectivity() {
WordItem w = new WordItem("a");
PhraseItem p = new PhraseItem();
fill(p);
@@ -362,7 +361,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testBaseClassPhraseSegments() {
+ void testBaseClassPhraseSegments() {
PhraseSegmentItem p = new PhraseSegmentItem("g", false, true);
fill(p);
assertEquals(4, p.encode(ByteBuffer.allocate(5000)));
@@ -373,18 +372,18 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testTermTypeBasic() {
- assertFalse(TermType.AND.equals(TermType.DEFAULT));
- assertFalse(TermType.AND.equals(Integer.valueOf(10)));
- assertTrue(TermType.AND.equals(TermType.AND));
+ void testTermTypeBasic() {
+ assertNotEquals(TermType.AND, TermType.DEFAULT);
+ assertNotEquals(TermType.AND, Integer.valueOf(10));
+ assertEquals(TermType.AND, TermType.AND);
assertSame(AndItem.class, TermType.DEFAULT.createItemClass().getClass());
assertSame(CompositeItem.class, TermType.DEFAULT.getItemClass());
- assertFalse(TermType.AND.hashCode() == TermType.PHRASE.hashCode());
+ assertNotNull(TermType.PHRASE.hashCode());
assertEquals("term type 'not'", TermType.NOT.toString());
}
@Test
- public void testRegexp() {
+ void testRegexp() {
RegExpItem empty = new RegExpItem("a", true, "");
assertTrue(empty.isFromQuery());
assertTrue(empty.isStemmed());
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
index 3d16859a79d..ec2a69fb9b0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
@@ -1,18 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Keep CompositeTaggableItem, SimpleTaggableItem and TaggableSegmentItem in
@@ -22,11 +19,11 @@ import org.junit.Test;
*/
public class TaggableItemsTestCase {
- @Before
+ @BeforeEach
public void setUp() throws Exception {
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
}
@@ -97,7 +94,7 @@ public class TaggableItemsTestCase {
}
@Test
- public void requireSimilarAPIs() {
+ void requireSimilarAPIs() {
final Method[] composite = CompositeTaggableItem.class
.getDeclaredMethods();
final Method[] simple = SimpleTaggableItem.class.getDeclaredMethods();
@@ -123,7 +120,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetUniqueID() {
+ final void testSetUniqueID() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
assertFalse(p.hasUniqueID());
@@ -133,7 +130,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetConnectivity() {
+ final void testSetConnectivity() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
assertEquals(0.0d, p.getConnectivity(), 1e-9);
@@ -145,7 +142,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetSignificance() {
+ final void testSetSignificance() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
// unset
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
index 4f39e07f6d3..c246abb14da 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.WordAlternativesItem.Alternative;
/**
@@ -18,7 +18,7 @@ import com.yahoo.prelude.query.WordAlternativesItem.Alternative;
public class WordAlternativesItemTestCase {
@Test
- public final void testWordAlternativesItem() {
+ final void testWordAlternativesItem() {
List<Alternative> terms = new ArrayList<>();
List<Alternative> expected;
terms.add(new Alternative("1", 1.0));
@@ -35,7 +35,7 @@ public class WordAlternativesItemTestCase {
}
@Test
- public final void testSetAlternatives() {
+ final void testSetAlternatives() {
List<Alternative> terms = new ArrayList<>();
terms.add(new Alternative("1", 1.0));
terms.add(new Alternative("2", 1.0));
@@ -43,19 +43,19 @@ public class WordAlternativesItemTestCase {
terms.add(new Alternative("1", 1.5));
terms.add(new Alternative("2", 0.5));
w.setAlternatives(terms);
- assertTrue("Could not overwrite alternative",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 1.5));
- assertTrue("Old alternative unexpectedly removed",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("2") && a.exactness == 1.0));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 1.5),
+ "Could not overwrite alternative");
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("2") && a.exactness == 1.0),
+ "Old alternative unexpectedly removed");
assertEquals(2, w.getAlternatives().size());
terms.add(new Alternative("3", 0.5));
w.setAlternatives(terms);
- assertTrue("Could not add new term",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5),
+ "Could not add new term");
}
@Test
- public final void testAddTerm() {
+ final void testAddTerm() {
List<Alternative> terms = new ArrayList<>();
terms.add(new Alternative("1", 1.0));
terms.add(new Alternative("2", 1.0));
@@ -63,12 +63,12 @@ public class WordAlternativesItemTestCase {
w.addTerm("1", 0.1);
assertEquals(terms, w.getAlternatives());
w.addTerm("1", 2.0);
- assertTrue("Could not add new alternative",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 2.0));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 2.0),
+ "Could not add new alternative");
assertEquals(2, w.getAlternatives().size());
w.addTerm("3", 0.5);
- assertTrue("Could not add new term",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5),
+ "Could not add new term");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
index 5e19f2e2ae6..40911fd6e11 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser;
-import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test UnicodePropertyDump gives expected data.
@@ -17,7 +17,7 @@ import org.junit.Test;
public class UnicodePropertyDumpTestCase {
@Test
- public final void testMain() throws IOException {
+ final void testMain() throws IOException {
ByteArrayOutputStream toCheck;
PrintStream out;
toCheck = new ByteArrayOutputStream();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
index a662afcd51c..cda966f714f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
@@ -7,14 +7,14 @@ import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Check default index propagates correctly to the tokenizer.
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class ExactMatchAndDefaultIndexTestCase {
@Test
- public void testExactMatchTokenization() {
+ void testExactMatchTokenization() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index = new Index("testexact");
index.setExact(true, null);
@@ -39,7 +39,7 @@ public class ExactMatchAndDefaultIndexTestCase {
}
@Test
- public void testDefaultIndexSpecialChars() {
+ void testDefaultIndexSpecialChars() {
Query q = new Query("?query=" + enc("dog & cat") + "&default-index=textsearch");
assertEquals("WEAKAND(100) textsearch:dog textsearch:cat", q.getModel().getQueryTree().getRoot().toString());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
index 77d8b2b973e..bd6b2f1f21d 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
@@ -24,14 +24,11 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.language.process.SpecialTokens;
import com.yahoo.prelude.query.parser.TestLinguistics;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests query parsing.
@@ -41,562 +38,562 @@ import static org.junit.Assert.assertTrue;
public class ParseTestCase {
private final ParsingTester tester = new ParsingTester();
-
+
@Test
- public void testSimpleTermQuery() {
+ void testSimpleTermQuery() {
tester.assertParsed("foobar", "foobar", Query.Type.ANY);
}
@Test
- public void testTermWithIndexPrefix() {
+ void testTermWithIndexPrefix() {
tester.assertParsed("url:foobar",
- "url:foobar",
- Query.Type.ANY);
+ "url:foobar",
+ Query.Type.ANY);
}
@Test
- public void testTermWithCatalogAndIndexPrefix() {
+ void testTermWithCatalogAndIndexPrefix() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ANY);
}
@Test
- public void testMultipleTermsWithUTF8EncodingOred() {
+ void testMultipleTermsWithUTF8EncodingOred() {
tester.assertParsed("OR l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
- "l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
- Query.Type.ANY);
+ "l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
+ Query.Type.ANY);
}
@Test
- public void testMultipleTermsWithMultiplePrefixes() {
+ void testMultipleTermsWithMultiplePrefixes() {
tester.assertParsed("RANK (+bar -normal.title:foo -baz) url:foobar",
- "url:foobar +bar -normal.title:foo -baz", Query.Type.ANY);
+ "url:foobar +bar -normal.title:foo -baz", Query.Type.ANY);
}
@Test
- public void testSimpleQueryDefaultOr() {
+ void testSimpleQueryDefaultOr() {
tester.assertParsed("OR foobar foo bar baz", "foobar foo bar baz", Query.Type.ANY);
}
@Test
- public void testOrAndNot() {
+ void testOrAndNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy -foobaz +bar", Query.Type.ANY);
+ "foobar +baz foo -xyzzy -foobaz +bar", Query.Type.ANY);
}
@Test
- public void testSimpleOrNestedAnd() {
+ void testSimpleOrNestedAnd() {
tester.assertParsed("RANK (OR foo bar baz) foobar xyzzy",
- "foobar +(foo bar baz) xyzzy", Query.Type.ANY);
+ "foobar +(foo bar baz) xyzzy", Query.Type.ANY);
}
@Test
- public void testSimpleOrNestedNot() {
+ void testSimpleOrNestedNot() {
tester.assertParsed("+(OR foobar xyzzy) -(AND foo bar baz)",
- "foobar -(foo bar baz) xyzzy", Query.Type.ANY);
+ "foobar -(foo bar baz) xyzzy", Query.Type.ANY);
}
@Test
- public void testOrNotNestedAnd() {
+ void testOrNotNestedAnd() {
tester.assertParsed("RANK (+(AND baz (OR foo bar baz) bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotNestedNot() {
+ void testOrAndNotNestedNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -(AND foo bar baz) -foobaz) foobar foo",
- "foobar +baz foo -xyzzy -(foo bar baz) -foobaz +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy -(foo bar baz) -foobaz +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedAnd() {
+ void testOrMultipleNestedAnd() {
tester.assertParsed("RANK (AND (OR fo ba foba) (OR foz baraz)) foobar foo bar baz",
- "foobar +(fo ba foba) foo bar +(foz baraz) baz",
- Query.Type.ANY);
+ "foobar +(fo ba foba) foo bar +(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedNot() {
+ void testOrMultipleNestedNot() {
tester.assertParsed("+(OR foobar foo bar baz) -(AND fo ba foba) -(AND foz baraz)",
- "foobar -(fo ba foba) foo bar -(foz baraz) baz",
- Query.Type.ANY);
+ "foobar -(fo ba foba) foo bar -(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedAnd() {
+ void testOrAndNotMultipleNestedAnd() {
tester.assertParsed("RANK (+(AND baz (OR foo bar baz) (OR foz bazaz) bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +(foz bazaz) +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +(foz bazaz) +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedNot() {
+ void testOrAndNotMultipleNestedNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -(AND foo bar baz) -foobaz -(AND foz bazaz)) foobar foo",
- "foobar +baz foo -xyzzy -(foo bar baz) -foobaz -(foz bazaz) +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy -(foo bar baz) -foobaz -(foz bazaz) +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedAndNot() {
+ void testOrMultipleNestedAndNot() {
tester.assertParsed("RANK (+(AND (OR ffoooo bbaarr) (OR oof rab raboof)) -(AND fo ba foba) -(AND foz baraz)) foobar foo bar baz",
- "foobar -(fo ba foba) foo +(ffoooo bbaarr) bar +(oof rab raboof) -(foz baraz) baz",
- Query.Type.ANY);
+ "foobar -(fo ba foba) foo +(ffoooo bbaarr) bar +(oof rab raboof) -(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedAndNot() {
+ void testOrAndNotMultipleNestedAndNot() {
tester.assertParsed("RANK (+(AND (OR ffoooo bbaarr) (OR oof rab raboof) baz xyxyzzy) -(AND fo ba foba) -foo -bar -(AND foz baraz)) foobar",
- "foobar -(fo ba foba) -foo +(ffoooo bbaarr) -bar +(oof rab raboof) -(foz baraz) +baz +xyxyzzy",
- Query.Type.ANY);
+ "foobar -(fo ba foba) -foo +(ffoooo bbaarr) -bar +(oof rab raboof) -(foz baraz) +baz +xyxyzzy",
+ Query.Type.ANY);
}
@Test
- public void testExplicitPhrase() {
+ void testExplicitPhrase() {
Item root = tester.assertParsed("\"foo bar foobar\"", "\"foo bar foobar\"", Query.Type.ANY);
assertTrue(root instanceof PhraseItem);
- assertTrue(((PhraseItem)root).isExplicit());
+ assertTrue(((PhraseItem) root).isExplicit());
}
@Test
- public void testPhraseWithIndex() {
+ void testPhraseWithIndex() {
tester.assertParsed("normal.title:\"foo bar foobar\"",
- "normal.title:\"foo bar foobar\"", Query.Type.ANY);
+ "normal.title:\"foo bar foobar\"", Query.Type.ANY);
}
@Test
- public void testPhrasesAndTerms() {
+ void testPhrasesAndTerms() {
tester.assertParsed("OR \"foo bar foobar\" xyzzy \"baz gaz faz\"",
- "\"foo bar foobar\" xyzzy \"baz gaz faz\"", Query.Type.ANY);
+ "\"foo bar foobar\" xyzzy \"baz gaz faz\"", Query.Type.ANY);
}
@Test
- public void testPhrasesAndTermsWithOperators() {
+ void testPhrasesAndTermsWithOperators() {
tester.assertParsed("RANK (+(AND \"baz gaz faz\" bazar) -\"foo bar foobar\") foofoo xyzzy",
- "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar",
- Query.Type.ANY);
+ "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar",
+ Query.Type.ANY);
}
@Test
- public void testSimpleTermQueryDefaultAnd() {
+ void testSimpleTermQueryDefaultAnd() {
tester.assertParsed("foobar", "foobar", Query.Type.ALL);
}
@Test
- public void testTermWithCatalogAndIndexPrefixDefaultAnd() {
+ void testTermWithCatalogAndIndexPrefixDefaultAnd() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ALL);
}
@Test
- public void testMultipleTermsWithMultiplePrefixesDefaultAnd() {
+ void testMultipleTermsWithMultiplePrefixesDefaultAnd() {
tester.assertParsed("+(AND url:foobar bar) -normal.title:foo -baz",
- "url:foobar +bar -normal.title:foo -baz",
- Query.Type.ALL);
+ "url:foobar +bar -normal.title:foo -baz",
+ Query.Type.ALL);
}
@Test
- public void testSimpleQueryDefaultAnd() {
+ void testSimpleQueryDefaultAnd() {
tester.assertParsed("AND foobar foo bar baz", "foobar foo bar baz", Query.Type.ALL);
}
@Test
- public void testNotDefaultAnd() {
+ void testNotDefaultAnd() {
tester.assertParsed("+(AND foobar (OR foo bar baz) xyzzy) -(AND foz baraz bazar)",
- "foobar +(foo bar baz) xyzzy -(foz baraz bazar)",
- Query.Type.ALL);
+ "foobar +(foo bar baz) xyzzy -(foz baraz bazar)",
+ Query.Type.ALL);
}
@Test
- public void testSimpleTermQueryDefaultPhrase() {
+ void testSimpleTermQueryDefaultPhrase() {
tester.assertParsed("foobar",
- "foobar",
- Query.Type.PHRASE);
+ "foobar",
+ Query.Type.PHRASE);
}
@Test
- public void testSimpleQueryDefaultPhrase() {
+ void testSimpleQueryDefaultPhrase() {
Item root = tester.assertParsed("\"foobar foo bar baz\"",
- "foobar foo bar baz",
- Query.Type.PHRASE);
+ "foobar foo bar baz",
+ Query.Type.PHRASE);
assertTrue(root instanceof PhraseItem);
- assertFalse(((PhraseItem)root).isExplicit());
+ assertFalse(((PhraseItem) root).isExplicit());
}
@Test
- public void testMultipleTermsWithMultiplePrefixesDefaultPhrase() {
+ void testMultipleTermsWithMultiplePrefixesDefaultPhrase() {
tester.assertParsed("\"url foobar bar normal title foo baz\"",
- "url:foobar +bar -normal.title:foo -baz",
- Query.Type.PHRASE);
+ "url:foobar +bar -normal.title:foo -baz",
+ Query.Type.PHRASE);
}
@Test
- public void testOdd1() {
+ void testOdd1() {
tester.assertParsed("AND window print error", "+window.print() +error",
- Query.Type.ALL);
+ Query.Type.ALL);
}
@Test
- public void testOdd2() {
+ void testOdd2() {
tester.assertParsed("normal.title:kaboom", "normal.title:\"kaboom\"",
- Query.Type.ALL);
+ Query.Type.ALL);
}
@Test
- public void testOdd2Uppercase() {
+ void testOdd2Uppercase() {
tester.assertParsed("normal.title:KABOOM", "NORMAL.TITLE:\"KABOOM\"", Query.Type.ALL);
}
@Test
- public void testOdd3() {
+ void testOdd3() {
tester.assertParsed("AND foo (OR size.all:[200;300] date.all:512)",
"foo +(size.all:[200;300] date.all:512)", Query.Type.ALL);
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
tester.assertParsed(null, null, Query.Type.ALL);
}
@Test
- public void testEmptyQuery() {
+ void testEmptyQuery() {
tester.assertParsed(null, "", Query.Type.ALL);
}
@Test
- public void testNotOnly() {
+ void testNotOnly() {
tester.assertParsed(null, "-foobar", Query.Type.ALL);
}
@Test
- public void testMultipleNotsOnlt() {
+ void testMultipleNotsOnlt() {
tester.assertParsed(null, "-foo -bar -foobar", Query.Type.ALL);
}
@Test
- public void testOnlyNotComposite() {
+ void testOnlyNotComposite() {
tester.assertParsed(null, "-(foo bar baz)", Query.Type.ALL);
}
@Test
- public void testNestedCompositesDefaultOr() {
+ void testNestedCompositesDefaultOr() {
tester.assertParsed("RANK (OR foobar bar baz) foo xyzzy",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.ANY);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.ANY);
}
@Test
- public void testNestedCompositesDefaultAnd() {
+ void testNestedCompositesDefaultAnd() {
tester.assertParsed("AND foo (OR foobar bar baz) xyzzy",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.ALL);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.ALL);
}
@Test
- public void testNestedCompositesPhraseDefault() {
+ void testNestedCompositesPhraseDefault() {
tester.assertParsed("\"foo foobar bar baz xyzzy\"",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.PHRASE);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.PHRASE);
}
@Test
- public void testNumeric() {
+ void testNumeric() {
tester.assertParsed("34", "34", Query.Type.ANY);
}
@Test
- public void testGreaterNumeric() {
+ void testGreaterNumeric() {
tester.assertParsed("<454", "<454", Query.Type.ANY);
}
@Test
- public void testGreaterNumericWithIndex() {
- IntItem item = (IntItem)tester.assertParsed("score:<454", "score:<454", Query.Type.ANY);
+ void testGreaterNumericWithIndex() {
+ IntItem item = (IntItem) tester.assertParsed("score:<454", "score:<454", Query.Type.ANY);
assertEquals("score", item.getIndexName());
assertEquals(454L, item.getToLimit().number());
assertFalse(item.getToLimit().isInclusive());
}
@Test
- public void testSmallerNumeric() {
+ void testSmallerNumeric() {
tester.assertParsed(">454", ">454", Query.Type.ANY);
}
@Test
- public void testSmallerNumericWithIndex() {
- IntItem item = (IntItem)tester.assertParsed("score:>454", "score:>454", Query.Type.ANY);
+ void testSmallerNumericWithIndex() {
+ IntItem item = (IntItem) tester.assertParsed("score:>454", "score:>454", Query.Type.ANY);
assertEquals("score", item.getIndexName());
assertEquals(454L, item.getFromLimit().number());
assertFalse(item.getFromLimit().isInclusive());
}
@Test
- public void testFullRange() {
+ void testFullRange() {
tester.assertParsed("[34;454]", "[34;454]", Query.Type.ANY);
}
@Test
- public void testFullRangeLimit() {
+ void testFullRangeLimit() {
tester.assertParsed("[34;454;7]", "[34;454;7]", Query.Type.ANY);
tester.assertParsed("[34;454;-7]", "[34;454;-7]", Query.Type.ANY);
}
@Test
- public void testLowOpenRange() {
+ void testLowOpenRange() {
tester.assertParsed("[;454]", "[;454]", Query.Type.ANY);
}
@Test
- public void testHiOpenRange() {
+ void testHiOpenRange() {
tester.assertParsed("[34;]", "[34;]", Query.Type.ANY);
}
@Test
- public void testNumericWithIndex() {
+ void testNumericWithIndex() {
tester.assertParsed("document.size:[34;454]", "document.size:[34;454]", Query.Type.ANY);
}
@Test
- public void testMultipleNumeric() {
+ void testMultipleNumeric() {
tester.assertParsed("OR [34;454] <34", "[34;454] <34", Query.Type.ANY);
}
@Test
- public void testMultipleIntegerWithIndex() {
+ void testMultipleIntegerWithIndex() {
tester.assertParsed("OR document.size:[34;454] date:>1234567890",
- "document.size:[34;454] date:>1234567890", Query.Type.ANY);
+ "document.size:[34;454] date:>1234567890", Query.Type.ANY);
}
@Test
- public void testMixedNumericAndOtherTerms() {
+ void testMixedNumericAndOtherTerms() {
tester.assertParsed("RANK (AND document.size:<1024 xyzzy) foo date:>123456890",
- "foo +document.size:<1024 +xyzzy date:>123456890",
- Query.Type.ANY);
+ "foo +document.size:<1024 +xyzzy date:>123456890",
+ Query.Type.ANY);
}
@Test
- public void testEmptyPhrase() {
+ void testEmptyPhrase() {
tester.assertParsed("\"to be or not\"", "\"\"to be or not", Query.Type.ANY);
}
@Test
- public void testItemPhraseEmptyPhrase() {
+ void testItemPhraseEmptyPhrase() {
tester.assertParsed("RANK to \"or not to be\"", "+to\"or not to be\"\"\"", Query.Type.ANY);
}
@Test
- public void testSimpleQuery() {
+ void testSimpleQuery() {
tester.assertParsed("OR if am \"f g 4 2\" maybe", "if am \" f g 4 2\"\" maybe", Query.Type.ANY);
}
@Test
- public void testExcessivePluses() {
+ void testExcessivePluses() {
tester.assertParsed("+(AND other is nothing) -test",
- "++other +++++is ++++++nothing -test", Query.Type.ANY);
+ "++other +++++is ++++++nothing -test", Query.Type.ANY);
}
@Test
- public void testMinusAndPluses() {
+ void testMinusAndPluses() {
tester.assertParsed(null, "--test+-if", Query.Type.ANY);
}
@Test
- public void testPlusesAndMinuses() {
+ void testPlusesAndMinuses() {
tester.assertParsed("AND a b c d d", "a+b+c+d--d", Query.Type.ANY);
}
@Test
- public void testNumbers() {
+ void testNumbers() {
tester.assertParsed("AND 123 2132odfd 934032 32423", "123+2132odfd.934032,,32423", Query.Type.ANY);
}
@Test
- public void testOtherSignsInQuote() {
+ void testOtherSignsInQuote() {
tester.assertParsed("AND 0032 4 320 24329043", "0032+4\\320.24329043", Query.Type.ANY);
}
@Test
- public void testGribberish() {
+ void testGribberish() {
tester.assertParsed("1349832840234l3040roer\u00e6lf12",
- ",1349832840234l3040roer\u00e6lf12",
- Query.Type.ANY);
+ ",1349832840234l3040roer\u00e6lf12",
+ Query.Type.ANY);
}
@Test
- public void testUrl() {
+ void testUrl() {
tester.assertParsed("AND www:www www:hotelaiguablava www:com",
- "+www:www.hotelaiguablava:com",
- Query.Type.ANY);
+ "+www:www.hotelaiguablava:com",
+ Query.Type.ANY);
}
@Test
- public void testUrlGribberish() {
+ void testUrlGribberish() {
tester.assertParsed("OR (AND 3 16) fast.type:lycosoffensive",
- "[ 3:16 fast.type:lycosoffensive",
- Query.Type.ANY);
+ "[ 3:16 fast.type:lycosoffensive",
+ Query.Type.ANY);
}
@Test
- public void testBracedWordAny() {
+ void testBracedWordAny() {
tester.assertParsed("foo", "(foo)", Query.Type.ANY);
}
@Test
- public void testBracedWordAll() {
+ void testBracedWordAll() {
tester.assertParsed("foo", "(foo)", Query.Type.ALL);
}
@Test
- public void testBracedWords() {
+ void testBracedWords() {
tester.assertParsed("OR (OR foo bar) (OR xyzzy foobar)",
"(foo bar) (xyzzy foobar)", Query.Type.ANY);
}
@Test
- public void testNullAdvanced() {
+ void testNullAdvanced() {
tester.assertParsed(null, null, Query.Type.ADVANCED);
}
@Test
- public void testEmptyAdvanced() {
+ void testEmptyAdvanced() {
tester.assertParsed(null, "", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAdvanced() {
+ void testSimpleAdvanced() {
tester.assertParsed("foobar", "foobar", Query.Type.ADVANCED);
}
@Test
- public void testPrefixAdvanced() {
+ void testPrefixAdvanced() {
tester.assertParsed("url:foobar", "url:foobar", Query.Type.ADVANCED);
}
@Test
- public void testPrefixWithDotAdvanced() {
+ void testPrefixWithDotAdvanced() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ADVANCED);
}
@Test
- public void testUTF8Advanced() {
+ void testUTF8Advanced() {
tester.assertParsed("m\u00fcnchen", "m\u00fcnchen", Query.Type.ADVANCED);
}
@Test
- public void testSimplePhraseAdvanced() {
+ void testSimplePhraseAdvanced() {
tester.assertParsed("\"foo bar foobar\"", "\"foo bar foobar\"", Query.Type.ADVANCED);
}
@Test
- public void testSimplePhraseWithIndexAdvanced() {
+ void testSimplePhraseWithIndexAdvanced() {
tester.assertParsed("normal.title:\"foo bar foobar\"",
- "normal.title:\"foo bar foobar\"",
- Query.Type.ADVANCED);
+ "normal.title:\"foo bar foobar\"",
+ Query.Type.ADVANCED);
}
@Test
- public void testMultiplePhrasesAdvanced() {
+ void testMultiplePhrasesAdvanced() {
tester.assertParsed("AND \"foo bar foobar\" \"baz gaz faz\"",
- "\"foo bar foobar\" and \"baz gaz faz\"",
- Query.Type.ADVANCED);
+ "\"foo bar foobar\" and \"baz gaz faz\"",
+ Query.Type.ADVANCED);
}
@Test
- public void testNumberAdvanced() {
+ void testNumberAdvanced() {
tester.assertParsed("34", "34", Query.Type.ADVANCED);
}
@Test
- public void testLargerNumberAdvanced() {
+ void testLargerNumberAdvanced() {
tester.assertParsed("<454", "<454", Query.Type.ADVANCED);
}
@Test
- public void testLesserNumberAdvanced() {
+ void testLesserNumberAdvanced() {
tester.assertParsed(">454", ">454", Query.Type.ADVANCED);
}
@Test
- public void testRangeAdvanced() {
+ void testRangeAdvanced() {
tester.assertParsed("[34;454]", "[34;454]", Query.Type.ADVANCED);
}
@Test
- public void testLowOpenRangeAdvanced() {
+ void testLowOpenRangeAdvanced() {
tester.assertParsed("[;454]", "[;454]", Query.Type.ADVANCED);
}
@Test
- public void testHighOpenRangeAdvanced() {
+ void testHighOpenRangeAdvanced() {
tester.assertParsed("[34;]", "[34;]", Query.Type.ADVANCED);
}
@Test
- public void testIdexedRangeAdvanced() {
+ void testIdexedRangeAdvanced() {
tester.assertParsed("document.size:[34;454]", "document.size:[34;454]", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAndAdvanced() {
+ void testSimpleAndAdvanced() {
tester.assertParsed("AND foo bar", "foo and bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleOrAdvanced() {
+ void testSimpleOrAdvanced() {
tester.assertParsed("OR foo bar", "foo or bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAndNotAdvanced() {
+ void testSimpleAndNotAdvanced() {
tester.assertParsed("+foo -bar", "foo andnot bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleRankAdvanced() {
+ void testSimpleRankAdvanced() {
tester.assertParsed("RANK foo bar", "foo rank bar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleAndAdvanced() {
+ void testMultipleAndAdvanced() {
tester.assertParsed("AND foo bar foobar", "foo and bar and foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleOrAdvanced() {
+ void testMultipleOrAdvanced() {
tester.assertParsed("OR foo bar foobar", "foo or bar or foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleAndnotAdvanced() {
+ void testMultipleAndnotAdvanced() {
tester.assertParsed("+foo -bar -foobar", "foo andnot bar andnot foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleRankAdvanced() {
+ void testMultipleRankAdvanced() {
tester.assertParsed("RANK foo bar foobar", "foo rank bar rank foobar", Query.Type.ADVANCED);
}
@Test
- public void testMixedAdvanced() {
+ void testMixedAdvanced() {
tester.assertParsed("OR (AND foo bar) foobar", "foo and bar or foobar", Query.Type.ADVANCED);
}
@Test
- public void testNestedAdvanced() {
+ void testNestedAdvanced() {
tester.assertParsed("AND foo (OR bar foobar)", "foo and (bar or foobar)", Query.Type.ADVANCED);
}
@Test
- public void testMultipleNestedAdvanced() {
+ void testMultipleNestedAdvanced() {
tester.assertParsed("+(AND foo xyzzy) -(OR bar foobar)",
- "(foo and xyzzy) andnot (bar or foobar)", Query.Type.ADVANCED);
+ "(foo and xyzzy) andnot (bar or foobar)", Query.Type.ADVANCED);
}
@Test
- public void testDoubleNestedAdvanced() {
+ void testDoubleNestedAdvanced() {
tester.assertParsed("AND foo (OR bar (OR xyzzy foobar))",
- "foo and (bar or (xyzzy or foobar))", Query.Type.ADVANCED);
+ "foo and (bar or (xyzzy or foobar))", Query.Type.ADVANCED);
}
@Test
- public void testDeeplyAdvanced() {
+ void testDeeplyAdvanced() {
tester.assertParsed(
"AND foo (OR bar (OR (AND (AND baz (+(OR bazar zyxxy) -fozbaz)) (OR boz bozor) xyzzy) foobar))",
"foo and (bar or ((baz and ((bazar or zyxxy) andnot fozbaz)) and (boz or bozor) and xyzzy or foobar))",
@@ -604,7 +601,7 @@ public class ParseTestCase {
}
@Test
- public void testDeeplyAdvancedUppercase() {
+ void testDeeplyAdvancedUppercase() {
tester.assertParsed(
"AND FOO (OR BAR (OR (AND (AND BAZ (+(OR BAZAR ZYXXY) -FOZBAZ)) (OR BOZ BOZOR) XYZZY) FOOBAR))",
"FOO AND (BAR OR ((BAZ AND ((BAZAR OR ZYXXY) ANDNOT FOZBAZ)) AND (BOZ OR BOZOR) AND XYZZY OR FOOBAR))",
@@ -612,230 +609,230 @@ public class ParseTestCase {
}
@Test
- public void testAbortedIntegerRange() {
+ void testAbortedIntegerRange() {
tester.assertParsed("AND audio.audall:744 audio.audall:ph",
"+audio.audall:[744 +audio.audall:ph", Query.Type.ANY);
}
@Test
- public void testJunk() {
+ void testJunk() {
tester.assertParsed("+l -fast.type:offensive",
",;'/.<l:>? -fast.type:offensive", Query.Type.ALL);
}
@Test
- public void testOneTermPhraseWithIndex() {
+ void testOneTermPhraseWithIndex() {
tester.assertParsed("normal.title:foo", "normal.title:\"foo\"", Query.Type.ANY);
}
@Test
- public void testOneTermPhraseWithIndexAdvanced() {
+ void testOneTermPhraseWithIndexAdvanced() {
tester.assertParsed("normal.title:foo", "normal.title:\"foo\"", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect1Advanced() {
+ void testIncorrect1Advanced() {
tester.assertParsed("\"to be or not\"", "\"\"to be or not", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect2Advanced() {
+ void testIncorrect2Advanced() {
tester.assertParsed("AND to \"or not to be\"", "+to\"or not to be\"\"\"", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect3Advanced() {
+ void testIncorrect3Advanced() {
tester.assertParsed("AND if am \"f g 4 2\" maybe",
"if am \" f g 4 2\"\" maybe", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect4Advanced() {
+ void testIncorrect4Advanced() {
tester.assertParsed("AND other is nothing test",
"++other +++++is ++++++nothing -test", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase1Advanced() {
+ void testImplicitPhrase1Advanced() {
tester.assertParsed("AND test if", "--test+-if", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase2Advanced() {
+ void testImplicitPhrase2Advanced() {
tester.assertParsed("AND a b c d d", "a+b+c+d--d", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase3Advanced() {
+ void testImplicitPhrase3Advanced() {
tester.assertParsed("AND 123 2132odfd 934032 32423",
"123+2132odfd.934032,,32423", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase4Advanced() {
+ void testImplicitPhrase4Advanced() {
tester.assertParsed("AND 0032 4 320 24329043", "0032+4\\320.24329043", Query.Type.ADVANCED);
}
@Test
- public void testUtf8Advanced() {
+ void testUtf8Advanced() {
tester.assertParsed("1349832840234l3040roer\u00e6lf12",
",1349832840234l3040roer\u00e6lf12", Query.Type.ADVANCED);
}
@Test
- public void testOperatorSearchAdvanced() {
+ void testOperatorSearchAdvanced() {
tester.assertParsed("RANK (OR (AND and and) or andnot) rank",
"and and and or or or andnot rank rank", Query.Type.ADVANCED);
}
@Test
- public void testIncorrectParenthesisAdvanced() {
+ void testIncorrectParenthesisAdvanced() {
tester.assertParsed("AND foo bar", "foo and bar )", Query.Type.ADVANCED);
}
@Test
- public void testOpeningParenthesisOnlyAdvanced() {
+ void testOpeningParenthesisOnlyAdvanced() {
tester.assertParsed("AND foo (OR bar (AND foobar xyzzy))",
"(foo and (bar or (foobar and xyzzy", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWeight() {
+ void testSimpleWeight() {
tester.assertParsed("foo!150", "foo!", Query.Type.ANY);
}
@Test
- public void testMultipleWeight() {
+ void testMultipleWeight() {
tester.assertParsed("foo!250", "foo!!!", Query.Type.ANY);
}
@Test
- public void testExplicitWeight() {
+ void testExplicitWeight() {
tester.assertParsed("foo!200", "foo!200", Query.Type.ANY);
}
@Test
- public void testExplicitZeroWeight() {
+ void testExplicitZeroWeight() {
tester.assertParsed("foo!0", "foo!0", Query.Type.ANY);
}
@Test
- public void testSimplePhraseWeight() {
+ void testSimplePhraseWeight() {
tester.assertParsed("\"foo bar\"!150", "\"foo bar\"!", Query.Type.ANY);
}
@Test
- public void testSingleHyphen() {
+ void testSingleHyphen() {
tester.assertParsed("AND a b", "a-b", Query.Type.ALL);
}
@Test
- public void testUserCase() {
+ void testUserCase() {
tester.assertParsed("\"a a\"", "\"a- a-*\"", Query.Type.ALL);
}
@Test
- public void testMultiplePhraseWeight() {
+ void testMultiplePhraseWeight() {
tester.assertParsed("\"foo bar\"!250", "\"foo bar\"!!!", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseWeight() {
+ void testExplicitPhraseWeight() {
tester.assertParsed("\"foo bar\"!200", "\"foo bar\"!200", Query.Type.ANY);
}
@Test
- public void testUrlSubmodeHyphen() {
+ void testUrlSubmodeHyphen() {
assertTrue(ParsingTester.createIndexFacts().newSession(new Query()).getIndex("url.all").isUriIndex());
tester.assertParsed("url.all:\"www-microsoft com\"", "url.all:www-microsoft.com", Query.Type.ANY);
}
@Test
- public void testUrlSubmodeUnderscore() {
+ void testUrlSubmodeUnderscore() {
tester.assertParsed("url.all:\"www_microsoft com\"", "url.all:www_microsoft.com", Query.Type.ANY);
}
@Test
- public void testUrlSubmode() {
+ void testUrlSubmode() {
tester.assertParsed("host.all:\"www-microsoft com $\"", "host.all:www-microsoft.com", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoringHost() {
+ void testExplicitHostNameAnchoringHost() {
tester.assertParsed("host.all:\"^ www-microsoft com $\"", "host.all:^www-microsoft.com$", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoringSite() {
+ void testExplicitHostNameAnchoringSite() {
tester.assertParsed("site:\"^ www-microsoft com $\"", "site:^www-microsoft.com$", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoring() {
+ void testExplicitHostNameAnchoring() {
tester.assertParsed("host.all:\"^ http www krangaz-central com index html $\"",
"host.all:^http://www.krangaz-central.com/index.html$",
Query.Type.ANY);
}
@Test
- public void testExplicitHostAnchoringRemoval() {
+ void testExplicitHostAnchoringRemoval() {
tester.assertParsed("host.all:\"www-microsoft com\"",
"host.all:www-microsoft.com*", Query.Type.ANY);
}
@Test
- public void testQuery1Any() {
+ void testQuery1Any() {
tester.assertParsed("RANK (AND fast \"search engine\") kernel",
"+fast +\"search engine\" kernel", Query.Type.ANY);
}
@Test
- public void testQuery1Advanced() {
+ void testQuery1Advanced() {
tester.assertParsed("RANK (AND fast \"search engine\") kernel",
"+fast and \"search engine\" rank kernel", Query.Type.ADVANCED);
}
@Test
- public void testQuery2Any() {
+ void testQuery2Any() {
tester.assertParsed("+(OR title:car bmw) -z3", "title:car bmw -z3",
Query.Type.ANY);
}
@Test
- public void testQuery2Advanced() {
+ void testQuery2Advanced() {
tester.assertParsed("+(OR title:car bmw) -z3", "title:car or bmw andnot z3", Query.Type.ADVANCED);
}
@Test
- public void testQuery3All() {
+ void testQuery3All() {
tester.assertParsed("+(AND FAST search domain:no pagedepth:0) -title:phrase",
- "FAST search -title:phrase domain:no Pagedepth:0",
- Query.Type.ALL);
+ "FAST search -title:phrase domain:no Pagedepth:0",
+ Query.Type.ALL);
}
@Test
- public void testQuery4Advanced() {
+ void testQuery4Advanced() {
tester.assertParsed("AND (+(AND FAST search) -title:phrase) domain:no pagedepth:0",
- "FAST and search andnot title:phrase and domain:no and Pagedepth:0",
- Query.Type.ADVANCED);
+ "FAST and search andnot title:phrase and domain:no and Pagedepth:0",
+ Query.Type.ADVANCED);
}
@Test
- public void testQuery5Any() {
+ void testQuery5Any() {
tester.assertParsed("AND alltheweb fast search", "+alltheweb +fast +search", Query.Type.ANY);
}
@Test
- public void testQuery6Any() {
+ void testQuery6Any() {
tester.assertParsed("RANK (+(AND query language) -sql) search", "+query +language -sql search", Query.Type.ANY);
}
@Test
- public void testQuery7Any() {
+ void testQuery7Any() {
tester.assertParsed(
"+(AND alltheweb (OR search engine)) -(OR excite altavista)",
"(alltheweb and (search or engine)) andnot (excite or altavista)",
@@ -843,7 +840,7 @@ public class ParseTestCase {
}
@Test
- public void testQuery8Advanced() {
+ void testQuery8Advanced() {
tester.assertParsed(
"RANK (AND \"search engines\" \"query processing\") \"fast search\"",
"(\"search engines\" and \"query processing\") rank \"fast search\"",
@@ -851,132 +848,132 @@ public class ParseTestCase {
}
@Test
- public void testPStrangeAdvanced() {
+ void testPStrangeAdvanced() {
tester.assertParsed("AND AND r.s:jnl", "( AND +r.s:jnl) ", Query.Type.ADVANCED);
}
@Test
- public void testEmptyNestAdvanced() {
+ void testEmptyNestAdvanced() {
tester.assertParsed(null, "() ", Query.Type.ADVANCED);
}
@Test
- public void testNestedBeginningAdvanced() {
+ void testNestedBeginningAdvanced() {
tester.assertParsed("AND (OR a b) c", "(a or b) and c", Query.Type.ADVANCED);
}
@Test
- public void testNestedPositiveAny() {
+ void testNestedPositiveAny() {
tester.assertParsed("AND (OR a b) c", "+(a b) +c", Query.Type.ANY);
}
@Test
- public void testParseAdvancedQuery() {
+ void testParseAdvancedQuery() {
tester.assertParsed("AND joplin remediation r.s:jnl",
"(joplin and + and remediation and +r.s:jnl)",
Query.Type.ADVANCED);
}
@Test
- public void testSimpleDotPhraseAny() {
+ void testSimpleDotPhraseAny() {
tester.assertParsed("OR a (AND b c) d", "a b.c d", Query.Type.ANY);
}
@Test
- public void testSimpleHyphenPhraseAny() {
+ void testSimpleHyphenPhraseAny() {
tester.assertParsed("OR a (AND b c) d", "a b-c d", Query.Type.ANY);
}
@Test
- public void testAnotherSimpleDotPhraseAny() {
+ void testAnotherSimpleDotPhraseAny() {
tester.assertParsed("OR (AND a b) c d", "a.b c d", Query.Type.ANY);
}
@Test
- public void testYetAnotherSimpleDotPhraseAny() {
+ void testYetAnotherSimpleDotPhraseAny() {
tester.assertParsed("OR a b (AND c d)", "a b c.d", Query.Type.ANY);
}
@Test
- public void testVariousSeparatorsPhraseAny() {
+ void testVariousSeparatorsPhraseAny() {
tester.assertParsed("AND a b c d", "a-b.c%d", Query.Type.ANY);
}
@Test
- public void testDoublyMarkedPhraseAny() {
+ void testDoublyMarkedPhraseAny() {
tester.assertParsed("OR a \"b c\" d", "a \"b.c\" d", Query.Type.ANY);
}
@Test
- public void testPartlyDoublyMarkedPhraseAny() {
+ void testPartlyDoublyMarkedPhraseAny() {
tester.assertParsed("OR a \"b c d\"", "a \"b.c d\"", Query.Type.ANY);
}
@Test
- public void testIndexedDottedPhraseAny() {
+ void testIndexedDottedPhraseAny() {
tester.assertParsed("OR a (AND url:b url:c) d", "a url:b.c d", Query.Type.ANY);
}
@Test
- public void testIndexedPlusedPhraseAny() {
+ void testIndexedPlusedPhraseAny() {
tester.assertParsed("OR a (AND normal.title:b normal.title:c) d", "a normal.title:b+c d", Query.Type.ANY);
}
@Test
- public void testNestedNotAny() {
+ void testNestedNotAny() {
tester.assertParsed(
"RANK (+(OR normal.title:foobar (AND url:www url:pvv url:org)) -foo) a",
"a +(normal.title:foobar url:www.pvv.org) -foo", Query.Type.ANY);
}
@Test
- public void testDottedPhraseAdvanced() {
+ void testDottedPhraseAdvanced() {
tester.assertParsed("OR a (AND b c)", "a or b.c", Query.Type.ADVANCED);
}
@Test
- public void testHyphenPhraseAdvanced() {
+ void testHyphenPhraseAdvanced() {
tester.assertParsed("OR (AND a (AND b c)) d", "a and b-c or d", Query.Type.ADVANCED);
}
@Test
- public void testAnotherDottedPhraseAdvanced() {
+ void testAnotherDottedPhraseAdvanced() {
tester.assertParsed("OR (AND a b) c", "a.b or c", Query.Type.ADVANCED);
}
@Test
- public void testNottedDottedPhraseAdvanced() {
+ void testNottedDottedPhraseAdvanced() {
tester.assertParsed("+a -(AND c d)", "a andnot c.d", Query.Type.ADVANCED);
}
@Test
- public void testVariousSeparatorsPhraseAdvanced() {
+ void testVariousSeparatorsPhraseAdvanced() {
tester.assertParsed("AND a b c d", "a-b.c%d", Query.Type.ADVANCED);
}
@Test
- public void testDoublyPhrasedAdvanced() {
+ void testDoublyPhrasedAdvanced() {
tester.assertParsed("OR (AND a \"b c\") d", "a and \"b.c\" or d", Query.Type.ADVANCED);
}
@Test
- public void testPartlyDoublyPhrasedAdvanced() {
+ void testPartlyDoublyPhrasedAdvanced() {
tester.assertParsed("OR a \"b c d\"", "a or \"b.c d\"", Query.Type.ADVANCED);
}
@Test
- public void testNestedDottedPhraseAdvanced() {
+ void testNestedDottedPhraseAdvanced() {
tester.assertParsed("AND a (OR url:\"b c\" d)", "a and(url:\"b.c\" or d)", Query.Type.ADVANCED);
}
@Test
- public void testNestedPlussedPhraseAdvanced() {
+ void testNestedPlussedPhraseAdvanced() {
tester.assertParsed("AND (OR a (AND normal.title:b normal.title:c)) d",
"a or normal.title:b+c and d", Query.Type.ADVANCED);
}
@Test
- public void testNottedNestedDottedPhraseAdvanced() {
+ void testNottedNestedDottedPhraseAdvanced() {
tester.assertParsed(
"+(AND a (OR normal.title:foobar (AND url:www url:pvv url:org))) -foo",
"a and (normal.title:foobar or url:www.pvv.org) andnot foo",
@@ -984,570 +981,570 @@ public class ParseTestCase {
}
@Test
- public void testPlusedThenQuotedPhraseAny() {
+ void testPlusedThenQuotedPhraseAny() {
tester.assertParsed("\"a b c\"", "a+\"b c\"", Query.Type.ANY);
}
@Test
- public void testPlusedTwiceThenQuotedPhraseAny() {
+ void testPlusedTwiceThenQuotedPhraseAny() {
tester.assertParsed("AND a b c d", "a+b+\"c d\"", Query.Type.ANY);
}
@Test
- public void testPlusedThenQuotedPhraseAdvanced() {
+ void testPlusedThenQuotedPhraseAdvanced() {
tester.assertParsed("\"a b c\"", "a+\"b c\"", Query.Type.ADVANCED);
}
@Test
- public void testPhrasesInBraces() {
+ void testPhrasesInBraces() {
tester.assertParsed("AND url.domain:microsoft url.domain:com",
"+(url.domain:microsoft.com)", Query.Type.ALL);
}
@Test
- public void testDoublyPhrasedPhrasesInBraces() {
+ void testDoublyPhrasedPhrasesInBraces() {
tester.assertParsed("url.domain:\"microsoft com\"",
"+(url.domain:\"microsoft.com\")", Query.Type.ALL);
}
@Test
- public void testSinglePrefixTerm() {
+ void testSinglePrefixTerm() {
Item root = tester.assertParsed("prefix*", "prefix*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSingleSubstringTerm() {
+ void testSingleSubstringTerm() {
Item root = tester.assertParsed("*substring*", "*substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSingleSuffixTerm() {
+ void testSingleSuffixTerm() {
Item root = tester.assertParsed("*suffix", "*suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testPrefixAndWordTerms() {
+ void testPrefixAndWordTerms() {
Item root = tester.assertParsed("OR foo prefix* bar", "foo prefix* bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof PrefixItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof PrefixItem);
}
@Test
- public void testSubstringAndWordTerms() {
+ void testSubstringAndWordTerms() {
Item root = tester.assertParsed("OR foo *substring* bar", "foo *substring* bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof SubstringItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof SubstringItem);
}
@Test
- public void testSuffixAndWordTerms() {
+ void testSuffixAndWordTerms() {
Item root = tester.assertParsed("OR foo *suffix bar", "foo *suffix bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof SuffixItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof SuffixItem);
}
@Test
- public void testPhraseNotPrefix() {
+ void testPhraseNotPrefix() {
tester.assertParsed("OR foo (AND prefix bar)", "foo prefix*bar", Query.Type.ANY);
}
@Test
- public void testPhraseNotSubstring() {
+ void testPhraseNotSubstring() {
tester.assertParsed("OR foo (AND substring bar)", "foo *substring*bar", Query.Type.ANY);
}
@Test
- public void testPhraseNotSuffix() {
+ void testPhraseNotSuffix() {
tester.assertParsed("OR (AND foo suffix) bar", "foo*suffix bar", Query.Type.ANY);
}
@Test
- public void testIndexedPrefix() {
+ void testIndexedPrefix() {
Item root = tester.assertParsed("foo.bar:prefix*", "foo.bar:prefix*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testIndexedSubstring() {
+ void testIndexedSubstring() {
Item root = tester.assertParsed("foo.bar:*substring*", "foo.bar:*substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testIndexedSuffix() {
+ void testIndexedSuffix() {
Item root = tester.assertParsed("foo.bar:*suffix", "foo.bar:*suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testIndexedPhraseNotPrefix() {
+ void testIndexedPhraseNotPrefix() {
tester.assertParsed("AND foo.bar:prefix foo.bar:xyzzy", "foo.bar:prefix*xyzzy", Query.Type.ANY);
}
@Test
- public void testIndexedPhraseNotSubstring() {
+ void testIndexedPhraseNotSubstring() {
tester.assertParsed("AND foo.bar:substring foo.bar:xyzzy", "foo.bar:*substring*xyzzy", Query.Type.ANY);
}
@Test
- public void testIndexedPhraseNotSuffix() {
+ void testIndexedPhraseNotSuffix() {
tester.assertParsed("AND foo.bar:xyzzy foo.bar:suffix", "foo.bar:xyzzy*suffix", Query.Type.ANY);
}
@Test
- public void testPrefixWithWeight() {
+ void testPrefixWithWeight() {
Item root = tester.assertParsed("prefix*!200", "prefix*!200", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSubstringWithWeight() {
+ void testSubstringWithWeight() {
Item root = tester.assertParsed("*substring*!200", "*substring*!200", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSuffixWithWeight() {
+ void testSuffixWithWeight() {
Item root = tester.assertParsed("*suffix!200", "*suffix!200", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
/** Non existing index → and **/
@Test
- public void testNonIndexPhraseNotPrefix() {
+ void testNonIndexPhraseNotPrefix() {
tester.assertParsed("AND void prefix", "void:prefix*", Query.Type.ANY);
}
@Test
- public void testNonIndexPhraseNotSubstring() {
+ void testNonIndexPhraseNotSubstring() {
tester.assertParsed("AND void substring", "void:*substring*", Query.Type.ANY);
}
@Test
- public void testNonIndexPhraseNotSuffix() {
+ void testNonIndexPhraseNotSuffix() {
tester.assertParsed("AND void suffix", "void:*suffix", Query.Type.ANY);
}
/** Explicit phrase → remove '*' **/
@Test
- public void testExplicitPhraseNotPrefix() {
+ void testExplicitPhraseNotPrefix() {
tester.assertParsed("\"prefix bar\"", "\"prefix* bar\"", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseNotSubstring() {
+ void testExplicitPhraseNotSubstring() {
tester.assertParsed("\"substring bar\"", "\"*substring* bar\"", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseNotSuffix() {
+ void testExplicitPhraseNotSuffix() {
tester.assertParsed("\"suffix bar\"", "\"*suffix bar\"", Query.Type.ANY);
}
/** Extra star is ignored */
@Test
- public void testPrefixExtraStar() {
+ void testPrefixExtraStar() {
Item root = tester.assertParsed("prefix*", "prefix**", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSubstringExtraStar() {
+ void testSubstringExtraStar() {
Item root = tester.assertParsed("*substring*", "**substring**", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSuffixExtraStar() {
+ void testSuffixExtraStar() {
Item root = tester.assertParsed("*suffix", "**suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testPrefixExtraSpace() {
+ void testPrefixExtraSpace() {
Item root = tester.assertParsed("prefix", "prefix *", Query.Type.ANY);
assertTrue(root instanceof WordItem);
}
@Test
- public void testSubstringExtraSpace() {
+ void testSubstringExtraSpace() {
Item root = tester.assertParsed("*substring*", "* substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSubstringExtraSpace2() {
+ void testSubstringExtraSpace2() {
Item root = tester.assertParsed("*substring", "* substring *", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testSuffixExtraSpace() {
+ void testSuffixExtraSpace() {
Item root = tester.assertParsed("*suffix", "* suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
/** Extra spaces with index **/
@Test
- public void testIndexPrefixExtraSpace() {
+ void testIndexPrefixExtraSpace() {
tester.assertParsed("AND foo prefix", "foo:prefix *", Query.Type.ANY);
}
@Test
- public void testIndexSubstringExtraSpace() {
+ void testIndexSubstringExtraSpace() {
Item root = tester.assertParsed("OR foo substring*", "foo:* substring*", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof PrefixItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof PrefixItem);
}
@Test
- public void testIndexSubstringExtraSpace2() {
+ void testIndexSubstringExtraSpace2() {
Item root = tester.assertParsed("OR foo substring", "foo:* substring *", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof WordItem);
}
@Test
- public void testIndexSuffixExtraSpace() {
+ void testIndexSuffixExtraSpace() {
Item root = tester.assertParsed("OR foo suffix", "foo:* suffix", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof WordItem);
}
/** Various tests for prefix, substring, and suffix terms **/
@Test
- public void testTermsWithStarsAndSpaces() {
+ void testTermsWithStarsAndSpaces() {
tester.assertParsed("OR foo *bar", "foo * bar", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndSpaces2() {
+ void testTermsWithStarsAndSpaces2() {
tester.assertParsed("OR foo *bar *baz", "foo * * bar * * baz", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndPlussAndMinus() {
+ void testTermsWithStarsAndPlussAndMinus() {
tester.assertParsed("+(AND *bar baz*) -*foo*", "+*bar -*foo* +baz*", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndPlussAndMinus2() {
+ void testTermsWithStarsAndPlussAndMinus2() {
tester.assertParsed("OR *bar *foo baz", "+ * bar - * foo * + baz *", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndExclamation() {
+ void testTermsWithStarsAndExclamation() {
tester.assertParsed("OR foo* 200 *bar* 200 *baz 200", "foo* !200 *bar* !200 *baz !200", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndExclamation2() {
+ void testTermsWithStarsAndExclamation2() {
tester.assertParsed("OR foo 200 *bar 200", "foo *!200 *bar *!200", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndParenthesis() {
+ void testTermsWithStarsAndParenthesis() {
tester.assertParsed("RANK *baz *bar* foo*", "(foo*) (*bar*) (*baz)", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndParenthesis2() {
+ void testTermsWithStarsAndParenthesis2() {
tester.assertParsed("RANK baz bar foo", "(foo)* *(bar)* *(baz)", Query.Type.ANY);
}
@Test
- public void testSimpleAndFilter() {
+ void testSimpleAndFilter() {
tester.assertParsed("AND bar |foo", "bar", "+foo", Query.Type.ANY);
}
@Test
- public void testSimpleRankFilter() {
+ void testSimpleRankFilter() {
tester.assertParsed("RANK bar |foo", "bar", "foo", Query.Type.ANY);
}
@Test
- public void testSimpleNotFilter() {
+ void testSimpleNotFilter() {
tester.assertParsed("+bar -|foo", "bar", "-foo", Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter1() {
+ void testSimpleCompoundFilter1() {
tester.assertParsed("RANK (AND bar |foo1) |foo2", "bar", "+foo1 foo2",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter2() {
+ void testSimpleCompoundFilter2() {
tester.assertParsed("+(AND bar |foo1) -|foo3", "bar", "+foo1 -foo3",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter3() {
+ void testSimpleCompoundFilter3() {
tester.assertParsed("RANK (+bar -|foo3) |foo2", "bar", "foo2 -foo3",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter4() {
+ void testSimpleCompoundFilter4() {
tester.assertParsed("RANK (+(AND bar |foo1) -|foo3) |foo2", "bar",
"+foo1 foo2 -foo3", Query.Type.ANY);
}
@Test
- public void testAndFilterEmptyQuery() {
+ void testAndFilterEmptyQuery() {
tester.assertParsed("|foo", "", "+foo", Query.Type.ANY);
}
@Test
- public void testRankFilterEmptyQuery() {
+ void testRankFilterEmptyQuery() {
tester.assertParsed("|foo", "", "foo", Query.Type.ANY);
}
@Test
- public void testNotFilterEmptyQuery() {
+ void testNotFilterEmptyQuery() {
tester.assertParsed(null, "", "-foo", Query.Type.ANY);
}
@Test
- public void testCompoundFilter1EmptyQuery() {
+ void testCompoundFilter1EmptyQuery() {
tester.assertParsed("RANK |foo1 |foo2", "", "+foo1 foo2", Query.Type.ANY);
}
@Test
- public void testCompoundFilter2EmptyQuery() {
+ void testCompoundFilter2EmptyQuery() {
tester.assertParsed("+|foo1 -|foo3", "", "+foo1 -foo3", Query.Type.ANY);
}
@Test
- public void testCompoundFilter3EmptyQuery() {
+ void testCompoundFilter3EmptyQuery() {
tester.assertParsed("+|foo2 -|foo3", "", "foo2 -foo3", Query.Type.ANY);
}
@Test
- public void testCompoundFilter4EmptyQuery() {
+ void testCompoundFilter4EmptyQuery() {
tester.assertParsed("RANK (+|foo1 -|foo3) |foo2", "", "+foo1 foo2 -foo3",
Query.Type.ANY);
}
@Test
- public void testMultitermAndFilter() {
+ void testMultitermAndFilter() {
tester.assertParsed("AND bar |foo |foz", "bar", "+foo +foz", Query.Type.ANY);
}
@Test
- public void testMultitermRankFilter() {
+ void testMultitermRankFilter() {
tester.assertParsed("RANK bar |foo |foz", "bar", "foo foz", Query.Type.ANY);
}
@Test
- public void testMultitermNotFilter() {
+ void testMultitermNotFilter() {
tester.assertParsed("+bar -|foo -|foz", "bar", "-foo -foz", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter1() {
+ void testMultitermCompoundFilter1() {
tester.assertParsed("RANK (AND bar |foo1 |foz1) |foo2 |foz2", "bar",
"+foo1 +foz1 foo2 foz2", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter2() {
+ void testMultitermCompoundFilter2() {
tester.assertParsed("+(AND bar |foo1 |foz1) -|foo3 -|foz3", "bar",
"+foo1 +foz1 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter3() {
+ void testMultitermCompoundFilter3() {
tester.assertParsed("RANK (+bar -|foo3 -|foz3) |foo2 |foz2", "bar",
"foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter4() {
+ void testMultitermCompoundFilter4() {
tester.assertParsed("RANK (+(AND bar |foo1 |foz1) -|foo3 -|foz3) |foo2 |foz2",
"bar", "+foo1 +foz1 foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermAndFilterEmptyQuery() {
+ void testMultitermAndFilterEmptyQuery() {
tester.assertParsed("AND |foo |foz", "", "+foo +foz", Query.Type.ANY);
}
@Test
- public void testMultitermRankFilterEmptyQuery() {
+ void testMultitermRankFilterEmptyQuery() {
tester.assertParsed("OR |foo |foz", "", "foo foz", Query.Type.ANY);
}
@Test
- public void testMultitermNotFilterEmptyQuery() {
+ void testMultitermNotFilterEmptyQuery() {
tester.assertParsed(null, "", "-foo -foz", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter1EmptyQuery() {
+ void testMultitermCompoundFilter1EmptyQuery() {
tester.assertParsed("RANK (AND |foo1 |foz1) |foo2 |foz2", "",
"+foo1 +foz1 foo2 foz2", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter2EmptyQuery() {
+ void testMultitermCompoundFilter2EmptyQuery() {
tester.assertParsed("+(AND |foo1 |foz1) -|foo3 -|foz3", "",
"+foo1 +foz1 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter3EmptyQuery() {
+ void testMultitermCompoundFilter3EmptyQuery() {
tester.assertParsed("+(OR |foo2 |foz2) -|foo3 -|foz3", "",
"foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter4EmptyQuery() {
+ void testMultitermCompoundFilter4EmptyQuery() {
tester.assertParsed("RANK (+(AND |foo1 |foz1) -|foo3 -|foz3) |foo2 |foz2", "",
"+foo1 +foz1 foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultipleDifferentPhraseSeparators() {
+ void testMultipleDifferentPhraseSeparators() {
tester.assertParsed("AND foo bar", "foo.-.bar", Query.Type.ANY);
}
@Test
- public void testNoisyFilter() {
+ void testNoisyFilter() {
tester.assertParsed("RANK (+(AND foobar kanoo) -|foo) |bar", "foobar and kanoo",
"-foo ;+;bar", Query.Type.ADVANCED);
}
@Test
- public void testReallyNoisyQuery1() {
+ void testReallyNoisyQuery1() {
tester.assertParsed("AND word another", "&word\"()/&#)(/&another!\"", Query.Type.ALL);
}
@Test
- public void testReallyNoisyQuery2() {
+ void testReallyNoisyQuery2() {
tester.assertParsed("AND \u03bc\u03bc hei", "&&&`\u00b5\u00b5=@hei", Query.Type.ALL);
}
@Test
- public void testReallyNoisyQuery3() {
+ void testReallyNoisyQuery3() {
tester.assertParsed("AND hei hallo du der", "hei-hallo;du;der", Query.Type.ALL);
}
@Test
- public void testNumberParsing() {
+ void testNumberParsing() {
Item root = tester.parseQuery("normal:400", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals(root.getCode(), 5);
}
@Test
- public void testRangeParsing() {
+ void testRangeParsing() {
Item root = tester.parseQuery("normal:[5;400]", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals(root.toString(), "normal:[5;400]");
assertEquals(root.getCode(), 5);
}
@Test
- public void testNumberAsPrefix() {
+ void testNumberAsPrefix() {
Item root = tester.assertParsed("89*", "89*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testNumberAsSubstring() {
+ void testNumberAsSubstring() {
Item root = tester.assertParsed("*89*", "*89*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testNumberAsSuffix() {
+ void testNumberAsSuffix() {
Item root = tester.assertParsed("*89", "*89", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testTheStupidSymbolsWhichAreNowWordCharactersInUnicode() {
+ void testTheStupidSymbolsWhichAreNowWordCharactersInUnicode() {
tester.assertParsed("AND yz a", "yz\u00A8\u00AA\u00AF", Query.Type.ANY);
}
@Test
- public void testTWoWords() {
+ void testTWoWords() {
tester.assertParsed("\"hei h\u00e5\"", "\"hei h\u00e5\"", Query.Type.ANY);
}
@Test
- public void testLoneStar() {
+ void testLoneStar() {
assertNull(tester.parseQuery("*", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE));
}
@Test
- public void testLoneStarWithFilter() {
+ void testLoneStarWithFilter() {
tester.assertParsed("|a", "*", "+a", Query.Type.ANY);
}
@Test
- public void testImplicitPhrasingWithIndex() {
+ void testImplicitPhrasingWithIndex() {
tester.assertParsed("AND a:b a:c", "a:/b/c", Query.Type.ANY);
}
@Test
- public void testSingleNoisyTermWithIndex() {
+ void testSingleNoisyTermWithIndex() {
tester.assertParsed("a:b", "a:/b", Query.Type.ANY);
}
@Test
- public void testSingleNoisyPhraseWithIndex() {
+ void testSingleNoisyPhraseWithIndex() {
tester.assertParsed("AND mail:yahoo mail:com", "mail:@yahoo.com", Query.Type.ANY);
}
@Test
- public void testPhraseWithWeightAndIndex() {
+ void testPhraseWithWeightAndIndex() {
tester.assertParsed("to:\"a b\"!150", "to:\"a b\"!150", Query.Type.ANY);
}
@Test
- public void testTermWithWeightAndIndex() {
+ void testTermWithWeightAndIndex() {
tester.assertParsed("to:a!150", "to:a!150", Query.Type.ANY);
}
@Test
- public void testPhrasingWithIndexAndQuerySyntax() {
+ void testPhrasingWithIndexAndQuerySyntax() {
tester.assertParsed("to:\"a b c\"", "to:\"a (b c)\"", Query.Type.ANY);
}
@Test
- public void testPhrasingWithIndexAndHalfBrokenQuerySyntax() {
+ void testPhrasingWithIndexAndHalfBrokenQuerySyntax() {
tester.assertParsed("to:\"a b c\"", "to:\"a +b c)\"", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm1() {
+ void testURLHostQueryOneTerm1() {
tester.assertParsed("site:\"com $\"", "site:com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm2() {
+ void testURLHostQueryOneTerm2() {
tester.assertParsed("site:com", "site:com*", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm3() {
+ void testURLHostQueryOneTerm3() {
tester.assertParsed("site:\"com $\"", "site:.com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm4() {
+ void testURLHostQueryOneTerm4() {
tester.assertParsed("site:\"^ com $\"", "site:^com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm5() {
+ void testURLHostQueryOneTerm5() {
tester.assertParsed("site:\"^ com\"", "site:^com*", Query.Type.ANY);
}
@Test
- public void testFullURLQuery() {
+ void testFullURLQuery() {
tester.assertParsed(
"url.all:\"http shopping yahoo-inc com 1080 this is a path shop d hab id 1804905709 frag1\"",
"url.all:http://shopping.yahoo-inc.com:1080/this/is/a/path/shop?d=hab&id=1804905709#frag1",
@@ -1555,7 +1552,7 @@ public class ParseTestCase {
}
@Test
- public void testURLQueryHyphen() {
+ void testURLQueryHyphen() {
tester.assertParsed(
"url.all:\"http news bbc co uk go rss test - sport1 hi tennis 4112866 stm\"",
"url.all:http://news.bbc.co.uk/go/rss/test/-/sport1/hi/tennis/4112866.stm",
@@ -1563,7 +1560,7 @@ public class ParseTestCase {
}
@Test
- public void testURLQueryUnderScoreNumber() {
+ void testURLQueryUnderScoreNumber() {
tester.assertParsed(
"url.all:\"ap 20050621 45_ap_on_re_la_am_ca aruba_missing_teen_5\"",
"url.all:/ap/20050621/45_ap_on_re_la_am_ca/aruba_missing_teen_5",
@@ -1571,7 +1568,7 @@ public class ParseTestCase {
}
@Test
- public void testOtherComplexUrls() {
+ void testOtherComplexUrls() {
tester.assertParsed(
"url.all:\"http redir folha com br redir online dinheiro rss091 http www1 folha uol com br folha dinheiro ult91u96593 shtml\"",
"url.all:http://redir.folha.com.br/redir/online/dinheiro/rss091/*http://www1.folha.uol.com.br/folha/dinheiro/ult91u96593.shtml",
@@ -1595,33 +1592,33 @@ public class ParseTestCase {
}
@Test
- public void testTooGreedyUrlParsing() {
+ void testTooGreedyUrlParsing() {
tester.assertParsed("AND site:\"nypost com $\" about", "site:nypost.com about",
Query.Type.ALL);
}
@Test
- public void testTooGreedyUrlParsing2() {
+ void testTooGreedyUrlParsing2() {
tester.assertParsed("AND site:\"nypost com $\" about foo",
"site:nypost.com about foo", Query.Type.ALL);
}
@Test
- public void testSimplerDurbin() {
+ void testSimplerDurbin() {
tester.assertParsed("+(OR language:en \"Durbin said\" a) -newstype:rssexclude",
"( a (\"Durbin said\" ) -newstype:rssexclude (language:en )",
Query.Type.ALL);
}
@Test
- public void testSimplerDurbin2() {
+ void testSimplerDurbin2() {
tester.assertParsed("+(AND \"Durbin said\" language:en) -newstype:rssexclude",
"( , (\"Durbin said\" ) -newstype:rssexclude (language:en )",
Query.Type.ALL);
}
@Test
- public void testDurbin() {
+ void testDurbin() {
tester.assertParsed(
"AND \"Richard Durbin\" Welfare (+(OR language:en \"Durbin said\" \"Durbin says\" \"Durbin added\" \"Durbin agreed\" \"Durbin questioned\" date:>1109664000) -newstype:rssexclude)",
"(\"Richard Durbin\" ) \"Welfare\" ((\"Durbin said\" \"Durbin says\" \"Durbin added\" \"Durbin agreed\" \"Durbin questioned\" ) -newstype:rssexclude date:>1109664000 (language:en )",
@@ -1629,35 +1626,35 @@ public class ParseTestCase {
}
@Test
- public void testTooLongQueryTerms() {
+ void testTooLongQueryTerms() {
tester.assertParsed("AND 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof filter ew 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof 2b 2f 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof",
"+/545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof&filter=ew:545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof!1000 =.2b..2f.545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof",
Query.Type.ALL);
}
@Test
- public void testNonSpecialTokenParsing() {
+ void testNonSpecialTokenParsing() {
ParsingTester customTester = new ParsingTester(SpecialTokens.empty());
customTester.assertParsed("OR c or c with (AND tcp ip)", "c# or c++ with tcp/ip", Query.Type.ANY);
}
@Test
- public void testNonIndexWithColons1() {
+ void testNonIndexWithColons1() {
tester.assertParsed("OR this is (AND notan iindex)", "this is notan:iindex", Query.Type.ANY);
}
@Test
- public void testNonIndexWithColons2() {
+ void testNonIndexWithColons2() {
tester.assertParsed("OR this is (AND notan iindex either)", "this is notan:iindex:either", Query.Type.ANY);
}
@Test
- public void testIndexThenUnderscoreTermBecomesIndex() {
+ void testIndexThenUnderscoreTermBecomesIndex() {
tester.assertParsed("AND name:batch name:article", "name:batch_article", Query.Type.ANY);
}
@Test
- public void testFakeCJKSegmenting() {
+ void testFakeCJKSegmenting() {
// "first" "second" and "third" are segments in the test language
Item item = tester.parseQuery("name:firstsecondthird", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
@@ -1675,7 +1672,7 @@ public class ParseTestCase {
}
@Test
- public void testFakeCJKSegmentingOfPhrase() {
+ void testFakeCJKSegmentingOfPhrase() {
// "first" "second" and "third" are segments in the test language
Item item = tester.parseQuery("name:\"firstsecondthird\"", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
@@ -1689,23 +1686,23 @@ public class ParseTestCase {
assertEquals("name", ((WordItem) segment.getItem(0)).getIndexName());
assertEquals("name", ((WordItem) segment.getItem(1)).getIndexName());
- assertEquals("name", ((WordItem)segment.getItem(2)).getIndexName());
+ assertEquals("name", ((WordItem) segment.getItem(2)).getIndexName());
}
@Test
- public void testAndItemAndImplicitPhrase() {
+ void testAndItemAndImplicitPhrase() {
tester.assertParsed("AND \u00d8 \u00d8 \u00d8 \u00d9",
- "\u00d8\u00b9\u00d8\u00b1\u00d8\u00a8\u00d9", "",
- Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
+ "\u00d8\u00b9\u00d8\u00b1\u00d8\u00a8\u00d9", "",
+ Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
}
@Test
- public void testAvoidMultiLevelAndForLongCJKQueries() {
+ void testAvoidMultiLevelAndForLongCJKQueries() {
Item root = tester.parseQuery(
"\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74",
"", Language.UNKNOWN, Query.Type.ALL, TestLinguistics.INSTANCE);
- assertTrue("Query tree too deep when parsing CJK queries.", 4 > stackDepth(0, root));
+ assertTrue(4 > stackDepth(0, root), "Query tree too deep when parsing CJK queries.");
}
private int stackDepth(int i, Item root) {
@@ -1724,151 +1721,151 @@ public class ParseTestCase {
}
@Test
- public void testFakeCJKSegmentingOfMultiplePhrases() {
+ void testFakeCJKSegmentingOfMultiplePhrases() {
Item item = tester.parseQuery("name:firstsecond.s", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals("AND (SAND name:first name:second) name:s", item.toString());
}
@Test
- public void testOrFilter() {
+ void testOrFilter() {
tester.assertParsed("AND d (OR |a |b)", "d", "+(a b)", Query.Type.ALL);
}
@Test
- public void testOrFilterWithTypeAdv() {
+ void testOrFilterWithTypeAdv() {
tester.assertParsed("AND d (OR |a |b)", "d", "+(a b)", Query.Type.ADVANCED);
}
@Test
- public void testPhraseFilter() {
+ void testPhraseFilter() {
tester.assertParsed("AND d |\"a b\"", "d", "+\"a b\"", Query.Type.ALL);
}
@Test
- public void testMinusAndFilter() {
+ void testMinusAndFilter() {
tester.assertParsed("+d -(AND |a |b)", "d", "-(a b)", Query.Type.ALL);
}
@Test
- public void testOrAndSomeTermsFilter() {
+ void testOrAndSomeTermsFilter() {
tester.assertParsed("RANK d |c |a |b |e", "d", "c (a b) e", Query.Type.ALL);
}
// This is an ugly parse tree, but it's at least reasonable
@Test
- public void testOrAndSomeTermsFilterAndAnAnd() {
- AndItem root=(AndItem)tester.assertParsed("AND (RANK d |c |a |b |e) (OR |e |f)", "d", "c (a b) e +(e f)", Query.Type.ALL);
+ void testOrAndSomeTermsFilterAndAnAnd() {
+ AndItem root = (AndItem) tester.assertParsed("AND (RANK d |c |a |b |e) (OR |e |f)", "d", "c (a b) e +(e f)", Query.Type.ALL);
assertFalse(root.isFilter()); // AND
assertFalse(root.getItem(0).isFilter()); // RANK
- assertFalse(((RankItem)root.getItem(0)).getItem(0).isFilter()); // d
- assertTrue(((RankItem)root.getItem(0)).getItem(1).isFilter()); // c
- assertTrue(((RankItem)root.getItem(0)).getItem(2).isFilter()); // a
- assertTrue(((RankItem)root.getItem(0)).getItem(3).isFilter()); // b
- assertTrue(((RankItem)root.getItem(0)).getItem(4).isFilter()); // e
+ assertFalse(((RankItem) root.getItem(0)).getItem(0).isFilter()); // d
+ assertTrue(((RankItem) root.getItem(0)).getItem(1).isFilter()); // c
+ assertTrue(((RankItem) root.getItem(0)).getItem(2).isFilter()); // a
+ assertTrue(((RankItem) root.getItem(0)).getItem(3).isFilter()); // b
+ assertTrue(((RankItem) root.getItem(0)).getItem(4).isFilter()); // e
assertFalse(root.getItem(1).isFilter()); // OR
- assertTrue(((OrItem)root.getItem(1)).getItem(0).isFilter()); // e
- assertTrue(((OrItem)root.getItem(1)).getItem(1).isFilter()); // f
+ assertTrue(((OrItem) root.getItem(1)).getItem(0).isFilter()); // e
+ assertTrue(((OrItem) root.getItem(1)).getItem(1).isFilter()); // f
}
@Test
- public void testUrlNotConsumingBrace() {
+ void testUrlNotConsumingBrace() {
tester.assertParsed("AND A (OR url.all:B url.all:C) D E", "A (url.all:B url.all:C) D E", Query.Type.ALL);
}
// Really a syntax error on part of the user, but it's part of
// the logic where balanced braces are allowed in URLs
@Test
- public void testUrlNotConsumingBrace2() {
+ void testUrlNotConsumingBrace2() {
tester.assertParsed("AND A (OR url.all:B url.all:C) D E",
"A (url.all:B url.all:C)D E", Query.Type.ALL);
}
@Test
- public void testSiteNotConsumingBrace() {
+ void testSiteNotConsumingBrace() {
tester.assertParsed("AND A (OR site:\"B $\" site:\"C $\") D E",
"A (site:B site:C) D E", Query.Type.ALL);
}
@Test
- public void testCommaOnlyLeadsToImplicitPhrasing() {
+ void testCommaOnlyLeadsToImplicitPhrasing() {
tester.assertParsed("AND A B C", "A,B,C", Query.Type.ALL);
}
@Test
- public void testBangDoesNotBindAcrossSpace() {
+ void testBangDoesNotBindAcrossSpace() {
tester.assertParsed("word", "word !", Query.Type.ALL);
}
@Test
- public void testLotsOfPlusMinus() {
+ void testLotsOfPlusMinus() {
tester.assertParsed("OR word term", "word - + - + - term", Query.Type.ANY);
}
@Test
- public void testLotsOfMinusPlus() {
+ void testLotsOfMinusPlus() {
tester.assertParsed("OR word term", "word - + - + term", Query.Type.ANY);
}
@Test
- public void testMinusDoesNotBindAcrossSpace() {
+ void testMinusDoesNotBindAcrossSpace() {
tester.assertParsed("OR word term", "word - term", Query.Type.ANY);
}
@Test
- public void testPlusDoesNotBindAcrossSpace() {
+ void testPlusDoesNotBindAcrossSpace() {
tester.assertParsed("OR word term", "word + term", Query.Type.ANY);
}
@Test
- public void testMinusDoesNotBindAcrossSpaceAllQuery() {
+ void testMinusDoesNotBindAcrossSpaceAllQuery() {
tester.assertParsed("AND word term", "word - term", Query.Type.ALL);
}
@Test
- public void testPlusDoesNotBindAcrossSpaceAllQuery() {
+ void testPlusDoesNotBindAcrossSpaceAllQuery() {
tester.assertParsed("AND word term", "word + term", Query.Type.ALL);
}
@Test
- public void testNoSpaceInIndexPrefix() {
+ void testNoSpaceInIndexPrefix() {
tester.assertParsed("AND url domain:s url.domain:b",
"url. domain:s url.domain:b", Query.Type.ALL);
}
@Test
- public void testNestedParensAndLittleElse() {
+ void testNestedParensAndLittleElse() {
tester.assertParsed("OR a b c d", "((a b) (c d))", Query.Type.ALL);
}
// This is simply to control it doesn't crash
@Test
- public void testNestedParensAndLittleElseMoreBroken() {
+ void testNestedParensAndLittleElseMoreBroken() {
tester.assertParsed("AND (OR a b) (OR c d)", "(a b) +(c d))", Query.Type.ALL);
}
@Test
- public void testNestedUnbalancedParensAndLittleElseMoreBroken() {
+ void testNestedUnbalancedParensAndLittleElseMoreBroken() {
tester.assertParsed("OR a b c d", "((a b) +(c d)", Query.Type.ALL);
}
@Test
- public void testUnbalancedParens() {
+ void testUnbalancedParens() {
tester.assertParsed("AND a b (OR c d)", "a b) +(c d))", Query.Type.ALL);
}
@Test
- public void testUnbalancedStartingParens() {
+ void testUnbalancedStartingParens() {
tester.assertParsed("OR a b c d", "((a b) +(c d", Query.Type.ALL);
}
@Test
- public void testJPMobileExceptionQuery() {
+ void testJPMobileExceptionQuery() {
tester.assertParsed("OR concat and (AND make string) 1 47 or",
- "(concat \"and\" (make-string 1 47) \"or\")", Query.Type.ALL);
+ "(concat \"and\" (make-string 1 47) \"or\")", Query.Type.ALL);
}
@Test
- public void testColonDoesNotBindAcrossSpace() {
+ void testColonDoesNotBindAcrossSpace() {
tester.assertParsed("b", "a: b", Query.Type.ALL);
tester.assertParsed("AND a b", "a : b", Query.Type.ALL);
tester.assertParsed("AND a b", "a :b", Query.Type.ALL);
@@ -1877,14 +1874,14 @@ public class ParseTestCase {
}
@Test
- public void testGermanUriDecompounding() {
+ void testGermanUriDecompounding() {
tester.assertParsed("url.all:\"kommunikationsfehler de\"",
- "url.all:kommunikationsfehler.de", "", Query.Type.ALL, Language.GERMAN);
+ "url.all:kommunikationsfehler.de", "", Query.Type.ALL, Language.GERMAN);
}
// Check the parser doesn't fail on these horrible query strings
@Test
- public void testTicket443882() {
+ void testTicket443882() {
tester.assertParsed(
"AND australian LOTTERY (+(OR language:en IN AFFILIATION WITH THE UK NATIONAL LOTTERY date:>1125475200) -newstype:rssexclude)",
"australian LOTTERY (IN AFFILIATION WITH THE UK NATIONAL LOTTERY -newstype:rssexclude date:>1125475200 (language:en )",
@@ -1900,7 +1897,7 @@ public class ParseTestCase {
}
@Test
- public void testParensInQuotes() {
+ void testParensInQuotes() {
tester.assertParsed("AND ringtone (OR a:\"Delivery SMAF large max 150kB 063\" a:\"RealMusic Delivery\")",
"ringtone AND (a:\"Delivery SMAF large max.150kB (063)\" OR a:\"RealMusic Delivery\" )",
Query.Type.ADVANCED);
@@ -1914,7 +1911,7 @@ public class ParseTestCase {
}
@Test
- public void testMixedCaseIndexNames() {
+ void testMixedCaseIndexNames() {
tester.assertParsed("AND mixedCase:a mixedCase:b notAnIndex c mixedCase:d",
"mixedcase:a MIXEDCASE:b notAnIndex:c mixedCase:d",
Query.Type.ALL);
@@ -1922,9 +1919,9 @@ public class ParseTestCase {
/** CJK special tokens should be recognized also on non-boundaries */
@Test
- public void testChineseSpecialTokens() {
+ void testChineseSpecialTokens() {
tester.assertParsed("AND cat tcp/ip zu foo dotnet bar dotnet dotnet c# c++ bar dotnet dotnet wiz",
- "cattcp/ipzu foo.netbar.net.netC#c++bar.net.netwiz","", Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
+ "cattcp/ipzu foo.netbar.net.netC#c++bar.net.netwiz", "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
}
/**
@@ -1932,69 +1929,69 @@ public class ParseTestCase {
* but right now it is not
*/
@Test
- public void testChineseSpecialTokensWithMultiSegmentReplace() {
+ void testChineseSpecialTokensWithMultiSegmentReplace() {
// special-token-fs is a special token, to be replaced by firstsecond, first and second are segments in test
- tester.assertParsed("AND tcp/ip firstsecond dotnet firstsecond (SAND first second)","tcp/ipspecial-token-fs.net special-token-fs firstsecond",
- "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, TestLinguistics.INSTANCE);
+ tester.assertParsed("AND tcp/ip firstsecond dotnet firstsecond (SAND first second)", "tcp/ipspecial-token-fs.net special-token-fs firstsecond",
+ "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, TestLinguistics.INSTANCE);
}
@Test
- public void testSpaceAndTermWeights() {
+ void testSpaceAndTermWeights() {
tester.assertParsed("AND yahoo!360 yahoo 360 yahoo!150 360 yahoo 360 yahoo yahoo!150 yahoo!200",
- "yahoo!360 yahoo !360 yahoo! 360 yahoo ! 360 yahoo !!! yahoo! ! yahoo!!", Query.Type.ALL);
+ "yahoo!360 yahoo !360 yahoo! 360 yahoo ! 360 yahoo !!! yahoo! ! yahoo!!", Query.Type.ALL);
}
@Test
- public void testNumbersAndNot() {
+ void testNumbersAndNot() {
tester.assertParsed("AND a -12", "a -12", Query.Type.ALL);
}
@Test
- public void testNumbersAndDoubleNot() {
+ void testNumbersAndDoubleNot() {
tester.assertParsed("+a --12", "a --12", Query.Type.ALL);
}
@Test
- public void testNegativeNumberWithIndex() {
+ void testNegativeNumberWithIndex() {
tester.assertParsed("normal:-12", "normal:-12", Query.Type.ALL);
}
@Test
- public void testNegativeTermPositiveNumberWithIndex() {
+ void testNegativeTermPositiveNumberWithIndex() {
tester.assertParsed("+a -normal:12", "a -normal:12", Query.Type.ALL);
}
@Test
- public void testNegativeTermNegativeNumberWithIndex() {
+ void testNegativeTermNegativeNumberWithIndex() {
tester.assertParsed("+a -normal:-12", "a -normal:-12", Query.Type.ALL);
}
@Test
- public void testNegativeTermPositiveNumberInParentheses() {
+ void testNegativeTermPositiveNumberInParentheses() {
tester.assertParsed("+a -12", "a -(12)", Query.Type.ALL);
tester.assertParsed("+a -(AND 12 15)", "a -(12 15)", Query.Type.ALL);
tester.assertParsed("+a -12 -15", "a -(12) -(15)", Query.Type.ALL);
}
@Test
- public void testSingleNegativeNumberLikeTerm() {
+ void testSingleNegativeNumberLikeTerm() {
tester.assertParsed("-12", "-12", Query.Type.ALL);
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
tester.assertParsed("normal:<-3", "normal:<-3", Query.Type.ALL);
tester.assertParsed("<-3", "<-3", Query.Type.ALL);
}
@Test
- public void testNegativeBiggerThan() {
+ void testNegativeBiggerThan() {
tester.assertParsed("normal:>-3", "normal:>-3", Query.Type.ALL);
tester.assertParsed(">-3", ">-3", Query.Type.ALL);
}
@Test
- public void testNegativesInRanges() {
+ void testNegativesInRanges() {
tester.assertParsed("normal:[-4;9]", "normal:[-4;9]", Query.Type.ALL);
tester.assertParsed("[-4;9]", "[-4;9]", Query.Type.ALL);
tester.assertParsed("normal:[-4;-9]", "normal:[-4;-9]", Query.Type.ALL);
@@ -2002,51 +1999,51 @@ public class ParseTestCase {
}
@Test
- public void testDecimal() {
- Item root=tester.assertParsed("2.2", "2.2", Query.Type.ALL);
+ void testDecimal() {
+ Item root = tester.assertParsed("2.2", "2.2", Query.Type.ALL);
assertTrue(root instanceof IntItem);
tester.assertParsed("normal:2.2", "normal:2.2", Query.Type.ALL);
}
@Test
- public void testVersionNumbers() {
+ void testVersionNumbers() {
tester.assertParsed("AND 1 0 9", "1.0.9", Query.Type.ALL);
}
@Test
- public void testDecimalNumbersAndNot() {
+ void testDecimalNumbersAndNot() {
tester.assertParsed("AND a -12.2", "a -12.2", Query.Type.ALL);
}
@Test
- public void testDecimalNumbersAndDoubleNot() {
+ void testDecimalNumbersAndDoubleNot() {
tester.assertParsed("+a --12.2", "a --12.2", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalNumberWithIndex() {
+ void testNegativeDecimalNumberWithIndex() {
tester.assertParsed("normal:-12.2", "normal:-12.2", Query.Type.ALL);
}
@Test
- public void testSingleNegativeDecimalNumberLikeTerm() {
+ void testSingleNegativeDecimalNumberLikeTerm() {
tester.assertParsed("-12.2", "-12.2", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalLessThan() {
+ void testNegativeDecimalLessThan() {
tester.assertParsed("normal:<-3.14", "normal:<-3.14", Query.Type.ALL);
tester.assertParsed("<-3.14", "<-3.14", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalBiggerThan() {
+ void testNegativeDecimalBiggerThan() {
tester.assertParsed("normal:>-3.14", "normal:>-3.14", Query.Type.ALL);
tester.assertParsed(">-3.14", ">-3.14", Query.Type.ALL);
}
@Test
- public void testNegativesDecimalInRanges() {
+ void testNegativesDecimalInRanges() {
tester.assertParsed("normal:[-4.16;9.2]", "normal:[-4.16;9.2]", Query.Type.ALL);
tester.assertParsed("[-4.16;9.2]", "[-4.16;9.2]", Query.Type.ALL);
tester.assertParsed("normal:[-4.16;-9.2]", "normal:[-4.16;-9.2]", Query.Type.ALL);
@@ -2054,12 +2051,12 @@ public class ParseTestCase {
}
@Test
- public void testRangesAndNoise() {
+ void testRangesAndNoise() {
tester.assertParsed("[2;3]", "[2;3]]", Query.Type.ALL);
}
@Test
- public void testIndexNoise() {
+ void testIndexNoise() {
tester.assertParsed("AND normal:a notanindex", "normal:a normal: notanindex:", Query.Type.ALL);
tester.assertParsed(null, "normal:", Query.Type.ALL);
tester.assertParsed(null, "normal:!", Query.Type.ALL);
@@ -2070,13 +2067,13 @@ public class ParseTestCase {
}
@Test
- public void testIndexNoiseAndExplicitPhrases() {
+ void testIndexNoiseAndExplicitPhrases() {
tester.assertParsed("normal:\"a b\"", "normal:\" a b\"", Query.Type.ALL);
tester.assertParsed("normal:\"a b\"", "normal:\"a b\"", Query.Type.ALL);
}
@Test
- public void testExactMatchParsing1() {
+ void testExactMatchParsing1() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2092,13 +2089,13 @@ public class ParseTestCase {
customTester.assertParsed("testexact1:/,%&#", "testexact1:/,%&#", Query.Type.ALL);
customTester.assertParsed("testexact2:/,%&#!!", "testexact2:/,%&#!!()/aa*::*&", Query.Type.ALL);
- customTester.assertParsed("AND word1 (OR testexact1:word2 testexact1:word3)","word1 AND (testexact1:word2 OR testexact1:word3 )",Query.Type.ADVANCED);
- customTester.assertParsed("AND word (OR testexact1:AND testexact1:OR)","word AND (testexact1: AND OR testexact1: OR )",Query.Type.ADVANCED);
+ customTester.assertParsed("AND word1 (OR testexact1:word2 testexact1:word3)", "word1 AND (testexact1:word2 OR testexact1:word3 )", Query.Type.ADVANCED);
+ customTester.assertParsed("AND word (OR testexact1:AND testexact1:OR)", "word AND (testexact1: AND OR testexact1: OR )", Query.Type.ADVANCED);
}
/** Testing terminators containing control characters in conjunction with those control characters */
@Test
- public void testExactMatchParsing2() {
+ void testExactMatchParsing2() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2108,12 +2105,12 @@ public class ParseTestCase {
IndexFacts indexFacts = new IndexFacts(new IndexModel(sd));
ParsingTester customTester = new ParsingTester(indexFacts);
- customTester.assertParsed("testexact1:_-_*!200","testexact1:_-_*!**!!",Query.Type.ALL);
+ customTester.assertParsed("testexact1:_-_*!200", "testexact1:_-_*!**!!", Query.Type.ALL);
}
/** Testing terminators containing control characters in conjunction with those control characters */
@Test
- public void testExactMatchParsing3() {
+ void testExactMatchParsing3() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2123,48 +2120,48 @@ public class ParseTestCase {
IndexFacts indexFacts = new IndexFacts(new IndexModel(sd));
ParsingTester customTester = new ParsingTester(indexFacts);
- customTester.assertParsed("testexact1:_-_*!200","testexact1:_-_**!!",Query.Type.ALL);
+ customTester.assertParsed("testexact1:_-_*!200", "testexact1:_-_**!!", Query.Type.ALL);
}
// bug 1393139
@Test
- public void testMinimalBritneyFilter() {
+ void testMinimalBritneyFilter() {
tester.assertParsed("RANK (+a -|c) b", "a RANK b", "-c", Query.Type.ADVANCED);
}
@Test
- public void testBritneyFilter() {
+ void testBritneyFilter() {
tester.assertParsed("RANK (+(AND performernameall:britney performernameall:spears songnameall:toxic |SongConsumable:1 |country:us |collapsedrecord:1 |doctype:song) -|collapsecount:0) (AND metadata:britney metadata:spears metadata:toxic)",
- "((performernameall:britney AND performernameall:spears AND songnameall:toxic) RANK (metadata:britney AND metadata:spears AND metadata:toxic))",
- "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
- Query.Type.ADVANCED);
+ "((performernameall:britney AND performernameall:spears AND songnameall:toxic) RANK (metadata:britney AND metadata:spears AND metadata:toxic))",
+ "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
+ Query.Type.ADVANCED);
tester.assertParsed("AND (+(AND (RANK (OR (AND performernameall:britney performernameall:spears songnameall:toxic) (AND performernameall:britney performernameall:spears songnameall:toxic)) (AND metadata:britney metadata:spears metadata:toxic)) |SongConsumable:1 |country:us |collapsedrecord:1) -|collapsecount:0) |doctype:song",
- "(((performernameall:britney AND performernameall:spears AND songnameall:toxic) OR (performernameall:britney AND performernameall:spears AND songnameall:toxic)) RANK (metadata:britney AND metadata:spears AND metadata:toxic)))",
- "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
- Query.Type.ADVANCED);
+ "(((performernameall:britney AND performernameall:spears AND songnameall:toxic) OR (performernameall:britney AND performernameall:spears AND songnameall:toxic)) RANK (metadata:britney AND metadata:spears AND metadata:toxic)))",
+ "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
+ Query.Type.ADVANCED);
}
// bug 1412840
@Test
- public void testGreedyPhrases() {
+ void testGreedyPhrases() {
tester.assertParsed("AND title:why title:\"1 2\"", "title:\"why\" title:\"&\" title:\"1/2\"", Query.Type.ALL);
}
// bug 1509347
@Test
- public void testUnderscoreInFieldNames() {
+ void testUnderscoreInFieldNames() {
tester.assertParsed("AND title:why score_under:what score_under:>5000",
- "title:why score_under:what score_under:>5000",
- Query.Type.ALL);
+ "title:why score_under:what score_under:>5000",
+ Query.Type.ALL);
}
// bug 1509347
@Test
- public void testLeadingUnderscoreInFieldNames() {
+ void testLeadingUnderscoreInFieldNames() {
tester.assertParsed("AND title:why _under_score_:what _under_score_:>5000",
- "title:why _under_score_:what _under_score_:>5000",
- Query.Type.ALL);
+ "title:why _under_score_:what _under_score_:>5000",
+ Query.Type.ALL);
}
// Re-add if underscore should be a word character
@@ -2185,7 +2182,7 @@ public class ParseTestCase {
// bug 524918
@Test
- public void testAdvancedSyntaxParensAndQuotes() {
+ void testAdvancedSyntaxParensAndQuotes() {
tester.assertParsed("OR a (AND \"b c d\" e)",
"a OR (\"b (c) d\" AND e)",
Query.Type.ADVANCED);
@@ -2195,7 +2192,7 @@ public class ParseTestCase {
// this needs to become series of tests where the tokenizer
// and parser will step on each other's toes.
@Test
- public void testStarFirstInAttributes() {
+ void testStarFirstInAttributes() {
tester.assertParsed("exactindex:*test",
"exactindex:*test",
Query.Type.ALL);
@@ -2203,162 +2200,162 @@ public class ParseTestCase {
}
@Test
- public void testOneWordWebParsing() {
- tester.assertParsed("a","a",Query.Type.WEB);
+ void testOneWordWebParsing() {
+ tester.assertParsed("a", "a", Query.Type.WEB);
}
@Test
- public void testTwoWordWebParsing() {
- tester.assertParsed("AND a b","a b",Query.Type.WEB);
+ void testTwoWordWebParsing() {
+ tester.assertParsed("AND a b", "a b", Query.Type.WEB);
}
@Test
- public void testPlusWordWebParsing1() {
- Item root=tester.assertParsed("AND a b","+a b",Query.Type.WEB);
- assertTrue(((AndItem)root).getItem(0).isProtected());
- assertFalse(((AndItem)root).getItem(1).isProtected());
+ void testPlusWordWebParsing1() {
+ Item root = tester.assertParsed("AND a b", "+a b", Query.Type.WEB);
+ assertTrue(((AndItem) root).getItem(0).isProtected());
+ assertFalse(((AndItem) root).getItem(1).isProtected());
}
@Test
- public void testPlusWordWebParsing2() {
- Item root=tester.assertParsed("AND a b","+a +b",Query.Type.WEB);
- assertTrue(((AndItem)root).getItem(0).isProtected());
- assertTrue(((AndItem)root).getItem(1).isProtected());
+ void testPlusWordWebParsing2() {
+ Item root = tester.assertParsed("AND a b", "+a +b", Query.Type.WEB);
+ assertTrue(((AndItem) root).getItem(0).isProtected());
+ assertTrue(((AndItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing1() {
- Item root=tester.assertParsed("+a -b","a -b",Query.Type.WEB);
- assertFalse(((NotItem)root).getItem(0).isProtected());
- assertTrue(((NotItem)root).getItem(1).isProtected());
+ void testNegativeWordsParsing1() {
+ Item root = tester.assertParsed("+a -b", "a -b", Query.Type.WEB);
+ assertFalse(((NotItem) root).getItem(0).isProtected());
+ assertTrue(((NotItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing2() {
- Item root=tester.assertParsed("+a -b","+a -b",Query.Type.WEB);
- assertTrue(((NotItem)root).getItem(0).isProtected());
- assertTrue(((NotItem)root).getItem(1).isProtected());
+ void testNegativeWordsParsing2() {
+ Item root = tester.assertParsed("+a -b", "+a -b", Query.Type.WEB);
+ assertTrue(((NotItem) root).getItem(0).isProtected());
+ assertTrue(((NotItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing3() {
- tester.assertParsed("+a -b","-b a",Query.Type.WEB);
+ void testNegativeWordsParsing3() {
+ tester.assertParsed("+a -b", "-b a", Query.Type.WEB);
}
@Test
- public void testNegativeWordsParsing4() {
- tester.assertParsed("+(AND a b) -c -d","a b -c -d",Query.Type.WEB);
+ void testNegativeWordsParsing4() {
+ tester.assertParsed("+(AND a b) -c -d", "a b -c -d", Query.Type.WEB);
}
@Test
- public void testNegativeWordsParsing5() {
- tester.assertParsed("+(AND a \"b c\" d) -e -f","a -e \"b c\" d -f",Query.Type.WEB);
+ void testNegativeWordsParsing5() {
+ tester.assertParsed("+(AND a \"b c\" d) -e -f", "a -e \"b c\" d -f", Query.Type.WEB);
}
@Test
- public void testPhraseWebParsing() {
- tester.assertParsed("\"a b\"","\"a b\"",Query.Type.WEB);
+ void testPhraseWebParsing() {
+ tester.assertParsed("\"a b\"", "\"a b\"", Query.Type.WEB);
}
@Test
- public void testPhraseAndExtraTermWebParsing() {
- tester.assertParsed("AND \"a b\" c","\"a b\" c",Query.Type.WEB);
+ void testPhraseAndExtraTermWebParsing() {
+ tester.assertParsed("AND \"a b\" c", "\"a b\" c", Query.Type.WEB);
}
@Test
- public void testNotOrWebParsing() {
- tester.assertParsed("AND a or b","a or b",Query.Type.WEB);
+ void testNotOrWebParsing() {
+ tester.assertParsed("AND a or b", "a or b", Query.Type.WEB);
}
@Test
- public void testNotOrALLParsing() {
- tester.assertParsed("AND a OR b","a OR b",Query.Type.ALL);
+ void testNotOrALLParsing() {
+ tester.assertParsed("AND a OR b", "a OR b", Query.Type.ALL);
}
@Test
- public void testOrParsing1() {
- tester.assertParsed("OR a b","a OR b",Query.Type.WEB);
+ void testOrParsing1() {
+ tester.assertParsed("OR a b", "a OR b", Query.Type.WEB);
}
@Test
- public void testOrParsing2() {
- tester.assertParsed("OR a b c","a OR b OR c",Query.Type.WEB);
+ void testOrParsing2() {
+ tester.assertParsed("OR a b c", "a OR b OR c", Query.Type.WEB);
}
@Test
- public void testOrParsing3() {
- tester.assertParsed("OR a (AND b c) \"d e\"","a OR b c OR \"d e\"",Query.Type.WEB);
+ void testOrParsing3() {
+ tester.assertParsed("OR a (AND b c) \"d e\"", "a OR b c OR \"d e\"", Query.Type.WEB);
}
@Test
- public void testOrParsing4() {
- tester.assertParsed("OR (AND or1 a) or2","or1 a OR or2",Query.Type.WEB);
+ void testOrParsing4() {
+ tester.assertParsed("OR (AND or1 a) or2", "or1 a OR or2", Query.Type.WEB);
}
@Test
- public void testOrCornerCase1() {
- tester.assertParsed("AND OR a","OR a",Query.Type.WEB);
+ void testOrCornerCase1() {
+ tester.assertParsed("AND OR a", "OR a", Query.Type.WEB);
}
@Test
- public void testOrCornerCase2() {
- tester.assertParsed("AND OR a","OR a OR",Query.Type.WEB); // Don't care
+ void testOrCornerCase2() {
+ tester.assertParsed("AND OR a", "OR a OR", Query.Type.WEB); // Don't care
}
@Test
- public void testOrCornerCase3() {
- tester.assertParsed("AND OR a","OR a OR OR",Query.Type.WEB); // Don't care
+ void testOrCornerCase3() {
+ tester.assertParsed("AND OR a", "OR a OR OR", Query.Type.WEB); // Don't care
}
@Test
- public void testOrCornerCase4() {
- tester.assertParsed("+(OR (AND a b) (AND d c) (AND g h)) -e -f","a b OR d c -e -f OR g h",Query.Type.WEB);
+ void testOrCornerCase4() {
+ tester.assertParsed("+(OR (AND a b) (AND d c) (AND g h)) -e -f", "a b OR d c -e -f OR g h", Query.Type.WEB);
}
@Test
- public void testOdd1Web() {
- tester.assertParsed("AND window print error", "+window.print() +error",Query.Type.WEB);
+ void testOdd1Web() {
+ tester.assertParsed("AND window print error", "+window.print() +error", Query.Type.WEB);
}
@Test
- public void testNotOnlyWeb() {
+ void testNotOnlyWeb() {
tester.assertParsed(null, "-foobar", Query.Type.WEB);
}
@Test
- public void testMultipleNotsOnltWeb() {
+ void testMultipleNotsOnltWeb() {
tester.assertParsed(null, "-foo -bar -foobar", Query.Type.WEB);
}
@Test
- public void testOnlyNotCompositeWeb() {
+ void testOnlyNotCompositeWeb() {
tester.assertParsed(null, "-(foo bar baz)", Query.Type.WEB);
}
@Test
- public void testSingleNegativeNumberLikeTermWeb() {
+ void testSingleNegativeNumberLikeTermWeb() {
tester.assertParsed("-12", "-12", Query.Type.WEB);
}
@Test
- public void testSingleNegativeDecimalNumberLikeTermWeb() {
+ void testSingleNegativeDecimalNumberLikeTermWeb() {
tester.assertParsed("-12.2", "-12.2", Query.Type.WEB);
}
@Test
- public void testDefaultWebIndices() {
- tester.assertParsed("AND notanindex b","notanindex:b", Query.Type.WEB);
- tester.assertParsed("site:\"b $\"","site:b", Query.Type.WEB);
- tester.assertParsed("hostname:b","hostname:b", Query.Type.WEB);
- tester.assertParsed("link:b","link:b", Query.Type.WEB);
- tester.assertParsed("url:b","url:b", Query.Type.WEB);
- tester.assertParsed("inurl:b","inurl:b", Query.Type.WEB);
- tester.assertParsed("intitle:b","intitle:b", Query.Type.WEB);
+ void testDefaultWebIndices() {
+ tester.assertParsed("AND notanindex b", "notanindex:b", Query.Type.WEB);
+ tester.assertParsed("site:\"b $\"", "site:b", Query.Type.WEB);
+ tester.assertParsed("hostname:b", "hostname:b", Query.Type.WEB);
+ tester.assertParsed("link:b", "link:b", Query.Type.WEB);
+ tester.assertParsed("url:b", "url:b", Query.Type.WEB);
+ tester.assertParsed("inurl:b", "inurl:b", Query.Type.WEB);
+ tester.assertParsed("intitle:b", "intitle:b", Query.Type.WEB);
}
@Test
- public void testHTMLWeb() {
- tester.assertParsed("AND h2 Title h2","<h2>Title</h2>",Query.Type.WEB);
+ void testHTMLWeb() {
+ tester.assertParsed("AND h2 Title h2", "<h2>Title</h2>", Query.Type.WEB);
}
/**
@@ -2366,82 +2363,82 @@ public class ParseTestCase {
* The information about added bangs is available from the origin as shown (do not use the weight to find this)
*/
@Test
- public void testShortcutsWeb() {
- tester.assertParsed("AND map new york","map new york",Query.Type.WEB);
+ void testShortcutsWeb() {
+ tester.assertParsed("AND map new york", "map new york", Query.Type.WEB);
- AndItem root=(AndItem)tester.assertParsed("AND map!150 new york","map! new york",Query.Type.WEB);
- assertEquals('!',((WordItem)root.getItem(0)).getOrigin().charAfter(0));
+ AndItem root = (AndItem) tester.assertParsed("AND map!150 new york", "map! new york", Query.Type.WEB);
+ assertEquals('!', ((WordItem) root.getItem(0)).getOrigin().charAfter(0));
- root=(AndItem)tester.assertParsed("AND barack obama news!150","barack obama news!",Query.Type.WEB);
- assertEquals('!',((WordItem)root.getItem(2)).getOrigin().charAfter(0));
+ root = (AndItem) tester.assertParsed("AND barack obama news!150", "barack obama news!", Query.Type.WEB);
+ assertEquals('!', ((WordItem) root.getItem(2)).getOrigin().charAfter(0));
}
@Test
- public void testZipCodeShortcutWeb() {
- tester.assertParsed("12345","12345",Query.Type.WEB);
- IntItem root=(IntItem)tester.assertParsed("00012!150","00012!",Query.Type.WEB);
- assertEquals('!',root.getOrigin().charAfter(0));
+ void testZipCodeShortcutWeb() {
+ tester.assertParsed("12345", "12345", Query.Type.WEB);
+ IntItem root = (IntItem) tester.assertParsed("00012!150", "00012!", Query.Type.WEB);
+ assertEquals('!', root.getOrigin().charAfter(0));
}
@Test
- public void testDouble() {
- Item number=tester.assertParsed("123456789.987654321","123456789.987654321",Query.Type.ALL);
+ void testDouble() {
+ Item number = tester.assertParsed("123456789.987654321", "123456789.987654321", Query.Type.ALL);
assertTrue(number instanceof IntItem);
}
@Test
- public void testLong() {
- Item number=tester.assertParsed("3000000000000","3000000000000",Query.Type.ALL);
+ void testLong() {
+ Item number = tester.assertParsed("3000000000000", "3000000000000", Query.Type.ALL);
assertTrue(number instanceof IntItem);
}
@Test
- public void testNear1() {
- tester.assertParsed("NEAR(2) new york","new NEAR york",Query.Type.ADVANCED);
+ void testNear1() {
+ tester.assertParsed("NEAR(2) new york", "new NEAR york", Query.Type.ADVANCED);
}
@Test
- public void testNear2() {
- tester.assertParsed("ONEAR(2) new york","new ONEAR york",Query.Type.ADVANCED);
+ void testNear2() {
+ tester.assertParsed("ONEAR(2) new york", "new ONEAR york", Query.Type.ADVANCED);
}
@Test
- public void testNear3() {
- tester.assertParsed("NEAR(3) new york","new NEAR(3) york",Query.Type.ADVANCED);
+ void testNear3() {
+ tester.assertParsed("NEAR(3) new york", "new NEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear4() {
- tester.assertParsed("ONEAR(3) new york","new ONEAR(3) york",Query.Type.ADVANCED);
+ void testNear4() {
+ tester.assertParsed("ONEAR(3) new york", "new ONEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear5() {
- tester.assertParsed("NEAR(3) map new york","map NEAR(3) new NEAR(3) york",Query.Type.ADVANCED);
+ void testNear5() {
+ tester.assertParsed("NEAR(3) map new york", "map NEAR(3) new NEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear6() {
- tester.assertParsed("ONEAR(3) map new york","map ONEAR(3) new ONEAR(3) york",Query.Type.ADVANCED);
+ void testNear6() {
+ tester.assertParsed("ONEAR(3) map new york", "map ONEAR(3) new ONEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear7() {
- tester.assertParsed("NEAR(4) (NEAR(3) map new) york","map NEAR(3) new NEAR(4) york",Query.Type.ADVANCED);
+ void testNear7() {
+ tester.assertParsed("NEAR(4) (NEAR(3) map new) york", "map NEAR(3) new NEAR(4) york", Query.Type.ADVANCED);
}
@Test
- public void testNear8() {
- tester.assertParsed("ONEAR(4) (ONEAR(3) map new) york","map ONEAR(3) new ONEAR(4) york",Query.Type.ADVANCED);
+ void testNear8() {
+ tester.assertParsed("ONEAR(4) (ONEAR(3) map new) york", "map ONEAR(3) new ONEAR(4) york", Query.Type.ADVANCED);
}
@Test
- public void testNearPrefix() {
- tester.assertParsed("NEAR(2) a b*","a NEAR b*",Query.Type.ADVANCED);
+ void testNearPrefix() {
+ tester.assertParsed("NEAR(2) a b*", "a NEAR b*", Query.Type.ADVANCED);
}
@Test
- public void testNestedBracesAndPhrases() {
+ void testNestedBracesAndPhrases() {
String userQuery = "(\"Secondary Curriculum\" (\"Key Stage 3\" OR KS3) (\"Key Stage 4\" OR KS4)) ";
tester.assertParsed(
"OR \"Secondary Curriculum\" \"Key Stage 3\" OR KS3 \"Key Stage 4\" OR KS4",
@@ -2458,53 +2455,53 @@ public class ParseTestCase {
}
@Test
- public void testYetAnotherCycleQuery() {
+ void testYetAnotherCycleQuery() {
tester.assertParsed("+(OR (+d -f) b) -c",
"( b -c ( d -f )",
Query.Type.ALL);
}
@Test
- public void testSimpleEquivAdvanced() {
+ void testSimpleEquivAdvanced() {
tester.assertParsed("EQUIV foo bar baz", "foo equiv bar equiv baz", Query.Type.ADVANCED);
}
@Test
- public void testEquivWordIntPhraseAdvanced() {
+ void testEquivWordIntPhraseAdvanced() {
tester.assertParsed("EQUIV foo 5 \"a b\"", "foo equiv 5 equiv \"a b\"", Query.Type.ADVANCED);
}
@Test
- public void testEquivRejectCompositeAdvanced() {
+ void testEquivRejectCompositeAdvanced() {
try {
tester.assertParsed("this should not parse", "foo equiv (a or b)", Query.Type.ADVANCED);
- } catch(Exception e) {
+ } catch (Exception e) {
// Success
}
}
@Test
- public void testSimpleWandAdvanced() {
+ void testSimpleWandAdvanced() {
tester.assertParsed("WEAKAND(100) foo bar baz", "foo wand bar wand baz", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWandAdvancedWithNonDefaultN() {
+ void testSimpleWandAdvancedWithNonDefaultN() {
tester.assertParsed("WEAKAND(32) foo bar baz", "foo weakand(32) bar weakand(32) baz", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWandAdvancedWithNonDefaultNAndWeights() {
+ void testSimpleWandAdvancedWithNonDefaultNAndWeights() {
tester.assertParsed("WEAKAND(32) foo!32 bar!64 baz", "foo!32 weakand(32) bar!64 weakand(32) baz", Query.Type.ADVANCED);
}
@Test
- public void testTwoRanges() {
- tester.assertParsed("AND score:[1.25;2.18] age:[25;30]","score:[1.25;2.18] AND age:[25;30]", Query.Type.ADVANCED);
+ void testTwoRanges() {
+ tester.assertParsed("AND score:[1.25;2.18] age:[25;30]", "score:[1.25;2.18] AND age:[25;30]", Query.Type.ADVANCED);
}
@Test
- public void testTooLargeTermWeights() {
+ void testTooLargeTermWeights() {
// This behavior is a bit silly:
tester.assertParsed("AND a 12345678901234567890", "a!12345678901234567890", Query.Type.ALL);
// but in light of
@@ -2515,7 +2512,7 @@ public class ParseTestCase {
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
Item root = tester.parseQuery("a'b&c'd", Language.ENGLISH, Query.Type.ALL);
assertTrue(root instanceof AndItem);
AndItem top = (AndItem) root;
@@ -2527,59 +2524,59 @@ public class ParseTestCase {
Item t2 = seg1.getItem(1);
Item t3 = seg2.getItem(0);
Item t4 = seg2.getItem(1);
- assertTrue(((TaggableItem)t2).hasUniqueID());
- assertTrue(((TaggableItem)t3).hasUniqueID());
- assertTrue(((TaggableItem)t1).getConnectedItem() == t2);
- assertTrue(((TaggableItem)t2).getConnectedItem() == t3);
- assertTrue(((TaggableItem)t3).getConnectedItem() == t4);
+ assertTrue(((TaggableItem) t2).hasUniqueID());
+ assertTrue(((TaggableItem) t3).hasUniqueID());
+ assertEquals(((TaggableItem) t1).getConnectedItem(), t2);
+ assertEquals(((TaggableItem) t2).getConnectedItem(), t3);
+ assertEquals(((TaggableItem) t3).getConnectedItem(), t4);
}
@Test
- public void testSiteAndSegmentPhrases() {
+ void testSiteAndSegmentPhrases() {
tester.assertParsed("host.all:\"www abc com x y-z $\"",
- "host.all:www.abc.com/x'y-z", "",
- Query.Type.ALL, Language.ENGLISH);
+ "host.all:www.abc.com/x'y-z", "",
+ Query.Type.ALL, Language.ENGLISH);
}
@Test
- public void testSiteAndSegmentPhrasesFollowedByText() {
+ void testSiteAndSegmentPhrasesFollowedByText() {
tester.assertParsed("AND host.all:\"www abc com x y-z $\" (SAND a b)",
- "host.all:www.abc.com/x'y-z a'b", "",
- Query.Type.ALL, Language.ENGLISH);
+ "host.all:www.abc.com/x'y-z a'b", "",
+ Query.Type.ALL, Language.ENGLISH);
}
@Test
- public void testIntItemFollowedByDot() {
- tester.assertParsed("AND Campion Ste 3 When To Her Lute Corinna Sings","Campion Ste: 3. When To Her Lute Corinna Sings", Query.Type.ALL);
+ void testIntItemFollowedByDot() {
+ tester.assertParsed("AND Campion Ste 3 When To Her Lute Corinna Sings", "Campion Ste: 3. When To Her Lute Corinna Sings", Query.Type.ALL);
}
@Test
- public void testNotIntItemIfPrecededByHyphen() {
- tester.assertParsed("AND Horny Horny '98 Radio Edit","Horny [Horny '98 Radio Edit]]", Query.Type.ALL);
+ void testNotIntItemIfPrecededByHyphen() {
+ tester.assertParsed("AND Horny Horny '98 Radio Edit", "Horny [Horny '98 Radio Edit]]", Query.Type.ALL);
}
@Test
- public void testNonAsciiNumber() {
+ void testNonAsciiNumber() {
tester.assertParsed("AND title:199 title:119 title:201 title:149", "title:199.119.201.149", Query.Type.ALL);
}
@Test
- public void testNoGrammar1() {
+ void testNoGrammar1() {
tester.assertParsed("WEAKAND(100) foobar", "foobar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar2() {
+ void testNoGrammar2() {
tester.assertParsed("WEAKAND(100) foobar", "-foobar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar3() {
+ void testNoGrammar3() {
tester.assertParsed("WEAKAND(100) foo bar", "foo -bar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar4() {
+ void testNoGrammar4() {
tester.assertParsed("WEAKAND(100) foo bar baz one two 37", "foo -(bar baz \"one two\" 37)", Query.Type.TOKENIZE);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
index 229416f7a85..ab314c4c1e7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
@@ -23,9 +23,7 @@ import com.yahoo.search.query.parser.ParserFactory;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* A utility for writing parser tests
@@ -62,6 +60,7 @@ public class ParsingTester {
* Returns an unfrozen version of the IndexFacts this will use.
* This can be used to add new indexes and passing the resulting IndexFacts to the constructor of this.
*/
+ @SuppressWarnings("deprecation")
public static IndexFacts createIndexFacts() {
String indexInfoConfigID = "file:src/test/java/com/yahoo/prelude/query/parser/test/parseindexinfo.cfg";
ConfigGetter<IndexInfoConfig> getter = new ConfigGetter<>(IndexInfoConfig.class);
@@ -118,10 +117,10 @@ public class ParsingTester {
Language language, Linguistics linguistics) {
Item root = parseQuery(toParse, filter, language, mode, linguistics);
if (parsed == null) {
- assertTrue("root should be null, but was " + root, root == null);
+ assertNull(root);
} else {
- assertNotNull("Got null from parsing " + toParse, root);
- assertEquals("Parse of '" + toParse + "'", parsed, root.toString());
+ assertNotNull(root, "Got null from parsing " + toParse);
+ assertEquals(parsed, root.toString(), "Parse of '" + toParse + "'");
}
return root;
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
index e7d938e6bd8..129563d1456 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser.test;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.CompositeItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
@@ -11,6 +9,8 @@ import com.yahoo.search.Query;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Check Substring in conjunction with query tokenization and parsing behaves properly.
*
@@ -19,15 +19,15 @@ import java.net.URLEncoder;
public class SubstringTestCase {
@Test
- public final void testTokenLengthAndLowercasing() {
+ final void testTokenLengthAndLowercasing() {
Query q = new Query("/?query=\u0130");
- WordItem root = (WordItem) ((CompositeItem)q.getModel().getQueryTree().getRoot()).getItem(0);
+ WordItem root = (WordItem) ((CompositeItem) q.getModel().getQueryTree().getRoot()).getItem(0);
assertEquals("\u0130", root.getRawWord());
}
@Test
- public final void testBug5968479() {
+ final void testBug5968479() {
String first = "\u0130\u015EBANKASI";
String second = "GAZ\u0130EM\u0130R";
Query q = new Query("/?query=" + enc(first) + "%20" + enc(second));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
index 5b660f78429..1ff5574ec03 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.language.process.SpecialTokenRegistry;
import com.yahoo.language.process.SpecialTokens;
import com.yahoo.prelude.query.parser.Token;
import com.yahoo.prelude.query.parser.Tokenizer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -29,9 +29,7 @@ import static com.yahoo.prelude.query.parser.Token.Kind.SPACE;
import static com.yahoo.prelude.query.parser.Token.Kind.STAR;
import static com.yahoo.prelude.query.parser.Token.Kind.UNDERSCORE;
import static com.yahoo.prelude.query.parser.Token.Kind.WORD;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the tokenizer
@@ -41,7 +39,7 @@ import static org.junit.Assert.assertTrue;
public class TokenizerTestCase {
@Test
- public void testPlainTokenization() {
+ void testPlainTokenization() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -76,14 +74,14 @@ public class TokenizerTestCase {
}
@Test
- public void testOutsideBMPCodepoints() {
+ void testOutsideBMPCodepoints() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
List<?> tokens = tokenizer.tokenize("\ud841\udd47");
assertEquals(new Token(WORD, "\ud841\udd47"), tokens.get(0));
}
@Test
- public void testOneSpecialToken() {
+ void testOneSpecialToken() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -93,7 +91,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenCombination() {
+ void testSpecialTokenCombination() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -121,7 +119,7 @@ public class TokenizerTestCase {
* separated by space, as special token recognition happens before tokenization
*/
@Test
- public void testSpecialTokenCJK() {
+ void testSpecialTokenCJK() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSubstringSpecialTokens(true);
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("replacing"));
@@ -146,7 +144,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenCaseInsensitive() {
+ void testSpecialTokenCaseInsensitive() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -162,7 +160,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenNonMatch() {
+ void testSpecialTokenNonMatch() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -187,7 +185,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenConfigurationDefault() {
+ void testSpecialTokenConfigurationDefault() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -212,7 +210,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenConfigurationOther() {
+ void testSpecialTokenConfigurationOther() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("other"));
@@ -247,7 +245,7 @@ public class TokenizerTestCase {
}
@Test
- public void testTokenReplacing() {
+ void testTokenReplacing() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("replacing"));
@@ -273,7 +271,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenization() {
+ void testExactMatchTokenization() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -286,8 +284,8 @@ public class TokenizerTestCase {
IndexFacts facts = new IndexFacts(new IndexModel(sd));
IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet());
- Tokenizer tokenizer=new Tokenizer(new SimpleLinguistics());
- List<?> tokens=tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*& b:c", "default", session);
+ Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
+ List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*& b:c", "default", session);
// tokenizer.print();
assertEquals(new Token(WORD, "normal"), tokens.get(0));
assertEquals(new Token(SPACE, " "), tokens.get(1));
@@ -317,7 +315,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationTerminatorTerminatesQuery() {
+ void testExactMatchTokenizationTerminatorTerminatesQuery() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -354,7 +352,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationWithTerminatorTerminatedByEndOfString() {
+ void testExactMatchTokenizationWithTerminatorTerminatedByEndOfString() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -391,7 +389,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationEndsByColon() {
+ void testExactMatchTokenizationEndsByColon() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -429,7 +427,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchHeuristics() {
+ void testExactMatchHeuristics() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -542,7 +540,7 @@ public class TokenizerTestCase {
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
assertEquals(new Token(STAR, "*"), tokens.get(2));
- assertEquals(new Token(WORD, "foobar*!100"),tokens.get(3));
+ assertEquals(new Token(WORD, "foobar*!100"), tokens.get(3));
assertEquals(new Token(EXCLAMATION, "!"), tokens.get(4));
tokens = tokenizer.tokenize("testexact1:foo(bar)", facts);
@@ -582,7 +580,7 @@ public class TokenizerTestCase {
tokens = tokenizer.tokenize("testexact1:\"news search\" testexact2:resolved", facts);
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
- assertEquals(new Token(WORD, "news search"),tokens.get(2));
+ assertEquals(new Token(WORD, "news search"), tokens.get(2));
assertEquals(new Token(SPACE, " "), tokens.get(3));
assertEquals(new Token(WORD, "testexact2"), tokens.get(4));
assertEquals(new Token(COLON, ":"), tokens.get(5));
@@ -592,7 +590,7 @@ public class TokenizerTestCase {
assertEquals(new Token(LBRACE, "("), tokens.get(0));
assertEquals(new Token(WORD, "testexact1"), tokens.get(1));
assertEquals(new Token(COLON, ":"), tokens.get(2));
- assertEquals(new Token(WORD, "news search"),tokens.get(3));
+ assertEquals(new Token(WORD, "news search"), tokens.get(3));
assertEquals(new Token(SPACE, " "), tokens.get(4));
assertEquals(new Token(WORD, "testexact1"), tokens.get(5));
assertEquals(new Token(COLON, ":"), tokens.get(6));
@@ -614,7 +612,7 @@ public class TokenizerTestCase {
tokens = tokenizer.tokenize("testexact1:\"news search\"!200", facts);
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
- assertEquals(new Token(WORD, "news search"),tokens.get(2));
+ assertEquals(new Token(WORD, "news search"), tokens.get(2));
assertEquals(new Token(EXCLAMATION, "!"), tokens.get(3));
assertEquals(new Token(NUMBER, "200"), tokens.get(4));
@@ -705,7 +703,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSingleQuoteAsWordCharacter() {
+ void testSingleQuoteAsWordCharacter() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
index 061089cd25f..f0b768a010f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
@@ -13,10 +13,10 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.Parser;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests guards against in single item phrases.
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertNull;
public class WashPhrasesTestCase {
@Test
- public void testSimplePositive() {
+ void testSimplePositive() {
PhraseItem root = new PhraseItem();
root.addItem(new WordItem("abc"));
@@ -34,7 +34,7 @@ public class WashPhrasesTestCase {
}
@Test
- public void testPositive1() {
+ void testPositive1() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
@@ -47,7 +47,7 @@ public class WashPhrasesTestCase {
}
@Test
- public void testPositive2() {
+ void testPositive2() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
@@ -64,22 +64,22 @@ public class WashPhrasesTestCase {
}
@Test
- public void testNoTerms() {
+ void testNoTerms() {
assertNull(transformQuery("\"\""));
}
@Test
- public void testNegative1() {
+ void testNegative1() {
assertEquals("\"abc def\"", transformQuery("\"abc def\""));
}
@Test
- public void testNegative2() {
+ void testNegative2() {
assertEquals("AND a \"abc def\" b", transformQuery("a \"abc def\" b"));
}
- @Test
- public void testNegative3() {
+ @Test
+ void testNegative3() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
index 1585e58ca5d..2bb8584cba3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
@@ -1,28 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.test;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* @author havardpe
*/
public class DotProductItemTestCase {
@Test
- public void testDotProductItem() {
+ void testDotProductItem() {
DotProductItem item = new DotProductItem("index_name");
assertEquals("index_name", item.getIndexName());
assertEquals(Item.ItemType.DOTPRODUCT, item.getItemType());
}
@Test
- public void testDotProductClone() {
+ void testDotProductClone() {
DotProductItem dpOrig = new DotProductItem("myDP");
- dpOrig.addToken("first",11);
+ dpOrig.addToken("first", 11);
dpOrig.getTokens();
DotProductItem dpClone = (DotProductItem) dpOrig.clone();
dpClone.addToken("second", 22);
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
index 28cf5008417..3e1abddbdf4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
@@ -5,9 +5,9 @@ import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals;
public class IntItemTestCase {
@Test
- public void testEquals() {
+ void testEquals() {
Query q1 = new Query("/?query=123%20456%20789");
Query q2 = new Query("/?query=123%20456");
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
index eb880bab826..c43d7e3b9d5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
@@ -10,11 +10,11 @@ import com.yahoo.prelude.query.PureWeightedInteger;
import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Item encoding tests
@@ -25,17 +25,17 @@ public class ItemEncodingTestCase {
private void assertType(ByteBuffer buffer, int etype, int features) {
byte type = buffer.get();
- assertEquals("Code", etype, type & 0x1f);
- assertEquals("Features", features, (type & 0xe0) >> 5);
+ assertEquals(etype, type & 0x1f, "Code");
+ assertEquals(features, (type & 0xe0) >> 5, "Features");
}
private void assertWeight(ByteBuffer buffer, int weight) {
int w = (weight > (1 << 5)) ? buffer.getShort() & 0x3fff: buffer.get();
- assertEquals("Weight", weight, w);
+ assertEquals(weight, w, "Weight");
}
@Test
- public void testWordItemEncoding() {
+ void testWordItemEncoding() {
WordItem word = new WordItem("test");
word.setWeight(150);
@@ -44,14 +44,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 1);
assertWeight(buffer, 150);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -59,20 +59,20 @@ public class ItemEncodingTestCase {
}
@Test
- public void testStartHostMarkerEncoding() {
+ void testStartHostMarkerEncoding() {
WordItem word = MarkerWordItem.createStartOfHost();
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = word.encode(buffer);
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 9, buffer.get());
- assertEquals("Word length", 9, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(9, buffer.get(), "Word length");
+ assertEquals(9, buffer.remaining(), "Word length");
assertEquals('S', buffer.get());
assertEquals('t', buffer.get());
assertEquals('A', buffer.get());
@@ -85,7 +85,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testEndHostMarkerEncoding() {
+ void testEndHostMarkerEncoding() {
WordItem word = MarkerWordItem.createEndOfHost();
ByteBuffer buffer = ByteBuffer.allocate(128);
@@ -93,13 +93,13 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 7, buffer.get());
- assertEquals("Word length", 7, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(7, buffer.get(), "Word length");
+ assertEquals(7, buffer.remaining(), "Word length");
assertEquals('E', buffer.get());
assertEquals('n', buffer.get());
assertEquals('D', buffer.get());
@@ -110,7 +110,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testFilterWordItemEncoding() {
+ void testFilterWordItemEncoding() {
WordItem word = new WordItem("test");
word.setFilter(true);
@@ -119,14 +119,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 4);
assertEquals(0x08, buffer.get());
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -134,7 +134,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testNoRankedNoPositionDataWordItemEncoding() {
+ void testNoRankedNoPositionDataWordItemEncoding() {
WordItem word = new WordItem("test");
word.setRanked(false);
word.setPositionData(false);
@@ -144,14 +144,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 4);
assertEquals(0x05, buffer.get());
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -159,10 +159,10 @@ public class ItemEncodingTestCase {
}
@Test
- public void testAndItemEncoding() {
+ void testAndItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- AndItem and=new AndItem();
+ AndItem and = new AndItem();
and.addItem(a);
and.addItem(b);
@@ -171,21 +171,21 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 1, 0);
- assertEquals("And arity", 2, buffer.get());
+ assertEquals(2, buffer.get(), "And arity");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testNearItemEncoding() {
+ void testNearItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- NearItem near=new NearItem(7);
+ NearItem near = new NearItem(7);
near.addItem(a);
near.addItem(b);
@@ -194,22 +194,22 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 11, 0);
- assertEquals("Near arity", 2, buffer.get());
- assertEquals("Limit", 7, buffer.get());
+ assertEquals(2, buffer.get(), "Near arity");
+ assertEquals(7, buffer.get(), "Limit");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testONearItemEncoding() {
+ void testONearItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- NearItem onear=new ONearItem(7);
+ NearItem onear = new ONearItem(7);
onear.addItem(a);
onear.addItem(b);
@@ -218,18 +218,18 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 12, 0);
- assertEquals("Near arity", 2, buffer.get());
- assertEquals("Limit", 7, buffer.get());
+ assertEquals(2, buffer.get(), "Near arity");
+ assertEquals(7, buffer.get(), "Limit");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testEquivItemEncoding() {
+ void testEquivItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
EquivItem equiv = new EquivItem();
@@ -241,17 +241,17 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 14, 0);
- assertEquals("Equiv arity", 2, buffer.get());
+ assertEquals(2, buffer.get(), "Equiv arity");
assertWord(buffer, "a");
assertWord(buffer, "b");
}
@Test
- public void testWandItemEncoding() {
+ void testWandItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
WeakAndItem wand = new WeakAndItem();
@@ -263,11 +263,11 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 16, 0);
- assertEquals("WeakAnd arity", 2, buffer.get());
- assertEquals("WeakAnd N", 100, buffer.getShort() & 0x3fff);
+ assertEquals(2, buffer.get(), "WeakAnd arity");
+ assertEquals(100, buffer.getShort() & 0x3fff, "WeakAnd N");
assertEquals(0, buffer.get());
assertWord(buffer, "a");
@@ -275,65 +275,66 @@ public class ItemEncodingTestCase {
}
@Test
- public void testPureWeightedStringEncoding() {
+ void testPureWeightedStringEncoding() {
PureWeightedString a = new PureWeightedString("a");
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 3, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(3, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 19, 0);
assertString(buffer, a.getString());
}
@Test
- public void testPureWeightedStringEncodingWithNonDefaultWeight() {
+ void testPureWeightedStringEncodingWithNonDefaultWeight() {
PureWeightedString a = new PureWeightedString("a", 7);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 4, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(4, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 19, 1);
assertWeight(buffer, 7);
assertString(buffer, a.getString());
}
@Test
- public void testPureWeightedIntegerEncoding() {
+ void testPureWeightedIntegerEncoding() {
PureWeightedInteger a = new PureWeightedInteger(23432568763534865l);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 9, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(9, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 20, 0);
- assertEquals("Value", a.getValue(), buffer.getLong());
+ assertEquals(a.getValue(), buffer.getLong(), "Value");
}
@Test
- public void testPureWeightedLongEncodingWithNonDefaultWeight() {
+ void testPureWeightedLongEncodingWithNonDefaultWeight() {
PureWeightedInteger a = new PureWeightedInteger(23432568763534865l, 7);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 10, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(10, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 20, 1);
assertWeight(buffer, 7);
- assertEquals("Value", a.getValue(), buffer.getLong());;
+ assertEquals(a.getValue(), buffer.getLong(), "Value");
+ ;
}
private void assertString(ByteBuffer buffer, String word) {
- assertEquals("Word length", word.length(), buffer.get());
+ assertEquals(word.length(), buffer.get(), "Word length");
for (int i=0; i<word.length(); i++) {
- assertEquals("Character at " + i,word.charAt(i), buffer.get());
+ assertEquals(word.charAt(i), buffer.get(), "Character at " + i);
}
}
private void assertWord(ByteBuffer buffer,String word) {
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
+ assertEquals(0, buffer.get(), "Index length");
assertString(buffer, word);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
index bd0bfd3f29a..1e4418f1b73 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.PhraseSegmentItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test methods changing phrase items.
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class PhraseItemTestCase {
@Test
- public void testAddItem() {
+ void testAddItem() {
PhraseItem p = new PhraseItem();
PhraseSegmentItem pp = new PhraseSegmentItem("", false, false);
PhraseItem ppp = new PhraseItem();
@@ -32,7 +32,7 @@ public class PhraseItemTestCase {
}
@Test
- public void testAddItemWithIndex() {
+ void testAddItemWithIndex() {
PhraseItem p = new PhraseItem();
PhraseSegmentItem pp = new PhraseSegmentItem("", false, false);
PhraseItem ppp = new PhraseItem();
@@ -48,7 +48,7 @@ public class PhraseItemTestCase {
}
@Test
- public void testSetItem() {
+ void testSetItem() {
PhraseItem backup = new PhraseItem();
PhraseSegmentItem segment = new PhraseSegmentItem("", false, false);
PhraseItem innerPhrase = new PhraseItem();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
index 1fe0ded8d6b..a27a11b8f15 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
@@ -3,14 +3,14 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.PredicateQueryItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Magnar Nedland
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertEquals;
public class PredicateQueryItemTestCase {
@Test
- public void requireThatItemConstantsAreSet() {
+ void requireThatItemConstantsAreSet() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(Item.ItemType.PREDICATE_QUERY, item.getItemType());
assertEquals("PREDICATE_QUERY_ITEM", item.getName());
@@ -29,7 +29,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatFeaturesCanBeAdded() {
+ void requireThatFeaturesCanBeAdded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(0, item.getFeatures().size());
item.addFeature("foo", "bar");
@@ -45,7 +45,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatRangeFeaturesCanBeAdded() {
+ void requireThatRangeFeaturesCanBeAdded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(0, item.getRangeFeatures().size());
item.addRangeFeature("foo", 23);
@@ -61,7 +61,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatToStringWorks() {
+ void requireThatToStringWorks() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
item.addFeature("foo", "bar");
@@ -73,7 +73,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatPredicateQueryItemCanBeEncoded() {
+ void requireThatPredicateQueryItemCanBeEncoded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
item.addFeature("foo", "bar");
@@ -84,12 +84,12 @@ public class PredicateQueryItemTestCase {
byte[] actual = new byte[buffer.remaining()];
buffer.get(actual);
assertArrayEquals(new byte[]{
- 23, // PREDICATE_QUERY code 23
- 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- 2, // 2 features
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
- 0}, // no range features
+ 23, // PREDICATE_QUERY code 23
+ 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
+ 2, // 2 features
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
+ 0}, // no range features
actual);
item.addRangeFeature("foo", 23);
@@ -100,19 +100,19 @@ public class PredicateQueryItemTestCase {
actual = new byte[buffer.remaining()];
buffer.get(actual);
assertArrayEquals(new byte[]{
- 23, // PREDICATE_QUERY code 23
- 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- 2, // 2 features
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
- 2, // 2 range features
- 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 23, -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 34, -1, -1, -1, -1, -1, -1, -1, -2}, // key, value, subquery
+ 23, // PREDICATE_QUERY code 23
+ 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
+ 2, // 2 features
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
+ 2, // 2 range features
+ 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 23, -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 34, -1, -1, -1, -1, -1, -1, -1, -2}, // key, value, subquery
actual);
}
@Test
- public void requireThatPredicateQueryItemWithManyAttributesCanBeEncoded() {
+ void requireThatPredicateQueryItemWithManyAttributesCanBeEncoded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
for (int i = 0; i < 200; ++i) {
@@ -126,11 +126,11 @@ public class PredicateQueryItemTestCase {
byte [] expectedPrefix = new byte[]{
23, // PREDICATE_QUERY code 23
9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- (byte)0x80, (byte)0xc8, // 200 features (0x80c8 => 0xc8 == 200)
+ (byte) 0x80, (byte) 0xc8, // 200 features (0x80c8 => 0xc8 == 200)
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- }; // ...
+ }; // ...
assertArrayEquals(expectedPrefix, Arrays.copyOfRange(actual, 0, expectedPrefix.length));
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
index cd8691d9db0..81aa28a5326 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
@@ -4,12 +4,9 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.*;
import com.yahoo.search.Query;
import com.yahoo.search.query.QueryTree;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -17,7 +14,7 @@ import static org.junit.Assert.assertFalse;
public class QueryCanonicalizerTestCase {
@Test
- public void testSingleLevelSingleItemComposite() {
+ void testSingleLevelSingleItemComposite() {
CompositeItem root = new AndItem();
root.addItem(new WordItem("word"));
@@ -25,7 +22,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testSingleLevelSingleItemNonReducibleComposite() {
+ void testSingleLevelSingleItemNonReducibleComposite() {
CompositeItem root = new WeakAndItem();
root.addItem(new WordItem("word"));
@@ -33,7 +30,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelSingleItemComposite() {
+ void testMultilevelSingleItemComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and2 = new AndItem();
@@ -45,7 +42,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelComposite() {
+ void testMultilevelComposite() {
// AND (RANK (AND a b c)) WAND(25,0.0,1.0)
AndItem and = new AndItem();
RankItem rank = new RankItem();
@@ -62,7 +59,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelEmptyComposite() {
+ void testMultilevelEmptyComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and2 = new AndItem();
@@ -73,7 +70,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelMultiBranchEmptyComposite() {
+ void testMultilevelMultiBranchEmptyComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and21 = new AndItem();
@@ -90,7 +87,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelMultiBranchSingleItemComposite() {
+ void testMultilevelMultiBranchSingleItemComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and21 = new AndItem();
@@ -108,7 +105,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelWeakAndCollapsing() {
+ void testMultilevelWeakAndCollapsing() {
CompositeItem root = new WeakAndItem();
CompositeItem l1 = new WeakAndItem();
CompositeItem l2 = new WeakAndItem();
@@ -132,7 +129,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testWeakAndCollapsingRequireSameNAndIndex() {
+ void testWeakAndCollapsingRequireSameNAndIndex() {
CompositeItem root = new WeakAndItem(10);
CompositeItem l1 = new WeakAndItem(100);
CompositeItem l2 = new WeakAndItem(100);
@@ -149,12 +146,12 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNullRoot() {
+ void testNullRoot() {
assertCanonicalized(null, "No query", new Query());
}
@Test
- public void testNestedNull() {
+ void testNestedNull() {
CompositeItem root = new AndItem();
CompositeItem or = new AndItem();
CompositeItem and = new AndItem();
@@ -169,7 +166,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNestedNullItem() {
+ void testNestedNullItem() {
CompositeItem root = new AndItem();
CompositeItem or = new AndItem();
CompositeItem and = new AndItem();
@@ -186,7 +183,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNestedNullAndSingle() {
+ void testNestedNullAndSingle() {
CompositeItem root = new AndItem();
CompositeItem or = new OrItem();
@@ -199,7 +196,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemovalOfUnnecessaryComposites() {
+ void testRemovalOfUnnecessaryComposites() {
CompositeItem root = new AndItem();
CompositeItem or = new OrItem();
@@ -215,21 +212,21 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of the same AND/OR should collapse */
@Test
- public void testMultilevelCollapsing() {
+ void testMultilevelCollapsing() {
CompositeItem root = new AndItem();
CompositeItem l1 = new AndItem();
CompositeItem l2 = new AndItem();
CompositeItem l3 = new AndItem();
-
+
root.addItem(l1);
l1.addItem(new WordItem("l1i1"));
l1.addItem(l2);
-
+
l2.addItem(new WordItem("l2i1"));
l2.addItem(l3);
l2.addItem(new WordItem("l2i2"));
-
+
l3.addItem(new WordItem("l3i1"));
l3.addItem(new WordItem("l3i2"));
@@ -238,7 +235,7 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of different composites should not collapse */
@Test
- public void testMultilevelNonCollapsing() {
+ void testMultilevelNonCollapsing() {
CompositeItem root = new AndItem();
CompositeItem l1 = new AndItem();
CompositeItem l2 = new OrItem();
@@ -259,7 +256,7 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of RANK should collapse */
@Test
- public void testMultilevelRankCollapsing() {
+ void testMultilevelRankCollapsing() {
CompositeItem root = new RankItem();
CompositeItem l1 = new RankItem();
CompositeItem l2 = new RankItem();
@@ -283,7 +280,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNegativeMustHaveNegatives() {
+ void testNegativeMustHaveNegatives() {
CompositeItem root = new NotItem();
root.addItem(new WordItem("positive"));
@@ -291,26 +288,26 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNegative() {
+ void testNegative() {
NotItem root = new NotItem();
root.addNegativeItem(new WordItem("negative"));
- assertCanonicalized("-negative",null, root);
+ assertCanonicalized("-negative", null, root);
}
@Test
- public void testNegativeOnly() {
+ void testNegativeOnly() {
CompositeItem root = new AndItem();
NotItem not = new NotItem();
root.addItem(not);
root.addItem(new WordItem("word"));
not.addNegativeItem(new WordItem("negative"));
- assertCanonicalized("AND (-negative) word",null, root);
+ assertCanonicalized("AND (-negative) word", null, root);
}
@Test
- public void testCollapseFalseItemInAnd() {
+ void testCollapseFalseItemInAnd() {
CompositeItem root = new AndItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem());
@@ -318,7 +315,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInOr() {
+ void testRemoveFalseItemInOr() {
CompositeItem root = new OrItem();
AndItem and = new AndItem(); // this gets collapse to just FALSE, which is then removed
root.addItem(and);
@@ -329,7 +326,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testCollapseFalseItemInNot() {
+ void testCollapseFalseItemInNot() {
CompositeItem root = new NotItem();
root.addItem(new FalseItem()); // false ANDNOT ... is false
root.addItem(new WordItem("i1"));
@@ -337,7 +334,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInNot() {
+ void testRemoveFalseItemInNot() {
CompositeItem root = new NotItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem()); // ... ANDNOT false is redundant
@@ -345,7 +342,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testCollapseFalseItemInRank() {
+ void testCollapseFalseItemInRank() {
CompositeItem root = new RankItem();
root.addItem(new FalseItem()); // false RANK ... is false
root.addItem(new WordItem("i1"));
@@ -353,7 +350,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInRank() {
+ void testRemoveFalseItemInRank() {
CompositeItem root = new RankItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem()); // ... RANK false is redundant
@@ -365,13 +362,13 @@ public class QueryCanonicalizerTestCase {
* (which strictly is an implementation detail which we should rather hide).
*/
@Test
- public void testConnexityAndCloning() {
+ void testConnexityAndCloning() {
Query q = new Query("?query=a%20b");
CompositeItem root = (CompositeItem) q.getModel().getQueryTree().getRoot();
((WordItem) root.getItem(0)).setConnectivity(root.getItem(1), java.lang.Math.E);
q = q.clone();
- assertNull("Not prepared yet", q.getRanking().getProperties().get("vespa.term.1.connexity"));
+ assertNull(q.getRanking().getProperties().get("vespa.term.1.connexity"), "Not prepared yet");
q.prepare();
assertEquals("2", q.getRanking().getProperties().get("vespa.term.1.connexity").get(0));
assertEquals("2.718281828459045", q.getRanking().getProperties().get("vespa.term.1.connexity").get(1));
@@ -385,7 +382,7 @@ public class QueryCanonicalizerTestCase {
* (which strictly is an implementation detail which we should rather hide).
*/
@Test
- public void testSignificance() {
+ void testSignificance() {
Query q = new Query("?query=a%20b");
CompositeItem root = (CompositeItem) q.getModel().getQueryTree().getRoot();
((WordItem) root.getItem(0)).setSignificance(0.5);
@@ -396,7 +393,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testPhraseWeight() {
+ void testPhraseWeight() {
PhraseItem root = new PhraseItem();
root.setWeight(200);
root.addItem(new WordItem("a"));
@@ -404,7 +401,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testEquivDuplicateRemoval() {
+ void testEquivDuplicateRemoval() {
{
EquivItem root = new EquivItem();
root.addItem(new WordItem("a"));
@@ -470,7 +467,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRankDuplicateCheapification() {
+ void testRankDuplicateCheapification() {
AndItem and = new AndItem();
WordItem shoe = new WordItem("shoe", "prod");
and.addItem(shoe);
@@ -491,7 +488,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void queryTreeExceedsAllowedSize() {
+ void queryTreeExceedsAllowedSize() {
Query query = new Query();
QueryTree tree = query.getModel().getQueryTree();
tree.setRoot(new WordItem("A"));
@@ -513,7 +510,7 @@ public class QueryCanonicalizerTestCase {
assertEquals(expectedError, error);
if (canonicalForm == null) {
- assertNull(null, query.getModel().getQueryTree().getRoot());
+ assertNull(query.getModel().getQueryTree().getRoot());
} else {
assertEquals(canonicalForm, query.getModel().getQueryTree().getRoot().toString());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
index a43f1a542c3..12d179b489e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
@@ -6,9 +6,9 @@ import com.yahoo.prelude.query.NotItem;
import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* <p>Tests that the correct query language strings are generated for various
@@ -24,14 +24,14 @@ import static org.junit.Assert.assertEquals;
public class QueryLanguageTestCase {
@Test
- public void testWord() {
+ void testWord() {
WordItem w = new WordItem("test");
assertEquals("test", w.toString());
}
@Test
- public void testWordWithIndex() {
+ void testWordWithIndex() {
WordItem w = new WordItem("test");
w.setIndexName("test.index");
@@ -39,7 +39,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
PhraseItem p = new PhraseItem();
p.addItem(new WordItem("part"));
@@ -49,7 +49,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testPhraseWithIndex() {
+ void testPhraseWithIndex() {
PhraseItem p = new PhraseItem();
p.addItem(new WordItem("part"));
@@ -60,7 +60,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testNotItem() {
+ void testNotItem() {
NotItem n = new NotItem();
n.addNegativeItem(new WordItem("notthis"));
@@ -70,22 +70,22 @@ public class QueryLanguageTestCase {
}
@Test
- public void testLanguagesInQueryParameter() {
+ void testLanguagesInQueryParameter() {
// Right parameter is the parameter given in the query, as language=
// Left parameter is the language sent to linguistics
// Ancient
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-cn");
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-Hans");
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-hans");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-tw");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-Hant");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-hant");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-cn");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-Hans");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-hans");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-tw");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-Hant");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-hant");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh");
assertLanguage(Language.ENGLISH, "en");
assertLanguage(Language.GERMAN, "de");
assertLanguage(Language.JAPANESE, "ja");
- assertLanguage(Language.fromLanguageTag("jp") ,"jp");
+ assertLanguage(Language.fromLanguageTag("jp"), "jp");
assertLanguage(Language.KOREAN, "ko");
// Since 2.0
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
index bfdc9ae1552..1abbc2d87dc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.Parser;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests query trees
@@ -24,7 +24,7 @@ public class QueryTestCase {
/** Tests that query hash and equality is value dependent only */
@Test
- public void testQueryEquality() {
+ void testQueryEquality() {
String query = "RANK (+(AND \"baz gaz faz\" bazar) -\"foo bar foobar\") foofoo xyzzy";
String filter = "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar";
@@ -37,11 +37,11 @@ public class QueryTestCase {
/** Check copy of query trees is a deep copy */
@Test
- public void testDeepCopy() {
+ void testDeepCopy() {
Item root1 = parseQuery("a and b and (c or d) and e rank f andnot g", null, Query.Type.ADVANCED);
Item root2 = root1.clone();
- assertTrue("Item.clone() should be a deep copy.",nonIdenticalTrees(root1, root2));
+ assertTrue(nonIdenticalTrees(root1, root2), "Item.clone() should be a deep copy.");
}
private static Item parseQuery(String query, String filter, Query.Type type) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
index 3032a7b625f..a2f5016645b 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
@@ -3,16 +3,16 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.RangeItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class RangeItemTestCase {
@Test
- public void testRangeConstruction() {
+ void testRangeConstruction() {
verifyRange(new RangeItem(5, 7, 9, "a", true), 9, true);
verifyRange(new RangeItem(5, 7, "a", true), 0, true);
verifyRange(new RangeItem(5, 7, "a"), 0, false);
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
index c05d7d48f6b..198ad2b46f9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
@@ -9,20 +9,18 @@ import com.yahoo.prelude.query.Substring;
import com.yahoo.prelude.query.TermItem;
import com.yahoo.prelude.query.WordAlternativesItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class SameElementItemTestCase {
@Test
- public void testAddItem() {
+ void testAddItem() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
@@ -31,18 +29,18 @@ public class SameElementItemTestCase {
}
@Test
- public void testClone() {
+ void testClone() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
s.addItem(new WordItem("d", "f3"));
assertEquals("structa:{f1:b f2:c f3:d}", s.toString());
- SameElementItem c = (SameElementItem)s.clone();
+ SameElementItem c = (SameElementItem) s.clone();
assertEquals("structa:{f1:b f2:c f3:d}", c.toString());
}
@Test
- public void requireAllChildrenHaveStructMemberNameSet() {
+ void requireAllChildrenHaveStructMemberNameSet() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
@@ -55,7 +53,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireAllowCommonPrefix() {
+ void requireAllowCommonPrefix() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "structaf2"));
@@ -63,7 +61,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireChildrenCanHavePrefixCommonWithParent() {
+ void requireChildrenCanHavePrefixCommonWithParent() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "structa.f2"));
@@ -71,7 +69,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireAllChildrenHaveNonEmptyTerm() {
+ void requireAllChildrenHaveNonEmptyTerm() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("", "f2"));
@@ -83,7 +81,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireNoChildrenAreWordAlternatives() {
+ void requireNoChildrenAreWordAlternatives() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new AndItem());
@@ -91,12 +89,12 @@ public class SameElementItemTestCase {
}
catch (IllegalArgumentException e) { // Success
assertEquals("Child item (AND ) should be an instance of class com.yahoo.prelude.query.TermItem but is class com.yahoo.prelude.query.AndItem",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireAllChildrenAreTermItems() {
+ void requireAllChildrenAreTermItems() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordAlternativesItem("test", true, new Substring("origin"), List.of(new WordAlternativesItem.Alternative("a", 0.3))));
@@ -118,13 +116,13 @@ public class SameElementItemTestCase {
}
@Test
- public void requireExtractSingleItemToExtractSingles() {
+ void requireExtractSingleItemToExtractSingles() {
verifyExtractSingle(new WordItem("b", "f1"));
verifyExtractSingle(new IntItem("7", "f1"));
}
@Test
- public void requireExtractSingleItemToExtractSinglesOnly() {
+ void requireExtractSingleItemToExtractSinglesOnly() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java
index 66653a95dbb..b0271bec896 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java
@@ -1,11 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.test;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.PhraseSegmentItem;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.WordItem;
/**
@@ -16,7 +15,7 @@ import com.yahoo.prelude.query.WordItem;
public class SegmentItemTestCase {
@Test
- public final void test() {
+ final void test() {
PhraseSegmentItem item = new PhraseSegmentItem("a b c", false, true);
item.addItem(new WordItem("a"));
item.addItem(new WordItem("b"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
index 6a13ea130bc..40753ee1533 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WandItem;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
import com.yahoo.prelude.query.textualrepresentation.TextualQueryRepresentation;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Unit tests for WandItem.
*/
@@ -22,7 +22,7 @@ public class WandItemTestCase {
private static final double DELTA = 0.0000001;
@Test
- public void requireThatWandItemCanBeConstructed() {
+ void requireThatWandItemCanBeConstructed() {
WandItem item = new WandItem("myfield", 10);
assertEquals("myfield", item.getIndexName());
assertEquals(10, item.getTargetNumHits());
@@ -32,14 +32,14 @@ public class WandItemTestCase {
}
@Test
- public void requireThatEncodeIsWorking() {
+ void requireThatEncodeIsWorking() {
WandItem item = createSimpleItem();
ByteBuffer actual = ByteBuffer.allocate(128);
ByteBuffer expect = ByteBuffer.allocate(128);
expect.put((byte) 22).put((byte) 1);
Item.putString("myfield", expect);
- expect.put((byte)10); // targetNumHits
+ expect.put((byte) 10); // targetNumHits
expect.putDouble(20); // scoreThreshold
expect.putDouble(2.0); // thresholdBoostFactor
new PureWeightedString("foo", 30).encode(expect);
@@ -53,19 +53,24 @@ public class WandItemTestCase {
}
@Test
- public void requireThatToStringIsWorking() {
- assertEquals("WAND(10,20.0,2.0) myfield{[30]:\"foo\"}", createSimpleItem().toString());
+ void requireThatToStringIsWorking() {
+ assertEquals("WAND(10,20.0,2.0) myfield{[30]:\"foo\"}", createSimpleItem().toString());
}
@Test
- public void requireThatDiscloseIsWorking() {
+ void requireThatDiscloseIsWorking() {
class TestDiscloser implements Discloser {
public final Map<String, Object> props = new HashMap<>();
+
public void addProperty(String key, Object value) {
props.put(key, value);
}
- public void setValue(Object value) {}
- public void addChild(Item item) {}
+
+ public void setValue(Object value) {
+ }
+
+ public void addChild(Item item) {
+ }
}
TestDiscloser discloser = new TestDiscloser();
createSimpleItem().disclose(discloser);
@@ -76,17 +81,17 @@ public class WandItemTestCase {
}
@Test
- public void testTextualRepresentation() {
+ void testTextualRepresentation() {
WandItem item = new WandItem("myfield", 10);
item.addToken("term1", 10);
item.setScoreThreshold(20);
item.setThresholdBoostFactor(2.0);
assertEquals("WAND[index=\"myfield\" scoreThreshold=20.0 targetNumHits=10 thresholdBoostFactor=2.0]{\n" +
- " PURE_WEIGHTED_STRING[weight=10]{\n" +
- " \"term1\"\n" +
- " }\n" +
- "}\n",
- new TextualQueryRepresentation(item).toString());
+ " PURE_WEIGHTED_STRING[weight=10]{\n" +
+ " \"term1\"\n" +
+ " }\n" +
+ "}\n",
+ new TextualQueryRepresentation(item).toString());
}
private static WandItem createSimpleItem() {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
index 8a335c9119d..1cd657a1940 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
@@ -6,19 +6,16 @@ import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WeightedSetItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class WeightedSetItemTestCase {
@Test
- public void testTokenAPI() {
+ void testTokenAPI() {
WeightedSetItem ws = new WeightedSetItem("index");
assertEquals(0, ws.getNumTokens());
assertNull(ws.getTokenWeight("bogus"));
@@ -55,11 +52,11 @@ public class WeightedSetItemTestCase {
}
@Test
- public void testNegativeWeight() {
+ void testNegativeWeight() {
WeightedSetItem ws = new WeightedSetItem("index");
assertEquals(Integer.valueOf(-10), ws.addToken("bad", -10));
assertEquals(1, ws.getNumTokens());
- assertEquals(Integer.valueOf(-10), ws.getTokenWeight("bad"));
+ assertEquals(Integer.valueOf(-10), ws.getTokenWeight("bad"));
}
static class FakeWSItem extends CompositeIndexedItem {
@@ -77,7 +74,7 @@ public class WeightedSetItemTestCase {
}
@Test
- public void testEncoding() {
+ void testEncoding() {
WeightedSetItem item = new WeightedSetItem("index");
// need 2 alternative reference encoding, as the encoding
// order is kept undefined to improve performance.
@@ -94,11 +91,11 @@ public class WeightedSetItemTestCase {
ByteBuffer actual = ByteBuffer.allocate(128);
ByteBuffer expect1 = ByteBuffer.allocate(128);
ByteBuffer expect2 = ByteBuffer.allocate(128);
- expect1.put((byte)15).put((byte)2);
+ expect1.put((byte) 15).put((byte) 2);
Item.putString("index", expect1);
new PureWeightedString("foo", 10).encode(expect1);
new PureWeightedString("bar", 20).encode(expect1);
- expect2.put((byte)15).put((byte)2);
+ expect2.put((byte) 15).put((byte) 2);
Item.putString("index", expect2);
new PureWeightedString("bar", 20).encode(expect2);
new PureWeightedString("foo", 10).encode(expect2);
@@ -110,9 +107,9 @@ public class WeightedSetItemTestCase {
expect2.flip();
if (actual.equals(expect1)) {
- assertFalse(actual.equals(expect2));
+ assertNotEquals(actual, expect2);
} else {
- assertTrue(actual.equals(expect2));
+ assertEquals(actual, expect2);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
index 213f912c0a5..cf65205fe34 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
@@ -11,11 +11,11 @@ import java.util.HashSet;
import java.util.Map;
import com.yahoo.prelude.query.Item;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
import com.yahoo.prelude.query.textualrepresentation.TextualQueryRepresentation;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Test of TextualQueryRepresentation.
@@ -102,14 +102,14 @@ public class TextualQueryRepresentationTestCase {
}
@Test
- public void testBasic() throws Exception {
+ void testBasic() throws Exception {
String basicText = getTextualQueryRepresentation(basic);
assertEquals(getCorrect("basic.txt"), basicText);
}
@Test
- public void testComposite() throws Exception {
+ void testComposite() throws Exception {
String compositeText = getTextualQueryRepresentation(composite);
assertEquals(getCorrect("composite.txt"), compositeText);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
index b3b96299b90..0c24da54ec4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
@@ -18,10 +18,10 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author Steinar Knutsen
@@ -32,9 +32,9 @@ public class CJKSearcherTestCase {
"querytransform/test/cjk-index-info.cfg", null);
@Test
- public void testTermWeight() {
+ void testTermWeight() {
assertTransformed("efg!10", "SAND e!10 fg!10",
- Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL, TestLinguistics.INSTANCE);
+ Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL, TestLinguistics.INSTANCE);
}
/**
@@ -43,14 +43,14 @@ public class CJKSearcherTestCase {
* must combine overlapping tokens as PHRASE, not AND to avoid a too high recall because of the token overlap.
*/
@Test
- public void testCjkQueryWithOverlappingTokens() {
+ void testCjkQueryWithOverlappingTokens() {
// The test language segmenter will segment "bcd" into the overlapping tokens "bc" "cd"
assertTransformed("bcd", "SAND bc cd", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL,
- TestLinguistics.INSTANCE);
+ TestLinguistics.INSTANCE);
// While "efg" will be segmented into one of the standard options, "e" "fg"
assertTransformed("efg", "SAND e fg", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL,
- TestLinguistics.INSTANCE);
+ TestLinguistics.INSTANCE);
}
private void assertTransformed(String queryString, String expected, Query.Type mode, Language actualLanguage,
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
index 498d6ca2980..3aaf941c6f5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
@@ -9,12 +9,12 @@ import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.CollapsePhraseSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Check CollapsePhraseSearcher works and only is triggered when it
@@ -25,14 +25,14 @@ import static org.junit.Assert.assertEquals;
public class CollapsePhraseSearcherTestCase {
@Test
- public void testSimplePositive() {
+ void testSimplePositive() {
PhraseItem root = new PhraseItem();
root.addItem(new WordItem("abc"));
assertEquals("abc", transformQuery(root));
}
@Test
- public void testPositive1() {
+ void testPositive1() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
PhraseItem embedded = new PhraseItem();
@@ -40,11 +40,11 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a bcd e",
- transformQuery(root));
+ transformQuery(root));
}
@Test
- public void testPositive2() {
+ void testPositive2() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
CompositeItem embedded = new AndItem();
@@ -55,21 +55,21 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a (AND bcd def) e",
- transformQuery(root));
+ transformQuery(root));
}
@Test
- public void testNoTerms() {
+ void testNoTerms() {
assertEquals("NULL", transformQuery("?query=" + enc("\"\"")));
}
@Test
- public void testNegative1() {
+ void testNegative1() {
assertEquals("WEAKAND(100) \"abc def\"", transformQuery("?query=" + enc("\"abc def\"")));
}
@Test
- public void testNegative2() {
+ void testNegative2() {
assertEquals("WEAKAND(100) a \"abc def\" b", transformQuery("?query=" + enc("a \"abc def\" b")));
}
@@ -83,7 +83,7 @@ public class CollapsePhraseSearcherTestCase {
}
@Test
- public void testNegative3() {
+ void testNegative3() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
CompositeItem embedded = new AndItem();
@@ -95,7 +95,7 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a (AND bcd \"def ghi\") e",
- transformQuery(root));
+ transformQuery(root));
}
private String transformQuery(String rawQuery) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
index a434fbd9949..16e27303fa8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
@@ -10,11 +10,11 @@ import com.yahoo.search.Query;
import com.yahoo.prelude.querytransform.LiteralBoostSearcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the complete field match query transformer
@@ -24,55 +24,55 @@ import static org.junit.Assert.assertEquals;
public class LiteralBoostSearcherTestCase {
@Test
- public void testSimpleQueryWithBoost() {
+ void testSimpleQueryWithBoost() {
assertEquals("RANK (WEAKAND(100) abc) default_literal:abc",
- transformQuery("?query=abc&source=cluster1&restrict=type1"));
+ transformQuery("?query=abc&source=cluster1&restrict=type1"));
}
@Test
- public void testSimpleQueryNoBoost() {
+ void testSimpleQueryNoBoost() {
assertEquals("WEAKAND(100) abc",
transformQuery("?query=abc&source=cluster1&restrict=type2"));
}
@Test
- public void testQueryWithExplicitIndex() {
+ void testQueryWithExplicitIndex() {
assertEquals("RANK (WEAKAND(100) absolute:abc) absolute_literal:abc",
transformQuery("?query=absolute:abc&source=cluster1&restrict=type1"));
}
@Test
- public void testQueryWithExplicitIndexNoBoost() {
+ void testQueryWithExplicitIndexNoBoost() {
assertEquals("WEAKAND(100) absolute:abc",
transformQuery("?query=absolute:abc&source=cluster1&restrict=type2"));
}
@Test
- public void testQueryWithNegativeBranch() {
- assertEquals("RANK (+(AND abc def) -ghi) "+
- "default_literal:abc default_literal:def",
- transformQuery("?query=abc and def andnot ghi&type=adv&source=cluster1&restrict=type1"));
+ void testQueryWithNegativeBranch() {
+ assertEquals("RANK (+(AND abc def) -ghi) " +
+ "default_literal:abc default_literal:def",
+ transformQuery("?query=abc and def andnot ghi&type=adv&source=cluster1&restrict=type1"));
}
@Test
- public void testJumbledQuery() {
+ void testJumbledQuery() {
assertEquals
- ("RANK (OR (+(OR abc def) -ghi) jkl) " +
- "default_literal:abc default_literal:def default_literal:jkl",
- transformQuery("?query=abc or def andnot ghi or jkl&type=adv&source=cluster1&restrict=type1"));
+ ("RANK (OR (+(OR abc def) -ghi) jkl) " +
+ "default_literal:abc default_literal:def default_literal:jkl",
+ transformQuery("?query=abc or def andnot ghi or jkl&type=adv&source=cluster1&restrict=type1"));
}
@Test
- public void testTermindexQuery() {
- assertEquals("RANK (+(WEAKAND(100) a b d) -c) default_literal:a "+
- "default_literal:b default_literal:d",
- transformQuery("?query=a b -c d&source=cluster1&restrict=type1"));
+ void testTermindexQuery() {
+ assertEquals("RANK (+(WEAKAND(100) a b d) -c) default_literal:a " +
+ "default_literal:b default_literal:d",
+ transformQuery("?query=a b -c d&source=cluster1&restrict=type1"));
}
@Test
- public void testQueryWithoutBoost() {
+ void testQueryWithoutBoost() {
assertEquals("RANK (AND nonexistant a nonexistant b) default_literal:nonexistant default_literal:a default_literal:nonexistant default_literal:b",
- transformQuery("?query=nonexistant:a nonexistant:b&source=cluster1&restrict=type1&type=all"));
+ transformQuery("?query=nonexistant:a nonexistant:b&source=cluster1&restrict=type1&type=all"));
}
private String transformQuery(String rawQuery) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
index 107a82f3186..16d6bd40178 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
@@ -5,41 +5,41 @@ import com.yahoo.search.Query;
import com.yahoo.prelude.querytransform.NoRankingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NoRankingSearcherTestCase {
Searcher s = new NoRankingSearcher();
@Test
- public void testDoSearch() {
+ void testDoSearch() {
Query q = new Query("?query=a&sorting=%2ba%20-b&ranking=hello");
assertEquals("hello", q.getRanking().getProfile());
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("unranked", q.getRanking().getProfile());
- }
+ }
@Test
- public void testSortOnRelevanceAscending() {
+ void testSortOnRelevanceAscending() {
Query q = new Query("?query=a&sorting=%2ba%20-b%20-[rank]&ranking=hello");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("hello", q.getRanking().getProfile());
- }
+ }
@Test
- public void testSortOnRelevanceDescending() {
+ void testSortOnRelevanceDescending() {
Query q = new Query("?query=a&sorting=%2ba%20-b%20-[rank]&ranking=hello");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("hello", q.getRanking().getProfile());
- }
+ }
@Test
- public void testNoSorting() {
+ void testNoSorting() {
Query q = new Query("?query=a");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("default", q.getRanking().getProfile());
- }
+ }
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
index 462e57a2b37..5a090a51415 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
@@ -7,9 +7,9 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.NonPhrasingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests non-phrasing
@@ -21,58 +21,58 @@ public class NonPhrasingSearcherTestCase {
private Searcher searcher;
@Test
- public void testSingleWordNonPhrasing() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleWordNonPhrasing() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+aword+kanoo");
+ Query query = new Query("?query=void+aword+kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
assertEquals("WEAKAND(100) void kanoo", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testMultipleWordNonPhrasing() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testMultipleWordNonPhrasing() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+tudor+vidor+kanoo");
+ Query query = new Query("?query=void+tudor+vidor+kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(2,item.getItemCount());
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(1)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(2, item.getItemCount());
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(1)).getWord());
}
@Test
- public void testNoNonPhrasingIfNoOtherPhrases() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoNonPhrasingIfNoOtherPhrases() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=tudor+vidor");
+ Query query = new Query("?query=tudor+vidor");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(2,item.getItemCount());
- assertEquals("tudor",((WordItem)item.getItem(0)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(1)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(2, item.getItemCount());
+ assertEquals("tudor", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(1)).getWord());
}
@Test
- public void testNoNonPhrasingIfSuggestOnly() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoNonPhrasingIfSuggestOnly() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+tudor+vidor+kanoo&suggestonly=true");
+ Query query = new Query("?query=void+tudor+vidor+kanoo&suggestonly=true");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(4,item.getItemCount());
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("tudor",((WordItem)item.getItem(1)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(2)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(3)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(4, item.getItemCount());
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("tudor", ((WordItem) item.getItem(1)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(2)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(3)).getWord());
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
index 7ab50118c6d..239f4500297 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.querytransform.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableList;
import com.yahoo.language.Linguistics;
@@ -19,7 +19,7 @@ import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.querytransform.NormalizingSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -38,35 +38,35 @@ public class NormalizingSearcherTestCase {
private static final Linguistics linguistics = new SimpleLinguistics();
@Test
- public void testNoNormalizingNecssary() {
+ void testNoNormalizingNecssary() {
Query query = new Query("/search?query=bilen&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) bilen", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAttributeQuery() {
+ void testAttributeQuery() {
Query query = new Query("/search?query=attribute:" + enc("b\u00e9yonc\u00e8 b\u00e9yonc\u00e8") + "&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) attribute:b\u00e9yonc\u00e8 beyonce", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testOneTermNormalizing() {
+ void testOneTermNormalizing() {
Query query = new Query("/search?query=b\u00e9yonc\u00e8&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) beyonce", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testOneTermNoNormalizingDifferentSearchDef() {
+ void testOneTermNoNormalizingDifferentSearchDef() {
Query query = new Query("/search?query=b\u00e9yonc\u00e8&search=cluster1&restrict=type2");
createExecution().search(query);
assertEquals("WEAKAND(100) béyoncè", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testTwoTermQuery() throws UnsupportedEncodingException {
+ void testTwoTermQuery() throws UnsupportedEncodingException {
Query query = new Query("/search?query=" + enc("b\u00e9yonc\u00e8 beyonc\u00e9") + "&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) beyonce beyonce", query.getModel().getQueryTree().getRoot().toString());
@@ -82,7 +82,7 @@ public class NormalizingSearcherTestCase {
}
@Test
- public void testPhraseQuery() {
+ void testPhraseQuery() {
Query query = new Query("/search?query=" + enc("\"b\u00e9yonc\u00e8 beyonc\u00e9\"") + "&search=cluster1&restrict=type1");
query.getTrace().setLevel(2);
createExecution().search(query);
@@ -90,7 +90,7 @@ public class NormalizingSearcherTestCase {
}
@Test
- public void testLiteralBoost() {
+ void testLiteralBoost() {
Query query = new Query("/search?query=nop&search=cluster1&restrict=type1");
List<WordAlternativesItem.Alternative> terms = new ArrayList<>();
Substring origin = new Substring(0, 5, "h\u00F4tels");
@@ -107,12 +107,12 @@ public class NormalizingSearcherTestCase {
assertEquals(.7d * .7d, a.exactness, 1e-15);
}
}
- assertTrue("Did not find the expected normalized form \"hotel\".", foundHotel);
+ assertTrue(foundHotel, "Did not find the expected normalized form \"hotel\".");
}
@Test
- public void testPhraseSegmentNormalization() {
+ void testPhraseSegmentNormalization() {
Query query = new Query("/search?query=&search=cluster1&restrict=type1");
PhraseSegmentItem phraseSegment = new PhraseSegmentItem("default", false, false);
phraseSegment.addItem(new WordItem("net"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
index 623c480796c..da7b29272a2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
@@ -5,14 +5,11 @@ import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.PhraseMatcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -20,118 +17,118 @@ import static org.junit.Assert.assertNull;
public class PhraseMatcherTestCase {
@Test
- public void testSingleItemMatching() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleItemMatching() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
matcher.setMatchSingleItems(true);
- List<?> matches=matcher.matchPhrases(new WordItem("aword"));
+ List<?> matches = matcher.matchPhrases(new WordItem("aword"));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("aword"),i.next());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("aword"), i.next());
assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingCaseInsensitive() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleItemMatchingCaseInsensitive() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
matcher.setMatchSingleItems(true);
final String mixedCase = "aWoRD";
- List<?> matches=matcher.matchPhrases(new WordItem(mixedCase));
+ List<?> matches = matcher.matchPhrases(new WordItem(mixedCase));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(mixedCase),i.next());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(mixedCase), i.next());
assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
+ void testSingleItemMatchingWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
matcher.setMatchSingleItems(true);
- List<?> matches=matcher.matchPhrases(new WordItem("awords"));
+ List<?> matches = matcher.matchPhrases(new WordItem("awords"));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("awords"),i.next());
- assertEquals("aword",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("awords"), i.next());
+ assertEquals("aword", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingCaseInsensitiveWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
+ void testSingleItemMatchingCaseInsensitiveWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
matcher.setMatchSingleItems(true);
final String mixedCase = "aWoRDS";
- List<?> matches=matcher.matchPhrases(new WordItem(mixedCase));
+ List<?> matches = matcher.matchPhrases(new WordItem(mixedCase));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(mixedCase),i.next());
- assertEquals("aword",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(mixedCase), i.next());
+ assertEquals("aword", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatching() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatching() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("this"));
and.addItem(new WordItem("is"));
and.addItem(new WordItem("a"));
and.addItem(new WordItem("test"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("this"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("a"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("test"),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("this"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("a"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("test"), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingCaseInsensitive() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingCaseInsensitive() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
final String firstWord = "thIs";
and.addItem(new WordItem(firstWord));
@@ -142,93 +139,93 @@ public class PhraseMatcherTestCase {
final String fourthWord = "tEst";
and.addItem(new WordItem(fourthWord));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(firstWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(secondWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(thirdWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(fourthWord),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(firstWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(secondWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(thirdWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(fourthWord), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingWithNumber() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingWithNumber() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("this"));
and.addItem(new WordItem("is"));
and.addItem(new IntItem("3"));
and.addItem(new WordItem("tests"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("this"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new IntItem("3"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("tests"),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("this"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new IntItem("3"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("tests"), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("thi"));
and.addItem(new WordItem("is"));
and.addItem(new WordItem("a"));
and.addItem(new WordItem("tests"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("thi"),i.next());
- assertEquals("this",i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("a"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("tests"),i.next());
- assertEquals("test",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("thi"), i.next());
+ assertEquals("this", i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("a"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("tests"), i.next());
+ assertEquals("test", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingCaseInsensitiveWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingCaseInsensitiveWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
final String firstWord = "thI";
and.addItem(new WordItem(firstWord));
@@ -239,24 +236,24 @@ public class PhraseMatcherTestCase {
final String fourthWord = "tEsts";
and.addItem(new WordItem(fourthWord));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(firstWord),i.next());
- assertEquals("this",i.getReplace());
- assertEquals(new WordItem(secondWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(thirdWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(fourthWord),i.next());
- assertEquals("test",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(firstWord), i.next());
+ assertEquals("this", i.getReplace());
+ assertEquals(new WordItem(secondWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(thirdWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(fourthWord), i.next());
+ assertEquals("test", i.getReplace());
assertFalse(i.hasNext());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
index 8f2ae910d1b..9eca9a5fed8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
@@ -11,10 +11,10 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.PhrasingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests phrasing stuff
@@ -25,104 +25,104 @@ import static org.junit.Assert.assertTrue;
public class PhrasingSearcherTestCase {
@Test
- public void testTotalPhrasing() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
+ void testTotalPhrasing() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
query.getModel().getQueryTree().setRoot(andItem);
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- Item item=((CompositeItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ Item item = ((CompositeItem) query.getModel().getQueryTree().getRoot()).getItem(0);
assertTrue(item instanceof PhraseItem);
- PhraseItem phrase=(PhraseItem)item;
- assertEquals(2,phrase.getItemCount());
- assertEquals("tudor",phrase.getWordItem(0).getWord());
- assertEquals("vidor",phrase.getWordItem(1).getWord());
- assertEquals("someindex",phrase.getIndexName());
+ PhraseItem phrase = (PhraseItem) item;
+ assertEquals(2, phrase.getItemCount());
+ assertEquals("tudor", phrase.getWordItem(0).getWord());
+ assertEquals("vidor", phrase.getWordItem(1).getWord());
+ assertEquals("someindex", phrase.getIndexName());
}
@Test
- public void testPartialPhrasing() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testPartialPhrasing() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void%20tudor%20vidor%20kanoo");
+ Query query = new Query("?query=void%20tudor%20vidor%20kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(2)).getWord());
-
- PhraseItem phrase=(PhraseItem)item.getItem(1);
- assertEquals(2,phrase.getItemCount());
- assertEquals("tudor",phrase.getWordItem(0).getWord());
- assertEquals("vidor",phrase.getWordItem(1).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(2)).getWord());
+
+ PhraseItem phrase = (PhraseItem) item.getItem(1);
+ assertEquals(2, phrase.getItemCount());
+ assertEquals("tudor", phrase.getWordItem(0).getWord());
+ assertEquals("vidor", phrase.getWordItem(1).getWord());
}
@Test
- public void testPartialPhrasingSuggestOnly() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testPartialPhrasingSuggestOnly() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void%20tudor%20vidor%20kanoo&suggestonly=true");
+ Query query = new Query("?query=void%20tudor%20vidor%20kanoo&suggestonly=true");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals("void", ((WordItem)item.getItem(0)).getWord());
- assertEquals("tudor",((WordItem)item.getItem(1)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(2)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(3)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("tudor", ((WordItem) item.getItem(1)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(2)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(3)).getWord());
}
@Test
- public void testNoPhrasingIfDifferentIndices() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","anotherindex"));
+ void testNoPhrasingIfDifferentIndices() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "anotherindex"));
query.getModel().getQueryTree().setRoot(andItem);
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
assertTrue(item.getItem(0) instanceof WordItem);
- WordItem word=(WordItem)item.getItem(0);
- assertEquals("tudor",word.getWord());
+ WordItem word = (WordItem) item.getItem(0);
+ assertEquals("tudor", word.getWord());
assertTrue(item.getItem(1) instanceof WordItem);
- word=(WordItem)item.getItem(1);
- assertEquals("vidor",word.getWord());
+ word = (WordItem) item.getItem(1);
+ assertEquals("vidor", word.getWord());
}
@Test
- public void testMultiplePhrases() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
-
- OrItem orItem=new OrItem();
+ void testMultiplePhrases() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
+
+ OrItem orItem = new OrItem();
andItem.addItem(orItem);
orItem.addItem(new WordItem("tudor"));
- AndItem andItem2=new AndItem();
- andItem2.addItem(new WordItem("this","anotherindex"));
- andItem2.addItem(new WordItem("is","anotherindex"));
- andItem2.addItem(new WordItem("a","anotherindex"));
- andItem2.addItem(new WordItem("test","anotherindex"));
- andItem2.addItem(new WordItem("tudor","anotherindex"));
- andItem2.addItem(new WordItem("vidor","anotherindex"));
+ AndItem andItem2 = new AndItem();
+ andItem2.addItem(new WordItem("this", "anotherindex"));
+ andItem2.addItem(new WordItem("is", "anotherindex"));
+ andItem2.addItem(new WordItem("a", "anotherindex"));
+ andItem2.addItem(new WordItem("test", "anotherindex"));
+ andItem2.addItem(new WordItem("tudor", "anotherindex"));
+ andItem2.addItem(new WordItem("vidor", "anotherindex"));
orItem.addItem(andItem2);
orItem.addItem(new WordItem("vidor"));
@@ -134,12 +134,12 @@ public class PhrasingSearcherTestCase {
}
@Test
- public void testNoDetection() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoDetection() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query();
- AndItem andItem=new AndItem();
+ Query query = new Query();
+ AndItem andItem = new AndItem();
andItem.addItem(new WordItem("no"));
andItem.addItem(new WordItem("such"));
andItem.addItem(new WordItem("phrase"));
@@ -152,11 +152,11 @@ public class PhrasingSearcherTestCase {
}
@Test
- public void testNoFileNoChange() {
+ void testNoFileNoChange() {
Searcher searcher = new PhrasingSearcher("");
- Query query=new Query();
- AndItem andItem=new AndItem();
+ Query query = new Query();
+ AndItem andItem = new AndItem();
andItem.addItem(new WordItem("no", "anindex"));
andItem.addItem(new WordItem("such", "anindex"));
andItem.addItem(new WordItem("phrase", "indexo"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
index b8c5244fb98..16bfd5f315e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
@@ -13,11 +13,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -25,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class QueryRewriteTestCase {
@Test
- public void testOptimizeByRestrict() {
+ void testOptimizeByRestrict() {
Query query = new Query("?query=sddocname:music");
query.getModel().setRestrict("music");
QueryRewrite.optimizeByRestrict(query);
@@ -33,7 +31,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void requireThatOptimizeByRestrictSimplifiesORItemsThatHaveFullRecallAndDontImpactRank() {
+ void requireThatOptimizeByRestrictSimplifiesORItemsThatHaveFullRecallAndDontImpactRank() {
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "foo", "sddocname:foo");
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "bar", "sddocname:bar");
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "baz", "sddocname:baz");
@@ -48,16 +46,16 @@ public class QueryRewriteTestCase {
}
@Test
- public void testRestrictRewriteDoesNotRemoveRankContributingTerms() {
+ void testRestrictRewriteDoesNotRemoveRankContributingTerms() {
Query query = query("sddocname:per OR foo OR bar", "per");
assertRewritten(query, "OR sddocname:per foo bar");
- ((OrItem)query.getModel().getQueryTree().getRoot()).getItem(2).setRanked(false); // set 'bar' unranked
+ ((OrItem) query.getModel().getQueryTree().getRoot()).getItem(2).setRanked(false); // set 'bar' unranked
assertRewritten(query, "OR sddocname:per foo");
assertRewritten("sddocname:per OR foo OR (bar AND fuz)", "per", "OR sddocname:per foo (AND bar fuz)");
}
@Test
- public void testRankContributingTermsAreNotRemovedOnFullRecall() {
+ void testRankContributingTermsAreNotRemovedOnFullRecall() {
Query query = new Query(QueryTestCase.httpEncode("?query=default:term1 OR default:term2 OR default:term3 OR sddocname:per&type=adv&recall=+id:1&restrict=per"));
RecallSearcher searcher = new RecallSearcher();
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -67,7 +65,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void requireThatOptimizeByRestrictSimplifiesANDItemsThatHaveZeroRecall() {
+ void requireThatOptimizeByRestrictSimplifiesANDItemsThatHaveZeroRecall() {
assertRewritten("sddocname:foo AND bar AND baz", "cox", "NULL");
assertRewritten("foo AND sddocname:bar AND baz", "cox", "NULL");
assertRewritten("foo AND bar AND sddocname:baz", "cox", "NULL");
@@ -82,7 +80,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void testRestrictRewrite() {
+ void testRestrictRewrite() {
assertRewritten("a AND b", "per", "AND a b");
assertRewritten("a OR b", "per", "OR a b");
assertRewritten("sddocname:per", "per", "sddocname:per");
@@ -94,9 +92,9 @@ public class QueryRewriteTestCase {
assertRewritten("sddocname:perder ANDNOT b", "per", "NULL");
assertRewritten("a ANDNOT sddocname:per a b", "per", "NULL");
}
-
+
@Test
- public void testRestrictRank() {
+ void testRestrictRank() {
assertRewritten("sddocname:per&filter=abc", "espen", "NULL");
assertRewritten("sddocname:per&filter=abc", "per", "RANK sddocname:per |abc");
assertRewritten("sddocname:per RANK bar", "per", "RANK sddocname:per bar");
@@ -119,7 +117,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void assertAndNotMovedUp() {
+ void assertAndNotMovedUp() {
Query query = new Query();
NotItem not = new NotItem();
not.addPositiveItem(new WordItem("a"));
@@ -139,7 +137,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void assertMultipleAndNotIsCollapsed() {
+ void assertMultipleAndNotIsCollapsed() {
Query query = new Query();
NotItem not1 = new NotItem();
not1.addPositiveItem(new WordItem("a"));
@@ -165,7 +163,7 @@ public class QueryRewriteTestCase {
AndItem a = (AndItem) n.getPositiveItem();
assertEquals(5, a.getItemCount());
assertEquals("na1", n.getItem(1).toString());
- assertEquals("na2",n.getItem(2).toString());
+ assertEquals("na2", n.getItem(2).toString());
assertEquals("nb", n.getItem(3).toString());
assertEquals("1", a.getItem(0).toString());
assertEquals("a", a.getItem(1).toString());
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
index 409d01b5c46..e2d1555701c 100755
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
@@ -16,12 +16,9 @@ import com.yahoo.prelude.query.NullItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.RecallSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -29,7 +26,7 @@ import static org.junit.Assert.fail;
public class RecallSearcherTestCase {
@Test
- public void testIgnoreEmptyProperty() {
+ void testIgnoreEmptyProperty() {
RecallSearcher searcher = new RecallSearcher();
Query query = new Query();
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -38,7 +35,7 @@ public class RecallSearcherTestCase {
}
@Test
- public void testDenyRankItems() {
+ void testDenyRankItems() {
RecallSearcher searcher = new RecallSearcher();
Query query = new Query("?recall=foo");
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -46,7 +43,7 @@ public class RecallSearcherTestCase {
}
@Test
- public void testParse() {
+ void testParse() {
List<String> empty = new ArrayList<>();
assertQueryTree("?query=foo", Arrays.asList("foo"), empty);
assertQueryTree("?recall=%2bfoo", empty, Arrays.asList("foo"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
index 55ce7ed4e99..bcb243b4563 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
@@ -17,10 +17,10 @@ import com.yahoo.search.config.IndexInfoConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:mathiasm@yahoo-inc.com">Mathias M. Lidal</a>
@@ -32,13 +32,13 @@ public class StemmingSearcherTestCase {
"querytransform/test/", null);
@Test
- public void testStemOnlySomeTerms() {
+ void testStemOnlySomeTerms() {
assertStem("/search?query=Holes in CVS and Subversion nostem:Found",
- "WEAKAND(100) hole in cvs and subversion nostem:Found");
+ "WEAKAND(100) hole in cvs and subversion nostem:Found");
}
@Test
- public void testPhraseSegmentTransforms() {
+ void testPhraseSegmentTransforms() {
Query q1 = buildQueryWithSegmentPhrase();
executeStemming(q1);
assertEquals("AND a 'd e'", q1.getModel().getQueryTree().getRoot().toString());
@@ -61,64 +61,65 @@ public class StemmingSearcherTestCase {
}
@Test
- public void testPreserveConnectivityToPhrase() {
+ void testPreserveConnectivityToPhrase() {
Query q1 = buildQueryWithSegmentPhrase();
- CompositeItem r = (CompositeItem)q1.getModel().getQueryTree().getRoot();
- WordItem first = (WordItem)r.getItem(0);
- PhraseSegmentItem second = (PhraseSegmentItem)r.getItem(1);
+ CompositeItem r = (CompositeItem) q1.getModel().getQueryTree().getRoot();
+ WordItem first = (WordItem) r.getItem(0);
+ PhraseSegmentItem second = (PhraseSegmentItem) r.getItem(1);
first.setConnectivity(second, 1.0d);
executeStemming(q1);
assertEquals("AND a 'd e'", q1.getModel().getQueryTree().getRoot().toString());
- r = (CompositeItem)q1.getModel().getQueryTree().getRoot();
- first = (WordItem)r.getItem(0);
- second = (PhraseSegmentItem)r.getItem(1);
+ r = (CompositeItem) q1.getModel().getQueryTree().getRoot();
+ first = (WordItem) r.getItem(0);
+ second = (PhraseSegmentItem) r.getItem(1);
var origSecond = first.getConnectedItem();
- assertEquals("Connectivity incorrect.", second, first.getConnectedItem());
+ assertEquals(second, first.getConnectedItem(), "Connectivity incorrect.");
}
@Test
- public void testDontStemPrefixes() {
+ void testDontStemPrefixes() {
assertStem("/search?query=ist*&language=de", "WEAKAND(100) ist*");
}
@Test
- public void testStemming() {
+ void testStemming() {
Query query = new Query("/search?query=");
executeStemming(query);
assertTrue(query.getModel().getQueryTree().getRoot() instanceof NullItem);
}
@Test
- public void testNounStemming() {
+ void testNounStemming() {
assertStem("/search?query=noun:towers noun:tower noun:tow",
- "WEAKAND(100) noun:tower noun:tower noun:tow");
+ "WEAKAND(100) noun:tower noun:tower noun:tow");
assertStem("/search?query=notnoun:towers notnoun:tower notnoun:tow",
- "WEAKAND(100) notnoun:tower notnoun:tower notnoun:tow");
+ "WEAKAND(100) notnoun:tower notnoun:tower notnoun:tow");
}
+ @SuppressWarnings("deprecation")
@Test
- public void testEmptyIndexInfo() {
+ void testEmptyIndexInfo() {
String indexInfoConfigID = "file:src/test/java/com/yahoo/prelude/querytransform/test/emptyindexinfo.cfg";
ConfigGetter<IndexInfoConfig> getter = new ConfigGetter<>(IndexInfoConfig.class);
IndexInfoConfig config = getter.getConfig(indexInfoConfigID);
- IndexFacts indexFacts = new IndexFacts(new IndexModel(config, (QrSearchersConfig)null));
+ IndexFacts indexFacts = new IndexFacts(new IndexModel(config, (QrSearchersConfig) null));
Query q = new Query(QueryTestCase.httpEncode("?query=cars"));
new Execution(new Chain<Searcher>(new StemmingSearcher(linguistics)),
- Execution.Context.createContextStub(indexFacts, linguistics)).search(q);
+ Execution.Context.createContextStub(indexFacts, linguistics)).search(q);
assertEquals("WEAKAND(100) cars", q.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testLiteralBoost() {
+ void testLiteralBoost() {
Query q = new Query(QueryTestCase.httpEncode("/search?language=en&search=three"));
WordItem scratch = new WordItem("trees", true);
scratch.setStemmed(false);
q.getModel().getQueryTree().setRoot(scratch);
executeStemming(q);
- assertTrue("Expected a set of word alternatives as root.",
- q.getModel().getQueryTree().getRoot() instanceof WordAlternativesItem);
+ assertTrue(q.getModel().getQueryTree().getRoot() instanceof WordAlternativesItem,
+ "Expected a set of word alternatives as root.");
WordAlternativesItem w = (WordAlternativesItem) q.getModel().getQueryTree().getRoot();
boolean foundExpectedBaseForm = false;
for (WordAlternativesItem.Alternative a : w.getAlternatives()) {
@@ -127,16 +128,16 @@ public class StemmingSearcherTestCase {
foundExpectedBaseForm = true;
}
}
- assertTrue("Did not find original word form in query.", foundExpectedBaseForm);
+ assertTrue(foundExpectedBaseForm, "Did not find original word form in query.");
}
@Test
- public void testMultipleStemming() {
+ void testMultipleStemming() {
Query q = new Query(QueryTestCase.httpEncode("/search?language=en&search=four&query=trees \"nouns girls\" flowers \"a verbs a\" girls&default-index=foobar"));
executeStemming(q);
- assertEquals("WEAKAND(100) WORD_ALTERNATIVES foobar:[ tree(0.7) trees(1.0) ] "+
- "foobar:\"noun girl\" WORD_ALTERNATIVES foobar:[ flower(0.7) flowers(1.0) ] "+
- "foobar:\"a verb a\" WORD_ALTERNATIVES foobar:[ girl(0.7) girls(1.0) ]", q.getModel().getQueryTree().getRoot().toString());
+ assertEquals("WEAKAND(100) WORD_ALTERNATIVES foobar:[ tree(0.7) trees(1.0) ] " +
+ "foobar:\"noun girl\" WORD_ALTERNATIVES foobar:[ flower(0.7) flowers(1.0) ] " +
+ "foobar:\"a verb a\" WORD_ALTERNATIVES foobar:[ girl(0.7) girls(1.0) ]", q.getModel().getQueryTree().getRoot().toString());
}
private Execution.Context newExecutionContext() {
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
index 4fffc450e74..156a0dcbb3e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
@@ -31,12 +31,9 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChain;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the BlendingSearcher class
@@ -125,7 +122,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testitTwoPhase() {
+ void testitTwoPhase() {
DocumentSourceSearcher chain1 = new DocumentSourceSearcher();
DocumentSourceSearcher chain2 = new DocumentSourceSearcher();
DocumentSourceSearcher chain3 = new DocumentSourceSearcher();
@@ -137,27 +134,63 @@ public class BlendingSearcherTestCase {
Result r3 = new Result(q);
r1.setTotalHitCount(13);
- r1.hits().add(new Hit("http://host1.com", 101){{setSource("one");}});
- r1.hits().add(new Hit("http://host2.com", 102){{setSource("one");}});
- r1.hits().add(new Hit("http://host3.com", 103){{setSource("one");}});
+ r1.hits().add(new Hit("http://host1.com", 101){
+ {
+ setSource("one");
+ }
+ });
+ r1.hits().add(new Hit("http://host2.com", 102){
+ {
+ setSource("one");
+ }
+ });
+ r1.hits().add(new Hit("http://host3.com", 103){
+ {
+ setSource("one");
+ }
+ });
chain1.addResult(q, r1);
r2.setTotalHitCount(17);
- r2.hits().add(new Hit("http://host1.com", 101){{setSource("two");}});
- r2.hits().add(new Hit("http://host2.com", 102){{setSource("two");}});
- r2.hits().add(new Hit("http://host4.com", 104){{setSource("two");}});
+ r2.hits().add(new Hit("http://host1.com", 101){
+ {
+ setSource("two");
+ }
+ });
+ r2.hits().add(new Hit("http://host2.com", 102){
+ {
+ setSource("two");
+ }
+ });
+ r2.hits().add(new Hit("http://host4.com", 104){
+ {
+ setSource("two");
+ }
+ });
chain2.addResult(q, r2);
r3.setTotalHitCount(37);
- r3.hits().add(new Hit("http://host5.com", 100){{setSource("three");}});
- r3.hits().add(new Hit("http://host6.com", 106){{setSource("three");}});
- r3.hits().add(new Hit("http://host7.com", 105){{setSource("three");}});
+ r3.hits().add(new Hit("http://host5.com", 100){
+ {
+ setSource("three");
+ }
+ });
+ r3.hits().add(new Hit("http://host6.com", 106){
+ {
+ setSource("three");
+ }
+ });
+ r3.hits().add(new Hit("http://host7.com", 105){
+ {
+ setSource("three");
+ }
+ });
chain3.addResult(q, r3);
BlendingSearcherWrapper blender1 = new BlendingSearcherWrapper();
blender1.addSource("one", chain1);
blender1.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br1 = new Execution(blender1, Execution.Context.createContextStub()).search(q);
assertEquals(3, br1.getHitCount());
assertEquals(13, br1.getTotalHitCount());
@@ -167,7 +200,7 @@ public class BlendingSearcherTestCase {
blender2.addSource("two", chain1);
blender2.addSource("three", chain2);
blender2.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br2 = new Execution(blender2, Execution.Context.createContextStub()).search(q);
assertEquals(6, br2.getHitCount());
assertEquals(30, br2.getTotalHitCount());
@@ -178,28 +211,28 @@ public class BlendingSearcherTestCase {
blender3.addSource("five", chain2);
blender3.addSource("six", chain3);
blender3.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br3 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(9, br3.getHitCount());
assertEquals(67, br3.getTotalHitCount());
assertEquals("http://host6.com/", br3.hits().get(0).getId().toString());
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br4 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(9, br4.getHitCount());
assertEquals("http://host6.com/", br4.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
Result br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
@@ -207,7 +240,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testMultipleBackendsWithDuplicateRemoval() {
+ void testMultipleBackendsWithDuplicateRemoval() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
Query q = new Query("/search?query=hannibal&search=a,b");
@@ -225,14 +258,14 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result cr = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(1, cr.getHitCount());
assertEquals(101, ((int) cr.hits().get(0).getRelevance().getScore()));
}
@Test
- public void testMultipleBackendsWithErrorMerging() {
+ void testMultipleBackendsWithErrorMerging() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
Query q = new Query("/search?query=hannibal&search=a,b");
@@ -249,25 +282,25 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result cr = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(2, cr.getHitCount());
assertEquals(1, cr.getConcreteHitCount());
com.yahoo.search.result.ErrorHit errorHit = cr.hits().getErrorHit();
Iterator errorIterator = errorHit.errorIterator();
List<String> errorList = Arrays.asList("Source 'a': No backends in service. Try later",
- "Source 'b': 2: Request too large");
+ "Source 'b': 2: Request too large");
String a = errorIterator.next().toString();
- assertTrue(a, errorList.contains(a));
+ assertTrue(errorList.contains(a), a);
String b = errorIterator.next().toString();
- assertTrue(a, errorList.contains(b));
+ assertTrue(errorList.contains(b), a);
assertFalse(errorIterator.hasNext());
assertEquals(102, ((int) cr.hits().get(1).getRelevance().getScore()));
assertEquals(com.yahoo.container.protect.Error.NO_BACKENDS_IN_SERVICE.code, cr.hits().getError().getCode());
}
@Test
- public void testBlendingWithSortSpec() {
+ void testBlendingWithSortSpec() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -310,7 +343,7 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(202, ((int) br.hits().get(0).getRelevance().getScore()));
assertEquals(103, ((int) br.hits().get(1).getRelevance().getScore()));
@@ -326,7 +359,7 @@ public class BlendingSearcherTestCase {
* But are we sure fsearch handles this case correctly?
*/
@Test
- public void testBlendingWithSortSpecAnd2Phase() {
+ void testBlendingWithSortSpecAnd2Phase() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -362,7 +395,7 @@ public class BlendingSearcherTestCase {
blender.addSource("chainedone", docSource1);
blender.addSource("chainedtwo", docSource2);
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(202, ((int) br.hits().get(0).getRelevance().getScore()));
assertEquals(103, ((int) br.hits().get(1).getRelevance().getScore()));
@@ -400,7 +433,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testOnlyFirstBackend() {
+ void testOnlyFirstBackend() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first");
@@ -410,7 +443,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testOnlySecondBackend() {
+ void testOnlySecondBackend() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=second");
@@ -421,7 +454,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testBothBackendsExplicitly() {
+ void testBothBackendsExplicitly() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first,second");
@@ -433,7 +466,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testBothBackendsImplicitly() {
+ void testBothBackendsImplicitly() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana");
@@ -445,7 +478,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testNonexistingBackendCausesError() {
+ void testNonexistingBackendCausesError() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=nonesuch");
@@ -459,7 +492,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testNonexistingBackendsCausesErrorOnFirst() {
+ void testNonexistingBackendsCausesErrorOnFirst() {
// Feel free to change to include all in the detail message...
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=nonesuch,orsuch");
@@ -471,11 +504,11 @@ public class BlendingSearcherTestCase {
assertEquals("Invalid query parameter", e.getMessage());
//TODO: Do not depend on sources order
assertEquals("4: Invalid query parameter: Could not resolve source ref 'nonesuch'. Could not resolve source ref 'orsuch'. Valid source refs are first, second.",
- e.toString());
+ e.toString());
}
@Test
- public void testExistingAndNonExistingBackendCausesBothErrorAndResult() {
+ void testExistingAndNonExistingBackendCausesBothErrorAndResult() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first,nonesuch,second");
@@ -488,11 +521,11 @@ public class BlendingSearcherTestCase {
ErrorMessage e = result.hits().getError();
//TODO: Do not depend on sources order
assertEquals("Could not resolve source ref 'nonesuch'. Valid source refs are first, second.",
- e.getDetailedMessage());
+ e.getDetailedMessage());
}
@Test
- public void testBlendingFederationWithGrouping() {
+ void testBlendingFederationWithGrouping() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -528,22 +561,22 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result result = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(2, result.hits().size());
assertTrue(result.hits().get(0) instanceof RootGroup);
- RootGroup resultRoot1 = (RootGroup)result.hits().get(0);
+ RootGroup resultRoot1 = (RootGroup) result.hits().get(0);
assertEquals(1, resultRoot1.asList().size());
assertTrue(result.hits().get(1) instanceof RootGroup);
- RootGroup resultRoot2 = (RootGroup)result.hits().get(1);
+ RootGroup resultRoot2 = (RootGroup) result.hits().get(1);
assertEquals(2, resultRoot2.asList().size());
}
/** Multiple document types in the same cluster are returned without a top level group representing each */
@Test
- public void testBlendingMultipleDocumentTypesWithGrouping() {
+ void testBlendingMultipleDocumentTypesWithGrouping() {
DocumentSourceSearcher docSource = new DocumentSourceSearcher();
Query q = new Query("/search?query=test");
@@ -574,23 +607,23 @@ public class BlendingSearcherTestCase {
docSource.addResult(q, r);
Chain<Searcher> chain = new Chain<>("main",
- new FillSearcher(),
- new BlendingSearcher(ComponentId.fromString("test"), new QrSearchersConfig.Builder().build()),
- docSource);
- q.setWindow( 0, 10);
+ new FillSearcher(),
+ new BlendingSearcher(ComponentId.fromString("test"), new QrSearchersConfig.Builder().build()),
+ docSource);
+ q.setWindow(0, 10);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(q);
assertEquals(3, result.hits().size());
assertTrue(result.hits().get(0) instanceof Group);
- Group resultSubGroup1 = (Group)result.hits().get(0);
+ Group resultSubGroup1 = (Group) result.hits().get(0);
assertEquals(4, resultSubGroup1.asList().size());
assertTrue(result.hits().get(1) instanceof Group);
- Group resultSubGroup2 = (Group)result.hits().get(1);
+ Group resultSubGroup2 = (Group) result.hits().get(1);
assertEquals(3, resultSubGroup2.asList().size());
assertTrue(result.hits().get(2) instanceof Group);
- Group resultSubGroup3 = (Group)result.hits().get(2);
+ Group resultSubGroup3 = (Group) result.hits().get(2);
assertEquals(2, resultSubGroup3.asList().size());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
index de6a55354fd..4a2a34a64c2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
@@ -21,18 +21,14 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the FieldCollapsingSearcher class
@@ -42,7 +38,7 @@ import static org.junit.Assert.assertTrue;
public class FieldCollapsingSearcherTestCase {
@Test
- public void testFieldCollapsingWithoutHits() {
+ void testFieldCollapsingWithoutHits() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
@@ -59,7 +55,7 @@ public class FieldCollapsingSearcherTestCase {
}
@Test
- public void testFieldCollapsingWithoutHitsHugeOffset() {
+ void testFieldCollapsingWithoutHitsHugeOffset() {
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -75,7 +71,7 @@ public class FieldCollapsingSearcherTestCase {
}
@Test
- public void testFieldCollapsing() {
+ void testFieldCollapsing() {
Map<Searcher, Searcher> chained = new HashMap<>();
// Set up
@@ -89,7 +85,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -106,14 +102,14 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testFieldCollapsingTwoPhase() {
+ void testFieldCollapsingTwoPhase() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -125,7 +121,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -142,14 +138,14 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10,0, r.hits().get(0));
- assertHit("http://acme.org/c.html", 9,1, r.hits().get(1));
- assertHit("http://acme.org/e.html", 8,2, r.hits().get(2));
- assertHit("http://acme.org/g.html", 7,3, r.hits().get(3));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
+ assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
+ assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
+ assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testNoCollapsingIfNotAskedTo() {
+ void testNoCollapsingIfNotAskedTo() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher();
@@ -158,7 +154,7 @@ public class FieldCollapsingSearcherTestCase {
Query q = new Query("?query=test_collapse");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -182,10 +178,10 @@ public class FieldCollapsingSearcherTestCase {
* an excessive number of backend requests
*/
@Test
- public void testCollapsingLargeCollection() {
+ void testCollapsingLargeCollection() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
- FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(4,2.0,"amid");
+ FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(4, 2.0, "amid");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(collapse, docsource);
@@ -193,7 +189,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 0));
r.hits().add(createHit("http://acme.org/d.html", 8, 0));
@@ -212,7 +208,7 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(2, r.getHitCount());
assertEquals(2, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/i.html", 5, 1, r.hits().get(1));
// Next results
@@ -220,17 +216,17 @@ public class FieldCollapsingSearcherTestCase {
r = doSearch(collapse, q, 2, 2, chained);
assertEquals(1, r.getHitCount());
assertEquals(2, docsource.getQueryCount());
- assertHit("http://acme.org/j.html",4, 2, r.hits().get(0));
+ assertHit("http://acme.org/j.html", 4, 2, r.hits().get(0));
}
/**
* Tests collapsing of "messy" data
*/
@Test
- public void testCollapsingDispersedCollection() {
+ void testCollapsingDispersedCollection() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
- FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(1,2.0,"amid");
+ FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(1, 2.0, "amid");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(collapse, docsource);
@@ -256,12 +252,12 @@ public class FieldCollapsingSearcherTestCase {
r = doSearch(collapse, q, 0, 3, chained);
assertEquals(2, r.getHitCount());
- assertHit("http://acme.org/a.html",10,1,r.hits().get(0));
- assertHit("http://acme.org/c.html",10,0,r.hits().get(1));
+ assertHit("http://acme.org/a.html", 10, 1, r.hits().get(0));
+ assertHit("http://acme.org/c.html", 10, 0, r.hits().get(1));
}
@Test
- public void testQueryTransformAndCollapsing() {
+ void testQueryTransformAndCollapsing() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -277,14 +273,14 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10,0));
- r.hits().add(createHit("http://acme.org/b.html", 9,0));
- r.hits().add(createHit("http://acme.org/c.html", 9,0));
- r.hits().add(createHit("http://acme.org/d.html", 8,0));
- r.hits().add(createHit("http://acme.org/e.html", 8,0));
- r.hits().add(createHit("http://acme.org/f.html", 7,0));
- r.hits().add(createHit("http://acme.org/g.html", 7,0));
- r.hits().add(createHit("http://acme.org/h.html", 6,1));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
+ r.hits().add(createHit("http://acme.org/b.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/c.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/d.html", 8, 0));
+ r.hits().add(createHit("http://acme.org/e.html", 8, 0));
+ r.hits().add(createHit("http://acme.org/f.html", 7, 0));
+ r.hits().add(createHit("http://acme.org/g.html", 7, 0));
+ r.hits().add(createHit("http://acme.org/h.html", 6, 1));
r.setTotalHitCount(8);
docsource.addResult(q, r);
@@ -294,12 +290,12 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(2, docsource.getQueryCount());
assertEquals(2, r.getHitCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/h.html", 6, 1, r.hits().get(1));
}
@Test
- public void testFieldCollapsingTwoPhaseSelectSummary() {
+ void testFieldCollapsingTwoPhaseSelectSummary() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -311,14 +307,14 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10,0));
- r.hits().add(createHit("http://acme.org/b.html", 9,0));
- r.hits().add(createHit("http://acme.org/c.html", 9,1));
- r.hits().add(createHit("http://acme.org/d.html", 8,1));
- r.hits().add(createHit("http://acme.org/e.html", 8,2));
- r.hits().add(createHit("http://acme.org/f.html", 7,2));
- r.hits().add(createHit("http://acme.org/g.html", 7,3));
- r.hits().add(createHit("http://acme.org/h.html", 6,3));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
+ r.hits().add(createHit("http://acme.org/b.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/c.html", 9, 1));
+ r.hits().add(createHit("http://acme.org/d.html", 8, 1));
+ r.hits().add(createHit("http://acme.org/e.html", 8, 2));
+ r.hits().add(createHit("http://acme.org/f.html", 7, 2));
+ r.hits().add(createHit("http://acme.org/g.html", 7, 3));
+ r.hits().add(createHit("http://acme.org/h.html", 6, 3));
r.setTotalHitCount(8);
docsource.addResult(q, r);
@@ -329,7 +325,7 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
assertTrue(r.isFilled("placeholder"));
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
@@ -343,18 +339,18 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(1, docsource.getQueryCount());
assertFalse(r.isFilled("placeholder"));
assertTrue(r.isFilled("short"));
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testFieldCollapsingWithGrouping() {
+ void testFieldCollapsingWithGrouping() {
// Set up
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
- Chain<Searcher> chain=new Chain<>(collapse,new AddAggregationStyleGroupingResultSearcher(),docsource);
+ Chain<Searcher> chain = new Chain<>(collapse, new AddAggregationStyleGroupingResultSearcher(), docsource);
// Caveat: Collapse is set to false, because that's what the
// collapser asks for
@@ -362,7 +358,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -380,7 +376,7 @@ public class FieldCollapsingSearcherTestCase {
// Assert that the regular hits are collapsed
assertEquals(4 + 1, result.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, result.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, result.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, result.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, result.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, result.hits().get(3));
@@ -388,12 +384,12 @@ public class FieldCollapsingSearcherTestCase {
// Assert that the aggregation group hierarchy is left intact
HitGroup root = getFirstGroupIn(result.hits());
assertNotNull(root);
- assertEquals("group:root:",root.getId().stringValue().substring(0, 11)); // The id ends by a global counter currently
+ assertEquals("group:root:", root.getId().stringValue().substring(0, 11)); // The id ends by a global counter currently
assertEquals(1, root.size());
- HitGroup groupList = (GroupList)root.get("grouplist:g1");
+ HitGroup groupList = (GroupList) root.get("grouplist:g1");
assertNotNull(groupList);
assertEquals(1, groupList.size());
- HitGroup group = (HitGroup)groupList.get("group:long:37");
+ HitGroup group = (HitGroup) groupList.get("group:long:37");
assertNotNull(group);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
index 6a230da4950..a10ecfb99e0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Visit the trace and check JSON payload is stored there when requested.
@@ -30,7 +30,7 @@ public class JSONDebugSearcherTestCase {
private static final String DUMPJSON = "?query=1&dumpjson=jsonfield&tracelevel=6";
@Test
- public void test() {
+ void test() {
Chain<Searcher> searchChain = makeSearchChain("{1: 2}", new JSONDebugSearcher());
Execution e = new Execution(searchChain, Execution.Context.createContextStub());
e.search(new Query(NODUMPJSON));
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
index 706d217269b..bd72ed9fd08 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.searcher.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import com.google.common.collect.ImmutableList;
import com.yahoo.component.ComponentId;
@@ -22,7 +20,7 @@ import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
import com.yahoo.prelude.searcher.JuniperSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.LinkedHashMap;
@@ -113,19 +111,19 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testFieldRewriting() {
+ void testFieldRewriting() {
Result check = createResult("\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&");
assertEquals(1, check.getHitCount());
assertEquals("<hi>XYZ</hi><sep />QWE<hi>JKL</hi>ASD&",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
check = createResult("a&b&c");
assertEquals(1, check.getHitCount());
assertEquals("a&b&c",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
}
@Test
- public void testNoRewritingDueToSearchDefinition() {
+ void testNoRewritingDueToSearchDefinition() {
Result check = createResult("two", "\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&");
assertEquals(1, check.getHitCount());
assertEquals("\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&",
@@ -137,20 +135,20 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testBoldingEquals() {
+ void testBoldingEquals() {
assertNotEquals(new Query("?query=12"), new Query("?query=12&bolding=false"));
}
@Test
- public void testUnboldedRewriting() {
+ void testUnboldedRewriting() {
Result check = createResult("one", "\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&", false);
assertEquals(1, check.getHitCount());
assertEquals("XYZ...QWEJKLASD&",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
}
@Test
- public void testAnnotatedSummaryFields() {
+ void testAnnotatedSummaryFields() {
Result check = createResult("\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E");
assertEquals(1, check.getHitCount());
assertEquals("Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />", check.hits().get(0).getField("dynteaser").toString());
@@ -185,7 +183,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightIsIgnored() {
// Look at bug 5707026 for details.
{
Result check = createResult("of\u001e\u001fyahoo\u001f\uFFFB! \uFFF9Angels\uFFFAangels\uFFFB \uFFF9\u001fYahoo\u001f\uFFFA\u001fyahoo\u001f\uFFFB! \uFFF9Angles\uFFFAangels\uFFFB \uFFF9is\uFFFAbe\u001e");
@@ -202,7 +200,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightAtTheBeginningIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightAtTheBeginningIsIgnored() {
{
Result check = createResult("\u001e\u001fIncomplete\uFFFAincomplete\uFFFB\u001f \uFFF9Original\uFFFAstemmed\uFFFB\u001e");
assertEquals(1, check.getHitCount());
@@ -221,7 +219,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightAtTheEndIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightAtTheEndIsIgnored() {
{
Result check = createResult("\u001e\uFFF9Original\uFFFAstemmed\uFFFB \u001f\uFFF9Incomplete\uFFFAincomplete\u001f\u001e");
assertEquals(1, check.getHitCount());
@@ -240,7 +238,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testExplicitTwoPhase() {
+ void testExplicitTwoPhase() {
Chain<Searcher> searchChain = createSearchChain("one", "\u001e\uFFFAbe\uFFFB within the set of \u001f\uFFF9documents\uFFFAdocument\uFFFB\u001f. \uFFF9phrases\uFFFA\u001E\uFFFA\uFFFB to as a remedy). Each of the \u001fdocument\u001f \uFFF9fields\uFFFAfield\uFFFB in a catalog can be \uFFF9\u001e");
Query q = new Query("?query=12");
Result check = createExecution(searchChain).search(q);
@@ -252,7 +250,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testCompoundWordsBolding() {
+ void testCompoundWordsBolding() {
Result check = createResult("\u001eTest \u001fkommunikations\u001f\u001ffehler\u001f");
assertEquals(1, check.getHitCount());
assertEquals("<sep />Test <hi>kommunikationsfehler</hi>", check.hits().get(0).getField("dynteaser").toString());
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
index 0a250c9b973..0024bf9cd66 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
@@ -11,10 +11,10 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test of MultipleResultsSearcher
@@ -30,7 +30,7 @@ public class MultipleResultsTestCase {
private Chain<Searcher> chain;
- @Before
+ @BeforeEach
public void setUp() {
docSource=new DocumentSourceSearcher();
searcher=new MultipleResultsSearcher();
@@ -38,11 +38,11 @@ public class MultipleResultsTestCase {
}
@Test
- public void testRetrieveHeterogenousHits() {
+ void testRetrieveHeterogenousHits() {
Query query = createQuery();
Result originalResult = new Result(query);
- int n1 = 15, n2 = 25, n3 = 25, n4=25;
+ int n1 = 15, n2 = 25, n3 = 25, n4 = 25;
addHits(originalResult, "others", n1);
addHits(originalResult, "music", n2);
addHits(originalResult, "movies", n3);
@@ -51,23 +51,23 @@ public class MultipleResultsTestCase {
docSource.addResult(query, originalResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size() );
- assertEquals( 15, moviesGroup.size() );
- assertEquals( 3, docSource.getQueryCount() );
+ assertEquals(15, musicGroup.size());
+ assertEquals(15, moviesGroup.size());
+ assertEquals(3, docSource.getQueryCount());
}
@Test
- public void testRetrieveHitsForGroup() {
+ void testRetrieveHitsForGroup() {
Query query = createQuery();
Result originalResult = new Result(query);
- int n1 = 200, n2=30;
+ int n1 = 200, n2 = 30;
addHits(originalResult, "music", n1, 1000);
addHits(originalResult, "movies", n2, 100);
originalResult.setTotalHitCount(n1 + n2);
@@ -81,18 +81,18 @@ public class MultipleResultsTestCase {
docSource.addResult(restrictedQuery, restrictedResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size());
- assertEquals( 15, moviesGroup.size());
+ assertEquals(15, musicGroup.size());
+ assertEquals(15, moviesGroup.size());
}
@Test
- public void testNoHitsForResultSet() {
+ void testNoHitsForResultSet() {
Query query = createQuery();
Result originalResult = new Result(query);
@@ -104,14 +104,14 @@ public class MultipleResultsTestCase {
docSource.addResult(query, originalResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size());
- assertEquals( 0, moviesGroup.size());
+ assertEquals(15, musicGroup.size());
+ assertEquals(0, moviesGroup.size());
}
private void addHits(Result result, String docName, int numHits,
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
index 43911b33161..755a1c11d47 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
@@ -10,12 +10,12 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests for the PosSearcher
@@ -31,7 +31,7 @@ public class PosSearcherTestCase {
* Tests basic lat/long input.
*/
@Test
- public void testBasics() {
+ void testBasics() {
Query q = new Query();
q.properties().set("pos.ll", "N0;E0");
doSearch(searcher, q, 0, 10);
@@ -47,44 +47,44 @@ public class PosSearcherTestCase {
* Tests basic bounding box input.
*/
@Test
- public void testBoundingBox() {
+ void testBoundingBox() {
Query q = new Query();
q.properties().set("pos.bb", "n=51.9,s=50.2,e=0.34,w=-10.01");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-10010000,50200000,340000,51900000]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=0,s=0,e=123.456789,w=-123.456789");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-123456789,0,123456789,0]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=12.345678,s=-12.345678,e=0,w=0");
doSearch(searcher, q, 0, 10);
assertEquals("[2,0,-12345678,0,12345678]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=0.000001,s=-0.000001,e=0.000001,w=-0.000001");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-1,-1,1,1]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
}
/**
* Tests basic bounding box input.
*/
@Test
- public void testBoundingBoxAndRadius() {
+ void testBoundingBoxAndRadius() {
Query q = new Query();
q.properties().set("pos.bb", "n=60.111,s=59.999,e=30.111,w=29.999");
q.properties().set("pos.ll", "N60;E30");
doSearch(searcher, q, 0, 10);
assertEquals(
"[2,29999000,59999000,30111000,60111000]" +
- "(2,30000000,60000000,450668,0,1,0,2147483647)",
+ "(2,30000000,60000000,450668,0,1,0,2147483647)",
q.getRanking().getLocation().toString());
}
@@ -92,7 +92,7 @@ public class PosSearcherTestCase {
* Tests different ways of specifying the radius.
*/
@Test
- public void testRadiusUnits() {
+ void testRadiusUnits() {
Query q = new Query();
q.properties().set("pos.ll", "N0;E0");
q.properties().set("pos.radius", "2km");
@@ -130,7 +130,7 @@ public class PosSearcherTestCase {
* Tests xy position (internal format).
*/
@Test
- public void testXY() {
+ void testXY() {
Query q = new Query();
q.properties().set("pos.xy", "22500;22500");
doSearch(searcher, q, 0, 10);
@@ -144,7 +144,7 @@ public class PosSearcherTestCase {
}
@Test
- public void testNotOverridingOldStyleParameters() {
+ void testNotOverridingOldStyleParameters() {
PosSearcher searcher = new PosSearcher();
Query q = new Query("?query=test&pos.ll=N10.15;E6.08&location=(2,-1100222,0,300,0,1,0,CalcLatLon)");
q.setTraceLevel(1);
@@ -156,7 +156,7 @@ public class PosSearcherTestCase {
* Tests input parameters that should report errors.
*/
@Test
- public void testInvalidInput() {
+ void testInvalidInput() {
PosSearcher searcher = new PosSearcher();
Result result;
@@ -164,18 +164,18 @@ public class PosSearcherTestCase {
q.properties().set("pos.ll", "NE74.14;E14.48");
result = doSearch(searcher, q, 0, 10);
assertEquals("Error in pos parameters: Unable to parse lat/long string 'NE74.14;E14.48': already set direction once, cannot add direction: E",
- ((ErrorHit)result.hits().get(0)).errors().iterator().next().getDetailedMessage());
+ ((ErrorHit) result.hits().get(0)).errors().iterator().next().getDetailedMessage());
q = new Query();
q.properties().set("pos.ll", "NE74.14;E14.48");
q.properties().set("pos.xy", "82400, 72800");
result = doSearch(searcher, q, 0, 10);
assertEquals("Error in pos parameters: Cannot handle both lat/long and xy coords at the same time",
- ((ErrorHit)result.hits().get(0)).errors().iterator().next().getDetailedMessage());
+ ((ErrorHit) result.hits().get(0)).errors().iterator().next().getDetailedMessage());
}
@Test
- public void testWrappingTheNorthPole() {
+ void testWrappingTheNorthPole() {
Query q = new Query();
q.properties().set("pos.ll", "N89.9985365158;E122.163600102");
q.properties().set("pos.radius", "20mi");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
index ef3526f2fb1..be297b5d6c3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
@@ -4,28 +4,26 @@ package com.yahoo.prelude.searcher.test;
import com.yahoo.component.ComponentId;
import com.yahoo.component.chain.Chain;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.language.simple.SimpleLinguistics;
+import com.yahoo.prelude.fastsearch.FastHit;
+import com.yahoo.prelude.hitfield.HitField;
import com.yahoo.prelude.searcher.QrQuotetableConfig;
-import com.yahoo.search.rendering.RendererRegistry;
-import com.yahoo.search.result.Hit;
-import com.yahoo.search.result.Relevance;
+import com.yahoo.prelude.searcher.QuotingSearcher;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
-import com.yahoo.prelude.fastsearch.FastHit;
-import com.yahoo.prelude.hitfield.HitField;
import com.yahoo.search.Searcher;
-import com.yahoo.prelude.searcher.QuotingSearcher;
+import com.yahoo.search.result.Hit;
+import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests hit property quoting.
@@ -34,16 +32,17 @@ import static org.junit.Assert.assertTrue;
*/
public class QuotingSearcherTestCase {
+ @SuppressWarnings("deprecation")
public static QuotingSearcher createQuotingSearcher(String configId) {
QrQuotetableConfig config = new ConfigGetter<>(QrQuotetableConfig.class).getConfig(configId);
return new QuotingSearcher(new ComponentId("QuotingSearcher"), config);
}
@Test
- public void testBasicQuoting() {
+ void testBasicQuoting() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -60,10 +59,10 @@ public class QuotingSearcherTestCase {
}
@Test
- public void testBasicQuotingWithNoisyStrings() {
+ void testBasicQuotingWithNoisyStrings() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -80,10 +79,10 @@ public class QuotingSearcherTestCase {
}
@Test
- public void testFieldQuotingWithNoisyStrings() {
+ void testFieldQuotingWithNoisyStrings() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -101,10 +100,10 @@ public class QuotingSearcherTestCase {
@Test
- public void testNoQuotingWithOtherTypes() {
+ void testNoQuotingWithOtherTypes() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
index 061c9bc5681..9375dc2a4b2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
@@ -17,10 +17,10 @@ import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.yql.YqlParser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Magnar Nedland
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertNull;
public class ValidatePredicateSearcherTestCase {
@Test
- public void testValidQuery() {
+ void testValidQuery() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate(predicate_field,0,{\"age\":20L})";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
@@ -36,7 +36,7 @@ public class ValidatePredicateSearcherTestCase {
}
@Test
- public void testQueryOutOfBounds() {
+ void testQueryOutOfBounds() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate(predicate_field,0,{\"age\":200L})";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
@@ -44,7 +44,7 @@ public class ValidatePredicateSearcherTestCase {
}
@Test
- public void queryFailsWhenPredicateFieldIsUsedInTermSearch() {
+ void queryFailsWhenPredicateFieldIsUsedInTermSearch() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate_field CONTAINS \"true\"";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
index 84b8ef32871..4090fbc5de3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
@@ -2,24 +2,22 @@
package com.yahoo.prelude.searcher.test;
import com.yahoo.component.chain.Chain;
-import com.yahoo.language.simple.SimpleLinguistics;
-import com.yahoo.search.Searcher;
-import com.yahoo.search.rendering.RendererRegistry;
-import com.yahoo.search.searchchain.Execution;
-import com.yahoo.vespa.config.search.AttributesConfig;
-import com.yahoo.search.config.ClusterConfig;
import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.container.QrSearchersConfig;
import com.yahoo.prelude.searcher.ValidateSortingSearcher;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
+import com.yahoo.search.Searcher;
+import com.yahoo.search.config.ClusterConfig;
+import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import com.yahoo.vespa.config.search.AttributesConfig;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Check sorting validation behaves OK.
@@ -30,6 +28,7 @@ public class ValidateSortingSearcherTestCase {
private final ValidateSortingSearcher searcher;
+ @SuppressWarnings("deprecation")
public ValidateSortingSearcherTestCase() {
QrSearchersConfig.Builder qrsCfg = new QrSearchersConfig.Builder();
qrsCfg.searchcluster(new QrSearchersConfig.Searchcluster.Builder().name("giraffes"));
@@ -43,7 +42,7 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void testBasicValidation() {
+ void testBasicValidation() {
assertNotNull(quoteAndTransform("+a -b +c"));
assertNotNull(quoteAndTransform("+a"));
assertNotNull(quoteAndTransform(null));
@@ -54,12 +53,12 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void testInvalidSpec() {
+ void testInvalidSpec() {
assertNull(quoteAndTransform("+a -e +c"));
}
@Test
- public void testConfigOverride() {
+ void testConfigOverride() {
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("title"));
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("uca(title)"));
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("+uca(title)"));
@@ -67,7 +66,7 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void requireThatQueryLocaleIsDefault() {
+ void requireThatQueryLocaleIsDefault() {
assertEquals("[ASCENDING:lowercase(a)]", quoteAndTransform("a"));
assertEquals("[ASCENDING:uca(a,en_US,PRIMARY)]", transform("a", "en-US"));
assertEquals("[ASCENDING:uca(a,en_NO,PRIMARY)]", transform("a", "en-NO"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
index bf99a709df3..3a366882475 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
@@ -8,11 +8,9 @@ import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.prelude.semantics.RuleBase;
import com.yahoo.prelude.semantics.RuleImporter;
import com.yahoo.prelude.semantics.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests parsing of semantic rules bases
@@ -24,33 +22,33 @@ public class SemanticsParserTestCase {
private final static String ROOT = "src/test/java/com/yahoo/prelude/semantics/parser/test/";
@Test
- public void testRuleReading() throws java.io.IOException, ParseException {
+ void testRuleReading() throws java.io.IOException, ParseException {
RuleBase rules = new RuleImporter(new SimpleLinguistics()).importFile(ROOT + "rules.sr");
Iterator<?> i = rules.ruleIterator();
assertEquals("[listing] [preposition] [place] -> listing:[listing] place:[place]!150",
- i.next().toString());
+ i.next().toString());
assertEquals("[listing] [place] +> place:[place]",
- i.next().toString());
+ i.next().toString());
assertEquals("[brand] -> brand:[brand]",
- i.next().toString());
+ i.next().toString());
assertEquals("[category] -> category:[category]",
- i.next().toString());
+ i.next().toString());
assertEquals("digital camera -> digicamera",
- i.next().toString());
+ i.next().toString());
assertEquals("(parameter.ranking='cat'), (parameter.ranking='cat0') -> one", i.next().toString());
assertFalse(i.hasNext());
i = rules.conditionIterator();
assertEquals("[listing] :- restaurant, shop, cafe, hotel",
- i.next().toString());
+ i.next().toString());
assertEquals("[preposition] :- in, at, near",
- i.next().toString());
+ i.next().toString());
assertEquals("[place] :- geary",
- i.next().toString());
+ i.next().toString());
assertEquals("[brand] :- sony, dell",
- i.next().toString());
+ i.next().toString());
assertEquals("[category] :- digital camera, camera, phone",
- i.next().toString());
+ i.next().toString());
assertFalse(i.hasNext());
assertTrue(rules.isDefault());
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java
index d1000e031da..8ff14011483 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test a case reported by Alibaba
@@ -15,23 +15,23 @@ public class AlibabaTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumberReplacement() {
- assertSemantics("AND nokia 3100","3100");
+ void testNumberReplacement() {
+ assertSemantics("AND nokia 3100", "3100");
}
@Test
- public void testRuleFollowingNumber() {
- assertSemantics("lenovo","legend");
+ void testRuleFollowingNumber() {
+ assertSemantics("lenovo", "legend");
}
@Test
- public void testCombinedNumberAndRegular1() {
- assertSemantics("AND lenovo nokia 3100","legend 3100");
+ void testCombinedNumberAndRegular1() {
+ assertSemantics("AND lenovo nokia 3100", "legend 3100");
}
@Test
- public void testCombinedNumberAndRegular2() {
- assertSemantics("AND nokia 3100 lenovo","3100 legend");
+ void testCombinedNumberAndRegular2() {
+ assertSemantics("AND nokia 3100 lenovo", "3100 legend");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java
index 9173053e660..dfba036efae 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests anchoring
@@ -15,7 +15,7 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSingleWordAnchoredBothSides() {
+ void testSingleWordAnchoredBothSides() {
assertSemantics("anchor", "word");
assertSemantics("anchor", "anotherword");
assertSemantics("notthisword", "notthisword");
@@ -23,7 +23,7 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMultiwordAnchored() {
+ void testMultiwordAnchored() {
assertSemantics("anchor", "this is complete");
assertSemantics("AND this is complete toomuch", "this is complete toomuch");
assertSemantics("anchor", "a phrase");
@@ -31,28 +31,28 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testFirstAnchored() {
- assertSemantics("anchor","first");
- assertSemantics("AND anchor andmore","first andmore");
- assertSemantics("AND before first","before first");
- assertSemantics("AND before first andmore","before first andmore");
+ void testFirstAnchored() {
+ assertSemantics("anchor", "first");
+ assertSemantics("AND anchor andmore", "first andmore");
+ assertSemantics("AND before first", "before first");
+ assertSemantics("AND before first andmore", "before first andmore");
}
@Test
- public void testLastAnchored() {
- assertSemantics("anchor","last");
- assertSemantics("AND andmore anchor","andmore last");
- assertSemantics("AND last after","last after");
- assertSemantics("AND andmore last after","andmore last after");
+ void testLastAnchored() {
+ assertSemantics("anchor", "last");
+ assertSemantics("AND andmore anchor", "andmore last");
+ assertSemantics("AND last after", "last after");
+ assertSemantics("AND andmore last after", "andmore last after");
}
@Test
- public void testFirstAndLastAnchored() {
- assertSemantics("AND anchor anchor","first last");
- assertSemantics("AND last first","last first");
- assertSemantics("AND anchor between anchor","first between last");
- assertSemantics("AND anchor last after","first last after");
- assertSemantics("AND before first anchor","before first last");
+ void testFirstAndLastAnchored() {
+ assertSemantics("AND anchor anchor", "first last");
+ assertSemantics("AND last first", "last first");
+ assertSemantics("AND anchor between anchor", "first between last");
+ assertSemantics("AND anchor last after", "first last after");
+ assertSemantics("AND before first anchor", "before first last");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
index 4493038fc86..b138ba50ca9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* Tests that ![a] is interpreted as "default:![a]", not as "!default:[a]",
@@ -16,9 +16,10 @@ public class AutomataNotTestCase extends RuleBaseAbstractTestCase {
super("automatanot.sr", "semantics.fsa");
}
+ // TODO: MAKE THIS WORK!
@Test
- @Ignore // TODO: MAKE THIS WORK!
- public void testAutomataNot() {
+ @Disabled
+ void testAutomataNot() {
if (System.currentTimeMillis() > 0) return;
assertSemantics("carpenter", "carpenter");
assertSemantics("RANK brukbar busname:brukbar", "brukbar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
index 71e36e45acc..a9c7202f7cd 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.prelude.semantics.RuleBase;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests rule bases using automatas for matching
@@ -23,62 +23,63 @@ public class AutomataTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testAutomataRuleBase() {
- RuleBase ruleBase=searcher.getDefaultRuleBase();
- assertEquals(RuleBase.class,ruleBase.getClass());
+ void testAutomataRuleBase() {
+ RuleBase ruleBase = searcher.getDefaultRuleBase();
+ assertEquals(RuleBase.class, ruleBase.getClass());
assertTrue(ruleBase.getSource().endsWith(root + "automatarules.sr"));
- assertEquals(root + "semantics.fsa",ruleBase.getAutomataFile());
+ assertEquals(root + "semantics.fsa", ruleBase.getAutomataFile());
- Query query=new Query("?query=sony+digital+camera");
- ruleBase.analyze(query,0);
+ Query query = new Query("?query=sony+digital+camera");
+ ruleBase.analyze(query, 0);
assertEquals("RANK (WEAKAND(100) sony digital camera) dsp1:sony dsp5:digicamera", query.getModel().getQueryTree().getRoot().toString());
- query=new Query("?query=sony+digital+camera&rules.reload");
- ruleBase=searcher.getDefaultRuleBase();
+ query = new Query("?query=sony+digital+camera&rules.reload");
+ ruleBase = searcher.getDefaultRuleBase();
assertTrue(ruleBase.getSource().endsWith(root + "automatarules.sr"));
- assertEquals(root + "semantics.fsa",ruleBase.getAutomataFile());
- ruleBase.analyze(query,0);
+ assertEquals(root + "semantics.fsa", ruleBase.getAutomataFile());
+ ruleBase.analyze(query, 0);
assertEquals("RANK (WEAKAND(100) sony digital camera) dsp1:sony dsp5:digicamera", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAutomataSingleQuery() {
- assertSemantics("RANK sony dsp1:sony","sony");
+ void testAutomataSingleQuery() {
+ assertSemantics("RANK sony dsp1:sony", "sony");
}
@Test
- public void testAutomataFilterIsIgnored() {
- assertSemantics("RANK sony |something dsp1:sony","sony&filter=something");
- assertSemantics("RANK something |sony","something&filter=sony");
+ void testAutomataFilterIsIgnored() {
+ assertSemantics("RANK sony |something dsp1:sony", "sony&filter=something");
+ assertSemantics("RANK something |sony", "something&filter=sony");
}
@Test
- public void testAutomataPluralMatches() {
- assertSemantics("RANK sonys dsp1:sony","sonys");
+ void testAutomataPluralMatches() {
+ assertSemantics("RANK sonys dsp1:sony", "sonys");
- assertSemantics("RANK (AND car cleaner) dsp1:\"car cleaners\" dsp5:\"car cleaners\"","car cleaner");
+ assertSemantics("RANK (AND car cleaner) dsp1:\"car cleaners\" dsp5:\"car cleaners\"", "car cleaner");
- assertSemantics("RANK (AND sony digitals cameras) dsp1:sony dsp5:digicamera","sony digitals cameras");
+ assertSemantics("RANK (AND sony digitals cameras) dsp1:sony dsp5:digicamera", "sony digitals cameras");
}
@Test
- public void testMatchingMultipleAutomataConditionsSingleWord() {
- assertSemantics("RANK carpenter dsp1:carpenter dsp5:carpenter","carpenter");
+ void testMatchingMultipleAutomataConditionsSingleWord() {
+ assertSemantics("RANK carpenter dsp1:carpenter dsp5:carpenter", "carpenter");
}
@Test
- public void testMatchingMultipleAutomataConditionsPhrase() {
- assertSemantics("RANK (AND car cleaners) dsp1:\"car cleaners\" dsp5:\"car cleaners\"","car cleaners");
+ void testMatchingMultipleAutomataConditionsPhrase() {
+ assertSemantics("RANK (AND car cleaners) dsp1:\"car cleaners\" dsp5:\"car cleaners\"", "car cleaners");
}
+ // TODO: Make this work again
@Test
- @Ignore // TODO: Make this work again
- public void testReplaceOnNoMatch() {
- assertSemantics("nomatch:sonny","sonny&donomatch");
- assertSemantics("RANK sony dsp1:sony","sony&donomatch");
- assertSemantics("RANK sonys dsp1:sony","sonys&donomatch");
- assertSemantics("AND nomatch:sonny nomatch:boy","sonny boy&donomatch");
- assertSemantics("RANK (AND sony nomatch:boy) dsp1:sony","sony boy&donomatch");
+ @Disabled
+ void testReplaceOnNoMatch() {
+ assertSemantics("nomatch:sonny", "sonny&donomatch");
+ assertSemantics("RANK sony dsp1:sony", "sony&donomatch");
+ assertSemantics("RANK sonys dsp1:sony", "sonys&donomatch");
+ assertSemantics("AND nomatch:sonny nomatch:boy", "sonny boy&donomatch");
+ assertSemantics("RANK (AND sony nomatch:boy) dsp1:sony", "sony boy&donomatch");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
index 06f7112f851..3a4f0344994 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
@@ -5,6 +5,8 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.component.chain.Chain;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.search.Query;
import com.yahoo.prelude.semantics.RuleImporter;
@@ -14,9 +16,7 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -50,47 +50,47 @@ public class BacktrackingTestCase {
// Literal terms ---------------
@Test
- public void testMultilevelBacktrackingLiteralTerms() {
- assertSemantics("WEAKAND(100) replaced","word1 word2 word5 word8");
+ void testMultilevelBacktrackingLiteralTerms() {
+ assertSemantics("WEAKAND(100) replaced", "word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingWontReorderOthertermsLiteralTerms() {
- assertSemantics("WEAKAND(100) other1 other2 other3 replaced","other1 other2 other3 word1 word2 word5 word8");
+ void testMultilevelBacktrackingWontReorderOthertermsLiteralTerms() {
+ assertSemantics("WEAKAND(100) other1 other2 other3 replaced", "other1 other2 other3 word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingWithMulticompoundMatchLiteralTerms() {
- assertSemantics("WEAKAND(100) other1 other2 other3 replaced","other1 other2 other3 word1 word2 word5-word8");
+ void testMultilevelBacktrackingWithMulticompoundMatchLiteralTerms() {
+ assertSemantics("WEAKAND(100) other1 other2 other3 replaced", "other1 other2 other3 word1 word2 word5-word8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchBeforeLiteralTerms() {
- assertSemantics("WEAKAND(100) word1 word2 word5 replaced","word1 word2 word5 word1 word2 word5 word8");
+ void testMultilevelBacktrackingPreservePartialMatchBeforeLiteralTerms() {
+ assertSemantics("WEAKAND(100) word1 word2 word5 replaced", "word1 word2 word5 word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchAfterLiteralTerms() {
- assertSemantics("WEAKAND(100) replaced word1 word2 word5","word1 word2 word5 word8 word1 word2 word5 ");
+ void testMultilevelBacktrackingPreservePartialMatchAfterLiteralTerms() {
+ assertSemantics("WEAKAND(100) replaced word1 word2 word5", "word1 word2 word5 word8 word1 word2 word5 ");
}
// reference terms ---------------
@Test
- public void testMultilevelBacktrackingReferenceTerms() {
- assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8","ref1 ref2 ref5 ref8");
+ void testMultilevelBacktrackingReferenceTerms() {
+ assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8", "ref1 ref2 ref5 ref8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchBeforeReferenceTerms() {
+ void testMultilevelBacktrackingPreservePartialMatchBeforeReferenceTerms() {
assertSemantics("WEAKAND(100) ref1 ref2 ref5 ref:ref1 ref:ref2 ref:ref5 ref:ref8",
- "ref1 ref2 ref5 ref1 ref2 ref5 ref8");
+ "ref1 ref2 ref5 ref1 ref2 ref5 ref8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchAfterReferenceTerms() {
+ void testMultilevelBacktrackingPreservePartialMatchAfterReferenceTerms() {
assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8 ref1 ref2 ref5",
- "ref1 ref2 ref5 ref8 ref1 ref2 ref5");
+ "ref1 ref2 ref5 ref8 ref1 ref2 ref5");
}
private Result doSearch(Searcher searcher, Query query, int offset, int hits) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
index 9e590698f4a..334ff8d05a6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests blending rules
@@ -19,9 +19,9 @@ public class BlendingTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter literal matching */
@Test
- public void testLiteralEquals() {
- assertParameterSemantics("AND a sun came cd","a sun came cd","search","[music]");
- assertParameterSemantics("AND driving audi","driving audi","search","[cars]");
+ void testLiteralEquals() {
+ assertParameterSemantics("AND a sun came cd", "a sun came cd", "search", "[music]");
+ assertParameterSemantics("AND driving audi", "driving audi", "search", "[cars]");
//assertParameterSemantics("AND audi music quality","audi music quality","search","carstereos",1);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java
index 0aaa5f2cea7..457a2063173 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests that using rule bases containing cjk characters work
@@ -15,14 +15,14 @@ public class CJKTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testIt() {
- assertSemantics("\u7d22a","a\u7d22");
- assertSemantics("\u7d22a","\u7d22a");
- assertSemantics("brand:\u7d22\u5c3c","\u7d22\u5c3c");
- assertSemantics("brand:\u60e0\u666e","\u60e0\u666e");
- assertSemantics("brand:\u4f73\u80fd","\u4f73\u80fd");
- assertSemantics("AND brand:\u4f73\u80fd \u7d22a","\u4f73\u80fd a\u7d22");
- assertSemantics("\u4f73\u80fd\u7d22\u5c3c","\u4f73\u80fd\u7d22\u5c3c");
+ void testIt() {
+ assertSemantics("\u7d22a", "a\u7d22");
+ assertSemantics("\u7d22a", "\u7d22a");
+ assertSemantics("brand:\u7d22\u5c3c", "\u7d22\u5c3c");
+ assertSemantics("brand:\u60e0\u666e", "\u60e0\u666e");
+ assertSemantics("brand:\u4f73\u80fd", "\u4f73\u80fd");
+ assertSemantics("AND brand:\u4f73\u80fd \u7d22a", "\u4f73\u80fd a\u7d22");
+ assertSemantics("\u4f73\u80fd\u7d22\u5c3c", "\u4f73\u80fd\u7d22\u5c3c");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java
index 988d69a55d3..0c5447c120a 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -17,30 +17,30 @@ public class ComparisonTestCase extends RuleBaseAbstractTestCase {
* different conditions (coffee, island)
*/
@Test
- public void testNamedConditionReturnComparison() {
+ void testNamedConditionReturnComparison() {
// Not sufficient that both conditions are matched
- assertSemantics("AND borneo arabica island:borneo coffee:arabica","borneo arabica");
+ assertSemantics("AND borneo arabica island:borneo coffee:arabica", "borneo arabica");
// They must match the same word
- assertSemantics("AND java noise island:java coffee:java control:ambigous off","java noise");
+ assertSemantics("AND java noise island:java coffee:java control:ambigous off", "java noise");
// Works also when there are other, not-equal matches
assertSemantics("AND borneo arabica java island:borneo island:java coffee:arabica coffee:java control:ambigous off",
- "borneo arabica java");
+ "borneo arabica java");
}
@Test
- public void testContainsAsSubstring() {
- assertSemantics("AND java island:java coffee:java control:ambigous off","java");
- assertSemantics("AND kanava island:kanava off","kanava");
- assertSemantics("AND borneo island:borneo","borneo");
+ void testContainsAsSubstring() {
+ assertSemantics("AND java island:java coffee:java control:ambigous off", "java");
+ assertSemantics("AND kanava island:kanava off", "kanava");
+ assertSemantics("AND borneo island:borneo", "borneo");
}
@Test
- public void testAlphanumericComparison() {
- assertSemantics("a","a");
- assertSemantics("AND z highletter","z");
- assertSemantics("AND p highletter","p");
+ void testAlphanumericComparison() {
+ assertSemantics("a", "a");
+ assertSemantics("AND z highletter", "z");
+ assertSemantics("AND p highletter", "p");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java
index a8fe78ac1ff..867a57aebeb 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,11 +13,11 @@ public class ComparisonsTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testLiteralEquals() {
- assertSemantics("a","a");
- assertSemantics("RANK a foo:a","a&ranking=category");
- assertSemantics("a","a&ranking=somethingelse");
- assertSemantics("a","a&otherparam=category");
+ void testLiteralEquals() {
+ assertSemantics("a", "a");
+ assertSemantics("RANK a foo:a", "a&ranking=category");
+ assertSemantics("a", "a&ranking=somethingelse");
+ assertSemantics("a", "a&otherparam=category");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
index 17eb4120b84..d7297bd79a4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.prelude.semantics.rule.ProductionRule;
import com.yahoo.prelude.semantics.rule.ReplacingProductionRule;
import com.yahoo.prelude.semantics.rule.SequenceCondition;
import com.yahoo.prelude.semantics.rule.TermCondition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ConditionTestCase {
@Test
- public void testTermCondition() {
+ void testTermCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("foo", linguistics);
Query query = new Query("?query=foo");
@@ -33,23 +33,23 @@ public class ConditionTestCase {
}
@Test
- public void testSequenceCondition() {
+ void testSequenceCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term1 = new TermCondition("foo", linguistics);
- TermCondition term2 = new TermCondition("bar",linguistics);
+ TermCondition term2 = new TermCondition("bar", linguistics);
SequenceCondition sequence = new SequenceCondition();
sequence.addCondition(term1);
sequence.addCondition(term2);
Query query = new Query("?query=foo+bar");
- assertTrue(query + " matches " + sequence,sequence.matches(new Evaluation(query, null).freshRuleEvaluation()));
+ assertTrue(sequence.matches(new Evaluation(query, null).freshRuleEvaluation()), query + " matches " + sequence);
Query query2 = new Query("?query=foo");
- assertFalse(query2 + " does not match " + sequence,sequence.matches(new Evaluation(query2, null).freshRuleEvaluation()));
+ assertFalse(sequence.matches(new Evaluation(query2, null).freshRuleEvaluation()), query2 + " does not match " + sequence);
Query query3 = new Query("?query=bar");
- assertFalse(query3 + " does not match " + sequence,sequence.matches(new Evaluation(query3, null).freshRuleEvaluation()));
+ assertFalse(sequence.matches(new Evaluation(query3, null).freshRuleEvaluation()), query3 + " does not match " + sequence);
}
@Test
- public void testChoiceCondition() {
+ void testChoiceCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term1 = new TermCondition("foo", linguistics);
TermCondition term2 = new TermCondition("bar", linguistics);
@@ -57,18 +57,18 @@ public class ConditionTestCase {
choice.addCondition(term1);
choice.addCondition(term2);
Query query1 = new Query("?query=foo+bar");
- assertTrue(query1 + " matches " + choice, choice.matches(new Evaluation(query1, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query1, null).freshRuleEvaluation()), query1 + " matches " + choice);
Query query2 = new Query("?query=foo");
- assertTrue(query2 + " matches " + choice, choice.matches(new Evaluation(query2, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query2, null).freshRuleEvaluation()), query2 + " matches " + choice);
Query query3 = new Query("?query=bar");
- assertTrue(query3 + " matches " + choice, choice.matches(new Evaluation(query3, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query3, null).freshRuleEvaluation()), query3 + " matches " + choice);
}
@Test
- public void testNamedConditionReference() {
+ void testNamedConditionReference() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("foo", linguistics);
- NamedCondition named = new NamedCondition("cond",term);
+ NamedCondition named = new NamedCondition("cond", term);
ConditionReference reference = new ConditionReference("cond");
// To initialize the condition reference...
@@ -81,7 +81,7 @@ public class ConditionTestCase {
ruleBase.initialize();
Query query = new Query("?query=foo");
- assertTrue(query + " matches " + reference,reference.matches(new Evaluation(query, null).freshRuleEvaluation()));
+ assertTrue(reference.matches(new Evaluation(query, null).freshRuleEvaluation()), query + " matches " + reference);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
index 0515417f515..569ae569f18 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
@@ -4,30 +4,28 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.component.chain.Chain;
import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.language.simple.SimpleLinguistics;
-import com.yahoo.prelude.semantics.SemanticRulesConfig;
-import com.yahoo.search.Query;
import com.yahoo.prelude.semantics.RuleBase;
import com.yahoo.prelude.semantics.RuleBaseException;
+import com.yahoo.prelude.semantics.SemanticRulesConfig;
import com.yahoo.prelude.semantics.SemanticSearcher;
+import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
-import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests creating a set of rule bases (the same set as in inheritingrules) from config
*
* @author bratseth
*/
+@SuppressWarnings("deprecation")
public class ConfigurationTestCase {
private static final String root="src/test/java/com/yahoo/prelude/semantics/test/rulebases/";
@@ -53,7 +51,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testReadingConfigurationRuleBase() {
+ void testReadingConfigurationRuleBase() {
RuleBase parent = searcher.getRuleBase("parent");
assertNotNull(parent);
assertEquals("parent", parent.getName());
@@ -61,7 +59,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testParent() {
+ void testParent() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", "parent");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "parent");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "parent.sr");
@@ -70,7 +68,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testChild1() {
+ void testChild1() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "child1.sr");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "child1");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "child1");
@@ -79,7 +77,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testChild2() {
+ void testChild2() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", "child2");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "child2.sr");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "child2.sr");
@@ -88,7 +86,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testGrandchild() {
+ void testGrandchild() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "grandchild.sr");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "grandchild");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "grandchild");
@@ -97,7 +95,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testSearcher() {
+ void testSearcher() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "grandchild");
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "grandchild.sd");
try {
@@ -111,14 +109,14 @@ public class ConfigurationTestCase {
assertSemanticsRulesOff("WEAKAND(100) vw cars", "vw cars");
assertSemantics("WEAKAND(100) vw car", "vw cars", "child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars","child2");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", "child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", "child1");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "child1");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "child1");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "child1");
assertSemantics("WEAKAND(100) vw car", "vw cars", "parent");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","parent");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "parent");
}
private Result doSearch(Searcher searcher, Query query, int offset, int hits) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
index 76c8c3966b7..a692217fef6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
@@ -5,10 +5,10 @@ import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.prelude.semantics.RuleBaseException;
import com.yahoo.prelude.semantics.RuleImporter;
import com.yahoo.prelude.semantics.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -18,7 +18,7 @@ public class DuplicateRuleTestCase {
private final String root = "src/test/java/com/yahoo/prelude/semantics/test/rulebases/";
@Test
- public void testDuplicateRuleBaseLoading() throws java.io.IOException, ParseException {
+ void testDuplicateRuleBaseLoading() throws java.io.IOException, ParseException {
if (System.currentTimeMillis() > 0) return; // TODO: Include this test...
try {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java
index 28ffe549711..0808092da65 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,8 +15,8 @@ public class Ellipsis2TestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testUnreferencedEllipsis() {
- assertSemantics("AND a b c someindex:\"a b c\"","a b c");
+ void testUnreferencedEllipsis() {
+ assertSemantics("AND a b c someindex:\"a b c\"", "a b c");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java
index 1c570220f52..d1fe2091bc2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,34 +15,34 @@ public class EllipsisTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testUnreferencedEllipsis() {
- assertSemantics("AND why is stench unpleasant about:stench","why is stench unpleasant");
- assertSemantics("AND why is the sky blue about:\"the sky\"","why is the sky blue");
+ void testUnreferencedEllipsis() {
+ assertSemantics("AND why is stench unpleasant about:stench", "why is stench unpleasant");
+ assertSemantics("AND why is the sky blue about:\"the sky\"", "why is the sky blue");
assertSemantics("AND why is aardwark almost always most relevant in dictionaries about:aardwark",
- "why is aardwark almost always most relevant in dictionaries");
+ "why is aardwark almost always most relevant in dictionaries");
}
@Test
- public void testReferencedEllipsis() {
- assertSemantics("album:parade","parade album");
- assertSemantics("album:\"a sun came\"","a sun came album");
- assertSemantics("album:parade","parade cd");
- assertSemantics("album:\"a sun came\"","a sun came cd");
+ void testReferencedEllipsis() {
+ assertSemantics("album:parade", "parade album");
+ assertSemantics("album:\"a sun came\"", "a sun came album");
+ assertSemantics("album:parade", "parade cd");
+ assertSemantics("album:\"a sun came\"", "a sun came cd");
}
@Test
- public void testEllipsisInNamedCondition() {
- assertSemantics("AND name:\"a sun came\" product:video","buy a sun came");
- assertSemantics("AND name:stalker product:video","buy stalker video");
- assertSemantics("AND name:\"the usual suspects\" product:video","buy the usual suspects video");
+ void testEllipsisInNamedCondition() {
+ assertSemantics("AND name:\"a sun came\" product:video", "buy a sun came");
+ assertSemantics("AND name:stalker product:video", "buy stalker video");
+ assertSemantics("AND name:\"the usual suspects\" product:video", "buy the usual suspects video");
}
@Test
- public void testMultipleEllipsis() {
- assertSemantics("AND from:paris to:texas","from paris to texas");
- assertSemantics("AND from:\"sao paulo\" to:\"real madrid\"","from sao paulo to real madrid");
- assertSemantics("AND from:\"from from\" to:oslo","from from from to oslo");
- assertSemantics("AND from:\"from from to\" to:koko","from from from to to koko"); // Matching is greedy left-right
+ void testMultipleEllipsis() {
+ assertSemantics("AND from:paris to:texas", "from paris to texas");
+ assertSemantics("AND from:\"sao paulo\" to:\"real madrid\"", "from sao paulo to real madrid");
+ assertSemantics("AND from:\"from from\" to:oslo", "from from from to oslo");
+ assertSemantics("AND from:\"from from to\" to:koko", "from from from to to koko"); // Matching is greedy left-right
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java
index 8f9c33dab51..d04ea0eabf9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,8 +13,8 @@ public class ExactMatchTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testCompleteMatch() {
- assertSemantics("AND primetime in no time","primetime notime");
+ void testCompleteMatch() {
+ assertSemantics("AND primetime in no time", "primetime notime");
}
/*
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
index c566b05405d..6ca055ff980 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -15,20 +15,20 @@ public class ExactMatchTrickTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testCompleteMatch() {
+ void testCompleteMatch() {
assertSemantics("AND default:primetime default:in default:no default:time", "primetime notime");
}
@Test
- public void testCompleteMatchWithNegative() { // Notice ordering bug
+ void testCompleteMatchWithNegative() { // Notice ordering bug
assertSemantics("+(AND default:primetime default:in default:time default:no TRUE) -regionexcl:us",
- new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv")));
+ new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv")));
}
@Test
- public void testCompleteMatchWithFilterAndNegative() {
+ void testCompleteMatchWithFilterAndNegative() {
assertSemantics("AND (+(AND default:primetime default:in default:time default:no TRUE) -regionexcl:us) |lang:en",
- new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv&filter=+lang:en")));
+ new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv&filter=+lang:en")));
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java
index 111f37bf8e4..13b65716ffc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ExpansionTestCase extends RuleBaseAbstractTestCase {
@@ -10,24 +10,24 @@ public class ExpansionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testOrExpansion() {
+ void testOrExpansion() {
assertSemantics("OR or1 or2 or3", "or1");
}
@Test
- public void testEquivExpansion1() {
+ void testEquivExpansion1() {
assertSemantics("EQUIV equiv1 equiv2 equiv3", "equiv1");
}
@Test
- public void testEquivExpansion2() {
+ void testEquivExpansion2() {
assertSemantics("EQUIV testfield:e1 testfield:e2 testfield:e3", "testfield:foo");
}
@Test
- public void testEquivExpansion3() {
+ void testEquivExpansion3() {
assertSemantics("AND testfield:e1 testfield:e2 testfield:e3 testfield:e1 testfield:e2 testfield:e3",
- "testfield:foo testfield:bar");
+ "testfield:foo testfield:bar");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
index baec0066fb3..e9fa8dfa4be 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
@@ -15,12 +15,9 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -58,7 +55,7 @@ public class InheritanceTestCase {
}
@Test
- public void testInclusion() {
+ void testInclusion() {
assertTrue(grandchild.includes("child1"));
assertTrue(grandchild.includes("child2"));
assertTrue(grandchild.includes("parent"));
@@ -74,8 +71,8 @@ public class InheritanceTestCase {
}
@Test
- public void testInclusionOrderAndContentDump() {
- StringTokenizer lines = new StringTokenizer(grandchild.toContentString(),"\n",false);
+ void testInclusionOrderAndContentDump() {
+ StringTokenizer lines = new StringTokenizer(grandchild.toContentString(), "\n", false);
assertEquals("vw -> audi", lines.nextToken());
assertEquals("car -> car", lines.nextToken());
assertEquals("[brand] [vehicle] -> vehiclebrand:[brand]", lines.nextToken());
@@ -88,7 +85,7 @@ public class InheritanceTestCase {
}
@Test
- public void testParent() {
+ void testParent() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", parent);
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", parent);
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", parent);
@@ -97,7 +94,7 @@ public class InheritanceTestCase {
}
@Test
- public void testChild1() {
+ void testChild1() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", child1);
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", child1);
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", child1);
@@ -106,25 +103,25 @@ public class InheritanceTestCase {
}
@Test
- public void testChild2() {
- assertSemantics("WEAKAND(100) vehiclebrand:audi","audi cars", child2);
- assertSemantics("WEAKAND(100) vehiclebrand:alfa","alfa bus", child2);
- assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv","bmw motorcycle", child2);
- assertSemantics("WEAKAND(100) vw car","vw cars", child2);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars", child2);
+ void testChild2() {
+ assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", child2);
+ assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", child2);
+ assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", child2);
+ assertSemantics("WEAKAND(100) vw car", "vw cars", child2);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", child2);
}
@Test
- public void testGrandchild() {
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:alfa","alfa bus", grandchild);
- assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv","bmw motorcycle", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars", grandchild);
+ void testGrandchild() {
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", grandchild);
+ assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", grandchild);
}
@Test
- public void testRuleBaseNames() {
+ void testRuleBaseNames() {
assertEquals("parent", parent.getName());
assertEquals("child1", child1.getName());
assertEquals("child2", child2.getName());
@@ -132,10 +129,10 @@ public class InheritanceTestCase {
}
@Test
- public void testSearcher() {
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=grandchild");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=grandchild.sd");
+ void testSearcher() {
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=grandchild");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=grandchild.sd");
try {
assertSemantics("WEAKAND(100) vw cars", "vw cars", "&rules.rulebase=doesntexist");
fail("No exception on missing rule base");
@@ -147,14 +144,14 @@ public class InheritanceTestCase {
assertSemantics("WEAKAND(100) vw cars", "vw cars", "&rules.off");
assertSemantics("WEAKAND(100) vw car", "vw cars", "&rules.rulebase=child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars","&rules.rulebase=child2");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", "&rules.rulebase=child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", "&rules.rulebase=child1");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=child1");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "&rules.rulebase=child1");
assertSemantics("WEAKAND(100) vw car", "vw cars", "&rules.rulebase=parent");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","&rules.rulebase=parent");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "&rules.rulebase=parent");
}
protected void assertSemantics(String result,String input,String ruleSelection) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
index d45e114e89f..0a12ea2c49f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.prelude.semantics.test;
import java.io.IOException;
import com.yahoo.prelude.semantics.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests label-dependent matching
@@ -19,30 +19,30 @@ public class LabelMatchingTestCase extends RuleBaseAbstractTestCase {
/** Tests that matching with no label matches the default label (index) only */
@Test
- public void testDefaultLabelMatching() throws IOException, ParseException {
- assertSemantics("matched:term","term");
- assertSemantics("alabel:term","alabel:term");
+ void testDefaultLabelMatching() throws IOException, ParseException {
+ assertSemantics("matched:term", "term");
+ assertSemantics("alabel:term", "alabel:term");
- assertSemantics("AND term2 hit","term2");
- assertSemantics("alabel:term2","alabel:term2");
+ assertSemantics("AND term2 hit", "term2");
+ assertSemantics("alabel:term2", "alabel:term2");
}
@Test
- public void testSpecificLabelMatchingInConditionReference() throws IOException, ParseException {
- assertSemantics("+dcattitle:restaurants -dcat:hotel","dcattitle:restaurants");
+ void testSpecificLabelMatchingInConditionReference() throws IOException, ParseException {
+ assertSemantics("+dcattitle:restaurants -dcat:hotel", "dcattitle:restaurants");
}
@Test
- public void testSpecificlabelMatchingInNestedCondition() throws IOException, ParseException {
- assertSemantics("three","foo:one");
- assertSemantics("three","foo:two");
- assertSemantics("bar:one","bar:one");
- assertSemantics("bar:two","bar:two");
- assertSemantics("foo:three","foo:three");
- assertSemantics("one","one");
- assertSemantics("two","two");
- assertSemantics("AND three three","foo:one foo:two");
- assertSemantics("AND bar:one bar:two","bar:one bar:two");
+ void testSpecificlabelMatchingInNestedCondition() throws IOException, ParseException {
+ assertSemantics("three", "foo:one");
+ assertSemantics("three", "foo:two");
+ assertSemantics("bar:one", "bar:one");
+ assertSemantics("bar:two", "bar:two");
+ assertSemantics("foo:three", "foo:three");
+ assertSemantics("one", "one");
+ assertSemantics("two", "two");
+ assertSemantics("AND three three", "foo:one foo:two");
+ assertSemantics("AND bar:one bar:two", "bar:one bar:two");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java
index 22b24e1a0b0..270c2789ec5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,17 +15,17 @@ public class MatchAllTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMatchAll() {
- assertSemantics("RANK a normtitle:a","a");
- assertSemantics("RANK (AND a b) normtitle:\"a b\"","a b");
- assertSemantics("RANK (AND a a b a) normtitle:\"a a b a\"","a a b a");
+ void testMatchAll() {
+ assertSemantics("RANK a normtitle:a", "a");
+ assertSemantics("RANK (AND a b) normtitle:\"a b\"", "a b");
+ assertSemantics("RANK (AND a a b a) normtitle:\"a a b a\"", "a a b a");
}
@Test
- public void testMatchAllFilterIsIgnored() {
- assertSemantics("RANK a |b normtitle:a","a&filter=b");
- assertSemantics("RANK (AND a b) |b |c normtitle:\"a b\"","a b&filter=b c");
- assertSemantics("RANK (AND a a b a) |a |a |c |d |b normtitle:\"a a b a\"","a a b a&filter=a a c d b");
+ void testMatchAllFilterIsIgnored() {
+ assertSemantics("RANK a |b normtitle:a", "a&filter=b");
+ assertSemantics("RANK (AND a b) |b |c normtitle:\"a b\"", "a b&filter=b c");
+ assertSemantics("RANK (AND a a b a) |a |a |c |d |b normtitle:\"a a b a\"", "a a b a&filter=a a c d b");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java
index c398f0ed99e..30a88e74e91 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Experiments with a way to match only if it doesn't remove all hard conditions in the query.
@@ -16,13 +16,13 @@ public class MatchOnlyIfNotOnlyTermTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMatch() {
+ void testMatch() {
assertSemantics("RANK showname:\"saturday night live\"!1000 (AND justin timberlake)", "justin timberlake snl");
assertSemantics("RANK showname:\"saturday night live\"!1000 (AND justin timberlake)", "justin timberlake saturday night live");
}
@Test
- public void testNoMatch() {
+ void testNoMatch() {
// TODO: This shows that we do match, i.e that currently the behavior is undesired
assertSemantics("showname:\"saturday night live\"!1000", "snl");
assertSemantics("showname:\"saturday night live\"!1000", "saturday night live");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java
index 006dcb3c714..49766cc027c 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests the rewriting in the semanticsearcher system test
@@ -11,7 +11,7 @@ import org.junit.Test;
public class MusicTestCase {
@Test
- public void testMusic() {
+ void testMusic() {
var tester = new RuleBaseTester("music.sr");
tester.assertSemantics("AND song:together artist:youngbloods", "together by youngbloods");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java
index fbdd72fe6ac..04bc3249efe 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests a case reported by tularam
@@ -16,20 +16,20 @@ public class NoStemmingTestCase extends RuleBaseAbstractTestCase {
/** Should rewrite correctly */
@Test
- public void testCorrectRewriting1() {
- assertSemantics("+(AND i:arts i:sciences TRUE) -i:b","i:as -i:b");
+ void testCorrectRewriting1() {
+ assertSemantics("+(AND i:arts i:sciences TRUE) -i:b", "i:as -i:b");
}
/** Should rewrite correctly too */
@Test
- public void testCorrectRewriting2() {
- assertSemantics("+(AND i:arts i:sciences i:crafts TRUE) -i:b","i:asc -i:b");
+ void testCorrectRewriting2() {
+ assertSemantics("+(AND i:arts i:sciences i:crafts TRUE) -i:b", "i:asc -i:b");
}
/** Should not rewrite */
@Test
- public void testNoRewriting() {
- assertSemantics("+i:a -i:s","i:a -i:s");
+ void testNoRewriting() {
+ assertSemantics("+i:a -i:s", "i:a -i:s");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java
index c76db0a7afd..0ec320c7780 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,11 +13,11 @@ public class NotTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testLiteralEquals() {
- assertSemantics("RANK a foo:a","a");
- assertSemantics("a","a&ranking=category");
- assertSemantics("RANK a foo:a","a&ranking=somethingelse");
- assertSemantics("RANK a foo:a","a&otherparam=category");
+ void testLiteralEquals() {
+ assertSemantics("RANK a foo:a", "a");
+ assertSemantics("a", "a&ranking=category");
+ assertSemantics("RANK a foo:a", "a&ranking=somethingelse");
+ assertSemantics("RANK a foo:a", "a&otherparam=category");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java
index b18cafdd161..60ccaa35cc4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numbers as conditions and productions
@@ -15,13 +15,13 @@ public class NumbersTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumbers() {
- assertSemantics("elite","1337");
- assertSemantics("1","one");
- assertSemantics("AND bort ned","opp");
- assertSemantics("AND kanoo knagg","foo bar");
- assertSemantics("AND 3 three","two 2");
- assertSemantics("AND 1 elite","one 1337");
+ void testNumbers() {
+ assertSemantics("elite", "1337");
+ assertSemantics("1", "one");
+ assertSemantics("AND bort ned", "opp");
+ assertSemantics("AND kanoo knagg", "foo bar");
+ assertSemantics("AND 3 three", "two 2");
+ assertSemantics("AND 1 elite", "one 1337");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java
index f76deeacbb5..b63b3579c76 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numeric terms
@@ -15,13 +15,13 @@ public class NumericTermsTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumericProduction() {
- assertSemantics("+restaurants -ycat2gc:96929265","restaurants");
+ void testNumericProduction() {
+ assertSemantics("+restaurants -ycat2gc:96929265", "restaurants");
}
@Test
- public void testNumericConditionAndProduction() {
- assertSemantics("48","49");
+ void testNumericConditionAndProduction() {
+ assertSemantics("48", "49");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java
index 1d6eea8d7de..045d8698547 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,14 +13,14 @@ public class OrPhraseTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testReplacing1() {
- assertSemantics("OR title:\"software engineer\" (AND new york)","software engineer new york");
- assertSemantics("title:\"software engineer\"","software engineer"); // Skip or when there is nothing else
+ void testReplacing1() {
+ assertSemantics("OR title:\"software engineer\" (AND new york)", "software engineer new york");
+ assertSemantics("title:\"software engineer\"", "software engineer"); // Skip or when there is nothing else
}
@Test
- public void testReplacing2() {
- assertSemantics("OR lotr \"lord of the rings\"","lotr");
+ void testReplacing2() {
+ assertSemantics("OR lotr \"lord of the rings\"", "lotr");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
index 5b1c38b7752..b9332effcb7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests parameter matching and production
@@ -19,8 +19,8 @@ public class Parameter2TestCase extends RuleBaseAbstractTestCase {
/** Tests parameter production */
@Test
- public void testParameterProduction() {
- assertRankParameterSemantics("WEAKAND(100) a","a&ranking=usrank","date",0);
+ void testParameterProduction() {
+ assertRankParameterSemantics("WEAKAND(100) a", "a&ranking=usrank", "date", 0);
}
private void assertRankParameterSemantics(String producedQuery,String inputQuery,
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
index b597443d1d3..7df1ccbc156 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests parameter matching and production
@@ -19,7 +19,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter literal matching */
@Test
- public void testLiteralEquals() {
+ void testLiteralEquals() {
assertSemantics("a", "a");
assertSemantics("RANK a foo:a", "a&ranking=category");
assertSemantics("a", "a&ranking=somethingelse");
@@ -28,7 +28,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter matching of larger */
@Test
- public void testLarger() {
+ void testLarger() {
assertSemantics("a", "a");
assertSemantics("AND a largepage", "a&hits=11");
assertSemantics("AND a largepage", "a&hits=12");
@@ -36,8 +36,8 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter containment matching */
@Test
- public void testContainsAsList() {
- assertSemantics("a","a");
+ void testContainsAsList() {
+ assertSemantics("a", "a");
assertSemantics("AND a intent:music", "a&search=music");
assertSemantics("AND a intent:music", "a&search=music,books");
assertSemantics("AND a intent:music", "a&search=kanoos,music,books");
@@ -45,7 +45,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter production */
@Test
- public void testParameterProduction() {
+ void testParameterProduction() {
assertParameterSemantics("AND a b c", "a b c", "search", "[letters, alphabet]");
assertParameterSemantics("AND a c d", "a c d", "search", "[letters, someletters]");
assertParameterSemantics("+(AND a d e) -letter:c", "a d e", "search", "[someletters]");
@@ -54,7 +54,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMultipleAlternativeParameterValuesInCondition() {
+ void testMultipleAlternativeParameterValuesInCondition() {
assertInputRankParameterSemantics("WEAKAND(100) one", "foo", "cat");
assertInputRankParameterSemantics("WEAKAND(100) one", "foo", "cat0");
assertInputRankParameterSemantics("WEAKAND(100) one", "bar", "cat");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
index fd9003e0e05..9536c1bfb7c 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* Tests that the phrase produced by an automata match can subsequently be replaced by an AND of the
@@ -16,14 +16,15 @@ public class PhraseMatchTestCase extends RuleBaseAbstractTestCase {
super("phrasematch.sr", "semantics.fsa");
}
+ // TODO: Work in progress
@Test
- @Ignore // TODO: Work in progress
- public void testLiteralEquals() {
- assertSemantics("AND retailer:digital retailer:camera","keyword:digital keyword:camera");
+ @Disabled
+ void testLiteralEquals() {
+ assertSemantics("AND retailer:digital retailer:camera", "keyword:digital keyword:camera");
}
@Test
- public void testMatchingPhrase() {
+ void testMatchingPhrase() {
assertSemantics("OR (AND iphone 7) i7", "iphone 7");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
index e892adc3b1c..44ebd4f1995 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
@@ -15,10 +15,10 @@ import com.yahoo.prelude.semantics.rule.ReferenceTermProduction;
import com.yahoo.prelude.semantics.rule.ReplacingProductionRule;
import com.yahoo.prelude.semantics.rule.TermCondition;
import com.yahoo.prelude.semantics.rule.TermProduction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertTrue;
public class ProductionRuleTestCase {
@Test
- public void testProductionRule() {
+ void testProductionRule() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("sony", linguistics);
NamedCondition named = new NamedCondition("brand", term);
@@ -46,7 +46,7 @@ public class ProductionRuleTestCase {
ruleBase.addRule(rule);
ruleBase.initialize();
- assertTrue("Brand is referenced", rule.matchReferences().contains("brand"));
+ assertTrue(rule.matchReferences().contains("brand"), "Brand is referenced");
Query query = new Query("?query=sony");
RuleEvaluation e = new Evaluation(query, null).freshRuleEvaluation();
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
index 84e47edae29..668251c0a1f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
@@ -14,7 +14,7 @@ import com.yahoo.search.test.QueryTestCase;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DO NOT USE. Use RuleBaseTester instead
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
index cc9e758a0e0..dc43ffc55e7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
@@ -14,7 +14,7 @@ import com.yahoo.search.test.QueryTestCase;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Helper for testing with a rule base.
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
index 69faed1da90..8d7c16f5544 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
@@ -8,8 +8,7 @@ import com.yahoo.prelude.query.parser.TestLinguistics;
import com.yahoo.search.Query;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
@@ -18,7 +17,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testBasicSubstitution() {
+ void testBasicSubstitution() {
Item a = parseQuery("firstsecond");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -27,7 +26,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionAndMoreTerms() {
+ void testSubstitutionAndMoreTerms() {
Item a = parseQuery("bcfirstsecondfg");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -36,7 +35,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionAndNot() {
+ void testSubstitutionAndNot() {
Item a = parseQuery("-firstsecond bc");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -45,7 +44,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionSomeNoise() {
+ void testSubstitutionSomeNoise() {
Item a = parseQuery("9270bcsecond2389");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
index bee65db4347..489afcb3088 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.prelude.query.NullItem;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests semantic searching
@@ -27,128 +27,128 @@ public class SemanticSearcherTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSingleShopping() {
+ void testSingleShopping() {
assertSemantics("brand:sony",
- "sony");
+ "sony");
assertSemantics("brand:sony!150",
- "sony!150");
+ "sony!150");
}
@Test
- public void testCombinedShopping() {
+ void testCombinedShopping() {
assertSemantics("AND brand:sony category:camera",
- "sony camera");
+ "sony camera");
}
@Test
- public void testPhrasedShopping() {
+ void testPhrasedShopping() {
assertSemantics("AND brand:sony category:\"digital camera\"",
- "sony digital camera");
+ "sony digital camera");
}
@Test
- public void testSimpleLocal() {
+ void testSimpleLocal() {
assertSemantics("AND listing:restaurant place:geary",
- "restaurant in geary");
+ "restaurant in geary");
}
@Test
- public void testLocal() {
+ void testLocal() {
assertSemantics("AND listing:restaurant place:\"geary street san francisco\"",
- "restaurant in geary street san francisco");
+ "restaurant in geary street san francisco");
}
@Test
- public void testLiteralReplacing() {
+ void testLiteralReplacing() {
assertSemantics("AND lord of rings", "lotr");
}
@Test
- public void testAddingAnd() {
+ void testAddingAnd() {
assertSemantics("AND bar foobar:bar",
- "bar");
+ "bar");
}
@Test
- public void testAddingRank() {
+ void testAddingRank() {
assertSemantics("RANK word foobar:word",
- "word");
+ "word");
}
@Test
- public void testFilterIsIgnored() {
+ void testFilterIsIgnored() {
assertSemantics("RANK word |a |word |b foobar:word",
- "word&filter=a word b");
+ "word&filter=a word b");
assertSemantics("RANK a |word |b",
- "a&filter=word b");
+ "a&filter=word b");
}
@Test
- public void testAddingNegative() {
+ void testAddingNegative() {
assertSemantics("+java -coffee",
- "java");
+ "java");
}
@Test
- public void testAddingNegativePluralToSingular() {
+ void testAddingNegativePluralToSingular() {
assertSemantics("+javas -coffee",
- "javas");
+ "javas");
}
@Test
- public void testCombined() {
+ void testCombined() {
assertSemantics("AND bar listing:restaurant place:\"geary street san francisco\" foobar:bar",
- "bar restaurant in geary street san francisco");
+ "bar restaurant in geary street san francisco");
}
@Test
- public void testStopWord() {
- assertSemantics("strokes","the strokes");
+ void testStopWord() {
+ assertSemantics("strokes", "the strokes");
}
@Test
- public void testStopWords1() {
- assertSemantics("strokes","be the strokes");
+ void testStopWords1() {
+ assertSemantics("strokes", "be the strokes");
}
@Test
- public void testStopWords2() {
- assertSemantics("strokes","the strokes be");
+ void testStopWords2() {
+ assertSemantics("strokes", "the strokes be");
}
@Test
- public void testDontRemoveEverything() {
- assertSemantics("the","the the the");
+ void testDontRemoveEverything() {
+ assertSemantics("the", "the the the");
}
@Test
- public void testMoreStopWordRemoval() {
- assertSemantics("hamlet","hamlet to be or not to be");
+ void testMoreStopWordRemoval() {
+ assertSemantics("hamlet", "hamlet to be or not to be");
}
@Test
- public void testTypeChange() {
- assertSemantics("RANK default:typechange doors","typechange doors");
+ void testTypeChange() {
+ assertSemantics("RANK default:typechange doors", "typechange doors");
}
@Test
- public void testTypeChangeWithSingularToPluralButNonReplaceWillNotSingularify() {
- assertSemantics("RANK default:typechange door","typechange door");
+ void testTypeChangeWithSingularToPluralButNonReplaceWillNotSingularify() {
+ assertSemantics("RANK default:typechange door", "typechange door");
}
@Test
- public void testExplicitContext() {
- assertSemantics("AND from:paris to:texas","paris to texas");
+ void testExplicitContext() {
+ assertSemantics("AND from:paris to:texas", "paris to texas");
}
@Test
- public void testOrProduction() {
+ void testOrProduction() {
assertSemantics("OR something somethingelse", "something");
}
// This test is order dependent. Fix it!!
@Test
- public void testWeightedSetItem() {
+ void testWeightedSetItem() {
Query q = new Query();
WeightedSetItem weightedSet = new WeightedSetItem("fieldName");
weightedSet.addToken("a", 1);
@@ -158,7 +158,7 @@ public class SemanticSearcherTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
Query query = new Query(""); // Causes a query containing a NullItem
doSearch(searcher, query, 0, 10);
assertEquals(NullItem.class, query.getModel().getQueryTree().getRoot().getClass()); // Still a NullItem
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java
index b8efbf7422b..c5277bf6ef6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests stemming.
@@ -11,43 +11,43 @@ import org.junit.Test;
public class StemmingTestCase {
@Test
- public void testRewritingDueToStemmingInQuery() {
+ void testRewritingDueToStemmingInQuery() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:vehicle TRUE) -i:s", "i:cars -i:s");
}
@Test
- public void testNoRewritingDueToStemmingInQueryWhenStemmingDisabled() {
+ void testNoRewritingDueToStemmingInQueryWhenStemmingDisabled() {
var tester = new RuleBaseTester("stemming-none.sr");
tester.assertSemantics("+i:cars -i:s", "i:cars -i:s");
}
@Test
- public void testRewritingDueToStemmingInRule() {
+ void testRewritingDueToStemmingInRule() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:animal TRUE) -i:s", "i:horse -i:s");
}
@Test
- public void testNoRewritingDueToStemmingInRuleWhenStemmingDisabled() {
+ void testNoRewritingDueToStemmingInRuleWhenStemmingDisabled() {
var tester = new RuleBaseTester("stemming-none.sr");
tester.assertSemantics("+i:horse -i:s", "i:horse -i:s");
}
@Test
- public void testRewritingDueToExactMatch() {
+ void testRewritingDueToExactMatch() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:arts i:sciences TRUE) -i:s", "i:as -i:s");
}
@Test
- public void testEnglishStemming() {
+ void testEnglishStemming() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("i:drive", "i:going");
}
@Test
- public void testFrenchStemming() {
+ void testFrenchStemming() {
var tester = new RuleBaseTester("stemming-french.sr");
tester.assertSemantics("i:going", "i:going");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
index a0c2cf4545c..207ae7f8877 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numeric terms
@@ -17,21 +17,21 @@ public class StopwordTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testStopwords() {
+ void testStopwords() {
assertSemantics("WEAKAND(100) mlr:ve mlr:heard mlr:beautiful mlr:world",
- new Query(QueryTestCase.httpEncode("?query=i don't know if you've heard, but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
+ new Query(QueryTestCase.httpEncode("?query=i don't know if you've heard, but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
}
/** If the query contains nothing but stopwords, we won't remove them */
@Test
- public void testOnlyStopwords() {
+ void testOnlyStopwords() {
assertSemantics("WEAKAND(100) mlr:the", new Query(QueryTestCase.httpEncode("?query=the the&default-index=mlr&tracelevel.rules=0")));
}
@Test
- public void testStopwordsInPhrase() {
+ void testStopwordsInPhrase() {
assertSemantics("WEAKAND(100) mlr:\"ve heard\" mlr:beautiful mlr:world",
- new Query(QueryTestCase.httpEncode("?query=\"i don't know if you've heard\", but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
+ new Query(QueryTestCase.httpEncode("?query=\"i don't know if you've heard\", but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java
index 8f69be2f710..65001cfcd44 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -9,7 +9,7 @@ import org.junit.Test;
public class SynonymTestCase {
@Test
- public void testReplacingBySynonyms() {
+ void testReplacingBySynonyms() {
var tester = new RuleBaseTester("synonyms.sr");
tester.assertSemantics("EQUIV index1:foo index1:baz index1:bar", "index1:foo");
tester.assertSemantics("EQUIV index1:foo index1:baz index1:bar", "index1:bar");
@@ -20,7 +20,7 @@ public class SynonymTestCase {
}
@Test
- public void testAddingSynonyms() {
+ void testAddingSynonyms() {
var tester = new RuleBaseTester("synonyms.sr");
tester.assertSemantics("EQUIV index2:foo index2:baz index2:bar", "index2:foo");
tester.assertSemantics("EQUIV index2:bar index2:foo index2:baz", "index2:bar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java
index 9bc64370030..c9eb30b3578 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests working with url indexes
@@ -15,8 +15,8 @@ public class UrlTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testFromDefaultToUrlIndex() {
- assertSemantics("fromurl:\"youtube com\"","youtube.com");
+ void testFromDefaultToUrlIndex() {
+ assertSemantics("fromurl:\"youtube com\"", "youtube.com");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java
index d89e6fdbfa3..e5d7408f3c0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,7 +13,7 @@ public class WeightingTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testWeighting() {
+ void testWeighting() {
assertSemantics("foo!150", "foo");
assertSemantics("AND foo!150 snip", "foo snip");
assertSemantics("AND foo!150 bar", "foo bar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
index 9ed84298838..edf039723fd 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.prelude.test;
import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests a case reported by MSBE
@@ -16,27 +16,28 @@ import static org.junit.Assert.assertEquals;
public class GetRawWordTestCase {
@Test
- public void testGetRawWord() {
+ void testGetRawWord() {
Query query = new Query("?query=%C4%B0%C5%9EBANKASI%20GAZ%C4%B0EM%C4%B0R&type=all&searchChain=vespa");
assertEquals("AND \u0130\u015EBANKASI GAZ\u0130EM\u0130R", query.getModel().getQueryTree().toString());
- AndItem root = (AndItem)query.getModel().getQueryTree().getRoot();
+ AndItem root = (AndItem) query.getModel().getQueryTree().getRoot();
{
- WordItem word = (WordItem)root.getItem(0);
+ WordItem word = (WordItem) root.getItem(0);
assertEquals("\u0130\u015EBANKASI", word.getRawWord());
assertEquals(0, word.getOrigin().start);
assertEquals(9, word.getOrigin().end);
}
{
- WordItem word = (WordItem)root.getItem(1);
+ WordItem word = (WordItem) root.getItem(1);
assertEquals("GAZ\u0130EM\u0130R", word.getRawWord());
assertEquals(10, word.getOrigin().start);
assertEquals(18, word.getOrigin().end);
}
- assertEquals("Total string is just these words",18,
- ((WordItem)root.getItem(0)).getOrigin().getSuperstring().length());
+ assertEquals(18,
+ ((WordItem) root.getItem(0)).getOrigin().getSuperstring().length(),
+ "Total string is just these words");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
index 0f7c9526533..4b24ba3671e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
@@ -1,39 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.test;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
import com.google.common.collect.ImmutableList;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.container.QrSearchersConfig;
-import com.yahoo.search.config.IndexInfoConfig;
-import com.yahoo.search.config.IndexInfoConfig.Indexinfo;
-import com.yahoo.search.config.IndexInfoConfig.Indexinfo.Alias;
-import com.yahoo.search.config.IndexInfoConfig.Indexinfo.Command;
import com.yahoo.language.process.StemMode;
import com.yahoo.prelude.Index;
import com.yahoo.prelude.IndexFacts;
import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
+import com.yahoo.search.config.IndexInfoConfig;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests using synthetic index names for IndexFacts class.
@@ -45,6 +33,7 @@ public class IndexFactsTestCase {
private static final String INDEXFACTS_TESTING = "file:src/test/java/com/yahoo/prelude/test/indexfactstesting.cfg";
+ @SuppressWarnings("deprecation")
private IndexFacts createIndexFacts() {
ConfigGetter<IndexInfoConfig> getter = new ConfigGetter<>(IndexInfoConfig.class);
IndexInfoConfig config = getter.getConfig(INDEXFACTS_TESTING);
@@ -67,7 +56,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testBasicCases() {
+ void testBasicCases() {
// First check default behavior
IndexFacts indexFacts = createIndexFacts();
Query q = newQuery("?query=a:b", indexFacts);
@@ -77,7 +66,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testDefaultPosition() {
+ void testDefaultPosition() {
Index a = new Index("a");
assertFalse(a.isDefaultPosition());
a.addCommand("any");
@@ -89,21 +78,21 @@ public class IndexFactsTestCase {
sd.addCommand("b", "any");
assertNull(sd.getDefaultPosition());
sd.addCommand("c", "default-position");
- assertTrue(sd.getDefaultPosition().equals("c"));
+ assertEquals(sd.getDefaultPosition(), "c");
SearchDefinition sd2 = new SearchDefinition("sd2");
sd2.addIndex(new Index("b").addCommand("any"));
assertNull(sd2.getDefaultPosition());
sd2.addIndex(a);
- assertTrue(sd2.getDefaultPosition().equals("a"));
+ assertEquals(sd2.getDefaultPosition(), "a");
IndexFacts indexFacts = createIndexFacts(ImmutableList.of(sd, sd2));
- assertTrue(indexFacts.getDefaultPosition(null).equals("a"));
- assertTrue(indexFacts.getDefaultPosition("sd").equals("c"));
+ assertEquals(indexFacts.getDefaultPosition(null), "a");
+ assertEquals(indexFacts.getDefaultPosition("sd"), "c");
}
@Test
- public void testIndicesInAnyConfigurationAreIndicesInDefault() {
+ void testIndicesInAnyConfigurationAreIndicesInDefault() {
IndexFacts.Session indexFacts = createIndexFacts().newSession(new Query());
assertTrue(indexFacts.isIndex("a"));
assertTrue(indexFacts.isIndex("b"));
@@ -113,21 +102,21 @@ public class IndexFactsTestCase {
}
@Test
- public void testDefaultIsUnionHostIndex() {
+ void testDefaultIsUnionHostIndex() {
IndexFacts.Session session = createIndexFacts().newSession(new Query());
assertTrue(session.getIndex("c").isHostIndex());
assertFalse(session.getIndex("a").isHostIndex());
}
@Test
- public void testDefaultIsUnionUriIndex() {
+ void testDefaultIsUnionUriIndex() {
IndexFacts indexFacts = createIndexFacts();
assertTrue(indexFacts.newSession(new Query()).getIndex("d").isUriIndex());
assertFalse(indexFacts.newSession(new Query()).getIndex("a").isUriIndex());
}
@Test
- public void testDefaultIsUnionStemMode() {
+ void testDefaultIsUnionStemMode() {
IndexFacts.Session session = createIndexFacts().newSession(new Query());
assertEquals(StemMode.NONE, session.getIndex("a").getStemMode());
assertEquals(StemMode.NONE, session.getIndex("b").getStemMode());
@@ -149,7 +138,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testExactMatching() {
+ void testExactMatching() {
assertExactIsWorking("test");
assertExactIsWorking("artist_name_ft_norm1");
@@ -166,7 +155,7 @@ public class IndexFactsTestCase {
Index e = nullSession.getIndex("e");
assertTrue(e.isExact());
- assertEquals("kj(/&",e.getExactTerminator());
+ assertEquals("kj(/&", e.getExactTerminator());
Index a = nullSession.getIndex("a");
assertFalse(a.isExact());
@@ -178,7 +167,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testComplexExactMatching() {
+ void testComplexExactMatching() {
SearchDefinition sd = new SearchDefinition("foobar");
String u_name = "foo_bar";
Index u_index = new Index(u_name);
@@ -199,7 +188,7 @@ public class IndexFactsTestCase {
// This is also backed by a system test on cause of complex config
@Test
- public void testRestrictLists1() {
+ void testRestrictLists1() {
Query query = new Query();
query.getModel().getSources().add("nalle");
query.getModel().getSources().add("one");
@@ -212,7 +201,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testRestrictLists2() {
+ void testRestrictLists2() {
Query query = new Query();
query.getModel().getSources().add("clusterTwo");
query.getModel().getRestrict().add("three");
@@ -232,7 +221,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testRestrictLists3() {
+ void testRestrictLists3() {
Query query = new Query();
query.getModel().getSources().add("clusterOne");
query.getModel().getRestrict().add("two");
@@ -251,7 +240,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testPredicateBounds() {
+ void testPredicateBounds() {
Index index = new Index("a");
assertEquals(Long.MIN_VALUE, index.getPredicateLowerBound());
assertEquals(Long.MAX_VALUE, index.getPredicateUpperBound());
@@ -273,7 +262,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testUriIndexAndRestrict() {
+ void testUriIndexAndRestrict() {
IndexInfoConfig.Builder b = new IndexInfoConfig.Builder();
IndexInfoConfig.Indexinfo.Builder b1 = new IndexInfoConfig.Indexinfo.Builder();
@@ -307,7 +296,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testConflictingAliases() {
+ void testConflictingAliases() {
SearchDefinition first = new SearchDefinition("first");
Index field1 = new Index("field1");
first.addIndex(field1);
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
index b34edbf208c..10573b63bdc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Runs a query thru the configured search chain from a real http channel
@@ -32,8 +32,8 @@ public class IntegrationTestCase {
}
@Test
- public void testQuery() throws java.io.IOException {
- /*
+ void testQuery() throws java.io.IOException {
+ /*
TODO: (JSB) This blocks forever on Linux (not Windows) because
the ServerSocketChannel.accept method in Server
seems to starve the test running thread,
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
index 07750613249..96a24ac92c8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.test;
import com.yahoo.prelude.Location;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the Location class. Currently does not test all "features" of Location class.
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class LocationTestCase {
@Test
- public void testAspect() {
+ void testAspect() {
//0 degrees latitude, on the equator
Location loc1 = new Location("[2,-1110000,330000,-1160000,340000](2,-1100222,0,300,0,1,0,CalcLatLon)");
assertEquals(loc1.toString(), "[2,-1110000,330000,-1160000,340000](2,-1100222,0,300,0,1,0,4294967295)");
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
index e77f0d00578..495f11e0780 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests null members in HashSet
@@ -15,7 +13,7 @@ import static org.junit.Assert.assertTrue;
public class NullSetMemberTestCase {
@Test
- public void testNullMember() {
+ void testNullMember() {
HashSet<?> s = new HashSet<>();
assertEquals(s.size(), 0);
assertFalse(s.contains(null));
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
index eaab7e12f33..95ecf3c2dba 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
@@ -14,12 +14,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.Sorting;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.Exceptions;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for query class
@@ -29,7 +29,7 @@ import static org.junit.Assert.*;
public class QueryTestCase {
@Test
- public void testBoolItem() {
+ void testBoolItem() {
var original = new BoolItem(false);
var cloned = original.clone();
assertNotSame(original, cloned);
@@ -37,7 +37,7 @@ public class QueryTestCase {
}
@Test
- public void testSimpleQueryParsing () {
+ void testSimpleQueryParsing() {
Query q = newQuery("/search?query=foobar&offset=10&hits=20&type=all");
assertEquals("foobar", ((WordItem) q.getModel().getQueryTree().getRoot()).getWord());
assertEquals(10, q.getOffset());
@@ -45,7 +45,7 @@ public class QueryTestCase {
}
@Test
- public void testAdvancedQueryParsing () {
+ void testAdvancedQueryParsing() {
Query q = newQuery("/search?query=fOObar and kanoo&offset=10&hits=20&filter=-foo +bar&type=adv&suggestonly=true");
assertEquals("AND (+(AND fOObar kanoo) -|foo) |bar", q.getModel().getQueryTree().getRoot().toString());
assertEquals(10, q.getOffset());
@@ -54,7 +54,7 @@ public class QueryTestCase {
}
@Test
- public void testAnyQueryParsing () {
+ void testAnyQueryParsing() {
Query q = newQuery("/search?query=foobar and kanoo&offset=10&hits=10&type=any&suggestonly=true&filter=-fast.type:offensive&encoding=latin1");
assertEquals("+(OR foobar and kanoo) -|fast.type:offensive", q.getModel().getQueryTree().getRoot().toString());
assertEquals(10, q.getOffset());
@@ -64,13 +64,13 @@ public class QueryTestCase {
}
@Test
- public void testLongQueryParsing() {
+ void testLongQueryParsing() {
Query q = newQuery("/p13n?query=news"
- +"interest:cnn!254+interest:cnnfn!171+interest:cnn+"
- +"financial!96+interest:"
- +"yahoo+com!253+interest:www+yahoo!138+"
- +"interest:www+yahoo+com!136"
- +"&hits=20&offset=0&vectorranking=queryrank");
+ + "interest:cnn!254+interest:cnnfn!171+interest:cnn+"
+ + "financial!96+interest:"
+ + "yahoo+com!253+interest:www+yahoo!138+"
+ + "interest:www+yahoo+com!136"
+ + "&hits=20&offset=0&vectorranking=queryrank");
assertEquals("/p13n", q.getHttpRequest().getUri().getPath());
assertEquals(0, q.getOffset());
assertEquals(20, q.getHits());
@@ -83,9 +83,9 @@ public class QueryTestCase {
* is not a number.
*/
@Test
- public void testGetParamInt() {
+ void testGetParamInt() {
Query q = newQuery("/search?query=foo%20bar&someint=10&notint=hello");
- assertEquals(10, (int)q.properties().getInteger("someint"));
+ assertEquals(10, (int) q.properties().getInteger("someint"));
// provoke an exception. if exception is not triggered
// we fail the test.
@@ -98,13 +98,13 @@ public class QueryTestCase {
}
@Test
- public void testUtf8Decoding() {
+ void testUtf8Decoding() {
Query q = new Query("/?query=beyonc%C3%A9&type=all");
assertEquals("beyonc\u00e9", ((WordItem) q.getModel().getQueryTree().getRoot()).getWord());
}
@Test
- public void testSortSpec() {
+ void testSortSpec() {
Query q = newQuery("?query=test&sortspec=+a -b c +[rank]");
assertNotNull(q.getRanking().getSorting());
List<Sorting.FieldOrder> sortSpec = q.getRanking().getSorting().fieldOrders();
@@ -120,13 +120,13 @@ public class QueryTestCase {
}
@Test
- public void testSortSpecLowerCase() {
+ void testSortSpecLowerCase() {
Query q = newQuery("?query=test&sortspec=-lowercase(name)");
assertNotNull(q.getRanking().getSorting());
List<Sorting.FieldOrder> sortSpec = q.getRanking().getSorting().fieldOrders();
assertEquals(sortSpec.size(), 1);
assertEquals(Sorting.Order.DESCENDING,
- sortSpec.get(0).getSortOrder());
+ sortSpec.get(0).getSortOrder());
assertEquals("name", sortSpec.get(0).getFieldName());
assertTrue(sortSpec.get(0).getSorter() instanceof Sorting.LowerCaseSorter);
}
@@ -143,7 +143,7 @@ public class QueryTestCase {
}
@Test
- public void testSortSpecUca() {
+ void testSortSpecUca() {
checkUcaUS("?query=test&sortspec=-uca(name,en_US)");
checkUcaUS("?query=test&sortspec=-UCA(name,en_US)");
checkSortSpecUcaUSOptional("?query=test&sortspec=-uca(name,en_US,tertiary)");
@@ -151,21 +151,21 @@ public class QueryTestCase {
}
@Test
- public void testInvalidSortFunction() {
+ void testInvalidSortFunction() {
assertQueryError(
"?query=test&sortspec=-ucca(name,en_US)",
"Could not set 'ranking.sorting' to '-ucca(name,en_US)': Unknown sort function 'ucca'");
}
@Test
- public void testMissingSortFunction() {
+ void testMissingSortFunction() {
assertQueryError(
"?query=test&sortspec=-(name)",
"Could not set 'ranking.sorting' to '-(name)': No sort function specified");
}
@Test
- public void testInvalidUcaStrength() {
+ void testInvalidUcaStrength() {
assertQueryError(
"?query=test&sortspec=-uca(name,en_US,tertary)",
"Could not set 'ranking.sorting' to '-uca(name,en_US,tertary)': Unknown collation strength: 'tertary'");
@@ -189,7 +189,7 @@ public class QueryTestCase {
* Extremely simple for now, will be used for pathological cases.
*/
@Test
- public void testHashCode() {
+ void testHashCode() {
Query p = newQuery("?query=foo&type=any");
Query q = newQuery("?query=foo&type=all");
assertTrue(p.hashCode() != q.hashCode());
@@ -197,17 +197,17 @@ public class QueryTestCase {
/** Test using the defauultindex feature */
@Test
- public void testDefaultIndex() {
+ void testDefaultIndex() {
Query q = newQuery("?query=hi hello keyword:kanoo " +
- "default:munkz \"phrases too\"&default-index=def");
+ "default:munkz \"phrases too\"&default-index=def");
assertEquals("WEAKAND(100) def:hi def:hello keyword:kanoo " +
- "default:munkz def:\"phrases too\"",
- q.getModel().getQueryTree().getRoot().toString());
+ "default:munkz def:\"phrases too\"",
+ q.getModel().getQueryTree().getRoot().toString());
}
- /** Test that GET parameter names are case in-sensitive */
- @Test
- public void testGETParametersCase() {
+ /** Test that GET parameter names are case in-sensitive */
+ @Test
+ void testGETParametersCase() {
Query q = newQuery("?QUERY=testing&hits=10&oFfSeT=10");
assertEquals("testing", q.getModel().getQueryString());
@@ -217,108 +217,108 @@ public class QueryTestCase {
@Test
- public void testNegativeHitValue() {
+ void testNegativeHitValue() {
assertQueryError(
"?query=test&hits=-1",
"Could not set 'hits' to '-1': Must be a positive number");
}
@Test
- public void testNaNHitValue() {
+ void testNaNHitValue() {
assertQueryError(
"?query=test&hits=NaN",
"Could not set 'hits' to 'NaN': 'NaN' is not a valid integer");
}
@Test
- public void testNoneHitValue() {
+ void testNoneHitValue() {
assertQueryError(
"?query=test&hits=(none)",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testNegativeOffsetValue() {
+ void testNegativeOffsetValue() {
assertQueryError(
"?query=test&offset=-1",
"Could not set 'offset' to '-1': Must be a positive number");
}
@Test
- public void testNaNOffsetValue() {
+ void testNaNOffsetValue() {
assertQueryError(
"?query=test&offset=NaN",
"Could not set 'offset' to 'NaN': 'NaN' is not a valid integer");
}
@Test
- public void testNoneOffsetValue() {
+ void testNoneOffsetValue() {
assertQueryError(
"?query=test&offset=(none)",
"Could not set 'offset' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testNoneHitsNegativeOffsetValue() {
+ void testNoneHitsNegativeOffsetValue() {
assertQueryError(
"?query=test&hits=(none)&offset=-10",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testFeedbackIsTransferredToResult() {
+ void testFeedbackIsTransferredToResult() {
assertQueryError(
"?query=test&hits=(none)&offset=-10",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testUnicodeNormalization() {
+ void testUnicodeNormalization() {
Linguistics linguistics = new SimpleLinguistics();
Query query = newQueryFromEncoded("?query=content:%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9&type=all", Language.ENGLISH,
- linguistics);
+ linguistics);
assertEquals("SONY", ((WordItem) query.getModel().getQueryTree().getRoot()).getWord());
query = newQueryFromEncoded("?query=foo&filter=+%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9&type=all", Language.ENGLISH,
- linguistics);
+ linguistics);
assertEquals("RANK foo |SONY", query.getModel().getQueryTree().getRoot().toString());
query = newQueryFromEncoded("?query=foo+AND+%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9)&type=adv",
- Language.ENGLISH, linguistics);
+ Language.ENGLISH, linguistics);
assertEquals("AND foo SONY", query.getModel().getQueryTree().getRoot().toString());
}
/** Test a vertical specific patch, see Tokenizer */
@Test
- @Ignore
- public void testPrivateUseCharacterParsing() {
+ @Disabled
+ void testPrivateUseCharacterParsing() {
Query query = newQuery("?query=%EF%89%AB");
assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
}
/** Test a vertical specific patch, see Tokenizer */
@Test
- @Ignore
- public void testOtherCharactersParsing() {
+ @Disabled
+ void testOtherCharactersParsing() {
Query query = newQuery(com.yahoo.search.test.QueryTestCase.httpEncode("?query=\u3007\u2e80\u2eff\u2ed0"));
assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(1)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(1)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(2)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(2)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(3)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(3)));
}
@Test
- public void testFreshness() {
+ void testFreshness() {
Query query = newQuery("?query=test&datetime=103");
- assertTrue(query.getRanking().getFreshness().getRefTime()==103);
+ assertEquals(query.getRanking().getFreshness().getRefTime(), 103);
query.getRanking().setFreshness("193");
- assertTrue(query.getRanking().getFreshness().getRefTime()==193);
+ assertEquals(query.getRanking().getFreshness().getRefTime(), 193);
query.getRanking().setFreshness("now");
assertTrue(query.getRanking().getFreshness().getSystemTimeInSecondsSinceEpoch() >= query.getRanking().getFreshness().getRefTime());
@@ -330,10 +330,10 @@ public class QueryTestCase {
}
@Test
- public void testCopy() {
+ void testCopy() {
Query qs = newQuery("?query=test&rankfeature.something=2");
assertEquals("WEAKAND(100) test", qs.getModel().getQueryTree().toString());
- assertEquals((int)qs.properties().getInteger("rankfeature.something"),2);
+ assertEquals((int) qs.properties().getInteger("rankfeature.something"), 2);
Query qp = new Query(qs);
assertEquals("WEAKAND(100) test", qp.getModel().getQueryTree().getRoot().toString());
assertFalse(qp.getRanking().getFeatures().isEmpty());
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
index edbfe558ffd..28afe0611d4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.prelude.test;
import java.util.Iterator;
import com.yahoo.search.Query;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.search.result.Hit;
import com.yahoo.search.Result;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Tests the result class
@@ -18,16 +18,16 @@ import static org.junit.Assert.assertEquals;
public class ResultTestCase {
@Test
- public void testHitOrdering() {
- Result result=new Result(new Query("dummy"));
- result.hits().add(new Hit("test:hit1",80));
- result.hits().add(new Hit("test:hit2",90));
- result.hits().add(new Hit("test:hit3",70));
+ void testHitOrdering() {
+ Result result = new Result(new Query("dummy"));
+ result.hits().add(new Hit("test:hit1", 80));
+ result.hits().add(new Hit("test:hit2", 90));
+ result.hits().add(new Hit("test:hit3", 70));
- Iterator<?> hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit2",90),hits.next());
- assertEquals(new Hit("test:hit1",80),hits.next());
- assertEquals(new Hit("test:hit3",70),hits.next());
+ Iterator<?> hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit2", 90), hits.next());
+ assertEquals(new Hit("test:hit1", 80), hits.next());
+ assertEquals(new Hit("test:hit3", 70), hits.next());
}
private void resultInit(Result result){
@@ -43,48 +43,48 @@ public class ResultTestCase {
}
@Test
- public void testHitTrimming(){
- Result result=new Result(new Query("dummy"));
+ void testHitTrimming() {
+ Result result = new Result(new Query("dummy"));
//case 1: keep some hits in the middle
resultInit(result);
result.hits().trim(3, 3);
- assertEquals(3,result.getHitCount());
- Iterator<Hit> hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit3",70),hits.next());
- assertEquals(new Hit("test:hit8",55),hits.next());
- assertEquals(new Hit("test:hit5",50),hits.next());
- assertEquals(false,hits.hasNext());
+ assertEquals(3, result.getHitCount());
+ Iterator<Hit> hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit3", 70), hits.next());
+ assertEquals(new Hit("test:hit8", 55), hits.next());
+ assertEquals(new Hit("test:hit5", 50), hits.next());
+ assertEquals(false, hits.hasNext());
//case 2: keep some hits at the end
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(5, 4);
- hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit5",50),hits.next());
- assertEquals(new Hit("test:hit4",40),hits.next());
- assertEquals(new Hit("test:hit6",20),hits.next());
- assertEquals(new Hit("test:hit7",20),hits.next());
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit5", 50), hits.next());
+ assertEquals(new Hit("test:hit4", 40), hits.next());
+ assertEquals(new Hit("test:hit6", 20), hits.next());
+ assertEquals(new Hit("test:hit7", 20), hits.next());
+ assertEquals(false, hits.hasNext());
//case 3: keep some hits at the beginning
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(0, 4);
- hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit2",90),hits.next());
- assertEquals(new Hit("test:hit1",80),hits.next());
- assertEquals(new Hit("test:hit9",75),hits.next());
- assertEquals(new Hit("test:hit3",70),hits.next());
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit2", 90), hits.next());
+ assertEquals(new Hit("test:hit1", 80), hits.next());
+ assertEquals(new Hit("test:hit9", 75), hits.next());
+ assertEquals(new Hit("test:hit3", 70), hits.next());
+ assertEquals(false, hits.hasNext());
//case 4: keep no hits
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(10, 4);
- hits= result.hits().deepIterator();
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(false, hits.hasNext());
}
//This test is broken
diff --git a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
index bf44c57a777..33d86658f8e 100644
--- a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
@@ -5,6 +5,8 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.component.ComponentId;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.Ping;
import com.yahoo.prelude.Pong;
import com.yahoo.search.Query;
@@ -16,9 +18,7 @@ import com.yahoo.search.cluster.PingableSearcher;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
public class ClusterSearcherTestCase {
@@ -144,26 +144,26 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testSimple() {
+ void testSimple() {
Hit blockingHit = new Hit("blocking");
Hit nonblockingHit = new Hit("nonblocking");
BlockingBackendSearcher blockingSearcher = new BlockingBackendSearcher(blockingHit);
- List<Searcher> searchers=new ArrayList<>();
+ List<Searcher> searchers = new ArrayList<>();
searchers.add(blockingSearcher);
searchers.add(new TestingBackendSearcher(nonblockingHit));
- ClusterSearcher<?> provider = new SearcherClusterSearcher(new ComponentId("simple"),searchers,new SimpleHasher<>());
+ ClusterSearcher<?> provider = new SearcherClusterSearcher(new ComponentId("simple"), searchers, new SimpleHasher<>());
Result blockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals(blockingHit,blockingResult.hits().get(0));
+ assertEquals(blockingHit, blockingResult.hits().get(0));
Result nonblockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals(nonblockingHit,nonblockingResult.hits().get(0));
+ assertEquals(nonblockingHit, nonblockingResult.hits().get(0));
blockingSearcher.setBlocking(true);
blockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals(blockingResult.hits().get(0),nonblockingHit);
+ assertEquals(blockingResult.hits().get(0), nonblockingHit);
nonblockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals(nonblockingResult.hits().get(0),nonblockingHit);
+ assertEquals(nonblockingResult.hits().get(0), nonblockingHit);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
index fa8d237aee0..8c98b344394 100644
--- a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
@@ -12,14 +12,14 @@ import com.yahoo.search.cluster.Hasher;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author bratseth
@@ -27,83 +27,83 @@ import static org.junit.Assert.assertNull;
public class ClusteredConnectionTestCase {
@Test
- public void testClustering() {
- Connection connection0=new Connection("0");
- Connection connection1=new Connection("1");
- Connection connection2=new Connection("2");
- List<Connection> connections=new ArrayList<>();
+ void testClustering() {
+ Connection connection0 = new Connection("0");
+ Connection connection1 = new Connection("1");
+ Connection connection2 = new Connection("2");
+ List<Connection> connections = new ArrayList<>();
connections.add(connection0);
connections.add(connection1);
connections.add(connection2);
MyBackend myBackend = new MyBackend(new ComponentId("test"), connections);
Result r;
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:2",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:2", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection2.setInService(false);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection1.setInService(false);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection0.setInService(false);
r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertEquals("Failed calling connection '2' in searcher 'test' for query 'NULL': Connection failed",
- r.hits().getError().getDetailedMessage());
+ r.hits().getError().getDetailedMessage());
connection0.setInService(true);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection1.setInService(true);
connection2.setInService(true);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:2",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:2", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
}
@Test
- public void testClusteringWithPing() {
- Connection connection0=new Connection("0");
- Connection connection1=new Connection("1");
- Connection connection2=new Connection("2");
- List<Connection> connections=new ArrayList<>();
+ void testClusteringWithPing() {
+ Connection connection0 = new Connection("0");
+ Connection connection1 = new Connection("1");
+ Connection connection2 = new Connection("2");
+ List<Connection> connections = new ArrayList<>();
connections.add(connection0);
connections.add(connection1);
connections.add(connection2);
- MyBackend myBackend=new MyBackend(new ComponentId("test"),connections);
+ MyBackend myBackend = new MyBackend(new ComponentId("test"), connections);
Result r;
@@ -114,14 +114,14 @@ public class ClusteredConnectionTestCase {
connection1.setInService(false);
connection0.setInService(false);
forcePing(myBackend);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertEquals("No backends in service. Try later", r.hits().getError().getMessage());
connection2.setInService(true);
connection1.setInService(true);
connection0.setInService(true);
forcePing(myBackend);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertNull(r.hits().getError());
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
index 42df2a829e3..715154e85ba 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
@@ -12,17 +12,14 @@ import com.yahoo.search.dispatch.searchcluster.PingFactory;
import com.yahoo.search.dispatch.searchcluster.Pinger;
import com.yahoo.search.dispatch.searchcluster.PongHandler;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -30,7 +27,7 @@ import static org.junit.Assert.fail;
public class DispatcherTest {
@Test
- public void requireThatDispatcherSupportsSearchPath() {
+ void requireThatDispatcherSupportsSearchPath() {
SearchCluster cl = new MockSearchCluster("1", 2, 2);
Query q = new Query();
q.getModel().setSearchPath("1/0"); // second node in first group
@@ -46,7 +43,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatDispatcherSupportsSingleNodeDirectDispatch() {
+ void requireThatDispatcherSupportsSingleNodeDirectDispatch() {
SearchCluster cl = new MockSearchCluster("1", 0, 0) {
@Override
public Optional<Node> localCorpusDispatchTarget() {
@@ -61,7 +58,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatInvokerConstructionIsRetriedAndLastAcceptsAnyCoverage() {
+ void requireThatInvokerConstructionIsRetriedAndLastAcceptsAnyCoverage() {
SearchCluster cl = new MockSearchCluster("1", 2, 1);
MockInvokerFactory invokerFactory = new MockInvokerFactory(cl, (n, acceptIncompleteCoverage) -> {
@@ -78,7 +75,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatInvokerConstructionDoesNotRepeatGroups() {
+ void requireThatInvokerConstructionDoesNotRepeatGroups() {
try {
SearchCluster cl = new MockSearchCluster("1", 2, 1);
@@ -94,49 +91,49 @@ public class DispatcherTest {
}
@Test
- public void testGroup0IsSelected() {
+ void testGroup0IsSelected() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.pingIterationCompleted();
assertEquals(0,
- dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
+ dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSkippedWhenItIsBlockingFeed() {
+ void testGroup0IsSkippedWhenItIsBlockingFeed() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is avoided",
- 1,
- (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue());
+ assertEquals(1,
+ (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue(),
+ "Blocking group is avoided");
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSelectedWhenMoreAreBlockingFeed() {
+ void testGroup0IsSelectedWhenMoreAreBlockingFeed() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.group(1).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is used when multiple groups are blocking",
- 0,
- dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
+ assertEquals(0,
+ dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue(),
+ "Blocking group is used when multiple groups are blocking");
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSelectedWhenItIsBlockingFeedWhenNoOthers() {
+ void testGroup0IsSelectedWhenItIsBlockingFeedWhenNoOthers() {
SearchCluster cluster = new MockSearchCluster("1", 1, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is used when there is no alternative",
- 0,
- (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue());
+ assertEquals(0,
+ (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue(),
+ "Blocking group is used when there is no alternative");
dispatcher.deconstruct();
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
index e07d38fbf10..1293975deb5 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
@@ -20,7 +20,7 @@ import com.yahoo.searchlib.aggregation.MinAggregationResult;
import com.yahoo.searchlib.expression.IntegerResultNode;
import com.yahoo.searchlib.expression.StringResultNode;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
@@ -38,11 +38,7 @@ import java.util.stream.StreamSupport;
import static com.yahoo.container.handler.Coverage.DEGRADED_BY_MATCH_PHASE;
import static com.yahoo.container.handler.Coverage.DEGRADED_BY_TIMEOUT;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -55,7 +51,7 @@ public class InterleavedSearchInvokerTest {
private final List<SearchInvoker> invokers = new ArrayList<>();
@Test
- public void requireThatAdaptiveTimeoutsAreNotUsedWithFullCoverageRequirement() throws IOException {
+ void requireThatAdaptiveTimeoutsAreNotUsedWithFullCoverageRequirement() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(100.0), 1, 3);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 3);
@@ -65,11 +61,11 @@ public class InterleavedSearchInvokerTest {
invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
}
@Test
- public void requireThatTimeoutsAreNotMarkedAsAdaptive() throws IOException {
+ void requireThatTimeoutsAreNotMarkedAsAdaptive() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(100.0), 1, 3);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 3);
@@ -79,15 +75,15 @@ public class InterleavedSearchInvokerTest {
Result result = invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
- assertNull("Result is not marked as an error", result.hits().getErrorHit());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
+ assertNull(result.hits().getErrorHit(), "Result is not marked as an error");
var message = findTrace(result, "Backend communication timeout");
- assertTrue("Timeout should be reported in a trace message", message.isPresent());
- assertTrue("Degradation reason is a normal timeout", result.getCoverage(false).isDegradedByTimeout());
+ assertTrue(message.isPresent(), "Timeout should be reported in a trace message");
+ assertTrue(result.getCoverage(false).isDegradedByTimeout(), "Degradation reason is a normal timeout");
}
@Test
- public void requireThatAdaptiveTimeoutDecreasesTimeoutWhenCoverageIsReached() throws IOException {
+ void requireThatAdaptiveTimeoutDecreasesTimeoutWhenCoverageIsReached() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(50.0), 1, 4);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 4);
@@ -98,15 +94,15 @@ public class InterleavedSearchInvokerTest {
Result result = invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
- assertNull("Result is not marked as an error", result.hits().getErrorHit());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
+ assertNull(result.hits().getErrorHit(), "Result is not marked as an error");
var message = findTrace(result, "Backend communication timeout");
- assertTrue("Timeout should be reported in a trace message", message.isPresent());
- assertTrue("Degradataion reason is an adaptive timeout", result.getCoverage(false).isDegradedByAdapativeTimeout());
+ assertTrue(message.isPresent(), "Timeout should be reported in a trace message");
+ assertTrue(result.getCoverage(false).isDegradedByAdapativeTimeout(), "Degradataion reason is an adaptive timeout");
}
@Test
- public void requireCorrectCoverageCalculationWhenAllNodesOk() throws IOException {
+ void requireCorrectCoverageCalculationWhenAllNodesOk() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
invokers.add(new MockInvoker(1, createCoverage(49845, 49845, 49845, 1, 1, 0)));
@@ -127,7 +123,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenResultsAreLimitedByMatchPhase() throws IOException {
+ void requireCorrectCoverageCalculationWhenResultsAreLimitedByMatchPhase() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(10101, 50155, 50155, 1, 1, DEGRADED_BY_MATCH_PHASE)));
invokers.add(new MockInvoker(1, createCoverage(13319, 49845, 49845, 1, 1, DEGRADED_BY_MATCH_PHASE)));
@@ -149,11 +145,11 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenResultsAreLimitedBySoftTimeout() throws IOException {
+ void requireCorrectCoverageCalculationWhenResultsAreLimitedBySoftTimeout() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(5000, 50155, 50155, 1, 1, DEGRADED_BY_TIMEOUT)));
invokers.add(new MockInvoker(1, createCoverage(4900, 49845, 49845, 1, 1, DEGRADED_BY_TIMEOUT)));
- SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()),0);
+ SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 0);
expectedEvents.add(new Event(null, 100, 0));
expectedEvents.add(new Event(null, 200, 1));
@@ -171,7 +167,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenOneNodeIsUnexpectedlyDown() throws IOException {
+ void requireCorrectCoverageCalculationWhenOneNodeIsUnexpectedlyDown() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
invokers.add(new MockInvoker(1, createCoverage(49845, 49845, 49845, 1, 1, 0)));
@@ -231,13 +227,13 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatTopKProbabilityOverrideTakesEffect() throws IOException {
+ void requireThatTopKProbabilityOverrideTakesEffect() throws IOException {
validateThatTopKProbabilityOverrideTakesEffect(null, 8, new Group(0, List.of()));
validateThatTopKProbabilityOverrideTakesEffect(0.8, 7, new Group(0, List.of()));
}
@Test
- public void requireThatTopKProbabilityOverrideIsDisabledOnContentSkew() throws IOException {
+ void requireThatTopKProbabilityOverrideIsDisabledOnContentSkew() throws IOException {
Node node0 = new Node(0, "host0", 0);
Node node1 = new Node(1, "host1", 0);
Group group = new Group(0, List.of(node0, node1));
@@ -249,7 +245,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatTopKProbabilityOverrideIsDisabledOnLittleContent() throws IOException {
+ void requireThatTopKProbabilityOverrideIsDisabledOnLittleContent() throws IOException {
Node node0 = new Node(0, "host0", 0);
Node node1 = new Node(1, "host1", 0);
Group group = new Group(0, List.of(node0, node1));
@@ -261,7 +257,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeySorting() throws IOException {
+ void requireThatMergeOfConcreteHitsObeySorting() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5, B5, new Group(0, List.of()));
query.setHits(12);
Result result = invoker.search(query, null);
@@ -281,7 +277,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeyOffset() throws IOException {
+ void requireThatMergeOfConcreteHitsObeyOffset() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5, B5, new Group(0, List.of()));
query.setHits(3);
query.setOffset(5);
@@ -303,7 +299,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeyOffsetWithAuxilliaryStuff() throws IOException {
+ void requireThatMergeOfConcreteHitsObeyOffsetWithAuxilliaryStuff() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5Aux, B5Aux, new Group(0, List.of()));
query.setHits(3);
query.setOffset(5);
@@ -327,7 +323,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatGroupingsAreMerged() throws IOException {
+ void requireThatGroupingsAreMerged() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
List<SearchInvoker> invokers = new ArrayList<>();
@@ -386,7 +382,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenDegradedCoverageIsExpected() throws IOException {
+ void requireCorrectCoverageCalculationWhenDegradedCoverageIsExpected() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
Coverage errorCoverage = new Coverage(0, 0, 0);
@@ -468,7 +464,7 @@ public class InterleavedSearchInvokerTest {
public SearchInvoker process(Query query, long currentTimeout) {
if (expectedTimeout != null) {
- assertEquals("Expecting timeout to be " + expectedTimeout, (long) expectedTimeout, currentTimeout);
+ assertEquals((long) expectedTimeout, currentTimeout, "Expecting timeout to be " + expectedTimeout);
}
clock.advance(Duration.ofMillis(delay));
if (query.getTimeLeft() < 0) {
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java
index a2080ce6b05..3d2ab17b15d 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class LeanHitTest {
private static final byte [] gidA = {'a'};
@@ -20,34 +18,39 @@ public class LeanHitTest {
assertTrue(c.compareTo(b) > 0);
assertTrue(c.compareTo(a) > 0);
}
+
@Test
- public void testOrderingByRelevance() {
+ void testOrderingByRelevance() {
assertEquals(0, new LeanHit(gidA, 0, 0, 1).compareTo(new LeanHit(gidA, 0, 0, 1)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 1),
new LeanHit(gidA, 0, 0, 0),
new LeanHit(gidA, 0, 0, -1));
}
+
@Test
- public void testOrderingByGid() {
+ void testOrderingByGid() {
assertEquals(0, new LeanHit(gidA, 0, 0, 1).compareTo(new LeanHit(gidA, 0, 0, 1)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 1),
new LeanHit(gidB, 0, 0, 1),
new LeanHit(gidC, 0, 0, 1));
}
+
@Test
- public void testOrderingBySortData() {
+ void testOrderingBySortData() {
assertEquals(0, new LeanHit(gidA, 0, 0, 0.0, gidA).compareTo(new LeanHit(gidA, 0, 0, 0.0, gidA)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 0.0, gidA),
new LeanHit(gidA, 0, 0, 0.0, gidB),
new LeanHit(gidA, 0, 0, 0.0, gidC));
}
+
@Test
- public void testRelevanceIsKeptEvenWithBySortData() {
+ void testRelevanceIsKeptEvenWithBySortData() {
assertEquals(1.3, new LeanHit(gidA, 0, 0, 1.3, gidA).getRelevance(), 0.0);
}
+
@Test
- public void testNaN2negativeInfinity() {
+ void testNaN2negativeInfinity() {
LeanHit nan = new LeanHit(gidA, 0, 0, Double.NaN);
assertFalse(Double.isNaN(nan.getRelevance()));
assertTrue(Double.isInfinite(nan.getRelevance()));
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
index e95fbc366a6..e9ed1c48302 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
@@ -6,8 +6,8 @@ import com.yahoo.search.dispatch.LoadBalancer.GroupStatus;
import com.yahoo.search.dispatch.searchcluster.Group;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
-import junit.framework.AssertionFailedError;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.opentest4j.AssertionFailedError;
import java.util.ArrayList;
import java.util.Collections;
@@ -16,9 +16,9 @@ import java.util.Optional;
import java.util.Random;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author ollivir
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertTrue;
public class LoadBalancerTest {
@Test
- public void requireThatLoadBalancerServesSingleNodeSetups() {
+ void requireThatLoadBalancerServesSingleNodeSetups() {
Node n1 = new Node(0, "test-node1", 0);
SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1), null, null);
LoadBalancer lb = new LoadBalancer(cluster, true);
@@ -39,7 +39,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerServesMultiGroupSetups() {
+ void requireThatLoadBalancerServesMultiGroupSetups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 1);
SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null, null);
@@ -53,7 +53,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerServesClusteredGroups() {
+ void requireThatLoadBalancerServesClusteredGroups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 0);
Node n3 = new Node(0, "test-node3", 1);
@@ -66,10 +66,10 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerReturnsDifferentGroups() {
+ void requireThatLoadBalancerReturnsDifferentGroups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 1);
- SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null,null);
+ SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null, null);
LoadBalancer lb = new LoadBalancer(cluster, true);
// get first group
@@ -86,7 +86,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireCorrectAverageSearchTimeDecay() {
+ void requireCorrectAverageSearchTimeDecay() {
final double delta = 0.00001;
GroupStatus gs = newGroupStatus(1);
@@ -115,7 +115,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireEqualDistributionInFlatWeightListWithAdaptiveScheduler() {
+ void requireEqualDistributionInFlatWeightListWithAdaptiveScheduler() {
List<GroupStatus> scoreboard = new ArrayList<>();
for (int i = 0; i < 5; i++) {
scoreboard.add(newGroupStatus(i));
@@ -134,7 +134,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatAdaptiveSchedulerObeysWeights() {
+ void requireThatAdaptiveSchedulerObeysWeights() {
List<GroupStatus> scoreboard = new ArrayList<>();
for (int i = 0; i < 5; i++) {
GroupStatus gs = newGroupStatus(i);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
index 3a1a60df7af..12cbe488485 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
@@ -3,16 +3,13 @@ package com.yahoo.search.dispatch;
import com.yahoo.search.dispatch.SearchPath.InvalidSearchPathException;
import com.yahoo.search.dispatch.searchcluster.Node;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -20,7 +17,7 @@ import static org.junit.Assert.fail;
public class SearchPathTest {
@Test
- public void requreThatSearchPathsAreParsedCorrectly() {
+ void requreThatSearchPathsAreParsedCorrectly() {
assertEquals(SearchPath.fromString("0/0").get().toString(), "0/0");
assertEquals(SearchPath.fromString("1/0").get().toString(), "1/0");
assertEquals(SearchPath.fromString("0/1").get().toString(), "0/1");
@@ -43,7 +40,7 @@ public class SearchPathTest {
}
@Test
- public void requreThatWildcardsAreDetected() {
+ void requreThatWildcardsAreDetected() {
assertFalse(SearchPath.fromString("").isPresent());
assertFalse(SearchPath.fromString("*/*").isPresent());
assertFalse(SearchPath.fromString("/").isPresent());
@@ -52,7 +49,7 @@ public class SearchPathTest {
}
@Test
- public void invalidRangeMustThrowException() {
+ void invalidRangeMustThrowException() {
try {
SearchPath.fromString("[p,0>/0");
fail("Expected exception");
@@ -63,7 +60,7 @@ public class SearchPathTest {
}
@Test
- public void invalidPartMustThrowException() {
+ void invalidPartMustThrowException() {
try {
SearchPath.fromString("p/0");
fail("Expected exception");
@@ -74,7 +71,7 @@ public class SearchPathTest {
}
@Test
- public void invalidRowMustThrowException() {
+ void invalidRowMustThrowException() {
try {
SearchPath.fromString("1,2,3/r");
fail("Expected exception");
@@ -92,8 +89,8 @@ public class SearchPathTest {
}
@Test
- public void searchPathMustFilterNodesBasedOnDefinition() {
- MockSearchCluster cluster = new MockSearchCluster("a",3, 3);
+ void searchPathMustFilterNodesBasedOnDefinition() {
+ MockSearchCluster cluster = new MockSearchCluster("a", 3, 3);
assertEquals(distKeysAsString(SearchPath.selectNodes("1/1", cluster)), "4");
assertEquals(distKeysAsString(SearchPath.selectNodes("/1", cluster)), "3,4,5");
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java
index 5dfcd8901da..283596322e6 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Locale;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class TopKEstimatorTest {
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbability() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbability() {
TopKEstimator estimator = new TopKEstimator(30, 0.999);
assertEquals(91.97368471911312, estimator.estimateExactK(200, 3), 0.0);
assertEquals(92, estimator.estimateK(200, 3));
@@ -27,8 +27,9 @@ public class TopKEstimatorTest {
assertEquals(44.909040374464155, estimator.estimateExactK(200, 10, 0.99999), 0.0);
assertEquals(45, estimator.estimateK(200, 10, 0.99999));
}
+
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K200() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K200() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(200, estimator.estimateExactK(200, 1), 0.0);
assertEquals(200, estimator.estimateK(200, 1));
@@ -39,7 +40,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K20() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K20() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(20, estimator.estimateExactK(20, 1), 0.0);
assertEquals(20, estimator.estimateK(20, 1));
@@ -50,7 +51,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Five9() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Five9() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(10, estimator.estimateExactK(10, 1), 0.0);
assertEquals(10, estimator.estimateK(10, 1));
@@ -61,7 +62,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Four9() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Four9() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(10, estimator.estimateExactK(10, 1), 0.0);
assertEquals(10, estimator.estimateK(10, 1));
@@ -72,21 +73,21 @@ public class TopKEstimatorTest {
}
@Test
- public void requireEstimatesAreRoundeUp() {
+ void requireEstimatesAreRoundeUp() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(5.794676146031378, estimator.estimateExactK(10, 10), 0.0);
assertEquals(6, estimator.estimateK(10, 10));
}
@Test
- public void requireEstimatesAreCappedAtInputK() {
+ void requireEstimatesAreCappedAtInputK() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(12.087323848369289, estimator.estimateExactK(10, 2), 0.0);
assertEquals(10, estimator.estimateK(10, 2));
}
@Test
- public void requireThatLargeKAreSane() {
+ void requireThatLargeKAreSane() {
System.out.println(dumpProbability(10, 0.05));
TopKEstimator idealEstimator = new TopKEstimator(30, 0.9999);
TopKEstimator skewedEstimator = new TopKEstimator(30, 0.9999, 0.05);
@@ -100,23 +101,23 @@ public class TopKEstimatorTest {
String expected =
"Prob/Hits: 1.0000000000 0.9999000000 0.9999900000 0.9999990000 0.9999999000 0.9999999900 0.9999999990 0.9999999999\n" +
- " 10: 10.000 6.000 7.000 8.000 9.000 10.000 10.000 10.000\n" +
- " 20: 10.000 4.500 5.000 5.500 6.500 7.000 7.500 8.000\n" +
- " 40: 10.000 3.500 4.000 4.250 4.750 5.250 5.500 6.000\n" +
- " 80: 10.000 2.750 3.000 3.250 3.625 3.875 4.250 4.500\n" +
- " 100: 10.000 2.600 2.800 3.100 3.300 3.600 3.900 4.200\n" +
- " 200: 10.000 2.100 2.250 2.450 2.650 2.800 3.000 3.200\n" +
- " 400: 10.000 1.775 1.900 2.025 2.150 2.275 2.425 2.575\n" +
- " 800: 10.000 1.538 1.625 1.713 1.813 1.900 2.000 2.100\n" +
- " 1000: 10.000 1.480 1.560 1.640 1.720 1.810 1.890 1.990\n" +
- " 2000: 10.000 1.340 1.395 1.450 1.510 1.570 1.630 1.695\n" +
- " 4000: 10.000 1.240 1.280 1.320 1.360 1.403 1.445 1.493\n" +
- " 8000: 10.000 1.170 1.198 1.225 1.254 1.284 1.315 1.348\n" +
- " 10000: 10.000 1.152 1.177 1.202 1.227 1.254 1.282 1.311\n" +
- " 20000: 10.000 1.108 1.125 1.143 1.161 1.180 1.199 1.220\n" +
- " 40000: 10.000 1.076 1.088 1.101 1.114 1.127 1.141 1.156\n" +
- " 80000: 10.000 1.054 1.062 1.071 1.080 1.090 1.100 1.110\n" +
- " 100000: 10.000 1.048 1.056 1.064 1.072 1.080 1.089 1.098\n";
+ " 10: 10.000 6.000 7.000 8.000 9.000 10.000 10.000 10.000\n" +
+ " 20: 10.000 4.500 5.000 5.500 6.500 7.000 7.500 8.000\n" +
+ " 40: 10.000 3.500 4.000 4.250 4.750 5.250 5.500 6.000\n" +
+ " 80: 10.000 2.750 3.000 3.250 3.625 3.875 4.250 4.500\n" +
+ " 100: 10.000 2.600 2.800 3.100 3.300 3.600 3.900 4.200\n" +
+ " 200: 10.000 2.100 2.250 2.450 2.650 2.800 3.000 3.200\n" +
+ " 400: 10.000 1.775 1.900 2.025 2.150 2.275 2.425 2.575\n" +
+ " 800: 10.000 1.538 1.625 1.713 1.813 1.900 2.000 2.100\n" +
+ " 1000: 10.000 1.480 1.560 1.640 1.720 1.810 1.890 1.990\n" +
+ " 2000: 10.000 1.340 1.395 1.450 1.510 1.570 1.630 1.695\n" +
+ " 4000: 10.000 1.240 1.280 1.320 1.360 1.403 1.445 1.493\n" +
+ " 8000: 10.000 1.170 1.198 1.225 1.254 1.284 1.315 1.348\n" +
+ " 10000: 10.000 1.152 1.177 1.202 1.227 1.254 1.282 1.311\n" +
+ " 20000: 10.000 1.108 1.125 1.143 1.161 1.180 1.199 1.220\n" +
+ " 40000: 10.000 1.076 1.088 1.101 1.114 1.127 1.141 1.156\n" +
+ " 80000: 10.000 1.054 1.062 1.071 1.080 1.090 1.100 1.110\n" +
+ " 100000: 10.000 1.048 1.056 1.064 1.072 1.080 1.089 1.098\n";
assertEquals(expected, dumpProbability(10, 0.0));
String expectedSkew =
"Prob/Hits: 1.0000000000 0.9999000000 0.9999900000 0.9999990000 0.9999999000 0.9999999900 0.9999999990 0.9999999999\n" +
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
index 6834a5edf9b..861ed4d165d 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
@@ -6,14 +6,12 @@ import com.yahoo.data.access.ArrayTraverser;
import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.ObjectTraverser;
import com.yahoo.data.access.Type;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author arnej
@@ -21,14 +19,14 @@ import static org.junit.Assert.assertTrue;
public class MatchFeatureDataTest {
@Test
- public void testHitValueAPI() {
+ void testHitValueAPI() {
List<String> names = List.of("foo", "bar", "baz", "qux", "quux");
var mf = new MatchFeatureData(names);
var hit = mf.addHit();
assertEquals(hit.type(), Type.OBJECT);
assertTrue(hit.valid());
hit.set(0, 1.0);
- byte[] somebytes = { 42, 0, 17 };
+ byte[] somebytes = {42, 0, 17};
hit.set(2, somebytes);
hit.set(4, 5.0);
hit.set(1, 2.0);
@@ -64,7 +62,7 @@ public class MatchFeatureDataTest {
var fields = hit.fields().iterator();
assertTrue(fields.hasNext());
- Map.Entry<String,Inspector> entry = fields.next();
+ Map.Entry<String, Inspector> entry = fields.next();
assertEquals("foo", entry.getKey());
assertEquals(f1.type(), entry.getValue().type());
assertEquals(f1.asDouble(), entry.getValue().asDouble(), 0.0);
@@ -94,9 +92,9 @@ public class MatchFeatureDataTest {
assertEquals(f5.asDouble(), entry.getValue().asDouble(), 0.0);
assertFalse(fields.hasNext());
-
+
assertEquals("{\"foo\":1.0,\"bar\":2.0,\"baz\":\"0x2A0011\",\"qux\":4.0,\"quux\":5.0}",
- hit.toString());
+ hit.toString());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
index 9953d1467e1..72b3095b2f9 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
@@ -12,14 +12,12 @@ import com.yahoo.search.dispatch.InvokerResult;
import com.yahoo.search.dispatch.LeanHit;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -29,38 +27,38 @@ public class ProtobufSerializationTest {
static final double DELTA = 0.000000000001;
@Test
- public void testQuerySerialization() {
+ void testQuerySerialization() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/tensortypes").compile();
Query query = new Query.Builder().setQueryProfile(registry.getComponent("profile1"))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
- SearchProtocol.SearchRequest request1 = ProtobufSerialization.convertFromQuery(query, 9,"serverId", 0.5);
+ SearchProtocol.SearchRequest request1 = ProtobufSerialization.convertFromQuery(query, 9, "serverId", 0.5);
assertEquals(9, request1.getHits());
assertEquals(0, request1.getRankPropertiesCount());
assertEquals(0, request1.getTensorRankPropertiesCount());
assertEquals(0, request1.getFeatureOverridesCount());
assertEquals(2, request1.getTensorFeatureOverridesCount());
assertEquals("\"\\001\\001\\003key\\001\\rpre_key1_post?\\360\\000\\000\\000\\000\\000\\000\"",
- contentsOf(request1.getTensorFeatureOverrides(0).getValue()));
+ contentsOf(request1.getTensorFeatureOverrides(0).getValue()));
assertEquals("\"\\006\\001\\001\\001x\\001?\\231\\231\\232\"",
- contentsOf(request1.getTensorFeatureOverrides(1).getValue()));
+ contentsOf(request1.getTensorFeatureOverrides(1).getValue()));
query.prepare(); // calling prepare() moves "overrides" to "features" - content stays the same
- SearchProtocol.SearchRequest request2 = ProtobufSerialization.convertFromQuery(query, 9,"serverId", 0.5);
+ SearchProtocol.SearchRequest request2 = ProtobufSerialization.convertFromQuery(query, 9, "serverId", 0.5);
assertEquals(9, request2.getHits());
assertEquals(0, request2.getRankPropertiesCount());
assertEquals(2, request2.getTensorRankPropertiesCount());
assertEquals("\"\\001\\001\\003key\\001\\rpre_key1_post?\\360\\000\\000\\000\\000\\000\\000\"",
- contentsOf(request2.getTensorRankProperties(0).getValue()));
+ contentsOf(request2.getTensorRankProperties(0).getValue()));
assertEquals("\"\\006\\001\\001\\001x\\001?\\231\\231\\232\"",
- contentsOf(request2.getTensorRankProperties(1).getValue()));
+ contentsOf(request2.getTensorRankProperties(1).getValue()));
assertEquals(0, request2.getFeatureOverridesCount());
assertEquals(0, request2.getTensorFeatureOverridesCount());
}
@Test
- public void testDocsumSerialization() {
+ void testDocsumSerialization() {
Query q = new Query("search/?query=test&hits=10&offset=3");
var builder = ProtobufSerialization.createDocsumRequestBuilder(q, "server", "summary", true, 0.5);
builder.setTimeout(0);
@@ -95,8 +93,9 @@ public class ProtobufSerializationTest {
}
return reply.build();
}
+
@Test
- public void testSearchReplyDecodingWithRelevance() {
+ void testSearchReplyDecodingWithRelevance() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, false), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
@@ -114,8 +113,9 @@ public class ProtobufSerializationTest {
hitNum++;
}
}
+
@Test
- public void testSearchReplyDecodingWithSortData() {
+ void testSearchReplyDecodingWithSortData() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, true), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
index c26bef05fb6..6789d0347d5 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
@@ -11,17 +11,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -29,7 +26,7 @@ import static org.junit.Assert.fail;
public class RpcSearchInvokerTest {
@Test
- public void testProtobufSerialization() throws IOException {
+ void testProtobufSerialization() throws IOException {
var compressionTypeHolder = new AtomicReference<CompressionType>();
var payloadHolder = new AtomicReference<byte[]>();
var lengthHolder = new AtomicInteger();
@@ -50,14 +47,14 @@ public class RpcSearchInvokerTest {
assertTrue(request.getQueryTreeBlob().size() > 0);
var invoker2 = new RpcSearchInvoker(mockSearcher(), new Node(8, "eight", 1), mockPool, 1000);
- RpcSearchInvoker.RpcContext context2 = (RpcSearchInvoker.RpcContext)invoker2.sendSearchRequest(q, context);
+ RpcSearchInvoker.RpcContext context2 = (RpcSearchInvoker.RpcContext) invoker2.sendSearchRequest(q, context);
assertSame(context, context2);
assertEquals(lengthHolder.get(), context.compressedPayload.uncompressedSize());
assertSame(context.compressedPayload.data(), payloadHolder.get());
}
@Test
- public void testProtobufSerializationWithMaxHitsSet() throws IOException {
+ void testProtobufSerializationWithMaxHitsSet() throws IOException {
int maxHits = 5;
var compressionTypeHolder = new AtomicReference<CompressionType>();
var payloadHolder = new AtomicReference<byte[]>();
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java
index c21bf623366..3d981c5e45a 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch.searchcluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class SearchClusterCoverageTest {
@Test
- public void two_groups_equal_docs() {
+ void two_groups_equal_docs() {
var tester = new SearchClusterTester(2, 3);
tester.setDocsPerNode(100, 0);
@@ -23,22 +23,22 @@ public class SearchClusterCoverageTest {
}
@Test
- public void two_groups_one_missing_docs() {
+ void two_groups_one_missing_docs() {
var tester = new SearchClusterTester(2, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 70, 1);
+ tester.setDocsPerNode(70, 1);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
assertFalse(tester.group(1).hasSufficientCoverage());
}
@Test
- public void three_groups_one_missing_docs() {
+ void three_groups_one_missing_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 87, 1); // min is set to 88 in MockSearchCluster
+ tester.setDocsPerNode(87, 1); // min is set to 88 in MockSearchCluster
tester.setDocsPerNode(100, 2);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
@@ -47,11 +47,11 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_missing_docs_but_too_few() {
+ void three_groups_one_missing_docs_but_too_few() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 89, 1); // min is set to 88 in MockSearchCluster
+ tester.setDocsPerNode(89, 1); // min is set to 88 in MockSearchCluster
tester.setDocsPerNode(100, 2);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
@@ -60,7 +60,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_too_many_docs() {
+ void three_groups_one_has_too_many_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -73,7 +73,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_a_node_down() {
+ void three_groups_one_has_a_node_down() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -87,7 +87,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_a_node_down_but_remaining_has_enough_docs() {
+ void three_groups_one_has_a_node_down_but_remaining_has_enough_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -96,12 +96,12 @@ public class SearchClusterCoverageTest {
tester.setWorking(1, 1, false);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
- assertTrue("Sufficient documents on remaining two nodes", tester.group(1).hasSufficientCoverage());
+ assertTrue(tester.group(1).hasSufficientCoverage(), "Sufficient documents on remaining two nodes");
assertTrue(tester.group(2).hasSufficientCoverage());
}
@Test
- public void one_group_few_docs_unbalanced() {
+ void one_group_few_docs_unbalanced() {
var tester = new SearchClusterTester(1, 2);
Node node0 = tester.group(0).nodes().get(0);
@@ -120,7 +120,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void one_group_many_docs_unbalanced() {
+ void one_group_many_docs_unbalanced() {
var tester = new SearchClusterTester(1, 2);
Node node0 = tester.group(0).nodes().get(0);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
index 94df796b370..473b24af19f 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
@@ -9,7 +9,7 @@ import com.yahoo.prelude.Pong;
import com.yahoo.search.cluster.ClusterMonitor;
import com.yahoo.search.dispatch.MockSearchCluster;
import com.yahoo.search.result.ErrorMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -19,9 +19,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -151,7 +149,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownButComesUpAfterPinging() {
+ void requireThatVipStatusIsDefaultDownButComesUpAfterPinging() {
try (State test = new State("cluster.1", 2, "a", "b")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isEmpty());
@@ -162,7 +160,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatZeroDocsAreFine() {
+ void requireThatZeroDocsAreFine() {
try (State test = new State("cluster.1", 2, "a", "b")) {
test.waitOneFullPingRound();
@@ -180,7 +178,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownWithLocalDispatch() {
+ void requireThatVipStatusIsDefaultDownWithLocalDispatch() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "b")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -191,7 +189,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusStaysUpWithLocalDispatchAndClusterSize1() {
+ void requireThatVipStatusStaysUpWithLocalDispatchAndClusterSize1() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost())) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -205,7 +203,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownWithLocalDispatchAndClusterSize2() {
+ void requireThatVipStatusIsDefaultDownWithLocalDispatchAndClusterSize2() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "otherhost")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -219,7 +217,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusDownWhenLocalIsDown() {
+ void requireThatVipStatusDownWhenLocalIsDown() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "b")) {
test.waitOneFullPingRound();
@@ -276,8 +274,8 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusDownRequireAllNodesDown() {
- verifyThatVipStatusDownRequireAllNodesDown(1,2);
+ void requireThatVipStatusDownRequireAllNodesDown() {
+ verifyThatVipStatusDownRequireAllNodesDown(1, 2);
verifyThatVipStatusDownRequireAllNodesDown(3, 3);
}
@@ -315,13 +313,13 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusUpRequireOnlyOneOnlineNode() {
+ void requireThatVipStatusUpRequireOnlyOneOnlineNode() {
verifyThatVipStatusUpRequireOnlyOneOnlineNode(1, 2);
verifyThatVipStatusUpRequireOnlyOneOnlineNode(3, 3);
}
@Test
- public void requireThatPingSequenceIsUpHeld() {
+ void requireThatPingSequenceIsUpHeld() {
Node node = new Node(1, "n", 1);
assertEquals(1, node.createPingSequenceId());
assertEquals(2, node.createPingSequenceId());
@@ -335,7 +333,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatEmptyGroupIsInBalance() {
+ void requireThatEmptyGroupIsInBalance() {
Group group = new Group(0, new ArrayList<>());
assertTrue(group.isBalanced());
group.aggregateNodeValues();
@@ -343,7 +341,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatSingleNodeGroupIsInBalance() {
+ void requireThatSingleNodeGroupIsInBalance() {
Group group = new Group(0, Arrays.asList(new Node(1, "n", 1)));
group.nodes().forEach(node -> node.setWorking(true));
assertTrue(group.isBalanced());
@@ -355,7 +353,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatMultiNodeGroupDetectsBalance() {
+ void requireThatMultiNodeGroupDetectsBalance() {
Group group = new Group(0, Arrays.asList(new Node(1, "n1", 1), new Node(2, "n2", 1)));
assertTrue(group.isBalanced());
group.nodes().forEach(node -> node.setWorking(true));
diff --git a/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
index da25baacd51..cb0d4ab923f 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
@@ -12,7 +12,7 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
@@ -20,8 +20,8 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests that sources representing document types which resolve to the same actual source
@@ -32,7 +32,7 @@ import static org.junit.Assert.assertEquals;
public class DuplicateSourceTestCase {
@Test
- public void testDuplicateSource() {
+ void testDuplicateSource() {
// Set up a single cluster and chain (chain1), containing a MockBackendSearcher and having 2 doc types (doc1, doc2)
MockBackendSearcher mockBackendSearcher = new MockBackendSearcher();
SearchChainRegistry searchChains = new SearchChainRegistry();
@@ -41,12 +41,12 @@ public class DuplicateSourceTestCase {
clusters.put("chain1", ImmutableList.of("doc1", "doc2"));
IndexFacts indexFacts = new IndexFacts(new IndexModel(clusters, Collections.emptyList()));
SearchChainResolver resolver = new SearchChainResolver.Builder()
- .addSearchChain(new ComponentId("chain1"), ImmutableList.of("doc1", "doc2"))
- .build();
+ .addSearchChain(new ComponentId("chain1"), ImmutableList.of("doc1", "doc2"))
+ .build();
FederationSearcher searcher = new FederationSearcher(new ComponentId("test"), resolver);
Result result = searcher.search(new Query("?query=test&sources=doc1%2cdoc2"),
- new Execution(Execution.Context.createContextStub(searchChains, indexFacts)));
+ new Execution(Execution.Context.createContextStub(searchChains, indexFacts)));
assertNull(result.hits().getError());
assertEquals(1, mockBackendSearcher.getInvocationCount());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java b/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
index a17104f888d..71004f5a98a 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
@@ -11,16 +11,14 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.FutureResult;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -34,7 +32,7 @@ public class FederationResultTest {
private final ManualClock clock = new ManualClock();
@Test
- public void testFederationResult() {
+ void testFederationResult() {
assertTimeout(ImmutableSet.of(), 100, 200, 180);
assertTimeout(ImmutableSet.of(), 480, 400, 400);
assertTimeout(ImmutableSet.of("dsp1"), 260, 280, 220);
@@ -56,9 +54,9 @@ public class FederationResultTest {
for (FederationResult.TargetResult targetResult : federationResult.all()) {
Result result = targetResult.getOrTimeoutError();
if (expectedTimeoutNames.contains(targetResult.target.getId().toString()))
- assertTrue(targetResult.target.getId() + " timed out", timedOut(result));
+ assertTrue(timedOut(result), targetResult.target.getId() + " timed out");
else
- assertFalse(targetResult.target.getId() + " did not time out", timedOut(result));
+ assertFalse(timedOut(result), targetResult.target.getId() + " did not time out");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
index 4bb6db40c66..2c83bc8cc00 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
@@ -20,17 +20,14 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.Execution.Context;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -40,19 +37,19 @@ public class FederationSearcherTest {
private static final String hasBeenFilled = "hasBeenFilled";
@Test
- public void require_that_hits_are_not_automatically_filled() {
+ void require_that_hits_are_not_automatically_filled() {
Result result = federationToSingleAddHitSearcher().search();
assertNotFilled(firstHitInFirstGroup(result));
}
@Test
- public void require_that_hits_can_be_filled() {
+ void require_that_hits_can_be_filled() {
Result result = federationToSingleAddHitSearcher().searchAndFill();
assertFilled(firstHitInFirstGroup(result));
}
@Test
- public void require_that_hits_can_be_filled_when_moved() {
+ void require_that_hits_can_be_filled_when_moved() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new AddHitSearcher());
@@ -80,7 +77,7 @@ public class FederationSearcherTest {
}
@Test
- public void require_that_hits_can_be_filled_for_multiple_chains_and_queries() {
+ void require_that_hits_can_be_filled_for_multiple_chains_and_queries() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new ModifyQueryAndAddHitSearcher("modified1"));
@@ -89,12 +86,12 @@ public class FederationSearcherTest {
Result result = tester.search();
tester.fill(result);
assertEquals(3, result.hits().getConcreteSize());
- for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext();)
+ for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext(); )
assertFilled(i.next());
}
@Test
- public void require_that_hits_that_time_out_in_fill_are_removed() {
+ void require_that_hits_that_time_out_in_fill_are_removed() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new TimeoutInFillSearcher());
@@ -104,13 +101,13 @@ public class FederationSearcherTest {
Result result = tester.search(query);
tester.fill(result);
assertEquals(1, result.hits().getConcreteSize());
- for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext();)
+ for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext(); )
assertFilled(i.next());
assertEquals("Timed out", result.hits().getError().getMessage());
}
@Test
- public void require_that_optional_search_chains_does_not_delay_federation() {
+ void require_that_optional_search_chains_does_not_delay_federation() {
BlockingSearcher blockingSearcher = new BlockingSearcher();
FederationTester tester = new FederationTester();
@@ -121,8 +118,8 @@ public class FederationSearcherTest {
assertEquals(2, result.getHitCount());
assertTrue(result.hits().get(0) instanceof HitGroup);
assertTrue(result.hits().get(1) instanceof HitGroup);
- HitGroup chain1Result = (HitGroup)result.hits().get(0);
- HitGroup chain2Result = (HitGroup)result.hits().get(1);
+ HitGroup chain1Result = (HitGroup) result.hits().get(0);
+ HitGroup chain2Result = (HitGroup) result.hits().get(1);
// Verify chain1 result: One filled hit
assertEquals(1, chain1Result.size());
@@ -141,21 +138,21 @@ public class FederationSearcherTest {
}
@Test
- public void require_that_calling_a_single_slow_source_with_long_timeout_does_not_delay_federation() {
+ void require_that_calling_a_single_slow_source_with_long_timeout_does_not_delay_federation() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1",
- new FederationOptions().setUseByDefault(true).setRequestTimeoutInMilliseconds(3600 * 1000),
- new BlockingSearcher() );
+ new FederationOptions().setUseByDefault(true).setRequestTimeoutInMilliseconds(3600 * 1000),
+ new BlockingSearcher());
Query query = new Query();
query.setTimeout(50); // make the test run faster
Result result = tester.search(query);
assertEquals(1, result.hits().size());
assertTrue(result.hits().get(0) instanceof HitGroup);
- HitGroup chain1Result = (HitGroup)result.hits().get(0);
+ HitGroup chain1Result = (HitGroup) result.hits().get(0);
assertEquals(1, chain1Result.size());
assertTrue(chain1Result.asList().get(0) instanceof ErrorHit);
- ErrorHit errorHit = (ErrorHit)chain1Result.get(0);
+ ErrorHit errorHit = (ErrorHit) chain1Result.get(0);
assertEquals(1, errorHit.errors().size());
ErrorMessage error = errorHit.errors().iterator().next();
assertEquals("chain1", error.getSource());
@@ -164,7 +161,7 @@ public class FederationSearcherTest {
}
@Test
- public void custom_federation_target() {
+ void custom_federation_target() {
ComponentId targetSelectorId = ComponentId.fromString("TargetSelector");
ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>();
targetSelectors.register(targetSelectorId, new TestTargetSelector());
@@ -182,7 +179,7 @@ public class FederationSearcherTest {
}
@Test
- public void target_selectors_can_have_multiple_targets() {
+ void target_selectors_can_have_multiple_targets() {
ComponentId targetSelectorId = ComponentId.fromString("TestMultipleTargetSelector");
ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>();
targetSelectors.register(targetSelectorId, new TestMultipleTargetSelector());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
index c2feb16df04..556cbea023f 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
@@ -19,17 +19,13 @@ import com.yahoo.search.test.QueryTestCase;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for federation searcher. The searcher is also tested in
@@ -60,13 +56,13 @@ public class FederationSearcherTestCase {
private FederationConfig.Builder builder;
private SearchChainRegistry chainRegistry;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
builder = new FederationConfig.Builder();
chainRegistry = new SearchChainRegistry();
}
- @After
+ @AfterEach
public void tearDown() {
builder = null;
chainRegistry = null;
@@ -93,7 +89,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testQueryProfileNestedReferencing() {
+ void testQueryProfileNestedReferencing() {
addChained(new MockSearcher(), "mySource1");
addChained(new MockSearcher(), "mySource2");
Chain<Searcher> mainChain = new Chain<>("default", createFederationSearcher());
@@ -110,7 +106,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceTwoSources() {
+ void testTraceTwoSources() {
Chain<Searcher> mainChain = twoTracingSources(false);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1"));
@@ -148,7 +144,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceOneSourceNoCloning() {
+ void testTraceOneSourceNoCloning() {
Chain<Searcher> mainChain = twoTracingSources(true);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1&sources=source1"));
@@ -163,7 +159,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceOneSourceWithCloning() {
+ void testTraceOneSourceWithCloning() {
Chain<Searcher> mainChain = twoTracingSources(false);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1&sources=source1"));
@@ -179,7 +175,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testPropertyPropagation() {
+ void testPropertyPropagation() {
Result result = searchWithPropertyPropagation();
assertEquals("source:mySource1", result.hits().get(0).getId().stringValue());
@@ -210,7 +206,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTopLevelHitGroupFieldPropagation() {
+ void testTopLevelHitGroupFieldPropagation() {
addChained(new MockSearcher(), "mySource1");
addChained(new AnotherMockSearcher(), "mySource2");
Chain<Searcher> mainChain = new Chain<>("default", createFederationSearcher());
@@ -256,7 +252,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testProviderSelectionFromQueryProperties() {
+ void testProviderSelectionFromQueryProperties() {
SearchChainRegistry registry = new SearchChainRegistry();
registry.register(new Chain<>("provider1", new MockProvider("provider1")));
registry.register(new Chain<>("provider2", new MockProvider("provider2")));
diff --git a/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
index 6f1570b702f..59547ecdd35 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
@@ -5,13 +5,13 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class HitCountTestCase {
@Test
- public void require_that_offset_and_hits_are_adjusted_when_federating() {
+ void require_that_offset_and_hits_are_adjusted_when_federating() {
final int chain1RelevanceMultiplier = 1;
final int chain2RelevanceMultiplier = 10;
@@ -38,7 +38,7 @@ public class HitCountTestCase {
}
@Test
- public void require_that_hit_counts_are_merged() {
+ void require_that_hit_counts_are_merged() {
final long chain1TotalHitCount = 3;
final long chain1DeepHitCount = 5;
@@ -56,7 +56,7 @@ public class HitCountTestCase {
}
@Test
- public void require_that_logging_hit_is_populated_with_result_count() {
+ void require_that_logging_hit_is_populated_with_result_count() {
final long chain1TotalHitCount = 9;
final long chain1DeepHitCount = 14;
diff --git a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
index 34224721487..5a551fdcdee 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
@@ -10,15 +10,13 @@ import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.federation.sourceref.Target;
import com.yahoo.search.federation.sourceref.UnresolvedSearchChainException;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Iterator;
import java.util.SortedSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -53,7 +51,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void check_default_search_chains() {
+ void check_default_search_chains() {
assertEquals(2, searchChainResolver.defaultTargets().size());
Iterator<Target> iterator = searchChainResolver.defaultTargets().iterator();
@@ -62,7 +60,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void require_error_message_for_invalid_source() {
+ void require_error_message_for_invalid_source() {
try {
resolve("no-such-source");
fail("Expected exception.");
@@ -72,7 +70,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_search_chain() throws Exception {
+ void lookup_search_chain() throws Exception {
SearchChainInvocationSpec res = resolve(searchChainId.getName());
assertEquals(searchChainId, res.searchChainId);
}
@@ -86,13 +84,13 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_source() throws Exception {
+ void lookup_source() throws Exception {
SearchChainInvocationSpec res = resolve(sourceId.getName());
assertIsSourceInProvider(res);
}
@Test
- public void lookup_source_search_chain_directly() throws Exception {
+ void lookup_source_search_chain_directly() throws Exception {
SearchChainInvocationSpec res = resolve(sourceChainInProviderId.stringValue());
assertIsSourceInProvider(res);
}
@@ -104,7 +102,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_source_for_provider2() throws Exception {
+ void lookup_source_for_provider2() throws Exception {
SearchChainInvocationSpec res = resolve(sourceId.getName(), provider2Id.getName());
assertEquals(provider2Id, res.provider);
assertEquals(sourceId, res.source);
@@ -112,7 +110,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lists_source_ref_description_for_top_level_targets() {
+ void lists_source_ref_description_for_top_level_targets() {
SortedSet<Target> topLevelTargets = searchChainResolver.allTopLevelTargets();
assertEquals(3, topLevelTargets.size());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
index acb68175921..97c93ed09ed 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.federation.sourceref.SourceRefResolver;
import com.yahoo.search.federation.sourceref.UnresolvedSearchChainException;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -19,9 +19,7 @@ import java.util.Set;
import java.util.TreeMap;
import static com.yahoo.search.federation.sourceref.test.SearchChainResolverTestCase.emptySourceToProviderMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for SourceRefResolver.
@@ -60,38 +58,38 @@ public class SourceRefResolverTestCase {
}
@Test
- public void check_test_assumptions() {
+ void check_test_assumptions() {
assertTrue(indexFacts.clustersHavingSearchDefinition("document1").containsAll(List.of("cluster1", "cluster2")));
}
@Test
- public void lookup_search_chain() throws Exception {
+ void lookup_search_chain() throws Exception {
Set<SearchChainInvocationSpec> searchChains = resolve(cluster1);
assertEquals(1, searchChains.size());
assertTrue(searchChainIds(searchChains).contains(cluster1));
}
@Test
- public void lookup_search_chains_for_document1() throws Exception {
+ void lookup_search_chains_for_document1() throws Exception {
Set<SearchChainInvocationSpec> searchChains = resolve("document1");
assertEquals(2, searchChains.size());
assertTrue(searchChainIds(searchChains).containsAll(List.of(cluster1, cluster2)));
}
@Test
- public void error_when_document_gives_cluster_without_matching_search_chain() {
+ void error_when_document_gives_cluster_without_matching_search_chain() {
try {
resolve("document3");
fail("Expected exception");
} catch (UnresolvedSearchChainException e) {
assertEquals("Failed to resolve cluster search chain 'cluster3' " +
- "when using source ref 'document3' as a document name.",
- e.getMessage());
+ "when using source ref 'document3' as a document name.",
+ e.getMessage());
}
}
@Test
- public void error_when_no_document_or_search_chain() {
+ void error_when_no_document_or_search_chain() {
try {
resolve("document4");
fail("Expected exception");
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java
index 217fd4af400..3dcfcb8480a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ public class ContinuationTestCase {
private static final String KNOWN_CONTINUATION = "BCBCBCBEBGBCBKCBACBKCCK";
@Test
- public void requireThatToStringCanBeParsedByFromString() {
+ void requireThatToStringCanBeParsedByFromString() {
Continuation cnt = Continuation.fromString(KNOWN_CONTINUATION);
assertNotNull(cnt);
assertEquals(KNOWN_CONTINUATION, cnt.toString());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
index bbb461a939c..4911a5b2543 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.search.grouping.request.EachOperation;
import com.yahoo.search.grouping.request.GroupingOperation;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -21,17 +21,17 @@ import static org.junit.Assert.*;
public class GroupingQueryParserTestCase {
@Test
- public void requireThatNoRequestIsSkipped() {
+ void requireThatNoRequestIsSkipped() {
assertEquals(Collections.emptyList(), executeQuery(null, null, null));
}
@Test
- public void requireThatEmptyRequestIsSkipped() {
+ void requireThatEmptyRequestIsSkipped() {
assertEquals(Collections.emptyList(), executeQuery("", null, null));
}
@Test
- public void requireThatRequestIsParsed() {
+ void requireThatRequestIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, null);
assertNotNull(lst);
assertEquals(1, lst.size());
@@ -41,7 +41,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatRequestListIsParsed() {
+ void requireThatRequestListIsParsed() {
List<GroupingRequest> lst = executeQuery("all();each()", null, null);
assertNotNull(lst);
assertEquals(2, lst.size());
@@ -50,7 +50,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatEachRightBelowAllParses() {
+ void requireThatEachRightBelowAllParses() {
List<GroupingRequest> lst = executeQuery("all(each(output(summary(bar))))",
null, null);
assertNotNull(lst);
@@ -64,9 +64,9 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatContinuationListIsParsed() {
+ void requireThatContinuationListIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))",
- "BCBCBCBEBGBCBKCBACBKCCK BCBBBBBDBF", null);
+ "BCBCBCBEBGBCBKCBACBKCCK BCBBBBBDBF", null);
assertNotNull(lst);
assertEquals(1, lst.size());
GroupingRequest req = lst.get(0);
@@ -76,7 +76,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatTimeZoneIsParsed() {
+ void requireThatTimeZoneIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, "cet");
assertNotNull(lst);
assertEquals(1, lst.size());
@@ -88,7 +88,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatTimeZoneHasUtcDefault() {
+ void requireThatTimeZoneHasUtcDefault() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, null);
assertNotNull(lst);
assertEquals(1, lst.size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
index 4bc827dde7a..458039fb872 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.search.Result;
import com.yahoo.search.grouping.result.Group;
import com.yahoo.search.grouping.result.RootGroup;
import com.yahoo.search.result.Hit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -15,7 +15,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
public class GroupingRequestTestCase {
@Test
- public void requireThatContinuationListIsMutable() {
+ void requireThatContinuationListIsMutable() {
GroupingRequest req = GroupingRequest.newInstance(new Query());
assertTrue(req.continuations().isEmpty());
@@ -41,7 +41,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatResultIsFound() {
+ void requireThatResultIsFound() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -57,7 +57,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatResultIsFoundAfterCloning() {
+ void requireThatResultIsFoundAfterCloning() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query.clone());
@@ -73,7 +73,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatParallelRequestsAreSupported() {
+ void requireThatParallelRequestsAreSupported() {
Query query = new Query();
Result res = new Result(query);
@@ -94,7 +94,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatRemovedResultIsNull() {
+ void requireThatRemovedResultIsNull() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -107,7 +107,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatNonGroupResultIsNull() {
+ void requireThatNonGroupResultIsNull() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -119,7 +119,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatGetRequestsReturnsAllRequests() {
+ void requireThatGetRequestsReturnsAllRequests() {
Query query = new Query();
assertEquals(Collections.emptyList(), query.getSelect().getGrouping());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
index 4f473b29918..4b5fb53b06a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.search.Query;
import com.yahoo.search.config.ClusterConfig;
import com.yahoo.search.grouping.request.GroupingOperation;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,13 +21,14 @@ import static org.junit.Assert.fail;
public class GroupingValidatorTestCase {
@Test
- public void requireThatAvailableAttributesDoNotThrow() {
+ void requireThatAvailableAttributesDoNotThrow() {
validateGrouping(List.of("foo", "bar"),
- "all(group(foo) each(output(max(bar))))");;
+ "all(group(foo) each(output(max(bar))))");
+ ;
}
@Test
- public void requireThatUnavailableAttributesThrow() {
+ void requireThatUnavailableAttributesThrow() {
try {
validateGrouping(List.of("foo"), "all(group(foo) each(output(max(bar))))");
fail("Excpected exception");
@@ -38,20 +39,20 @@ public class GroupingValidatorTestCase {
}
@Test
- public void requireThatEnableFlagPreventsThrow() {
+ void requireThatEnableFlagPreventsThrow() {
Query query = createQuery("all(group(foo) each(output(max(bar))))");
query.properties().set(GroupingValidator.PARAM_ENABLED, "false");
validateGrouping(List.of("foo"), query);
}
@Test
- public void available_primitive_map_attribute_does_not_throw() {
+ void available_primitive_map_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value"),
"all(group(map{\"foo\"}) each(output(count())))");
}
@Test
- public void unavailable_primitive_map_key_attribute_throws() {
+ void unavailable_primitive_map_key_attribute_throws() {
try {
validateGrouping(List.of("null"), "all(group(map{\"foo\"}) each(output(count())))");
fail("Expected exception");
@@ -62,7 +63,7 @@ public class GroupingValidatorTestCase {
}
@Test
- public void unavailable_primitive_map_value_attribute_throws() {
+ void unavailable_primitive_map_value_attribute_throws() {
try {
validateGrouping(List.of("map.key"), "all(group(map{\"foo\"}) each(output(count())))");
fail("Expected exception");
@@ -73,13 +74,13 @@ public class GroupingValidatorTestCase {
}
@Test
- public void available_struct_map_attribute_does_not_throw() {
+ void available_struct_map_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value.name"),
"all(group(map{\"foo\"}.name) each(output(count())))");
}
@Test
- public void unavailable_struct_map_key_attribute_throws() {
+ void unavailable_struct_map_key_attribute_throws() {
try {
validateGrouping(List.of("null"), "all(group(map{\"foo\"}.name) each(output(count())))");
fail("Expected exception");
@@ -90,7 +91,7 @@ public class GroupingValidatorTestCase {
}
@Test
- public void unavailable_struct_map_value_attribute_throws() {
+ void unavailable_struct_map_value_attribute_throws() {
try {
validateGrouping(List.of("map.key"), "all(group(map{\"foo\"}.name) each(output(count())))");
fail("Expected exception");
@@ -101,16 +102,16 @@ public class GroupingValidatorTestCase {
}
@Test
- public void available_key_source_attribute_does_not_throw() {
+ void available_key_source_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value", "key_source"),
"all(group(map{attribute(key_source)}) each(output(count())))");
}
@Test
- public void unavailable_key_source_attribute_throws() {
+ void unavailable_key_source_attribute_throws() {
try {
validateGrouping(List.of("map.key", "map.value"),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (UnavailableAttributeException e) {
@@ -119,29 +120,29 @@ public class GroupingValidatorTestCase {
}
@Test
- public void key_source_attribute_with_mismatching_data_type_throws() {
+ void key_source_attribute_with_mismatching_data_type_throws() {
try {
validateGrouping(setupMismatchingKeySourceAttribute(false),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Grouping request references key source attribute 'key_source' with data type 'INT32' " +
- "that is different than data type 'STRING' of key attribute 'map.key'",
- e.getMessage());
+ "that is different than data type 'STRING' of key attribute 'map.key'",
+ e.getMessage());
}
}
@Test
- public void key_source_attribute_with_multi_value_collection_type_throws() {
+ void key_source_attribute_with_multi_value_collection_type_throws() {
try {
validateGrouping(setupMismatchingKeySourceAttribute(true),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Grouping request references key source attribute 'key_source' which is not of single value type",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
index cb771ecb678..ffb69267212 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
@@ -15,11 +15,9 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author andreer
@@ -27,21 +25,21 @@ import static org.junit.Assert.fail;
public class UniqueGroupingSearcherTestCase {
@Test
- public void testSkipGroupingBasedDedup() {
+ void testSkipGroupingBasedDedup() {
Result result = search("?query=foo",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
assertEquals(0, result.hits().size());
}
@Test
- public void testSkipGroupingBasedDedupIfMultiLevelSorting() {
+ void testSkipGroupingBasedDedupIfMultiLevelSorting() {
Result result = search("?query=foo&unique=fingerprint&sorting=-pubdate%20-[rank]",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
assertEquals(0, result.hits().size());
}
@Test
- public void testIllegalSortingSpec() {
+ void testIllegalSortingSpec() {
try {
search("?query=foo&unique=fingerprint&sorting=-1",
new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
@@ -49,31 +47,31 @@ public class UniqueGroupingSearcherTestCase {
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains("Could not set 'ranking.sorting' to '-1': " +
- "Illegal attribute name '1' for sorting. " +
- "Requires '[\\[]*[a-zA-Z_][\\.a-zA-Z0-9_-]*[\\]]*'"));
+ "Illegal attribute name '1' for sorting. " +
+ "Requires '[\\[]*[a-zA-Z_][\\.a-zA-Z0-9_-]*[\\]]*'"));
}
}
@Test
- public void testGroupingBasedDedupNoGroupingHits() {
+ void testGroupingBasedDedupNoGroupingHits() {
Result result = search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, true));
+ new MockResultProvider(0, true));
assertEquals(0, result.hits().size());
}
@Test
- public void testGroupingBasedDedupWithEmptyGroupingHitsList() {
+ void testGroupingBasedDedupWithEmptyGroupingHitsList() {
Result result = search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
+ new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
assertEquals(0, result.hits().size());
assertEquals(0, result.getTotalHitCount());
}
@Test
- public void testGroupingBasedDedupWithNullGroupingResult() {
+ void testGroupingBasedDedupWithNullGroupingResult() {
try {
search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
fail();
} catch (IllegalStateException e) {
assertEquals("Failed to produce deduped result set.", e.getMessage());
@@ -81,7 +79,7 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testGroupingBasedDedupWithGroupingHits() {
+ void testGroupingBasedDedupWithGroupingHits() {
GroupList fingerprint = new GroupList("fingerprint");
fingerprint.add(makeHitGroup("1"));
fingerprint.add(makeHitGroup("2"));
@@ -105,7 +103,7 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testGroupingBasedDedupWithGroupingHitsAndSorting() {
+ void testGroupingBasedDedupWithGroupingHitsAndSorting() {
GroupList fingerprint = new GroupList("fingerprint");
fingerprint.add(makeSortingHitGroup("1"));
fingerprint.add(makeSortingHitGroup("2"));
@@ -130,29 +128,29 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testBuildGroupingExpression() {
+ void testBuildGroupingExpression() {
assertEquals("all(group(title) max(11) output(count() as(uniqueCount)) each(max(1) each(output(summary())) " +
- "as(uniqueHits)))",
- UniqueGroupingSearcher
- .buildGroupingExpression("title", 11, null, null)
- .toString());
+ "as(uniqueHits)))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("title", 11, null, null)
+ .toString());
assertEquals("all(group(fingerprint) max(5) output(count() as(uniqueCount)) each(max(1) " +
- "each(output(summary(attributeprefetch))) as(uniqueHits)))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, "attributeprefetch", null)
- .toString());
+ "each(output(summary(attributeprefetch))) as(uniqueHits)))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, "attributeprefetch", null)
+ .toString());
assertEquals("all(group(fingerprint) max(5) order(neg(max(pubdate))) output(count() as(uniqueCount)) each(" +
- "all(group(neg(pubdate)) max(1) order(neg(max(pubdate))) each(each(output(summary())) " +
- "as(uniqueHits)) as(uniqueGroups))))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, null, new Sorting("-pubdate"))
- .toString());
+ "all(group(neg(pubdate)) max(1) order(neg(max(pubdate))) each(each(output(summary())) " +
+ "as(uniqueHits)) as(uniqueGroups))))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, null, new Sorting("-pubdate"))
+ .toString());
assertEquals("all(group(fingerprint) max(5) order(min(pubdate)) output(count() as(uniqueCount)) each(" +
- "all(group(pubdate) max(1) order(min(pubdate)) each(each(output(summary(attributeprefetch))) " +
- "as(uniqueHits)) as(uniqueGroups))))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, "attributeprefetch", new Sorting("+pubdate"))
- .toString());
+ "all(group(pubdate) max(1) order(min(pubdate)) each(each(output(summary(attributeprefetch))) " +
+ "as(uniqueHits)) as(uniqueGroups))))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, "attributeprefetch", new Sorting("+pubdate"))
+ .toString());
}
private static Group makeHitGroup(String name) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
index 50058f3777f..d7a888792d9 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ChoiceFormat;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -22,7 +22,7 @@ public class BucketResolverTestCase {
// --------------------------------------------------------------------------------
@Test
- public void testResolve() {
+ void testResolve() {
BucketResolver resolver = new BucketResolver();
resolver.push(new StringValue("a"), true);
try {
@@ -71,32 +71,32 @@ public class BucketResolverTestCase {
}
@Test
- public void testBucketType() {
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("a"), new LongValue(1L)),
- "Bucket type mismatch, expected 'StringValue' got 'LongValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("a"), new DoubleValue(1.0)),
- "Bucket type mismatch, expected 'StringValue' got 'DoubleValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(1L), new StringValue("a")),
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(1L), new DoubleValue(1.0)),
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(1.0), new StringValue("a")),
- "Bucket type mismatch, expected 'DoubleValue' got 'StringValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(1.0), new LongValue(1L)),
- "Bucket type mismatch, expected 'DoubleValue' got 'LongValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))),
- "Bucket type mismatch, cannot both be infinity.");
+ void testBucketType() {
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new LongValue(1L)),
+ "Bucket type mismatch, expected 'StringValue' got 'LongValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new DoubleValue(1.0)),
+ "Bucket type mismatch, expected 'StringValue' got 'DoubleValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new StringValue("a")),
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new DoubleValue(1.0)),
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new StringValue("a")),
+ "Bucket type mismatch, expected 'DoubleValue' got 'StringValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new LongValue(1L)),
+ "Bucket type mismatch, expected 'DoubleValue' got 'LongValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))),
+ "Bucket type mismatch, cannot both be infinity.");
}
@Test
- public void testBucketOrder() {
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(2L), new LongValue(1L)),
- "Bucket to-value can not be less than from-value.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(2.0), new DoubleValue(1.0)),
- "Bucket to-value can not be less than from-value.");
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("b"), new StringValue("a")),
- "Bucket to-value can not be less than from-value.");
+ void testBucketOrder() {
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(2L), new LongValue(1L)),
+ "Bucket to-value can not be less than from-value.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(2.0), new DoubleValue(1.0)),
+ "Bucket to-value can not be less than from-value.");
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("b"), new StringValue("a")),
+ "Bucket to-value can not be less than from-value.");
}
public void assertBucketRange(BucketValue expected, ConstantValue from, boolean inclusiveFrom, ConstantValue to, boolean inclusiveTo) {
@@ -123,7 +123,7 @@ public class BucketResolverTestCase {
}
@Test
- public void requireThatBucketRangesWork() {
+ void requireThatBucketRangesWork() {
BucketValue expected = new LongBucket(2, 5);
assertBucketRange(expected, new LongValue(1), false, new LongValue(4), true);
assertBucketRange(expected, new LongValue(1), false, new LongValue(5), false);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
index 24ce3cfea32..1f800b37ff0 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class ExpressionVisitorTestCase {
@Test
- public void requireThatExpressionsAreVisited() {
+ void requireThatExpressionsAreVisited() {
GroupingOperation op = new AllOperation();
final List<GroupingExpression> lst = new LinkedList<>();
@@ -38,7 +38,7 @@ public class ExpressionVisitorTestCase {
}
@Test
- public void requireThatChildOperationsAreVisited() {
+ void requireThatChildOperationsAreVisited() {
GroupingOperation root, parentA, childA1, childA2, parentB, childB1;
root = new AllOperation()
.addChild(parentA = new AllOperation()
@@ -69,7 +69,7 @@ public class ExpressionVisitorTestCase {
}
@Test
- public void requireThatExpressionsArgumentsAreVisited() {
+ void requireThatExpressionsArgumentsAreVisited() {
final List<GroupingExpression> lst = new LinkedList<>();
GroupingExpression arg1 = new AttributeValue("arg1");
lst.add(arg1);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
index 0e89f348449..d1ab7117677 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.search.grouping.request;
import com.yahoo.search.grouping.request.parser.ParseException;
import com.yahoo.search.grouping.request.parser.TokenMgrException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -15,7 +15,7 @@ import static org.junit.Assert.*;
public class GroupingOperationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
GroupingOperation op = new AllOperation();
GroupingExpression exp = new AttributeValue("alias");
op.putAlias("alias", exp);
@@ -88,7 +88,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatFromStringAsListParsesAllOperations() {
+ void requireThatFromStringAsListParsesAllOperations() {
List<GroupingOperation> lst = GroupingOperation.fromStringAsList("");
assertTrue(lst.isEmpty());
@@ -107,7 +107,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatFromStringAcceptsOnlyOneOperation() {
+ void requireThatFromStringAcceptsOnlyOneOperation() {
try {
GroupingOperation.fromString("");
fail();
@@ -125,7 +125,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatParseExceptionsAreRethrown() {
+ void requireThatParseExceptionsAreRethrown() {
try {
GroupingOperation.fromString("all(foo)");
fail();
@@ -136,7 +136,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatTokenErrorsAreRethrown() {
+ void requireThatTokenErrorsAreRethrown() {
try {
GroupingOperation.fromString("all(\\foo)");
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
index d22c2dee7b6..823993b6bc6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
@@ -1,19 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
*/
public class MathFunctionsTestCase {
-
+
@Test
- public void testMathFunctions() {
+ void testMathFunctions() {
//if this fails, update the count AND add a test in each of the two blocks below
assertEquals(21, MathFunctions.Function.values().length);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java
index 734e2c6a0cb..39fdc7fc3a6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -18,40 +18,40 @@ public class MathResolverTestCase {
// --------------------------------------------------------------------------------
@Test
- public void testOperators() {
+ void testOperators() {
MathResolver resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.ADD, new LongValue(2));
assertEquals("add(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.SUB, new LongValue(2));
assertEquals("sub(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.DIV, new LongValue(2));
assertEquals("div(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.MOD, new LongValue(2));
assertEquals("mod(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.MUL, new LongValue(2));
assertEquals("mul(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
}
@Test
- public void testOperatorPrecedence() {
+ void testOperatorPrecedence() {
assertResolve("add(add(1, 2), 3)", MathResolver.Type.ADD, MathResolver.Type.ADD);
assertResolve("add(1, sub(2, 3))", MathResolver.Type.ADD, MathResolver.Type.SUB);
assertResolve("add(1, div(2, 3))", MathResolver.Type.ADD, MathResolver.Type.DIV);
@@ -83,21 +83,21 @@ public class MathResolverTestCase {
assertResolve("mul(mul(1, 2), 3)", MathResolver.Type.MUL, MathResolver.Type.MUL);
assertResolve("add(1, sub(div(2, mod(3, mul(4, 5))), 6))",
- MathResolver.Type.ADD, MathResolver.Type.DIV, MathResolver.Type.MOD,
- MathResolver.Type.MUL, MathResolver.Type.SUB);
+ MathResolver.Type.ADD, MathResolver.Type.DIV, MathResolver.Type.MOD,
+ MathResolver.Type.MUL, MathResolver.Type.SUB);
assertResolve("add(sub(1, div(mod(mul(2, 3), 4), 5)), 6)",
- MathResolver.Type.SUB, MathResolver.Type.MUL, MathResolver.Type.MOD,
- MathResolver.Type.DIV, MathResolver.Type.ADD);
+ MathResolver.Type.SUB, MathResolver.Type.MUL, MathResolver.Type.MOD,
+ MathResolver.Type.DIV, MathResolver.Type.ADD);
assertResolve("add(1, sub(2, div(3, mod(4, mul(5, 6)))))",
- MathResolver.Type.ADD, MathResolver.Type.SUB, MathResolver.Type.DIV,
- MathResolver.Type.MOD, MathResolver.Type.MUL);
+ MathResolver.Type.ADD, MathResolver.Type.SUB, MathResolver.Type.DIV,
+ MathResolver.Type.MOD, MathResolver.Type.MUL);
assertResolve("add(sub(div(mod(mul(1, 2), 3), 4), 5), 6)",
- MathResolver.Type.MUL, MathResolver.Type.MOD, MathResolver.Type.DIV,
- MathResolver.Type.SUB, MathResolver.Type.ADD);
+ MathResolver.Type.MUL, MathResolver.Type.MOD, MathResolver.Type.DIV,
+ MathResolver.Type.SUB, MathResolver.Type.ADD);
}
@Test
- public void testOperatorSupport() {
+ void testOperatorSupport() {
MathResolver resolver = new MathResolver();
for (MathResolver.Type type : MathResolver.Type.values()) {
if (type == MathResolver.Type.ADD) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
index dfa297b4fa6..03223f786e8 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -21,18 +21,18 @@ public class RawBufferTestCase {
// --------------------------------------------------------------------------------
@Test
- public void requireThatCompareWorks() {
+ void requireThatCompareWorks() {
RawBuffer buffer = new RawBuffer();
- buffer.put((byte)'a');
- buffer.put((byte)'b');
+ buffer.put((byte) 'a');
+ buffer.put((byte) 'b');
RawBuffer buffer2 = new RawBuffer();
- buffer2.put((byte)'k');
- buffer2.put((byte)'a');
+ buffer2.put((byte) 'k');
+ buffer2.put((byte) 'a');
ArrayList<Byte> backing = new ArrayList<>();
- backing.add((byte)'a');
- backing.add((byte)'b');
+ backing.add((byte) 'a');
+ backing.add((byte) 'b');
RawBuffer buffer3 = new RawBuffer(backing);
assertEquals(buffer.compareTo(buffer2), -1);
@@ -41,9 +41,9 @@ public class RawBufferTestCase {
}
@Test
- public void requireThatToStringWorks() {
+ void requireThatToStringWorks() {
assertToString(Arrays.asList("a".getBytes()[0], "b".getBytes()[0]), "{97,98}");
- assertToString(Arrays.asList((byte)2, (byte)6), "{2,6}");
+ assertToString(Arrays.asList((byte) 2, (byte) 6), "{2,6}");
}
public void assertToString(List<Byte> data, String expected) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java
index c02e46fae98..e2b4dc4f34b 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.*;
public class RequestTestCase {
@Test
- public void requireThatApiWorks() {
+ void requireThatApiWorks() {
GroupingOperation op = new AllOperation()
.setGroupBy(new AttributeValue("foo"))
.addOrderBy(new CountAggregator())
@@ -22,19 +22,19 @@ public class RequestTestCase {
.addOutput(new CountAggregator())
.addOutput(new MinAggregator(new AttributeValue("bar")))
.addChild(new EachOperation()
- .addOutput(new AddFunction(
- new LongValue(69),
- new AttributeValue("baz")))
- .addOutput(new SummaryValue("cox"))));
+ .addOutput(new AddFunction(
+ new LongValue(69),
+ new AttributeValue("baz")))
+ .addOutput(new SummaryValue("cox"))));
assertEquals("all(group(foo) order(count()) all() each() " +
- "each(output(count(), min(bar)) each(output(add(69, baz), summary(cox)))))",
- op.toString());
+ "each(output(count(), min(bar)) each(output(add(69, baz), summary(cox)))))",
+ op.toString());
op.resolveLevel(1);
GroupingExpression exp = op.getGroupBy();
assertNotNull(exp);
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
assertEquals(1, op.getNumOrderBy());
assertNotNull(exp = op.getOrderBy(0));
assertTrue(exp instanceof CountAggregator);
@@ -49,9 +49,9 @@ public class RequestTestCase {
assertTrue(exp instanceof CountAggregator);
assertNotNull(exp = op.getOutput(1));
assertTrue(exp instanceof MinAggregator);
- assertNotNull(exp = ((MinAggregator)exp).getExpression());
+ assertNotNull(exp = ((MinAggregator) exp).getExpression());
assertTrue(exp instanceof AttributeValue);
- assertEquals("bar", ((AttributeValue)exp).getAttributeName());
+ assertEquals("bar", ((AttributeValue) exp).getAttributeName());
assertEquals(1, op.getNumChildren());
assertNotNull(op = op.getChild(0));
@@ -59,24 +59,24 @@ public class RequestTestCase {
assertEquals(2, op.getNumOutputs());
assertNotNull(exp = op.getOutput(0));
assertTrue(exp instanceof AddFunction);
- assertEquals(2, ((AddFunction)exp).getNumArgs());
- GroupingExpression arg = ((AddFunction)exp).getArg(0);
+ assertEquals(2, ((AddFunction) exp).getNumArgs());
+ GroupingExpression arg = ((AddFunction) exp).getArg(0);
assertNotNull(arg);
assertTrue(arg instanceof LongValue);
- assertEquals(69L, ((LongValue)arg).getValue().longValue());
- assertNotNull(arg = ((AddFunction)exp).getArg(1));
+ assertEquals(69L, ((LongValue) arg).getValue().longValue());
+ assertNotNull(arg = ((AddFunction) exp).getArg(1));
assertTrue(arg instanceof AttributeValue);
- assertEquals("baz", ((AttributeValue)arg).getAttributeName());
+ assertEquals("baz", ((AttributeValue) arg).getAttributeName());
assertNotNull(exp = op.getOutput(1));
assertTrue(exp instanceof SummaryValue);
- assertEquals("cox", ((SummaryValue)exp).getSummaryName());
+ assertEquals("cox", ((SummaryValue) exp).getSummaryName());
}
@Test
- public void requireThatPredefinedApiWorks() {
+ void requireThatPredefinedApiWorks() {
PredefinedFunction fnc = new LongPredefined(new AttributeValue("foo"),
- new LongBucket(1, 2),
- new LongBucket(3, 4));
+ new LongBucket(1, 2),
+ new LongBucket(3, 4));
assertEquals(2, fnc.getNumBuckets());
BucketValue bucket = fnc.getBucket(0);
assertNotNull(bucket);
@@ -91,7 +91,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatBucketIntegrityIsChecked() {
+ void requireThatBucketIntegrityIsChecked() {
try {
new LongBucket(2, 1);
} catch (IllegalArgumentException e) {
@@ -99,37 +99,37 @@ public class RequestTestCase {
}
try {
new LongPredefined(new AttributeValue("foo"),
- new LongBucket(3, 4),
- new LongBucket(1, 2));
+ new LongBucket(3, 4),
+ new LongBucket(1, 2));
} catch (IllegalArgumentException e) {
assertEquals("Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatAliasWorks() {
+ void requireThatAliasWorks() {
GroupingOperation all = new AllOperation();
all.putAlias("myalias", new AttributeValue("foo"));
GroupingExpression exp = all.getAlias("myalias");
assertNotNull(exp);
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
GroupingOperation each = new EachOperation();
all.addChild(each);
assertNotNull(exp = each.getAlias("myalias"));
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
each.putAlias("myalias", new AttributeValue("bar"));
assertNotNull(exp = each.getAlias("myalias"));
assertTrue(exp instanceof AttributeValue);
- assertEquals("bar", ((AttributeValue)exp).getAttributeName());
+ assertEquals("bar", ((AttributeValue) exp).getAttributeName());
}
@Test
- public void testOrderBy() {
+ void testOrderBy() {
GroupingOperation all = new AllOperation();
all.addOrderBy(new AttributeValue("foo"));
try {
@@ -143,7 +143,7 @@ public class RequestTestCase {
}
@Test
- public void testMax() {
+ void testMax() {
GroupingOperation all = new AllOperation();
all.setMax(69);
try {
@@ -156,10 +156,10 @@ public class RequestTestCase {
}
@Test
- public void testAccuracy() {
+ void testAccuracy() {
GroupingOperation all = new AllOperation();
all.setAccuracy(0.53);
- assertEquals((long)(100.0 * all.getAccuracy()), 53);
+ assertEquals((long) (100.0 * all.getAccuracy()), 53);
try {
all.setAccuracy(1.2);
fail();
@@ -175,7 +175,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelChange() {
+ void testLevelChange() {
GroupingOperation all = new AllOperation();
all.resolveLevel(0);
assertEquals(0, all.getLevel());
@@ -198,7 +198,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelInheritance() {
+ void testLevelInheritance() {
GroupingOperation grandParent, parent, child, grandChild;
grandParent = new AllOperation()
.addChild(parent = new EachOperation()
@@ -213,7 +213,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelPropagation() {
+ void testLevelPropagation() {
GroupingOperation all = new AllOperation()
.setGroupBy(new AttributeValue("foo"))
.addOrderBy(new MaxAggregator(new AttributeValue("bar")))
@@ -224,6 +224,6 @@ public class RequestTestCase {
assertEquals(0, all.getGroupBy().getLevel());
assertEquals(1, all.getOrderBy(0).getLevel());
assertEquals(1, all.getChild(0).getOutput(0).getLevel());
- assertEquals(0, ((AggregatorNode)all.getChild(0).getOutput(0)).getExpression().getLevel());
+ assertEquals(0, ((AggregatorNode) all.getChild(0).getOutput(0)).getExpression().getLevel());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
index 56444a99ed3..c95451e991c 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
@@ -2,7 +2,7 @@
package com.yahoo.search.grouping.request.parser;
import com.yahoo.search.grouping.request.GroupingOperation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedHashMap;
@@ -26,7 +26,7 @@ public class GroupingParserBenchmarkTest {
}
@Test
- public void requireThatGroupingParserIsFast() {
+ void requireThatGroupingParserIsFast() {
List<String> inputs = getInputs();
long ignore = 0;
long now = 0;
@@ -39,9 +39,9 @@ public class GroupingParserBenchmarkTest {
}
}
long micros = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - now);
- System.out.format("%d \u03bcs (avg %.2f)\n", micros, (double)micros / (NUM_RUNS * inputs.size()));
+ System.out.format("%d \u03bcs (avg %.2f)\n", micros, (double) micros / (NUM_RUNS * inputs.size()));
for (Map.Entry<String, Long> entry : PREV_RESULTS.entrySet()) {
- System.out.format("%-20s : %4.2f\n", entry.getKey(), (double)micros / entry.getValue());
+ System.out.format("%-20s : %4.2f\n", entry.getKey(), (double) micros / entry.getValue());
}
System.out.println("\nignore " + ignore);
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
index 0dfd4685c0f..dd55dd46e5e 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
@@ -9,17 +9,13 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.yql.VespaGroupingStep;
import com.yahoo.search.yql.YqlParser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -27,7 +23,7 @@ import static org.junit.Assert.fail;
public class GroupingParserTestCase {
@Test
- public void requireThatMathAllowsWhitespace() {
+ void requireThatMathAllowsWhitespace() {
for (String op : Arrays.asList("+", " +", " + ", "+ ",
"-", " -", " - ", "- ",
"*", " *", " * ", "* ",
@@ -41,7 +37,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testRequestList() {
+ void testRequestList() {
List<GroupingOperation> lst = GroupingOperation.fromStringAsList("all();each();all() where(true);each()");
assertNotNull(lst);
assertEquals(4, lst.size());
@@ -52,113 +48,113 @@ public class GroupingParserTestCase {
}
@Test
- public void testAttributeFunctions() {
+ void testAttributeFunctions() {
assertParse("all(group(foo) each(output(sum(attribute(bar)))))",
- "all(group(foo) each(output(sum(attribute(bar)))))");
+ "all(group(foo) each(output(sum(attribute(bar)))))");
assertParse("all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))",
- "all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))");
+ "all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))");
assertParse("all(group(foo) each(output(sum(array.at(bar, 42.0)))))",
- "all(group(foo) each(output(sum(array.at(bar, 42.0)))))");
+ "all(group(foo) each(output(sum(array.at(bar, 42.0)))))");
}
@Test
- public void requireThatTokenImagesAreNotReservedWords() {
+ void requireThatTokenImagesAreNotReservedWords() {
List<String> images = Arrays.asList("acos",
- "acosh",
- "accuracy",
- "add",
- "alias",
- "all",
- "and",
- "array",
- "as",
- "at",
- "asin",
- "asinh",
- "atan",
- "atanh",
- "attribute",
- "avg",
- "bucket",
- "cat",
- "cbrt",
- "cos",
- "cosh",
- "count",
- "debugwait",
- "div",
- "docidnsspecific",
- "each",
- "exp",
- "fixedwidth",
- "floor",
- "group",
- "hint",
- "hypot",
- "log",
- "log1p",
- "log10",
- "math",
- "max",
- "md5",
- "min",
- "mod",
- "mul",
- "neg",
- "normalizesubject",
- "now",
- "or",
- "order",
- "output",
- "pow",
- "precision",
- "predefined",
- "relevance",
- "reverse",
- "sin",
- "sinh",
- "size",
- "sort",
- "stddev",
- "interpolatedlookup",
- "sqrt",
- "strcat",
- "strlen",
- "sub",
- "sum",
- "summary",
- "tan",
- "tanh",
- "time",
- "date",
- "dayofmonth",
- "dayofweek",
- "dayofyear",
- "hourofday",
- "minuteofhour",
- "monthofyear",
- "secondofminute",
- "year",
- "todouble",
- "tolong",
- "toraw",
- "tostring",
- "true",
- "false",
- "uca",
- "where",
- "x",
- "xor",
- "xorbit",
- "y",
- "zcurve");
+ "acosh",
+ "accuracy",
+ "add",
+ "alias",
+ "all",
+ "and",
+ "array",
+ "as",
+ "at",
+ "asin",
+ "asinh",
+ "atan",
+ "atanh",
+ "attribute",
+ "avg",
+ "bucket",
+ "cat",
+ "cbrt",
+ "cos",
+ "cosh",
+ "count",
+ "debugwait",
+ "div",
+ "docidnsspecific",
+ "each",
+ "exp",
+ "fixedwidth",
+ "floor",
+ "group",
+ "hint",
+ "hypot",
+ "log",
+ "log1p",
+ "log10",
+ "math",
+ "max",
+ "md5",
+ "min",
+ "mod",
+ "mul",
+ "neg",
+ "normalizesubject",
+ "now",
+ "or",
+ "order",
+ "output",
+ "pow",
+ "precision",
+ "predefined",
+ "relevance",
+ "reverse",
+ "sin",
+ "sinh",
+ "size",
+ "sort",
+ "stddev",
+ "interpolatedlookup",
+ "sqrt",
+ "strcat",
+ "strlen",
+ "sub",
+ "sum",
+ "summary",
+ "tan",
+ "tanh",
+ "time",
+ "date",
+ "dayofmonth",
+ "dayofweek",
+ "dayofyear",
+ "hourofday",
+ "minuteofhour",
+ "monthofyear",
+ "secondofminute",
+ "year",
+ "todouble",
+ "tolong",
+ "toraw",
+ "tostring",
+ "true",
+ "false",
+ "uca",
+ "where",
+ "x",
+ "xor",
+ "xorbit",
+ "y",
+ "zcurve");
for (String image : images) {
assertParse("all(group(" + image + "))", "all(group(" + image + "))");
}
}
@Test
- public void testTokenizedWhitespace() {
+ void testTokenizedWhitespace() {
String expected = "all(group(foo) each(output(max(bar))))";
assertParse(" all(group(foo)each(output(max(bar))))", expected);
@@ -182,7 +178,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testOperationTypes() {
+ void testOperationTypes() {
assertParse("all()");
assertParse("each()");
assertParse("all(each())");
@@ -193,21 +189,21 @@ public class GroupingParserTestCase {
assertParse("all(each() each())");
assertParse("each(all() all())");
assertIllegalArgument("each(all() each())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) all() each())",
- "Operation 'each(group(foo) all() each())' can not group single hit.");
+ "Operation 'each(group(foo) all() each())' can not group single hit.");
assertIllegalArgument("each(each() all())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) each() all())",
- "Operation 'each(group(foo) each() all())' can not group single hit.");
+ "Operation 'each(group(foo) each() all())' can not group single hit.");
assertIllegalArgument("each(each() each())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) each() each())",
- "Operation 'each(group(foo) each() each())' can not group single hit.");
+ "Operation 'each(group(foo) each() each())' can not group single hit.");
}
@Test
- public void testOperationParts() {
+ void testOperationParts() {
assertParse("all(group(foo))");
assertParse("all(hint(foo))");
assertParse("all(hint(foo) hint(bar))");
@@ -232,7 +228,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testComplexExpressionTypes() {
+ void testComplexExpressionTypes() {
// fixedwidth
assertParse("all(group(fixedwidth(foo, 1)))");
assertParse("all(group(fixedwidth(foo, 1.2)))");
@@ -315,43 +311,43 @@ public class GroupingParserTestCase {
assertParse("all(group(predefined(foo, bucket({'b', 'a'}, {'k', 'a'}), bucket({'k', 'a'}, {'u', 'b'}))))");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2.0))))",
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, '2'))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(3.0, 4.0))))",
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket('3', '4'))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(\"3\", \"4\"))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(three, four))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket<-inf, inf>)))",
- "Bucket type mismatch, cannot both be infinity");
+ "Bucket type mismatch, cannot both be infinity");
assertIllegalArgument("all(group(predefined(foo, bucket<inf, -inf>)))",
- "Encountered \" \"inf\" \"inf\"\" at line 1, column 34.");
+ "Encountered \" \"inf\" \"inf\"\" at line 1, column 34.");
assertIllegalArgument("all(group(predefined(foo, bucket(2, 1))))",
- "Bucket to-value can not be less than from-value.");
+ "Bucket to-value can not be less than from-value.");
assertIllegalArgument("all(group(predefined(foo, bucket(3, 4), bucket(1, 2))))",
- "Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.");
+ "Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.");
assertIllegalArgument("all(group(predefined(foo, bucket(b, a))))",
- "Bucket to-value can not be less than from-value.");
+ "Bucket to-value can not be less than from-value.");
assertIllegalArgument("all(group(predefined(foo, bucket(b, -inf))))",
- "Encountered \" \"-inf\" \"-inf\"\" at line 1, column 37.");
+ "Encountered \" \"-inf\" \"-inf\"\" at line 1, column 37.");
assertIllegalArgument("all(group(predefined(foo, bucket(c, d), bucket(a, b))))",
- "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[\"a\", \"b\">.");
+ "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[\"a\", \"b\">.");
assertIllegalArgument("all(group(predefined(foo, bucket(c, d), bucket(-inf, e))))",
- "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[-inf, \"e\">.");
+ "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[-inf, \"e\">.");
assertIllegalArgument("all(group(predefined(foo, bucket(u, inf), bucket(e, i))))",
- "Buckets must be monotonically increasing, got bucket[\"u\", inf> before bucket[\"e\", \"i\">.");
+ "Buckets must be monotonically increasing, got bucket[\"u\", inf> before bucket[\"e\", \"i\">.");
// xorbit
assertParse("all(group(xorbit(foo, 1)))");
}
@Test
- public void testInfixArithmetic() {
+ void testInfixArithmetic() {
assertParse("all(group(1))", "all(group(1))");
assertParse("all(group(1+2))", "all(group(add(1, 2)))");
assertParse("all(group(1-2))", "all(group(sub(1, 2)))");
@@ -371,16 +367,16 @@ public class GroupingParserTestCase {
}
@Test
- public void testOperationLabel() {
+ void testOperationLabel() {
assertParse("each() as(foo)",
- "each() as(foo)");
+ "each() as(foo)");
assertParse("all(each() as(foo)" +
- " each() as(bar))",
- "all(each() as(foo) each() as(bar))");
+ " each() as(bar))",
+ "all(each() as(foo) each() as(bar))");
assertParse("all(group(a) each(each() as(foo)" +
- " each() as(bar))" +
- " each() as(baz))",
- "all(group(a) each(each() as(foo) each() as(bar)) each() as(baz))");
+ " each() as(bar))" +
+ " each() as(baz))",
+ "all(group(a) each(each() as(foo) each() as(bar)) each() as(baz))");
assertIllegalArgument("all() as(foo)", "Encountered \" \"as\" \"as\"\" at line 1, column 7.");
assertIllegalArgument("all(all() as(foo))", "Encountered \" \"as\" \"as\"\" at line 1, column 11.");
@@ -388,58 +384,58 @@ public class GroupingParserTestCase {
}
@Test
- public void testAttributeName() {
+ void testAttributeName() {
assertParse("all(group(foo))");
assertIllegalArgument("all(group(foo.))",
- "Encountered \" \")\" \")\"\" at line 1, column 15.");
+ "Encountered \" \")\" \")\"\" at line 1, column 15.");
assertParse("all(group(foo.bar))");
assertIllegalArgument("all(group(foo.bar.))",
- "Encountered \" \")\" \")\"\" at line 1, column 19.");
+ "Encountered \" \")\" \")\"\" at line 1, column 19.");
assertParse("all(group(foo.bar.baz))");
}
@Test
- public void testOutputLabel() {
+ void testOutputLabel() {
assertParse("all(output(min(a) as(foo)))",
- "all(output(min(a) as(foo)))");
+ "all(output(min(a) as(foo)))");
assertParse("all(output(min(a) as(foo), max(b) as(bar)))",
- "all(output(min(a) as(foo), max(b) as(bar)))");
+ "all(output(min(a) as(foo), max(b) as(bar)))");
assertIllegalArgument("all(output(min(a)) as(foo))",
- "Encountered \" \"as\" \"as\"\" at line 1, column 20.");
+ "Encountered \" \"as\" \"as\"\" at line 1, column 20.");
}
@Test
- public void testRootWhere() {
+ void testRootWhere() {
String expected = "all(where(bar) all(group(foo)))";
assertParse("all(where(bar) all(group(foo)))", expected);
assertParse("all(group(foo)) where(bar)", expected);
}
@Test
- public void testParseBadRequest() {
+ void testParseBadRequest() {
assertIllegalArgument("output(count())",
- "Encountered \" \"output\" \"output\"\" at line 1, column 1.");
+ "Encountered \" \"output\" \"output\"\" at line 1, column 1.");
assertIllegalArgument("each(output(count()))",
- "Expression 'count()' not applicable for single hit.");
+ "Expression 'count()' not applicable for single hit.");
assertIllegalArgument("all(output(count())))",
- "Encountered \" \")\" \")\"\" at line 1, column 21.");
+ "Encountered \" \")\" \")\"\" at line 1, column 21.");
}
@Test
- public void testAttributeFunction() {
+ void testAttributeFunction() {
assertParse("all(group(attribute(foo)))");
assertParse("all(group(attribute(foo)) order(sum(attribute(a))))");
}
@Test
- public void testAccuracy() {
+ void testAccuracy() {
assertParse("all(accuracy(0.5))");
assertParse("all(group(foo) accuracy(1.0))");
}
@Test
- public void testMapSyntax() {
+ void testMapSyntax() {
assertParse("all(group(my.little{key}))", "all(group(my.little{\"key\"}))");
assertParse("all(group(my.little{key }))", "all(group(my.little{\"key\"}))");
assertParse("all(group(my.little{\"key\"}))", "all(group(my.little{\"key\"}))");
@@ -458,7 +454,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testMapSyntaxWithKeySourceAttribute() {
+ void testMapSyntaxWithKeySourceAttribute() {
assertAttributeMapLookup("all(group(my_map{attribute(my_attr)}))",
"my_map.key", "my_map.value", "", "my_attr");
assertAttributeMapLookup("all(group(my_map{attribute(my_attr)}.name))",
@@ -487,7 +483,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testMisc() {
+ void testMisc() {
for (String fnc : Arrays.asList("time.date",
"time.dayofmonth",
"time.dayofweek",
@@ -536,39 +532,39 @@ public class GroupingParserTestCase {
// TODO: assertParseRequest("all(group(a) each(output(xor(xorbit(b)) xor(xorbit(b, 64)))))");
assertParse("all(group(artist) each(each(output(summary()))))");
assertParse("all(group(artist) max(13) each(group(fixedwidth(year, 21.34)) max(55) output(count()) " +
- "each(each(output(summary())))))");
+ "each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket(7, 19), bucket(90, 300))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket(7.1, 19.0), bucket(90.7, 300.0))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket('a', 'b'), bucket('cd'))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(output(count()))");
assertParse("all(group(album) output(count()))");
assertParse("all(group(album) each(output(count())))");
assertParse("all(group(artist) each(group(album) output(count()))" +
- " each(group(song) output(count())))");
+ " each(group(song) output(count())))");
assertParse("all(group(artist) output(count())" +
- " each(group(album) output(count())" +
- " each(group(song) output(count())" +
- " each(each(output(summary()))))))");
+ " each(group(album) output(count())" +
+ " each(group(song) output(count())" +
+ " each(each(output(summary()))))))");
assertParse("all(group(album) order(-$total=sum(length)) each(output($total)))");
assertParse("all(group(album) max(1) each(output(sum(length))))");
assertParse("all(group(artist) each(max(2) each(output(summary()))))");
assertParse("all(group(artist) max(3)" +
- " each(group(album as(albumsongs)) each(each(output(summary()))))" +
- " each(group(album as(albumlength)) output(sum(sum(length)))))");
+ " each(group(album as(albumsongs)) each(each(output(summary()))))" +
+ " each(group(album as(albumlength)) output(sum(sum(length)))))");
assertParse("all(group(artist) max(15)" +
- " each(group(album) " +
- " each(group(song)" +
- " each(max(2) each(output(summary()))))))");
+ " each(group(album) " +
+ " each(group(song)" +
+ " each(max(2) each(output(summary()))))))");
assertParse("all(group(artist) max(15)" +
- " each(group(album)" +
- " each(group(song)" +
- " each(max(2) each(output(summary())))))" +
- " each(group(song) max(5) order(sum(popularity))" +
- " each(output(sum(sold)) each(output(summary())))))");
+ " each(group(album)" +
+ " each(group(song)" +
+ " each(max(2) each(output(summary())))))" +
+ " each(group(song) max(5) order(sum(popularity))" +
+ " each(output(sum(sold)) each(output(summary())))))");
assertParse("all(group(artist) order(max(relevance) * count()) each(output(count())))");
assertParse("all(group(artist) each(output(sum(popularity) / count())))");
@@ -576,9 +572,9 @@ public class GroupingParserTestCase {
assertParse("all(group(debugwait(artist, 3.3, true)))");
assertParse("all(group(debugwait(artist, 3.3, false)))");
assertIllegalArgument("all(group(debugwait(artist, -3.3, true)))",
- "Encountered \" \"-\" \"-\"\" at line 1, column 29");
+ "Encountered \" \"-\" \"-\"\" at line 1, column 29");
assertIllegalArgument("all(group(debugwait(artist, 3.3, lol)))",
- "Encountered \" <IDENTIFIER> \"lol\"\" at line 1, column 34");
+ "Encountered \" <IDENTIFIER> \"lol\"\" at line 1, column 34");
assertParse("all(group(artist) each(output(stddev(simple))))");
// Test max()
@@ -588,35 +584,35 @@ public class GroupingParserTestCase {
}
@Test
- public void testBucket() {
+ void testBucket() {
List<GroupingOperation> operations = assertParse("all(group(predefined(artist, bucket('a'), bucket('c', 'z'))))");
assertEquals(1, operations.size());
assertEquals("all(group(predefined(artist, bucket[\"a\", \"a \">, bucket[\"c\", \"z\">)))",
- operations.get(0).toString());
+ operations.get(0).toString());
}
@Test
- public void requireThatParseExceptionMessagesContainErrorMarker() {
+ void requireThatParseExceptionMessagesContainErrorMarker() {
assertIllegalArgument("foo",
- "Encountered \" <IDENTIFIER> \"foo\"\" at line 1, column 1.\n\n" +
- "Was expecting one of:\n\n" +
- "<SPACE> ...\n" +
- " \"all\" ...\n" +
- " \"each\" ...\n" +
- " \n" +
- "At position:\n" +
- "foo\n" +
- "^");
+ "Encountered \" <IDENTIFIER> \"foo\"\" at line 1, column 1.\n\n" +
+ "Was expecting one of:\n\n" +
+ "<SPACE> ...\n" +
+ " \"all\" ...\n" +
+ " \"each\" ...\n" +
+ " \n" +
+ "At position:\n" +
+ "foo\n" +
+ "^");
assertIllegalArgument("\n foo",
- "Encountered \" <IDENTIFIER> \"foo\"\" at line 2, column 2.\n\n" +
- "Was expecting one of:\n\n" +
- "<SPACE> ...\n" +
- " \"all\" ...\n" +
- " \"each\" ...\n" +
- " \n" +
- "At position:\n" +
- " foo\n" +
- " ^");
+ "Encountered \" <IDENTIFIER> \"foo\"\" at line 2, column 2.\n\n" +
+ "Was expecting one of:\n\n" +
+ "<SPACE> ...\n" +
+ " \"all\" ...\n" +
+ " \"each\" ...\n" +
+ " \n" +
+ "At position:\n" +
+ " foo\n" +
+ " ^");
}
// --------------------------------------------------------------------------------
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
index c97bf150645..3e1cff54737 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
@@ -23,15 +23,15 @@ import com.yahoo.searchlib.aggregation.Grouping;
import com.yahoo.searchlib.aggregation.HitsAggregationResult;
import com.yahoo.searchlib.aggregation.hll.SparseSketch;
import com.yahoo.searchlib.expression.StringResultNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -39,42 +39,42 @@ import static org.junit.Assert.assertTrue;
public class FlatteningSearcherTestCase {
@Test
- public void testFlatteningSearcher() {
+ void testFlatteningSearcher() {
Query query = new Query("?query=test");
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) output(count()) each(each(output(summary(bar)))))"));
Grouping group0 = new Grouping(0);
group0.setRoot(new Group()
- .addAggregationResult(new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69))
- .addChild(new Group().setId(new StringResultNode("unique1"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- )
- )
- .addChild(new Group().setId(new StringResultNode("unique2"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- )
- ));
+ .addAggregationResult(new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69))
+ .addChild(new Group().setId(new StringResultNode("unique1"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ )
+ )
+ .addChild(new Group().setId(new StringResultNode("unique2"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ )
+ ));
Grouping group1 = new Grouping(0);
group1.setRoot(new Group()
- .addChild(new Group().setId(new StringResultNode("unique1"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- .addHit(fs4Hit(0.7))
- .addHit(fs4Hit(0.6))
- .addHit(fs4Hit(0.3))
- )
- )
- .addChild(new Group().setId(new StringResultNode("unique2"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- .addHit(fs4Hit(0.5))
- .addHit(fs4Hit(0.4))
- )
- ));
+ .addChild(new Group().setId(new StringResultNode("unique1"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ .addHit(fs4Hit(0.7))
+ .addHit(fs4Hit(0.6))
+ .addHit(fs4Hit(0.3))
+ )
+ )
+ .addChild(new Group().setId(new StringResultNode("unique2"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ .addHit(fs4Hit(0.5))
+ .addHit(fs4Hit(0.4))
+ )
+ ));
Execution execution = newExecution(new FlatteningSearcher(),
- new GroupingExecutor(ComponentId.fromString("grouping")),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(group0), null),
- new GroupingListHit(List.of(group1), null))));
+ new GroupingExecutor(ComponentId.fromString("grouping")),
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(group0), null),
+ new GroupingListHit(List.of(group1), null))));
Result result = execution.search(query);
assertEquals(5, result.hits().size());
assertFlat(result);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
index 01eba55924f..7b2f0d52742 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.result;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.*;
public class GroupIdTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
ValueGroupId valueId = new DoubleId(6.9);
assertEquals(6.9, valueId.getValue());
BucketGroupId rangeId = new DoubleBucketId(6.0, 9.0);
@@ -24,11 +24,11 @@ public class GroupIdTestCase {
assertEquals(6L, rangeId.getFrom());
assertEquals(9L, rangeId.getTo());
- valueId = new RawId(new byte[] { 6, 9 });
- assertArrayEquals(new byte[] { 6, 9 }, (byte[])valueId.getValue());
- rangeId = new RawBucketId(new byte[] { 6, 9 }, new byte[] { 9, 6 });
- assertArrayEquals(new byte[] { 6, 9 }, (byte[])rangeId.getFrom());
- assertArrayEquals(new byte[] { 9, 6 }, (byte[])rangeId.getTo());
+ valueId = new RawId(new byte[]{6, 9});
+ assertArrayEquals(new byte[]{6, 9}, (byte[]) valueId.getValue());
+ rangeId = new RawBucketId(new byte[]{6, 9}, new byte[]{9, 6});
+ assertArrayEquals(new byte[]{6, 9}, (byte[]) rangeId.getFrom());
+ assertArrayEquals(new byte[]{9, 6}, (byte[]) rangeId.getTo());
valueId = new StringId("69");
assertEquals("69", valueId.getValue());
@@ -41,14 +41,14 @@ public class GroupIdTestCase {
}
@Test
- public void requireThatToStringCorrespondsToType() {
+ void requireThatToStringCorrespondsToType() {
assertEquals("group:double:6.9", new DoubleId(6.9).toString());
assertEquals("group:double_bucket:6.0:9.0", new DoubleBucketId(6.0, 9.0).toString());
assertEquals("group:long:69", new LongId(69L).toString());
assertEquals("group:long_bucket:6:9", new LongBucketId(6L, 9L).toString());
assertEquals("group:null", new NullId().toString());
- assertEquals("group:raw:[6, 9]", new RawId(new byte[] { 6, 9 }).toString());
- assertEquals("group:raw_bucket:[6, 9]:[9, 6]", new RawBucketId(new byte[] { 6, 9 }, new byte[] { 9, 6 }).toString());
+ assertEquals("group:raw:[6, 9]", new RawId(new byte[]{6, 9}).toString());
+ assertEquals("group:raw_bucket:[6, 9]:[9, 6]", new RawBucketId(new byte[]{6, 9}, new byte[]{9, 6}).toString());
assertTrue(new RootId(0).toString().startsWith("group:root:"));
assertEquals("group:string:69", new StringId("69").toString());
assertEquals("group:string_bucket:6:9", new StringBucketId("6", "9").toString());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
index 33e8f119ec9..3c583c88d5a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.search.grouping.result;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertSame;
public class GroupListTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
GroupList lst = new GroupList("foo");
assertEquals("foo", lst.getLabel());
assertEquals(0, lst.continuations().size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
index 47f82205689..4e359531b7a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.grouping.result;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertNull;
public class GroupTestCase {
@Test
- public void requireThatListsAreAccessibleByLabel() {
+ void requireThatListsAreAccessibleByLabel() {
Group grp = new Group(new LongId(69L), new Relevance(1));
grp.add(new Hit("hit"));
grp.add(new HitList("hitList"));
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
index 2404af09c7a..5f1d2d3f125 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.search.grouping.result;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertSame;
public class HitListTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
HitList lst = new HitList("foo");
assertEquals("foo", lst.getLabel());
assertEquals(0, lst.continuations().size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
index 1035c9d9284..8e98f49df48 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
@@ -6,13 +6,13 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.text.Utf8;
import com.yahoo.text.XMLWriter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class HitRendererTestCase {
@Test
- public void requireThatGroupListsRenderAsExpected() {
+ void requireThatGroupListsRenderAsExpected() {
assertRender(new GroupList("foo"), "<grouplist label=\"foo\"></grouplist>\n");
assertRender(new GroupList("b\u00e6z"), "<grouplist label=\"b\u00e6z\"></grouplist>\n");
@@ -28,21 +28,21 @@ public class HitRendererTestCase {
lst.continuations().put("bar.key", new MyContinuation("bar.val"));
lst.continuations().put("baz.key", new MyContinuation("baz.val"));
assertRender(lst, "<grouplist label=\"foo\">\n" +
- "<continuation id=\"bar.key\">bar.val</continuation>\n" +
- "<continuation id=\"baz.key\">baz.val</continuation>\n" +
- "</grouplist>\n");
+ "<continuation id=\"bar.key\">bar.val</continuation>\n" +
+ "<continuation id=\"baz.key\">baz.val</continuation>\n" +
+ "</grouplist>\n");
}
@Test
- public void requireThatGroupIdsRenderAsExpected() {
+ void requireThatGroupIdsRenderAsExpected() {
assertRender(newGroup(new DoubleId(6.9)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"double\">6.9</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"double\">6.9</id>\n" +
+ "</group>\n");
assertRender(newGroup(new LongId(69L)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"long\">69</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"long\">69</id>\n" +
+ "</group>\n");
assertRender(newGroup(new BoolId(true)),
"<group relevance=\"1.0\">\n" +
"<id type=\"bool\">true</id>\n" +
@@ -52,89 +52,89 @@ public class HitRendererTestCase {
"<id type=\"bool\">false</id>\n" +
"</group>\n");
assertRender(newGroup(new NullId()),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"null\"/>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"null\"/>\n" +
+ "</group>\n");
assertRender(newGroup(new RawId(Utf8.toBytes("foo"))),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"raw\">[102, 111, 111]</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"raw\">[102, 111, 111]</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringId("foo")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string\">foo</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringId("b\u00e6z")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">b\u00e6z</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string\">b\u00e6z</id>\n" +
+ "</group>\n");
assertRender(newGroup(new DoubleBucketId(6.9, 9.6)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"double_bucket\">\n<from>6.9</from>\n<to>9.6</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"double_bucket\">\n<from>6.9</from>\n<to>9.6</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new LongBucketId(6L, 9L)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"long_bucket\">\n<from>6</from>\n<to>9</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"long_bucket\">\n<from>6</from>\n<to>9</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringBucketId("bar", "baz")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string_bucket\">\n<from>bar</from>\n<to>baz</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string_bucket\">\n<from>bar</from>\n<to>baz</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringBucketId("b\u00e6r", "b\u00e6z")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string_bucket\">\n<from>b\u00e6r</from>\n<to>b\u00e6z</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string_bucket\">\n<from>b\u00e6r</from>\n<to>b\u00e6z</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new RawBucketId(Utf8.toBytes("bar"), Utf8.toBytes("baz"))),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"raw_bucket\">\n<from>[98, 97, 114]</from>\n<to>[98, 97, 122]</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"raw_bucket\">\n<from>[98, 97, 114]</from>\n<to>[98, 97, 122]</to>\n</id>\n" +
+ "</group>\n");
}
@Test
- public void requireThatGroupsRenderAsExpected() {
+ void requireThatGroupsRenderAsExpected() {
Group group = newGroup(new StringId("foo"));
group.setField("foo", "bar");
group.setField("baz", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "<output label=\"foo\">bar</output>\n" +
- "<output label=\"baz\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"string\">foo</id>\n" +
+ "<output label=\"foo\">bar</output>\n" +
+ "<output label=\"baz\">cox</output>\n" +
+ "</group>\n");
group = newGroup(new StringId("foo"));
group.setField("foo", "b\u00e6r");
group.setField("b\u00e5z", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "<output label=\"foo\">b\u00e6r</output>\n" +
- "<output label=\"b\u00e5z\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"string\">foo</id>\n" +
+ "<output label=\"foo\">b\u00e6r</output>\n" +
+ "<output label=\"b\u00e5z\">cox</output>\n" +
+ "</group>\n");
}
@Test
- public void requireThatRootGroupsRenderAsExpected() {
+ void requireThatRootGroupsRenderAsExpected() {
RootGroup group = new RootGroup(0, new MyContinuation("69"));
group.setField("foo", "bar");
group.setField("baz", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"root\"/>\n" +
- "<continuation id=\"this\">69</continuation>\n" +
- "<output label=\"foo\">bar</output>\n" +
- "<output label=\"baz\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"root\"/>\n" +
+ "<continuation id=\"this\">69</continuation>\n" +
+ "<output label=\"foo\">bar</output>\n" +
+ "<output label=\"baz\">cox</output>\n" +
+ "</group>\n");
group = new RootGroup(0, new MyContinuation("96"));
group.setField("foo", "b\u00e6r");
group.setField("b\u00e5z", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"root\"/>\n" +
- "<continuation id=\"this\">96</continuation>\n" +
- "<output label=\"foo\">b\u00e6r</output>\n" +
- "<output label=\"b\u00e5z\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"root\"/>\n" +
+ "<continuation id=\"this\">96</continuation>\n" +
+ "<output label=\"foo\">b\u00e6r</output>\n" +
+ "<output label=\"b\u00e5z\">cox</output>\n" +
+ "</group>\n");
}
@Test
- public void requireThatHitListsRenderAsExpected() {
+ void requireThatHitListsRenderAsExpected() {
assertRender(new HitList("foo"), "<hitlist label=\"foo\"></hitlist>\n");
assertRender(new HitList("b\u00e6z"), "<hitlist label=\"b\u00e6z\"></hitlist>\n");
@@ -142,10 +142,10 @@ public class HitRendererTestCase {
lst.continuations().put("bar.key", new MyContinuation("bar.val"));
lst.continuations().put("baz.key", new MyContinuation("baz.val"));
assertRender(lst, "<hitlist label=\"foo\">\n" +
- "<continuation id=\"bar.key\">bar.val</continuation>\n" +
- "<continuation id=\"baz.key\">baz.val</continuation>\n" +
- "</hitlist>\n");
-}
+ "<continuation id=\"bar.key\">bar.val</continuation>\n" +
+ "<continuation id=\"baz.key\">baz.val</continuation>\n" +
+ "</hitlist>\n");
+ }
private static Group newGroup(GroupId id) {
return new Group(id, new Relevance(1));
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
index a440fcaac7a..ee177709b59 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.*;
public class CompositeContinuationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
CompositeContinuation cnt = new CompositeContinuation();
Iterator<EncodableContinuation> it = cnt.iterator();
assertFalse(it.hasNext());
@@ -37,51 +37,51 @@ public class CompositeContinuationTestCase {
}
@Test
- public void requireThatCompositeContinuationsAreFlattened() {
+ void requireThatCompositeContinuationsAreFlattened() {
assertEncode("BCBCBCBEBGBCBKCBACBKCCK",
- newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
assertEncode("BCBBBBBDBFBCBJBPCBJCCJ",
- newComposite(newComposite(newOffset(-1, -1, -2, -3)), newComposite(newOffset(-5, -8, -13, -21))));
+ newComposite(newComposite(newOffset(-1, -1, -2, -3)), newComposite(newOffset(-5, -8, -13, -21))));
}
@Test
- public void requireThatEmptyStringCanBeDecoded() {
+ void requireThatEmptyStringCanBeDecoded() {
assertDecode("", new CompositeContinuation());
}
@Test
- public void requireThatCompositeContinuationsCanBeDecoded() {
+ void requireThatCompositeContinuationsCanBeDecoded() {
assertDecode("BCBCBCBEBGBCBKCBACBKCCK",
- newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
assertDecode("BCBBBBBDBFBCBJBPCBJCCJ",
- newComposite(newOffset(-1, -1, -2, -3), newOffset(-5, -8, -13, -21)));
+ newComposite(newOffset(-1, -1, -2, -3), newOffset(-5, -8, -13, -21)));
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(newComposite().hashCode(), newComposite().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
CompositeContinuation cnt = newComposite();
- assertFalse(cnt.equals(new Object()));
+ assertNotEquals(cnt, new Object());
assertEquals(cnt, newComposite());
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3))));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21))));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
cnt = newComposite(newOffset(1, 1, 2, 3));
- assertFalse(cnt.equals(new Object()));
+ assertNotEquals(cnt, new Object());
assertEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21))));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
cnt = newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21));
- assertFalse(cnt.equals(new Object()));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3))));
+ assertNotEquals(cnt, new Object());
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
assertEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
}
private static CompositeContinuation newComposite(EncodableContinuation... children) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
index 4a7c6179db7..268a3ceb635 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
@@ -34,7 +34,7 @@ import com.yahoo.searchlib.expression.ConstantNode;
import com.yahoo.searchlib.expression.IntegerResultNode;
import com.yahoo.searchlib.expression.StringResultNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -45,12 +45,7 @@ import java.util.List;
import java.util.Map;
import java.util.Queue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -58,14 +53,14 @@ import static org.junit.Assert.fail;
public class GroupingExecutorTestCase {
@Test
- public void requireThatNullRequestsPass() {
+ void requireThatNullRequestsPass() {
Result res = newExecution(new GroupingExecutor()).search(newQuery());
assertNotNull(res);
assertEquals(0, res.hits().size());
}
@Test
- public void requireThatEmptyRequestsPass() {
+ void requireThatEmptyRequestsPass() {
Query query = newQuery();
GroupingRequest.newInstance(query).setRootOperation(new AllOperation());
Result res = newExecution(new GroupingExecutor()).search(query);
@@ -74,7 +69,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatRequestsAreTransformed() {
+ void requireThatRequestsAreTransformed() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -90,7 +85,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatEachBelowAllDoesNotBlowUp() {
+ void requireThatEachBelowAllDoesNotBlowUp() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(each(output(summary(bar))))"));
@@ -100,7 +95,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatSearchIsMultiPass() {
+ void requireThatSearchIsMultiPass() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -110,7 +105,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatPassRequestsSingleLevel() {
+ void requireThatPassRequestsSingleLevel() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -126,7 +121,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatAggregationPerHitWithoutGroupingDoesNotWorkYet() {
+ void requireThatAggregationPerHitWithoutGroupingDoesNotWorkYet() {
try {
execute("each(output(strlen(customer)))");
fail();
@@ -136,19 +131,19 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatAggregationWithoutGroupingWorks() {
- List<Grouping> groupings=execute("all(output(count()))");
- assertEquals(1,groupings.size());
+ void requireThatAggregationWithoutGroupingWorks() {
+ List<Grouping> groupings = execute("all(output(count()))");
+ assertEquals(1, groupings.size());
assertEquals(0, groupings.get(0).getLevels().size());
assertEquals(ConstantNode.class, groupings.get(0).getRoot().getAggregationResults().get(0).getExpression().getClass());
}
@Test
- public void requireThatGroupingIsParallel() {
+ void requireThatGroupingIsParallel() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))) as(max)" +
- " each(output(min(bar))) as(min))"));
+ " each(output(min(bar))) as(min))"));
GroupingCounter cnt = new GroupingCounter();
newExecution(new GroupingExecutor(), cnt).search(query);
assertEquals(2, cnt.passList.size());
@@ -157,11 +152,11 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatParallelGroupingIsNotRedundant() {
+ void requireThatParallelGroupingIsNotRedundant() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))) as(shallow)" +
- " each(group(baz) each(output(max(cox)))) as(deep))"));
+ " each(group(baz) each(output(max(cox)))) as(deep))"));
GroupingCounter cnt = new GroupingCounter();
newExecution(new GroupingExecutor(), cnt).search(query);
assertEquals(3, cnt.passList.size());
@@ -171,7 +166,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatPassResultsAreMerged() {
+ void requireThatPassResultsAreMerged() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(min(bar), max(bar))))"));
@@ -187,14 +182,14 @@ public class GroupingExecutorTestCase {
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
);
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grpA), null),
- new GroupingListHit(List.of(grpB), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grpA), null),
+ new GroupingListHit(List.of(grpB), null))));
Group grp = req.getResultGroup(exec.search(query));
assertEquals(1, grp.size());
Hit hit = grp.get(0);
assertTrue(hit instanceof GroupList);
- GroupList lst = (GroupList)hit;
+ GroupList lst = (GroupList) hit;
assertEquals(3, lst.size());
assertNotNull(hit = lst.get("group:string:uniqueA"));
assertEquals(6L, hit.getField("max(bar)"));
@@ -206,7 +201,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatUnexpectedGroupingResultsAreIgnored() {
+ void requireThatUnexpectedGroupingResultsAreIgnored() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -220,14 +215,14 @@ public class GroupingExecutorTestCase {
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("unexpected")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(96)).setTag(3)))
);
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grpExpected), null),
- new GroupingListHit(List.of(grpUnexpected), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grpExpected), null),
+ new GroupingListHit(List.of(grpUnexpected), null))));
Group grp = req.getResultGroup(exec.search(query));
assertEquals(1, grp.size());
Hit hit = grp.get(0);
assertTrue(hit instanceof GroupList);
- GroupList lst = (GroupList)hit;
+ GroupList lst = (GroupList) hit;
assertEquals(1, lst.size());
assertNotNull(hit = lst.get("group:string:expected"));
assertEquals(69L, hit.getField("max(bar)"));
@@ -235,7 +230,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatHitsAreFilled() {
+ void requireThatHitsAreFilled() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -243,20 +238,20 @@ public class GroupingExecutorTestCase {
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
+ ));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))),
- new FillRequestThrower());
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))),
+ new FillRequestThrower());
Result res = exec.search(query);
-
+
// Fill with summary specified in grouping
try {
exec.fill(res);
@@ -275,59 +270,59 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatUnfilledHitsRenderError() {
+ void requireThatUnfilledHitsRenderError() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, "bar")
- .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, "bar")
+ .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))),
- new FillErrorProvider());
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))),
+ new FillErrorProvider());
Result res = exec.search(query);
exec.fill(res);
assertNotNull(res.hits().getError());
}
@Test
- public void requireThatGroupRelevanceCanBeSynthesized() {
+ void requireThatGroupRelevanceCanBeSynthesized() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) order(count()) each(output(count())))"));
Grouping grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(new CountAggregationResult(1))
- .addOrderBy(new AggregationRefNode(0), true))
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("bar"))
- .addAggregationResult(new CountAggregationResult(2))
- .addOrderBy(new AggregationRefNode(0), true)));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(new CountAggregationResult(1))
+ .addOrderBy(new AggregationRefNode(0), true))
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("bar"))
+ .addAggregationResult(new CountAggregationResult(2))
+ .addOrderBy(new AggregationRefNode(0), true)));
Result res = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp), null),
- new GroupingListHit(List.of(grp), null)))).search(query);
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp), null),
+ new GroupingListHit(List.of(grp), null)))).search(query);
- GroupList groupList = (GroupList)req.getResultGroup(res).get(0);
+ GroupList groupList = (GroupList) req.getResultGroup(res).get(0);
assertEquals(1.0, groupList.get(0).getRelevance().getScore(), 1E-6);
assertEquals(0.5, groupList.get(1).getRelevance().getScore(), 1E-6);
}
@Test
- public void requireThatErrorsAreHandled() {
+ void requireThatErrorsAreHandled() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -335,20 +330,20 @@ public class GroupingExecutorTestCase {
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
+ ));
ErrorProvider err = new ErrorProvider(1);
Execution exec = newExecution(new GroupingExecutor(),
- err,
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))));
+ err,
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))));
Result res = exec.search(query);
assertNotNull(res.hits().getError());
assertEquals(Error.TIMEOUT.code, res.hits().getError().getCode());
@@ -356,10 +351,10 @@ public class GroupingExecutorTestCase {
err = new ErrorProvider(0);
exec = newExecution(new GroupingExecutor(),
- err,
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))));
+ err,
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))));
res = exec.search(query);
assertNotNull(res.hits().getError());
assertEquals(Error.TIMEOUT.code, res.hits().getError().getCode());
@@ -367,39 +362,39 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatHitsAreFilledWithCorrectSummary() {
+ void requireThatHitsAreFilledWithCorrectSummary() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar))) as(bar) " +
- " each(output(summary(baz))) as(baz)))"));
+ " each(output(summary(baz))) as(baz)))"));
Grouping pass0A = new Grouping(0);
pass0A.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping pass0B = new Grouping(1);
pass0B.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "baz"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "baz"))
+ ));
GlobalId gid1 = new GlobalId((new DocumentId("id:ns:type::1")).getGlobalId());
GlobalId gid2 = new GlobalId((new DocumentId("id:ns:type::2")).getGlobalId());
Grouping pass1A = new Grouping(0);
pass1A.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(1, gid1, 3)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(1, gid1, 3)))
+ ));
Grouping pass1B = new Grouping(1);
pass1B.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "baz").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid2, 6)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "baz").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid2, 6)))
+ ));
SummaryMapper sm = new SummaryMapper();
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(Arrays.asList(pass0A, pass0B), null),
- new GroupingListHit(Arrays.asList(pass1A, pass1B), null))),
- sm);
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(Arrays.asList(pass0A, pass0B), null),
+ new GroupingListHit(Arrays.asList(pass1A, pass1B), null))),
+ sm);
exec.fill(exec.search(query), "default");
assertEquals(2, sm.hitsBySummary.size());
@@ -408,51 +403,51 @@ public class GroupingExecutorTestCase {
assertEquals(1, lst.size());
Hit hit = lst.get(0);
assertTrue(hit instanceof FastHit);
- assertEquals(1, ((FastHit)hit).getPartId());
- assertEquals(gid1, ((FastHit)hit).getGlobalId());
+ assertEquals(1, ((FastHit) hit).getPartId());
+ assertEquals(gid1, ((FastHit) hit).getGlobalId());
assertNotNull(lst = sm.hitsBySummary.get("baz"));
assertNotNull(lst);
assertEquals(1, lst.size());
hit = lst.get(0);
assertTrue(hit instanceof FastHit);
- assertEquals(4, ((FastHit)hit).getPartId());
- assertEquals(gid2, ((FastHit)hit).getGlobalId());
+ assertEquals(4, ((FastHit) hit).getPartId());
+ assertEquals(gid2, ((FastHit) hit).getGlobalId());
}
@Test
- public void requireThatDefaultSummaryNameFillsHitsWithNull() {
+ void requireThatDefaultSummaryNameFillsHitsWithNull() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary()))) as(foo))"));
Grouping pass0 = new Grouping(0);
pass0.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME))));
Grouping pass1 = new Grouping(0);
pass1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME)
- .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME)
+ .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(pass0), null),
- new GroupingListHit(List.of(pass1), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(pass0), null),
+ new GroupingListHit(List.of(pass1), null))));
Result res = exec.search(query);
exec.fill(res);
- Hit hit = ((HitList)((Group)((GroupList)req.getResultGroup(res).get(0)).get(0)).get(0)).get(0);
+ Hit hit = ((HitList) ((Group) ((GroupList) req.getResultGroup(res).get(0)).get(0)).get(0)).get(0);
assertTrue(hit instanceof FastHit);
assertTrue(hit.isFilled(null));
}
@Test
- public void requireThatHitsAreAttachedToCorrectQuery() {
+ void requireThatHitsAreAttachedToCorrectQuery() {
Query queryA = newQuery();
GroupingRequest req = GroupingRequest.newInstance(queryA);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -460,24 +455,24 @@ public class GroupingExecutorTestCase {
Grouping grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
GroupingListHit pass0 = new GroupingListHit(List.of(grp), null);
GlobalId gid = new GlobalId((new DocumentId("id:ns:type::1")).getGlobalId());
grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid, 6)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid, 6)))
+ ));
GroupingListHit pass1 = new GroupingListHit(List.of(grp), null);
Query queryB = newQuery(); // required by GroupingListHit.getSearchQuery()
pass1.setQuery(queryB);
QueryMapper qm = new QueryMapper();
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(pass0, pass1)),
- qm);
+ new ResultProvider(Arrays.asList(pass0, pass1)),
+ qm);
exec.fill(exec.search(queryA));
assertEquals(1, qm.hitsByQuery.size());
assertTrue(qm.hitsByQuery.containsKey(queryB));
@@ -488,7 +483,7 @@ public class GroupingExecutorTestCase {
* (triggered by the exc.search call in the below).
*/
@Test
- public void testRankProperties() {
+ void testRankProperties() {
final double delta = 0.000000001;
Execution exc = newExecution(new GroupingExecutor());
{
@@ -532,7 +527,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void testIllegalQuery() {
+ void testIllegalQuery() {
Execution exc = newExecution(new GroupingExecutor());
Query query = new Query();
@@ -541,14 +536,14 @@ public class GroupingExecutorTestCase {
Result result = exc.search(query);
com.yahoo.search.result.ErrorMessage message = result.hits().getError();
- assertNotNull("Got error", message);
+ assertNotNull(message, "Got error");
assertEquals("Illegal query", message.getMessage());
assertEquals("No query", message.getDetailedMessage());
assertEquals(3, message.getCode());
}
@Test
- public void testResultsFromMultipleDocumentTypes() {
+ void testResultsFromMultipleDocumentTypes() {
Query query = newQuery();
GroupingRequest request = GroupingRequest.newInstance(query);
request.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(min(bar), max(bar))))"));
@@ -556,38 +551,38 @@ public class GroupingExecutorTestCase {
Map<String, List<GroupingListHit>> resultsByDocumentType = new HashMap<>();
Grouping groupA1 = new Grouping(0);
groupA1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(6)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(6)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
);
Grouping groupA2 = new Grouping(0);
groupA2.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueB")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueB")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
);
Grouping groupB1 = new Grouping(0);
groupB1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(2)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(3)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(2)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(3)).setTag(4)))
);
Grouping groupB2 = new Grouping(0);
groupB2.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueC")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(7)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(11)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueC")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(7)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(11)).setTag(4)))
);
resultsByDocumentType.put("typeA", List.of(new GroupingListHit(List.of(groupA1), null),
- new GroupingListHit(List.of(groupA2), null)));
+ new GroupingListHit(List.of(groupA2), null)));
resultsByDocumentType.put("typeB", List.of(new GroupingListHit(List.of(groupB1), null),
- new GroupingListHit(List.of(groupB2), null)));
+ new GroupingListHit(List.of(groupB2), null)));
Execution execution = newExecution(new GroupingExecutor(),
- new MockClusterSearcher(),
- new MultiDocumentTypeResultProvider(resultsByDocumentType));
+ new MockClusterSearcher(),
+ new MultiDocumentTypeResultProvider(resultsByDocumentType));
Result result = execution.search(query);
Group group = request.getResultGroup(result);
assertEquals(1, group.size());
Hit hit = group.get(0);
assertTrue(hit instanceof GroupList);
- GroupList list = (GroupList)hit;
+ GroupList list = (GroupList) hit;
assertEquals(4, list.size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
index c6503617da5..c41fb03f2f5 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,14 +14,14 @@ public class GroupingTransformTestCase {
private static final int REQUEST_ID = 0;
@Test
- public void requireThatLabelCanBeSet() {
+ void requireThatLabelCanBeSet() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
assertEquals("foo", transform.getLabel(1));
}
@Test
- public void requireThatLabelCanNotBeReplaced() {
+ void requireThatLabelCanNotBeReplaced() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
try {
@@ -29,12 +29,12 @@ public class GroupingTransformTestCase {
fail();
} catch (IllegalStateException e) {
assertEquals("Can not set label of my_type 1 to 'bar' because it is already set to 'foo'.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatLabelIsUniqueAmongSiblings() {
+ void requireThatLabelIsUniqueAmongSiblings() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
try {
@@ -42,26 +42,26 @@ public class GroupingTransformTestCase {
fail();
} catch (UnsupportedOperationException e) {
assertEquals("Can not use my_type label 'foo' for multiple siblings.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatMaxDefaultsToZero() {
+ void requireThatMaxDefaultsToZero() {
GroupingTransform transform = newTransform();
assertEquals(0, transform.getMax(6));
assertEquals(0, transform.getMax(9));
}
@Test
- public void requireThatMaxCanBeSet() {
+ void requireThatMaxCanBeSet() {
GroupingTransform transform = newTransform();
transform.putMax(0, 69, "my_type");
assertEquals(69, transform.getMax(0));
}
@Test
- public void requireThatMaxCanNotBeReplaced() {
+ void requireThatMaxCanNotBeReplaced() {
GroupingTransform transform = newTransform();
transform.putMax(0, 6, "my_type");
try {
@@ -69,27 +69,27 @@ public class GroupingTransformTestCase {
fail();
} catch (IllegalStateException e) {
assertEquals("Can not set max of my_type 0 to 9 because it is already set to 6.",
- e.getMessage());
+ e.getMessage());
}
assertEquals(6, transform.getMax(0));
}
@Test
- public void requireThatOffsetDefaultsToZero() {
+ void requireThatOffsetDefaultsToZero() {
GroupingTransform transform = newTransform();
assertEquals(0, transform.getOffset(6));
assertEquals(0, transform.getOffset(9));
}
@Test
- public void requireThatOffsetContinuationsCanBeAdded() {
+ void requireThatOffsetContinuationsCanBeAdded() {
GroupingTransform transform = newTransform();
transform.addContinuation(newStableOffset(newResultId(), 6, 9));
assertEquals(9, transform.getOffset(6));
}
@Test
- public void requireThatOffsetByIdCanBeReplaced() {
+ void requireThatOffsetByIdCanBeReplaced() {
GroupingTransform transform = newTransform();
ResultId id = newResultId(6, 9);
transform.addContinuation(newStableOffset(id, 0, 6));
@@ -103,7 +103,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatOffsetByTagEqualsHighestSibling() {
+ void requireThatOffsetByTagEqualsHighestSibling() {
GroupingTransform transform = newTransform();
transform.addContinuation(newStableOffset(newResultId(1), 69, 6));
assertEquals(6, transform.getOffset(69));
@@ -116,7 +116,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeReplaced() {
+ void requireThatOffsetContinuationsCanBeReplaced() {
GroupingTransform transform = newTransform();
ResultId id = newResultId(6, 9);
transform.addContinuation(newStableOffset(id, 1, 1));
@@ -136,7 +136,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatUnstableOffsetsAreTracked() {
+ void requireThatUnstableOffsetsAreTracked() {
GroupingTransform transform = newTransform();
ResultId stableId = newResultId(6);
transform.addContinuation(newStableOffset(stableId, 1, 1));
@@ -148,17 +148,17 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatCompositeContinuationsAreDecomposed() {
+ void requireThatCompositeContinuationsAreDecomposed() {
GroupingTransform transform = newTransform();
transform.addContinuation(new CompositeContinuation()
- .add(newStableOffset(newResultId(), 6, 9))
- .add(newStableOffset(newResultId(), 9, 6)));
+ .add(newStableOffset(newResultId(), 6, 9))
+ .add(newStableOffset(newResultId(), 9, 6)));
assertEquals(9, transform.getOffset(6));
assertEquals(6, transform.getOffset(9));
}
@Test
- public void requireThatUnsupportedContinuationsCanNotBeAdded() {
+ void requireThatUnsupportedContinuationsCanNotBeAdded() {
GroupingTransform transform = newTransform();
try {
transform.addContinuation(new Continuation() {
@@ -174,7 +174,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatUnrelatedContinuationsAreIgnored() {
+ void requireThatUnrelatedContinuationsAreIgnored() {
GroupingTransform transform = new GroupingTransform(REQUEST_ID);
ResultId id = ResultId.valueOf(REQUEST_ID + 1, 1);
transform.addContinuation(new OffsetContinuation(id, 2, 3, OffsetContinuation.FLAG_UNSTABLE));
@@ -184,7 +184,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatToStringIsVerbose() {
+ void requireThatToStringIsVerbose() {
GroupingTransform transform = new GroupingTransform(REQUEST_ID);
transform.putLabel(1, 1, "label1", "type1");
transform.putLabel(2, 2, "label2", "type2");
@@ -193,19 +193,19 @@ public class GroupingTransformTestCase {
transform.putMax(5, 5, "type5");
transform.putMax(6, 6, "type6");
assertEquals("groupingTransform {\n" +
- "\tlabels {\n" +
- "\t\t1 : label1\n" +
- "\t\t2 : label2\n" +
- "\t}\n" +
- "\toffsets {\n" +
- "\t\t3 : 3\n" +
- "\t\t4 : 4\n" +
- "\t}\n" +
- "\tmaxes {\n" +
- "\t\t5 : 5\n" +
- "\t\t6 : 6\n" +
- "\t}\n" +
- "}", transform.toString());
+ "\tlabels {\n" +
+ "\t\t1 : label1\n" +
+ "\t\t2 : label2\n" +
+ "\t}\n" +
+ "\toffsets {\n" +
+ "\t\t3 : 3\n" +
+ "\t\t4 : 4\n" +
+ "\t}\n" +
+ "\tmaxes {\n" +
+ "\t\t5 : 5\n" +
+ "\t\t6 : 6\n" +
+ "\t}\n" +
+ "}", transform.toString());
}
private static GroupingTransform newTransform() {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
index b3afd8c5f50..5263583f771 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
@@ -17,11 +17,11 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.searchlib.aggregation.FS4Hit;
import com.yahoo.searchlib.aggregation.VdsHit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -33,7 +33,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatHitsAreConverted() {
+ void requireThatHitsAreConverted() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
Hit hit = converter.toSearchHit("default", new FS4Hit(1, createGlobalId(2), 3).setContext(context()));
assertNotNull(hit);
@@ -45,7 +45,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatContextDataIsCopied() {
+ void requireThatContextDataIsCopied() {
Hit ctxHit = context();
ctxHit.setSource("69");
Query ctxQuery = new Query();
@@ -55,14 +55,14 @@ public class HitConverterTestCase {
Hit hit = converter.toSearchHit("default", new FS4Hit(1, createGlobalId(2), 3).setContext(ctxHit));
assertNotNull(hit);
assertTrue(hit instanceof FastHit);
- assertEquals(1, ((FastHit)hit).getPartId());
- assertEquals(createGlobalId(2), ((FastHit)hit).getGlobalId());
+ assertEquals(1, ((FastHit) hit).getPartId());
+ assertEquals(createGlobalId(2), ((FastHit) hit).getGlobalId());
assertSame(ctxQuery, hit.getQuery());
assertEquals(ctxHit.getSource(), hit.getSource());
}
@Test
- public void requireThatSummaryClassIsSet() {
+ void requireThatSummaryClassIsSet() {
Searcher searcher = new MySearcher();
HitConverter converter = new HitConverter(searcher, new Query());
Hit hit = converter.toSearchHit("69", new FS4Hit(1, createGlobalId(2), 3).setContext(context()));
@@ -72,7 +72,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatHitHasContext() {
+ void requireThatHitHasContext() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
try {
converter.toSearchHit("69", new FS4Hit(1, createGlobalId(2), 3));
@@ -83,7 +83,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatUnsupportedHitClassThrows() {
+ void requireThatUnsupportedHitClassThrows() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
try {
converter.toSearchHit("69", new com.yahoo.searchlib.aggregation.Hit() {
@@ -107,10 +107,10 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatVdsHitCanBeConverted() {
+ void requireThatVdsHitCanBeConverted() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
GroupingListHit context = new GroupingListHit(null, sixtynine());
- VdsHit lowHit = new VdsHit("id:ns:type::", new byte[] { 0x55, 0x55, 0x55, 0x55 }, 1);
+ VdsHit lowHit = new VdsHit("id:ns:type::", new byte[]{0x55, 0x55, 0x55, 0x55}, 1);
lowHit.setContext(context);
Hit hit = converter.toSearchHit("69", lowHit);
assertNotNull(hit);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
index 7d0827f0eb7..c574a99d2c0 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +11,7 @@ import static org.junit.Assert.fail;
public class IntegerDecoderTestCase {
@Test
- public void requireThatIntDecoderWorksAsExpected() {
+ void requireThatIntDecoderWorksAsExpected() {
assertDecode("A", 0);
assertDecode("BC", 1);
assertDecode("CBI", 12);
@@ -29,7 +28,7 @@ public class IntegerDecoderTestCase {
}
@Test
- public void requireThatDecoderThrowsExceptionOnBadInput() {
+ void requireThatDecoderThrowsExceptionOnBadInput() {
try {
new IntegerDecoder("B").next();
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
index e7a4f1572c5..c644607b3ae 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class IntegerEmbedderTestCase {
@Test
- public void requireThatIntEncoderWorksAsExpected() {
+ void requireThatIntEncoderWorksAsExpected() {
assertEncode("A", 0);
assertEncode("BC", 1);
assertEncode("CBI", 12);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
index 7242e5ba054..513f8c89f05 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +12,7 @@ import static org.junit.Assert.*;
public class OffsetContinuationTestCase {
@Test
- public void requireThatNullResultIdThrowsException() {
+ void requireThatNullResultIdThrowsException() {
try {
new OffsetContinuation(null, 0, 0, 0);
fail();
@@ -22,7 +22,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
OffsetContinuation cnt = new OffsetContinuation(ResultId.valueOf(1), 2, 3, 4);
assertEquals(ResultId.valueOf(1), cnt.getResultId());
assertEquals(2, cnt.getTag());
@@ -44,7 +44,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeEncoded() {
+ void requireThatOffsetContinuationsCanBeEncoded() {
assertEncode("BCBCBCBEBG", newOffset(1, 1, 2, 3));
assertEncode("BCBKCBACBKCCK", newOffset(5, 8, 13, 21));
assertEncode("BCBBBBBDBF", newOffset(-1, -1, -2, -3));
@@ -52,7 +52,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeDecoded() {
+ void requireThatOffsetContinuationsCanBeDecoded() {
assertDecode("BCBCBCBEBG", newOffset(1, 1, 2, 3));
assertDecode("BCBKCBACBKCCK", newOffset(5, 8, 13, 21));
assertDecode("BCBBBBBDBF", newOffset(-1, -1, -2, -3));
@@ -60,18 +60,18 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(newOffset(1, 1, 2, 3).hashCode(), newOffset(1, 1, 2, 3).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Continuation cnt = newOffset(1, 1, 2, 3);
- assertFalse(cnt.equals(new Object()));
- assertFalse(cnt.equals(newOffset(0, 1, 2, 3)));
- assertFalse(cnt.equals(newOffset(1, 0, 2, 3)));
- assertFalse(cnt.equals(newOffset(1, 1, 0, 3)));
- assertFalse(cnt.equals(newOffset(1, 1, 2, 0)));
+ assertNotEquals(cnt, new Object());
+ assertNotEquals(cnt, newOffset(0, 1, 2, 3));
+ assertNotEquals(cnt, newOffset(1, 0, 2, 3));
+ assertNotEquals(cnt, newOffset(1, 1, 0, 3));
+ assertNotEquals(cnt, newOffset(1, 1, 2, 0));
assertEquals(cnt, newOffset(1, 1, 2, 3));
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
index cfcbc435ba5..f8e67a10076 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
@@ -26,7 +26,7 @@ import com.yahoo.searchlib.expression.StringResultNode;
import com.yahoo.searchlib.expression.TimeStampFunctionNode;
import com.yahoo.searchlib.expression.ToStringFunctionNode;
import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -34,9 +34,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -44,19 +42,19 @@ import static org.junit.Assert.fail;
public class RequestBuilderTestCase {
@Test
- public void requireThatAllAggregationResulsAreSupported() {
- assertLayout("all(group(a) each(output(avg(b))))", "[[{ Attribute, result = [Average] }]]");
- assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
- assertLayout("all(group(a) each(output(max(b))))", "[[{ Attribute, result = [Max] }]]");
- assertLayout("all(group(a) each(output(min(b))))", "[[{ Attribute, result = [Min] }]]");
- assertLayout("all(group(a) each(output(sum(b))))", "[[{ Attribute, result = [Sum] }]]");
- assertLayout("all(group(a) each(each(output(summary()))))", "[[{ Attribute, result = [Hits] }]]");
- assertLayout("all(group(a) each(output(xor(b))))", "[[{ Attribute, result = [Xor] }]]");
- assertLayout("all(group(a) each(output(stddev(b))))", "[[{ Attribute, result = [StandardDeviation] }]]");
+ void requireThatAllAggregationResulsAreSupported() {
+ assertLayout("all(group(a) each(output(avg(b))))", "[[{ Attribute, result = [Average] }]]");
+ assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
+ assertLayout("all(group(a) each(output(max(b))))", "[[{ Attribute, result = [Max] }]]");
+ assertLayout("all(group(a) each(output(min(b))))", "[[{ Attribute, result = [Min] }]]");
+ assertLayout("all(group(a) each(output(sum(b))))", "[[{ Attribute, result = [Sum] }]]");
+ assertLayout("all(group(a) each(each(output(summary()))))", "[[{ Attribute, result = [Hits] }]]");
+ assertLayout("all(group(a) each(output(xor(b))))", "[[{ Attribute, result = [Xor] }]]");
+ assertLayout("all(group(a) each(output(stddev(b))))", "[[{ Attribute, result = [StandardDeviation] }]]");
}
@Test
- public void requireThatExpressionCountAggregationResultIsSupported() {
+ void requireThatExpressionCountAggregationResultIsSupported() {
RequestBuilder builder = new RequestBuilder(0);
builder.setRootOperation(GroupingOperation.fromString("all(group(foo) output(count()))"));
builder.build();
@@ -73,28 +71,28 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTopNIsHonoured() {
+ void requireThatTopNIsHonoured() {
List<Grouping> gl = getRequestList("all(max(3) all(group(product_id) max(5) each(output(sum(price)))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsHonouredWhenNested() {
+ void requireThatTopNIsHonouredWhenNested() {
List<Grouping> gl = getRequestList("all( all(max(3) all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsInherited() {
+ void requireThatTopNIsInherited() {
List<Grouping> gl = getRequestList("all(max(7) all( all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(7, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsMinimum() {
+ void requireThatTopNIsMinimum() {
List<Grouping> gl = getRequestList("all(max(7) all(max(3) all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
@@ -104,7 +102,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTopNIsIndividual() {
+ void requireThatTopNIsIndividual() {
List<Grouping> gl = getRequestList("all( all(max(3) all(group(product_id) max(5) each(output(sum(price))))) all(group(filter_cluster3) order(count()) each(output(count()))))");
assertEquals(2, gl.size());
assertEquals(3, gl.get(0).getTopN());
@@ -117,7 +115,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAllExpressionNodesAreSupported() {
+ void requireThatAllExpressionNodesAreSupported() {
assertLayout("all(group(add(a,b)) each(output(count())))", "[[{ Add, result = [Count] }]]");
assertLayout("all(group(and(a,b)) each(output(count())))", "[[{ And, result = [Count] }]]");
assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
@@ -188,22 +186,22 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatForceSinglePassIsSupported() {
+ void requireThatForceSinglePassIsSupported() {
assertForceSinglePass("all(group(foo) each(output(count())))", "[false]");
assertForceSinglePass("all(group(foo) hint(singlepass) each(output(count())))", "[true]");
assertForceSinglePass("all(hint(singlepass) " +
- " all(group(foo) each(output(count())))" +
- " all(group(bar) each(output(count()))))",
- "[true, true]");
+ " all(group(foo) each(output(count())))" +
+ " all(group(bar) each(output(count()))))",
+ "[true, true]");
// it would be really nice if this test returned [true, true], but that is not how the AST is built
assertForceSinglePass("all(all(group(foo) hint(singlepass) each(output(count())))" +
- " all(group(bar) hint(singlepass) each(output(count()))))",
- "[false, false]");
+ " all(group(bar) hint(singlepass) each(output(count()))))",
+ "[false, false]");
}
@Test
- public void requireThatThereCanBeOnlyOneBuildCall() {
+ void requireThatThereCanBeOnlyOneBuildCall() {
RequestBuilder builder = new RequestBuilder(0);
builder.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(count())))"));
builder.build();
@@ -216,148 +214,148 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNullSummaryClassProvidesDefault() {
+ void requireThatNullSummaryClassProvidesDefault() {
RequestBuilder reqBuilder = new RequestBuilder(0);
reqBuilder.setRootOperation(new AllOperation()
- .setGroupBy(new AttributeValue("foo"))
- .addChild(new EachOperation()
- .addChild(new EachOperation()
- .addOutput(new SummaryValue()))));
+ .setGroupBy(new AttributeValue("foo"))
+ .addChild(new EachOperation()
+ .addChild(new EachOperation()
+ .addOutput(new SummaryValue()))));
reqBuilder.setDefaultSummaryName(null);
reqBuilder.build();
- HitsAggregationResult hits = (HitsAggregationResult)reqBuilder.getRequestList().get(0)
- .getLevels().get(0)
- .getGroupPrototype()
- .getAggregationResults().get(0);
+ HitsAggregationResult hits = (HitsAggregationResult) reqBuilder.getRequestList().get(0)
+ .getLevels().get(0)
+ .getGroupPrototype()
+ .getAggregationResults().get(0);
assertEquals(ExpressionConverter.DEFAULT_SUMMARY_NAME, hits.getSummaryClass());
}
@Test
- public void requireThatGroupOfGroupsAreNotSupported() {
+ void requireThatGroupOfGroupsAreNotSupported() {
// "Can not group list of groups."
assertBuildFail("all(group(a) all(group(avg(b)) each(each(each(output(summary()))))))",
"Can not operate on list of list of groups.");
}
@Test
- public void requireThatAnonymousListsAreNotSupported() {
+ void requireThatAnonymousListsAreNotSupported() {
assertBuildFail("all(group(a) all(each(each(output(summary())))))",
- "Can not create anonymous list of groups.");
+ "Can not create anonymous list of groups.");
}
@Test
- public void requireThatOffsetContinuationCanModifyGroupingLevel() {
+ void requireThatOffsetContinuationCanModifyGroupingLevel() {
assertOffset("all(group(a) max(5) each(output(count())))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [5, 11], hits = [] }]]");
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [5, 11], hits = [] }]]");
assertOffset("all(group(a) max(5) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [5, 11], hits = [] }]," +
- " [{ tag = 4, max = [5, 6], hits = [] }]]");
+ " each(output(count())) as(bar))",
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [5, 11], hits = [] }]," +
+ " [{ tag = 4, max = [5, 6], hits = [] }]]");
assertOffset("all(group(a) max(5) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
+ " each(output(count())) as(bar))",
newComposite(newOffset(2, 5), newOffset(4, 10)),
"[[{ tag = 2, max = [5, 11], hits = [] }]," +
" [{ tag = 4, max = [5, 16], hits = [] }]]");
}
@Test
- public void requireThatOffsetContinuationCanModifyHitAggregator() {
+ void requireThatOffsetContinuationCanModifyHitAggregator() {
assertOffset("all(group(a) each(max(5) each(output(summary()))))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]]");
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]]");
assertOffset("all(group(a) each(max(5) each(output(summary()))) as(foo)" +
- " each(max(5) each(output(summary()))) as(bar))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 6] }] }]]");
+ " each(max(5) each(output(summary()))) as(bar))",
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 6] }] }]]");
assertOffset("all(group(a) each(max(5) each(output(summary()))) as(foo)" +
- " each(max(5) each(output(summary()))) as(bar))",
- newComposite(newOffset(3, 5), newOffset(5, 10)),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 16] }] }]]");
+ " each(max(5) each(output(summary()))) as(bar))",
+ newComposite(newOffset(3, 5), newOffset(5, 10)),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 16] }] }]]");
}
@Test
- public void requireThatOffsetContinuationIsNotAppliedToGroupingLevelWithoutMax() {
+ void requireThatOffsetContinuationIsNotAppliedToGroupingLevelWithoutMax() {
assertOffset("all(group(a) each(output(count())))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [0, -1], hits = [] }]]");
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [] }]]");
}
@Test
- public void requireThatOffsetContinuationIsNotAppliedToHitAggregatorWithoutMax() {
+ void requireThatOffsetContinuationIsNotAppliedToHitAggregatorWithoutMax() {
assertOffset("all(group(a) each(each(output(summary()))))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [0, -1] }] }]]");
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [0, -1] }] }]]");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectRequestedGroupLists() {
+ void requireThatUnstableContinuationsDoNotAffectRequestedGroupLists() {
String request = "all(group(a) max(5) each(group(b) max(5) each(output(count())) as(a1_b1)" +
- " each(output(count())) as(a1_b2)) as(a1)" +
- " each(group(b) max(5) each(output(count())) as(a2_b1)" +
- " each(output(count())) as(a2_b2)) as(a2))";
+ " each(output(count())) as(a1_b2)) as(a1)" +
+ " each(group(b) max(5) each(output(count())) as(a2_b1)" +
+ " each(output(count())) as(a2_b2)) as(a2))";
CompositeContinuation session = newComposite(newOffset(2, 5), newOffset(3, 5), newOffset(5, 5),
- newOffset(7, 5), newOffset(8, 5), newOffset(10, 5));
+ newOffset(7, 5), newOffset(8, 5), newOffset(10, 5));
assertOffset(request, newComposite(session),
- "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(7, 10)),
- "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10), newUnstableOffset(7, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectRequestedHitLists() {
+ void requireThatUnstableContinuationsDoNotAffectRequestedHitLists() {
String request = "all(group(a) max(5) each(max(5) each(output(summary())) as(a1_h1)" +
- " each(output(summary())) as(a1_h2)) as(a1)" +
- " each(max(5) each(output(summary())) as(a2_h1)" +
- " each(output(summary())) as(a2_h2)) as(a2))";
+ " each(output(summary())) as(a1_h2)) as(a1)" +
+ " each(max(5) each(output(summary())) as(a2_h1)" +
+ " each(output(summary())) as(a2_h2)) as(a2))";
CompositeContinuation session = newComposite(newOffset(2, 5), newOffset(3, 5), newOffset(4, 5),
- newOffset(5, 5), newOffset(6, 5), newOffset(7, 5));
+ newOffset(5, 5), newOffset(6, 5), newOffset(7, 5));
assertOffset(request, newComposite(session),
- "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(5, 10)),
- "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10), newUnstableOffset(5, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
}
@Test
- public void requireThatExpressionsCanBeAliased() {
+ void requireThatExpressionsCanBeAliased() {
OutputWriter writer = (groupingList, transform) -> groupingList.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0)
- .toString();
+ .toString();
RequestTest test = new RequestTest();
test.expectedOutput = new SumAggregationResult().setTag(3).setExpression(new AttributeNode("price")).toString();
@@ -373,89 +371,89 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatGroupingLayoutIsCorrect() {
+ void requireThatGroupingLayoutIsCorrect() {
assertLayout("all(group(artist) each(max(69) output(count()) each(output(summary()))))",
- "[[{ Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count()) all(group(album) each(output(count()) all(group(song) each(max(69) output(count()) each(output(summary()))))))))",
- "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }, { Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }, { Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count())))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(group(artist) order(sum(price)) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(artist) each(max(69) output(count()) each(output(summary(foo)))))",
- "[[{ Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count()) all(group(album) each(output(count())))))",
- "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }]]");
assertLayout("all(group(artist) max(5) each(output(count()) all(group(album) max(3) each(output(count())))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
assertLayout("all(group(artist) max(5) each(output(count()) all(group(album) max(3) each(output(count())))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
assertLayout("all(group(foo) max(10) each(output(count()) all(group(bar) max(10) each(output(count())))))",
- "[[{ Attribute, max = [11, 11], result = [Count] }, { Attribute, max = [11, 11], result = [Count] }]]");
+ "[[{ Attribute, max = [11, 11], result = [Count] }, { Attribute, max = [11, 11], result = [Count] }]]");
assertLayout("all(group(a) max(5) each(max(69) output(count()) each(output(summary()))))",
- "[[{ Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(a) max(5) each(output(count()) all(group(b) max(5) each(max(69) output(count()) each(output(summary()))))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(a) max(5) each(output(count()) all(group(b) max(5) each(output(count()) all(group(c) max(5) each(max(69) output(count()) each(output(summary()))))))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(output(count())))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(output(count())))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(max(1) output(count()) each(output(summary()))))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count, Hits] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count, Hits] }]]");
assertLayout("all(group(predefined(n,bucket(1,3),bucket(6,9))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(predefined(f,bucket(1.0,3.0),bucket(6.0,9.0))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(predefined(s,bucket(\"ab\",\"cd\"),bucket(\"ef\",\"gh\"))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(a) max(5) each(output(count())))",
- "[[{ Attribute, max = [6, 6], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }]]");
assertLayout("all(group(a) max(5) each(output(count())))",
- "[[{ Attribute, max = [6, 6], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }]]");
assertLayout("all(max(9) all(group(a) each(output(count()))))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(where(true) all(group(a) each(output(count()))))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(group(a) order(sum(n)) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(a) max(2) each(output(count())))",
- "[[{ Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(a) max(2) precision(10) each(output(count())))",
- "[[{ Attribute, max = [3, 10], result = [Count] }]]");
+ "[[{ Attribute, max = [3, 10], result = [Count] }]]");
assertLayout("all(group(fixedwidth(a,1)) each(output(count())))",
- "[[{ FixedWidthBucket, result = [Count] }]]");
+ "[[{ FixedWidthBucket, result = [Count] }]]");
}
@Test
- public void requireThatAggregatorCanBeUsedAsArgumentToOrderByFunction() {
+ void requireThatAggregatorCanBeUsedAsArgumentToOrderByFunction() {
assertLayout("all(group(a) order(sum(price) * count()) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [Multiply]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [Multiply]] }]]");
assertLayout("all(group(a) order(sum(price) + 4) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum], order = [[1], [Add]] }]]");
+ "[[{ Attribute, result = [Sum], order = [[1], [Add]] }]]");
assertLayout("all(group(a) order(sum(price) + 4, count()) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum, Count], order = [[1, 2], [Add, AggregationRef]] }]]");
+ "[[{ Attribute, result = [Sum, Count], order = [[1, 2], [Add, AggregationRef]] }]]");
assertLayout("all(group(a) order(sum(price) + 4, -count()) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum, Count], order = [[1, -2], [Add, AggregationRef]] }]]");
+ "[[{ Attribute, result = [Sum, Count], order = [[1, -2], [Add, AggregationRef]] }]]");
}
@Test
- public void requireThatSameAggregatorCanBeUsedMultipleTimes() {
+ void requireThatSameAggregatorCanBeUsedMultipleTimes() {
assertLayout("all(group(a) each(output(count() as(b),count() as(c))))",
- "[[{ Attribute, result = [Count, Count] }]]");
+ "[[{ Attribute, result = [Count, Count] }]]");
}
@Test
- public void requireThatSiblingAggregatorsCanNotShareSameLabel() {
+ void requireThatSiblingAggregatorsCanNotShareSameLabel() {
assertBuildFail("all(group(a) each(output(count(),count())))",
- "Can not use output label 'count()' for multiple siblings.");
+ "Can not use output label 'count()' for multiple siblings.");
assertBuildFail("all(group(a) each(output(count() as(b),count() as(b))))",
"Can not use output label 'b' for multiple siblings.");
}
@Test
- public void requireThatOrderByReusesOutputResults() {
+ void requireThatOrderByReusesOutputResults() {
assertLayout("all(group(a) order(count()) each(output(count())))",
"[[{ Attribute, result = [Count], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(a) order(count()) each(output(count() as(b))))",
@@ -463,40 +461,40 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNoopBranchesArePruned() {
+ void requireThatNoopBranchesArePruned() {
assertLayout("all()", "[]");
assertLayout("all(group(a))", "[]");
assertLayout("all(group(a) each())", "[]");
String expectedA = "[{ Attribute, result = [Count] }]";
assertLayout("all(group(a) each(output(count())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all()))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b))))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each())",
- Arrays.asList(expectedA).toString());
+ " each())",
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b)))",
- Arrays.asList(expectedA).toString());
+ " each(group(b)))",
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b) each()))",
- Arrays.asList(expectedA).toString());
+ " each(group(b) each()))",
+ Arrays.asList(expectedA).toString());
String expectedB = "[{ Attribute }, { Attribute, result = [Count] }]";
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b) each(output(count()))))",
- Arrays.asList(expectedB, expectedA).toString());
+ " each(group(b) each(output(count()))))",
+ Arrays.asList(expectedB, expectedA).toString());
}
@Test
- public void requireThatAggregationLevelIsValidatedFails() {
+ void requireThatAggregationLevelIsValidatedFails() {
assertBuildFail("all(group(artist) output(sum(length)))",
"Expression 'length' not applicable for single group.");
assertBuild("all(group(artist) each(output(count())))");
@@ -506,46 +504,46 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatCountOnListOfGroupsIsValidated() {
+ void requireThatCountOnListOfGroupsIsValidated() {
assertBuild("all(group(artist) output(count()))");
assertBuild("all(group(artist) each(group(album) output(count())))");
}
@Test
- public void requireThatGroupByIsValidated() {
+ void requireThatGroupByIsValidated() {
assertBuild("all(group(artist) each(output(count())))");
assertBuildFail("all(group(sum(artist)) each(output(count())))",
- "Expression 'sum(artist)' not applicable for single hit.");
+ "Expression 'sum(artist)' not applicable for single hit.");
assertBuild("all(group(artist) each(group(album) each(output(count()))))");
assertBuildFail("all(group(artist) each(group(sum(album)) each(output(count()))))",
- "Expression 'sum(album)' not applicable for single hit.");
+ "Expression 'sum(album)' not applicable for single hit.");
}
@Test
- public void requireThatGroupingLevelIsValidated() {
+ void requireThatGroupingLevelIsValidated() {
assertBuild("all(group(artist))");
assertBuild("all(group(artist) each(group(album)))");
assertBuildFail("all(group(artist) all(group(sum(price))))",
- "Can not operate on list of list of groups.");
+ "Can not operate on list of list of groups.");
assertBuild("all(group(artist) each(group(album) each(group(song))))");
assertBuildFail("all(group(artist) each(group(album) all(group(sum(price)))))",
- "Can not operate on list of list of groups.");
+ "Can not operate on list of list of groups.");
}
@Test
- public void requireThatOrderByIsValidated() {
+ void requireThatOrderByIsValidated() {
assertBuildFail("all(order(length))",
- "Can not order single group content.");
+ "Can not order single group content.");
assertBuild("all(group(artist) order(sum(length)))");
assertBuildFail("all(group(artist) each(order(length)))",
- "Can not order single group content.");
+ "Can not order single group content.");
assertBuild("all(group(artist) each(group(album) order(sum(length))))");
assertBuildFail("all(group(artist) each(group(album) each(order(length))))",
- "Can not order single group content.");
+ "Can not order single group content.");
}
@Test
- public void requireThatOrderByHasCorrectReference() {
+ void requireThatOrderByHasCorrectReference() {
assertOrderBy("all(group(a) order(count()) each(output(count())))", "[[[1]]]");
assertOrderBy("all(group(a) order(-count()) each(output(count())))", "[[[-1]]]");
assertOrderBy("all(group(a) order(count()) each(output(count(),sum(b))))", "[[[1]]]");
@@ -565,23 +563,23 @@ public class RequestBuilderTestCase {
assertOrderBy("all(group(a) order(-count(),-sum(b)) each(output(sum(b), count())))", "[[[-1, -2]]]");
assertOrderBy("all(group(a) order(count()) each(output(count())) as(foo)" +
- " each(output(sum(b))) as(bar))",
- "[[[1]], [[1]]]");
+ " each(output(sum(b))) as(bar))",
+ "[[[1]], [[1]]]");
}
@Test
- public void requireThatWhereIsValidated() {
+ void requireThatWhereIsValidated() {
assertBuild("all(where(true))");
assertBuild("all(where($query))");
assertBuildFail("all(where(foo))",
- "Operation 'where' does not support 'foo'.");
+ "Operation 'where' does not support 'foo'.");
assertBuildFail("all(group(artist) where(true))",
- "Can not apply 'where' to non-root group.");
+ "Can not apply 'where' to non-root group.");
}
@Test
- public void requireThatRootAggregationCanBeTransformed() {
+ void requireThatRootAggregationCanBeTransformed() {
RequestTest test = new RequestTest();
test.expectedOutput = CountAggregationResult.class.getName();
test.request = "all(output(count()))";
@@ -590,68 +588,68 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatExpressionsCanBeLabeled() {
+ void requireThatExpressionsCanBeLabeled() {
assertLabel("all(group(a) each(output(count())))",
- "[[{ label = 'a', results = [count()] }]]");
+ "[[{ label = 'a', results = [count()] }]]");
assertLabel("all(group(a) each(output(count())) as(b))",
- "[[{ label = 'b', results = [count()] }]]");
+ "[[{ label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count()))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }]]");
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(group(c) each(output(count())))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]]");
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]]");
assertBuildFail("all(group(a) each(output(count())) each(output(count())))",
- "Can not use group list label 'a' for multiple siblings.");
+ "Can not use group list label 'a' for multiple siblings.");
assertBuildFail("all(all(group(a) each(output(count())))" +
- " all(group(a) each(output(count()))))",
- "Can not use group list label 'a' for multiple siblings.");
+ " all(group(a) each(output(count()))))",
+ "Can not use group list label 'a' for multiple siblings.");
assertLabel("all(group(a) each(output(count())) as(a1)" +
- " each(output(count())) as(a2))",
- "[[{ label = 'a1', results = [count()] }], [{ label = 'a2', results = [count()] }]]");
+ " each(output(count())) as(a2))",
+ "[[{ label = 'a1', results = [count()] }], [{ label = 'a2', results = [count()] }]]");
assertLabel("all(group(a) each(all(group(b) each(output(count())))" +
- " all(group(c) each(output(count())))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a', results = [] }, { label = 'c', results = [count()] }]]");
+ " all(group(c) each(output(count())))))",
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a', results = [] }, { label = 'c', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count()))) as(a1)" +
- " each(group(b) each(output(count()))) as(a2))",
- "[[{ label = 'a1', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a2', results = [] }, { label = 'b', results = [count()] }]]");
+ " each(group(b) each(output(count()))) as(a2))",
+ "[[{ label = 'a1', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a2', results = [] }, { label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(group(c) each(output(count())))) as(a1)" +
- " each(group(b) each(group(e) each(output(count())))) as(a2))",
- "[[{ label = 'a1', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]," +
- " [{ label = 'a2', results = [] }, { label = 'b', results = [] }, { label = 'e', results = [count()] }]]");
+ " each(group(b) each(group(e) each(output(count())))) as(a2))",
+ "[[{ label = 'a1', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]," +
+ " [{ label = 'a2', results = [] }, { label = 'b', results = [] }, { label = 'e', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count())) as(b1)" +
- " each(output(count())) as(b2)))",
- "[[{ label = 'a', results = [] }, { label = 'b1', results = [count()] }]," +
- " [{ label = 'a', results = [] }, { label = 'b2', results = [count()] }]]");
+ " each(output(count())) as(b2)))",
+ "[[{ label = 'a', results = [] }, { label = 'b1', results = [count()] }]," +
+ " [{ label = 'a', results = [] }, { label = 'b2', results = [count()] }]]");
assertBuildFail("all(group(a) each(each(output(summary() as(foo)))))",
- "Can not label expression 'summary()'.");
+ "Can not label expression 'summary()'.");
assertLabel("all(group(foo) each(each(output(summary()))))",
- "[[{ label = 'foo', results = [hits] }]]");
+ "[[{ label = 'foo', results = [hits] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)))",
- "[[{ label = 'foo', results = [bar] }]]");
+ "[[{ label = 'foo', results = [bar] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)) as(baz))",
- "[[{ label = 'baz', results = [bar] }]]");
+ "[[{ label = 'baz', results = [bar] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)" +
- " each(output(summary())) as(baz)))",
- "[[{ label = 'foo', results = [bar] }]," +
- " [{ label = 'foo', results = [baz] }]]");
+ " each(output(summary())) as(baz)))",
+ "[[{ label = 'foo', results = [bar] }]," +
+ " [{ label = 'foo', results = [baz] }]]");
assertLabel("all(group(foo) each(each(output(summary())))" +
- " each(each(output(summary()))) as(bar))",
- "[[{ label = 'bar', results = [hits] }]," +
- " [{ label = 'foo', results = [hits] }]]");
+ " each(each(output(summary()))) as(bar))",
+ "[[{ label = 'bar', results = [hits] }]," +
+ " [{ label = 'foo', results = [hits] }]]");
}
@Test
- public void requireThatOrderByResultsAreNotLabeled() {
+ void requireThatOrderByResultsAreNotLabeled() {
assertLabel("all(group(a) each(output(min(b), max(b), avg(b))))",
- "[[{ label = 'a', results = [min(b), max(b), avg(b)] }]]");
+ "[[{ label = 'a', results = [min(b), max(b), avg(b)] }]]");
assertLabel("all(group(a) order(min(b)) each(output(max(b), avg(b))))",
- "[[{ label = 'a', results = [max(b), avg(b), null] }]]");
+ "[[{ label = 'a', results = [max(b), avg(b), null] }]]");
assertLabel("all(group(a) order(min(b), max(b)) each(output(avg(b))))",
- "[[{ label = 'a', results = [avg(b), null, null] }]]");
+ "[[{ label = 'a', results = [avg(b), null, null] }]]");
}
@Test
- public void requireThatTimeZoneIsAppliedToTimeFunctions() {
+ void requireThatTimeZoneIsAppliedToTimeFunctions() {
for (String timePart : Arrays.asList("dayofmonth", "dayofweek", "dayofyear", "hourofday",
"minuteofhour", "monthofyear", "secondofminute", "year"))
{
@@ -665,17 +663,17 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTimeDateIsExpanded() {
+ void requireThatTimeDateIsExpanded() {
RequestTest test = new RequestTest();
test.expectedOutput = new StrCatFunctionNode()
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.Year, true)))
+ TimeStampFunctionNode.TimePart.Year, true)))
.addArg(new ConstantNode(new StringResultNode("-")))
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.Month, true)))
+ TimeStampFunctionNode.TimePart.Month, true)))
.addArg(new ConstantNode(new StringResultNode("-")))
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.MonthDay, true)))
+ TimeStampFunctionNode.TimePart.MonthDay, true)))
.toString();
test.request = "all(output(avg(time.date(foo))))";
test.outputWriter = (groupingList, transform) -> groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression().toString();
@@ -683,7 +681,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNowIsResolvedToCurrentTime() {
+ void requireThatNowIsResolvedToCurrentTime() {
RequestTest test = new RequestTest();
test.expectedOutput = Boolean.toString(true);
test.request = "all(output(avg(now() - foo)))";
@@ -693,8 +691,8 @@ public class RequestBuilderTestCase {
@Override
public String write(List<Grouping> groupingList, GroupingTransform transform) {
AddFunctionNode add =
- (AddFunctionNode)groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression();
- long nowValue = ((ConstantNode)add.getArg(0)).getValue().getInteger();
+ (AddFunctionNode) groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression();
+ long nowValue = ((ConstantNode) add.getArg(0)).getValue().getInteger();
boolean preCond = nowValue >= (before / 1000);
long after = System.currentTimeMillis();
boolean postCond = nowValue <= (after / 1000);
@@ -706,7 +704,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAttributeMapLookupNodeIsCreatedFromKey() {
+ void requireThatAttributeMapLookupNodeIsCreatedFromKey() {
RequestTest test = new RequestTest();
test.expectedOutput = AttributeMapLookupNode.fromKey("map{\"my_key\"}", "map.key", "map.value", "my_key").toString();
test.request = "all(group(map{\"my_key\"}) each(output(count())))";
@@ -715,7 +713,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAttributeMapLookupNodeIsCreatedFromKeySourceAttribute() {
+ void requireThatAttributeMapLookupNodeIsCreatedFromKeySourceAttribute() {
RequestTest test = new RequestTest();
test.expectedOutput = AttributeMapLookupNode.fromKeySourceAttribute("map{attribute(key_source)}", "map.key", "map.value", "key_source").toString();
test.request = "all(group(map{attribute(key_source)}) each(output(count())))";
@@ -724,7 +722,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_default_max_values_from_request_builder_restricts_max_groups_and_hits() {
+ void require_that_default_max_values_from_request_builder_restricts_max_groups_and_hits() {
int defaultMaxHits = 19;
int defaultMaxGroups = 7;
RequestBuilder builder = new RequestBuilder(0)
@@ -735,12 +733,12 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(defaultMaxGroups + 1, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(defaultMaxHits + 1, hitsAggregation.getMaxHits());
}
@Test
- public void require_that_default_max_values_from_request_builder_respects_explicit_max() {
+ void require_that_default_max_values_from_request_builder_respects_explicit_max() {
{
RequestBuilder builder = new RequestBuilder(0)
.setDefaultMaxGroups(7)
@@ -750,7 +748,7 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(12, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(22, hitsAggregation.getMaxHits());
}
{
@@ -762,21 +760,21 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(-1, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(-1, hitsAggregation.getMaxHits());
}
}
@Test
- public void require_that_total_groups_and_summaries_calculation_is_correct() {
+ void require_that_total_groups_and_summaries_calculation_is_correct() {
assertTotalGroupsAndSummaries(5, "all(group(a) max(5) each(output(count())))");
- assertTotalGroupsAndSummaries(5+5*7, "all(group(a) max(5) each(max(7) each(output(summary()))))");
- assertTotalGroupsAndSummaries(3+3*5+3*5*7+3*5*7*11,
+ assertTotalGroupsAndSummaries(5 + 5 * 7, "all(group(a) max(5) each(max(7) each(output(summary()))))");
+ assertTotalGroupsAndSummaries(3 + 3 * 5 + 3 * 5 * 7 + 3 * 5 * 7 * 11,
"all( group(a) max(3) each(output(count())" +
- " all(group(b) max(5) each(output(count())" +
- " all(group(c) max(7) each(max(11) output(count())" +
- " each(output(summary()))))))))");
- assertTotalGroupsAndSummaries(2*(3+3*5),
+ " all(group(b) max(5) each(output(count())" +
+ " all(group(c) max(7) each(max(11) output(count())" +
+ " each(output(summary()))))))))");
+ assertTotalGroupsAndSummaries(2 * (3 + 3 * 5),
"all(" +
" all(group(a) max(3) each(output(count()) max(5) each(output(summary())))) " +
" all(group(b) max(3) each(output(count()) max(5) each(output(summary())))))");
@@ -784,14 +782,24 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_unbounded_queries_fails_when_global_max_is_enabled() {
+ void require_that_total_groups_restriction_can_be_disabled() {
+ assertTotalGroupsAndSummaries(3 + 3 * 5 + 3 * 5 * 7 + 3 * 5 * 7 * 100,
+ -1, // disable
+ "all( group(a) max(3) each(output(count())" +
+ " all(group(b) max(5) each(output(count())" +
+ " all(group(c) max(7) each(max(100) output(count())" +
+ " each(output(summary()))))))))");
+ }
+
+ @Test
+ void require_that_unbounded_queries_fails_when_global_max_is_enabled() {
assertQueryFailsOnGlobalMax(4, "all(group(a) max(5) each(output(count())))", "5 > 4");
assertQueryFailsOnGlobalMax(Long.MAX_VALUE, "all(group(a) each(output(count())))", "unbounded number of groups");
assertQueryFailsOnGlobalMax(Long.MAX_VALUE, "all(group(a) max(5) each(each(output(summary()))))", "unbounded number of summaries");
}
@Test
- public void require_that_default_precision_factor_overrides_implicit_precision() {
+ void require_that_default_precision_factor_overrides_implicit_precision() {
int factor = 3;
RequestBuilder builder = new RequestBuilder(0)
.setDefaultPrecisionFactor(factor)
@@ -801,7 +809,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_explicit_precision_has_precedence() {
+ void require_that_explicit_precision_has_precedence() {
RequestBuilder builder = new RequestBuilder(0)
.setDefaultPrecisionFactor(3)
.setRootOperation(GroupingOperation.fromString("all(group(foo)max(5)precision(10)each(output(count())))"));
@@ -810,10 +818,15 @@ public class RequestBuilderTestCase {
}
private static void assertTotalGroupsAndSummaries(long expected, String query) {
+ assertTotalGroupsAndSummaries(expected, Long.MAX_VALUE, query);
+ }
+
+ private static void assertTotalGroupsAndSummaries(long expected, long globalMaxGroups, String query) {
RequestBuilder builder = new RequestBuilder(0)
- .setRootOperation(GroupingOperation.fromString(query)).setGlobalMaxGroups(Long.MAX_VALUE);
+ .setRootOperation(GroupingOperation.fromString(query)).setGlobalMaxGroups(globalMaxGroups);
builder.build();
- assertEquals(expected, builder.totalGroupsAndSummaries().orElseThrow());
+ if (globalMaxGroups >= 0) // otherwise, totalGroupsAndSummaries is not computed
+ assertEquals(expected, builder.totalGroupsAndSummaries().orElseThrow());
}
private static void assertQueryFailsOnGlobalMax(long globalMax, String query, String errorSubstring) {
@@ -938,11 +951,13 @@ public class RequestBuilderTestCase {
String expectedOutput;
OutputWriter outputWriter;
Continuation continuation;
+
}
- private static interface OutputWriter {
+ private interface OutputWriter {
String write(List<Grouping> groupingList, GroupingTransform transform);
+
}
private static class OffsetWriter implements OutputWriter {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
index 3bc5a7c245c..019a022b7e6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
@@ -13,12 +13,12 @@ import com.yahoo.search.result.Relevance;
import com.yahoo.searchlib.aggregation.*;
import com.yahoo.searchlib.aggregation.hll.SparseSketch;
import com.yahoo.searchlib.expression.*;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -29,28 +29,28 @@ public class ResultBuilderTestCase {
private static final int ROOT_IDX = 0;
@Test
- public void requireThatAllGroupIdsCanBeConverted() {
+ void requireThatAllGroupIdsCanBeConverted() {
assertGroupId("group:6.9", new FloatResultNode(6.9));
assertGroupId("group:69", new IntegerResultNode(69));
assertGroupId("group:null", new NullResultNode());
- assertGroupId("group:[6, 9]", new RawResultNode(new byte[] { 6, 9 }));
+ assertGroupId("group:[6, 9]", new RawResultNode(new byte[]{6, 9}));
assertGroupId("group:a", new StringResultNode("a"));
assertGroupId("group:6.9:9.6", new FloatBucketResultNode(6.9, 9.6));
assertGroupId("group:6:9", new IntegerBucketResultNode(6, 9));
assertGroupId("group:a:b", new StringBucketResultNode("a", "b"));
- assertGroupId("group:[6, 9]:[9, 6]", new RawBucketResultNode(new RawResultNode(new byte[] { 6, 9 }),
- new RawResultNode(new byte[] { 9, 6 })));
+ assertGroupId("group:[6, 9]:[9, 6]", new RawBucketResultNode(new RawResultNode(new byte[]{6, 9}),
+ new RawResultNode(new byte[]{9, 6})));
}
@Test
- public void requireThatUnknownGroupIdThrows() {
+ void requireThatUnknownGroupIdThrows() {
assertBuildFail("all(group(a) each(output(count())))",
- Arrays.asList(newGrouping(new Group().setTag(2).setId(new MyResultNode()))),
- "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyResultNode");
+ Arrays.asList(newGrouping(new Group().setTag(2).setId(new MyResultNode()))),
+ "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyResultNode");
}
@Test
- public void requireThatAllExpressionNodesCanBeConverted() {
+ void requireThatAllExpressionNodesCanBeConverted() {
assertResult("0", new AverageAggregationResult(new IntegerResultNode(6), 9));
assertResult("69", new CountAggregationResult(69));
assertResult("69", new MaxAggregationResult(new IntegerResultNode(69)));
@@ -61,89 +61,89 @@ public class ResultBuilderTestCase {
}
@Test
- public void requireThatUnknownExpressionNodeThrows() {
+ void requireThatUnknownExpressionNodeThrows() {
assertBuildFail("all(group(a) each(output(count())))",
- Arrays.asList(newGrouping(newGroup(2, 2, new MyAggregationResult().setTag(3)))),
- "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyAggregationResult");
+ Arrays.asList(newGrouping(newGroup(2, 2, new MyAggregationResult().setTag(3)))),
+ "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyAggregationResult");
}
@Test
- public void requireThatRootResultsAreIncluded() {
+ void requireThatRootResultsAreIncluded() {
assertLayout("all(output(count()))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, count()=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, count()=69}[]");
}
@Test
- public void requireThatRootResultsAreIncludedUsingExpressionCountAggregationResult() {
+ void requireThatRootResultsAreIncludedUsingExpressionCountAggregationResult() {
assertLayout("all(group(a) output(count()))",
new Grouping().setRoot(newGroup(1, new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69).setTag(2))),
"RootGroup{id=group:root, count()=69}[]");
}
@Test
- public void requireThatNestedGroupingResultsCanBeTransformed() {
+ void requireThatNestedGroupingResultsCanBeTransformed() {
Grouping grouping = new Grouping()
.setRoot(new Group()
- .setTag(1)
- .addChild(new Group()
- .setTag(2)
- .setId(new StringResultNode("foo"))
- .addAggregationResult(new CountAggregationResult(10).setTag(3))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("foo_a"))
- .addAggregationResult(new CountAggregationResult(15)
- .setTag(5)))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("foo_b"))
- .addAggregationResult(new CountAggregationResult(16)
- .setTag(5))))
- .addChild(new Group()
- .setTag(2)
- .setId(new StringResultNode("bar"))
- .addAggregationResult(new CountAggregationResult(20).setTag(3))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("bar_a"))
- .addAggregationResult(
- new CountAggregationResult(25)
- .setTag(5)))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("bar_b"))
- .addAggregationResult(
- new CountAggregationResult(26)
- .setTag(5)))));
+ .setTag(1)
+ .addChild(new Group()
+ .setTag(2)
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(new CountAggregationResult(10).setTag(3))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("foo_a"))
+ .addAggregationResult(new CountAggregationResult(15)
+ .setTag(5)))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("foo_b"))
+ .addAggregationResult(new CountAggregationResult(16)
+ .setTag(5))))
+ .addChild(new Group()
+ .setTag(2)
+ .setId(new StringResultNode("bar"))
+ .addAggregationResult(new CountAggregationResult(20).setTag(3))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("bar_a"))
+ .addAggregationResult(
+ new CountAggregationResult(25)
+ .setTag(5)))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("bar_b"))
+ .addAggregationResult(
+ new CountAggregationResult(26)
+ .setTag(5)))));
assertLayout("all(group(artist) max(5) each(output(count() as(baz)) all(group(album) " +
- "max(5) each(output(count() as(cox))) as(group_album))) as(group_artist))",
- grouping,
- "RootGroup{id=group:root}[GroupList{label=group_artist}[" +
- "Group{id=group:foo, baz=10}[GroupList{label=group_album}[Group{id=group:foo_a, cox=15}[], Group{id=group:foo_b, cox=16}[]]], " +
- "Group{id=group:bar, baz=20}[GroupList{label=group_album}[Group{id=group:bar_a, cox=25}[], Group{id=group:bar_b, cox=26}[]]]]]");
+ "max(5) each(output(count() as(cox))) as(group_album))) as(group_artist))",
+ grouping,
+ "RootGroup{id=group:root}[GroupList{label=group_artist}[" +
+ "Group{id=group:foo, baz=10}[GroupList{label=group_album}[Group{id=group:foo_a, cox=15}[], Group{id=group:foo_b, cox=16}[]]], " +
+ "Group{id=group:bar, baz=20}[GroupList{label=group_album}[Group{id=group:bar_a, cox=25}[], Group{id=group:bar_b, cox=26}[]]]]]");
}
@Test
- public void requireThatParallelResultsAreTransformed() {
+ void requireThatParallelResultsAreTransformed() {
assertBuild("all(group(foo) each(output(count())) as(bar) each(output(count())) as(baz))",
- Arrays.asList(new Grouping().setRoot(newGroup(1, 0)),
- new Grouping().setRoot(newGroup(1, 0))));
+ Arrays.asList(new Grouping().setRoot(newGroup(1, 0)),
+ new Grouping().setRoot(newGroup(1, 0))));
assertBuildFail("all(group(foo) each(output(count())) as(bar) each(output(count())) as(baz))",
- Arrays.asList(new Grouping().setRoot(newGroup(2)),
- new Grouping().setRoot(newGroup(3))),
- "Expected 1 group, got 2.");
+ Arrays.asList(new Grouping().setRoot(newGroup(2)),
+ new Grouping().setRoot(newGroup(3))),
+ "Expected 1 group, got 2.");
}
@Test
- public void requireThatTagsAreHandledCorrectly() {
+ void requireThatTagsAreHandledCorrectly() {
assertBuild("all(group(a) each(output(count())))",
Arrays.asList(newGrouping(
newGroup(7, new CountAggregationResult(0)))));
}
@Test
- public void requireThatEmptyBranchesArePruned() {
+ void requireThatEmptyBranchesArePruned() {
assertBuildFail("all()", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
assertBuildFail("all(group(a))", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
assertBuildFail("all(group(a) each())", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
@@ -156,71 +156,71 @@ public class ResultBuilderTestCase {
assertLayout("all(group(a) each(output(count()) all(group(b) each())))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each())))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each() as(foo))", grouping, expectedOutput);
+ " each() as(foo))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each(group(b)) as(foo))", grouping, expectedOutput);
+ " each(group(b)) as(foo))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each(group(b) each()) as(foo))", grouping, expectedOutput);
+ " each(group(b) each()) as(foo))", grouping, expectedOutput);
}
@Test
- public void requireThatGroupListsAreLabeled() {
+ void requireThatGroupListsAreLabeled() {
assertLayout("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
assertLayout("all(group(a) each(output(count())) as(bar))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=bar}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=bar}[Group{id=group:2, count()=69}[]]]");
}
@Test
- public void requireThatHitListsAreLabeled() {
+ void requireThatHitListsAreLabeled() {
assertLayout("all(group(foo) each(each(output(summary()))))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)) as(baz))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=baz}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=baz}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)" +
- " each(output(summary())) as(baz)))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
- newGrouping(newGroup(2, newHitList(4, 2)))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}], " +
- "HitList{label=baz}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ " each(output(summary())) as(baz)))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
+ newGrouping(newGroup(2, newHitList(4, 2)))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}], " +
+ "HitList{label=baz}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())))" +
- " each(each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
- newGrouping(newGroup(4, newHitList(5, 2)))),
- "RootGroup{id=group:root}[" +
- "GroupList{label=foo}[Group{id=group:2}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]], " +
- "GroupList{label=bar}[Group{id=group:4}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ " each(each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
+ newGrouping(newGroup(4, newHitList(5, 2)))),
+ "RootGroup{id=group:root}[" +
+ "GroupList{label=foo}[Group{id=group:2}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]], " +
+ "GroupList{label=bar}[Group{id=group:4}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
}
@Test
- public void requireThatOutputsAreLabeled() {
+ void requireThatOutputsAreLabeled() {
assertLayout("all(output(count()))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, count()=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, count()=69}[]");
assertLayout("all(output(count() as(foo)))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, foo=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, foo=69}[]");
assertLayout("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
assertLayout("all(group(a) each(output(count() as(foo))))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, foo=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, foo=69}[]]]");
}
@Test
- public void requireThatExpressionCountCanUseExactGroupCount() {
+ void requireThatExpressionCountCanUseExactGroupCount() {
Group root1 = newGroup(1, new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 42).setTag(2));
Grouping grouping1 = new Grouping().setRoot(root1);
@@ -260,35 +260,35 @@ public class ResultBuilderTestCase {
@Test
- public void requireThatResultContinuationContainsCurrentPages() {
+ void requireThatResultContinuationContainsCurrentPages() {
String request = "all(group(a) max(2) each(output(count())))";
Grouping result = newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4)));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4)));
assertResultCont(request, result, newOffset(newResultId(0), 2, 0), "[]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 1), "[0=1]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 2), "[0=2]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 3), "[0=3]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- "[]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ "[]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- newOffset(newResultId(0), 2, 1),
- "[0=1]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ newOffset(newResultId(0), 2, 1),
+ "[0=1]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- newComposite(newOffset(newResultId(0), 2, 2),
- newOffset(newResultId(1), 4, 1)),
- "[0=2, 1=1]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ newComposite(newOffset(newResultId(0), 2, 2),
+ newOffset(newResultId(1), 4, 1)),
+ "[0=2, 1=1]");
request = "all(group(a) each(max(2) each(output(summary()))))";
result = newGrouping(newGroup(2, newHitList(3, 4)));
@@ -298,436 +298,436 @@ public class ResultBuilderTestCase {
assertResultCont(request, result, newOffset(newResultId(0, 0, 0), 3, 3), "[0.0.0=3]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- "[]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ "[]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- newOffset(newResultId(0, 0, 0), 3, 1),
- "[0.0.0=1]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ newOffset(newResultId(0, 0, 0), 3, 1),
+ "[0.0.0=1]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(1, 0, 0), 5, 1)),
- "[0.0.0=2, 1.0.0=1]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
+ newOffset(newResultId(1, 0, 0), 5, 1)),
+ "[0.0.0=2, 1.0.0=1]");
}
@Test
- public void requireThatGroupListContinuationsAreNotCreatedWhenUnlessMaxIsSet() {
+ void requireThatGroupListContinuationsAreNotCreatedWhenUnlessMaxIsSet() {
assertContinuation("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4))),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:1', {}, [] }, { 'group:2', {}, [] }, { 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4))),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:1', {}, [] }, { 'group:2', {}, [] }, { 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSet() {
+ void requireThatGroupListContinuationsCanBeSet() {
String request = "all(group(a) max(2) each(output(count())))";
Grouping result = newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4)));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4)));
assertContinuation(request, result, newOffset(newResultId(0), 2, 0),
- "{ 'group:root', {}, [{ 'grouplist:a', {next=2}, [" +
- "{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {next=2}, [" +
+ "{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 1),
- "{ 'group:root', {}, [{ 'grouplist:a', {next=3, prev=0}, [" +
- "{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {next=3, prev=0}, [" +
+ "{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 2),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=0}, [" +
- "{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=0}, [" +
+ "{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 3),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=1}, [" +
- "{ 'group:4', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=1}, [" +
+ "{ 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 4),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
- "] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
+ "] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 5),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
- "] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
+ "] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSetInSiblingGroups() {
+ void requireThatGroupListContinuationsCanBeSetInSiblingGroups() {
String request = "all(group(a) each(group(b) max(2) each(output(count()))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301, new CountAggregationResult(1)),
- newGroup(3, 302, new CountAggregationResult(2)),
- newGroup(3, 303, new CountAggregationResult(3)),
- newGroup(3, 304, new CountAggregationResult(4))),
- newGroup(2, 202,
- newGroup(3, 305, new CountAggregationResult(5)),
- newGroup(3, 306, new CountAggregationResult(6)),
- newGroup(3, 307, new CountAggregationResult(7)),
- newGroup(3, 308, new CountAggregationResult(8))));
+ newGroup(3, 301, new CountAggregationResult(1)),
+ newGroup(3, 302, new CountAggregationResult(2)),
+ newGroup(3, 303, new CountAggregationResult(3)),
+ newGroup(3, 304, new CountAggregationResult(4))),
+ newGroup(2, 202,
+ newGroup(3, 305, new CountAggregationResult(5)),
+ newGroup(3, 306, new CountAggregationResult(6)),
+ newGroup(3, 307, new CountAggregationResult(7)),
+ newGroup(3, 308, new CountAggregationResult(8))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 0),
- newOffset(newResultId(0, 1, 0), 2, 5)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [{ 'group:301', {}, [] }, { 'group:302', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 5)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [{ 'group:301', {}, [] }, { 'group:302', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 1),
- newOffset(newResultId(0, 1, 0), 2, 4)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:302', {}, [] }, { 'group:303', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 4)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:302', {}, [] }, { 'group:303', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 2),
- newOffset(newResultId(0, 1, 0), 2, 3)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:303', {}, [] }, { 'group:304', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:308', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 3)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:303', {}, [] }, { 'group:304', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:308', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 3),
- newOffset(newResultId(0, 1, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:304', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:307', {}, [] }, { 'group:308', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:304', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:307', {}, [] }, { 'group:308', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 4),
- newOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:306', {}, [] }, { 'group:307', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:306', {}, [] }, { 'group:307', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 5),
- newOffset(newResultId(0, 1, 0), 2, 0)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [{ 'group:305', {}, [] }, { 'group:306', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 0)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [{ 'group:305', {}, [] }, { 'group:306', {}, [] }] }] }] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSetInSiblingGroupLists() {
+ void requireThatGroupListContinuationsCanBeSetInSiblingGroupLists() {
String request = "all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))";
+ " each(output(count())) as(bar))";
List<Grouping> result = Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4))),
- newGrouping(newGroup(4, 1, new CountAggregationResult(1)),
- newGroup(4, 2, new CountAggregationResult(2)),
- newGroup(4, 3, new CountAggregationResult(3)),
- newGroup(4, 4, new CountAggregationResult(4))));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4))),
+ newGrouping(newGroup(4, 1, new CountAggregationResult(1)),
+ newGroup(4, 2, new CountAggregationResult(2)),
+ newGroup(4, 3, new CountAggregationResult(3)),
+ newGroup(4, 4, new CountAggregationResult(4))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 0),
- newOffset(newResultId(1), 4, 5)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=2}, [] }] }");
+ newOffset(newResultId(1), 4, 5)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=2}, [] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 1),
- newOffset(newResultId(1), 4, 4)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=2}, [] }] }");
+ newOffset(newResultId(1), 4, 4)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=2}, [] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 2),
- newOffset(newResultId(1), 4, 3)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=1}, [{ 'group:4', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 3)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=1}, [{ 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 3),
- newOffset(newResultId(1), 4, 2)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=1}, [{ 'group:4', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 2)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=1}, [{ 'group:4', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 4),
- newOffset(newResultId(1), 4, 1)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=2}, [] }, " +
- "{ 'grouplist:bar', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 1)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=2}, [] }, " +
+ "{ 'grouplist:bar', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 5),
- newOffset(newResultId(1), 4, 0)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=2}, [] }, " +
- "{ 'grouplist:bar', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 0)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=2}, [] }, " +
+ "{ 'grouplist:bar', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectSiblingGroupLists() {
+ void requireThatUnstableContinuationsDoNotAffectSiblingGroupLists() {
String request = "all(group(a) each(group(b) max(2) each(group(c) max(2) each(output(count())))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301,
- newGroup(4, 401, new CountAggregationResult(1)),
- newGroup(4, 402, new CountAggregationResult(1)),
- newGroup(4, 403, new CountAggregationResult(1)),
- newGroup(4, 404, new CountAggregationResult(1))),
- newGroup(3, 302,
- newGroup(4, 405, new CountAggregationResult(1)),
- newGroup(4, 406, new CountAggregationResult(1)),
- newGroup(4, 407, new CountAggregationResult(1)),
- newGroup(4, 408, new CountAggregationResult(1))),
- newGroup(3, 303,
- newGroup(4, 409, new CountAggregationResult(1)),
- newGroup(4, 410, new CountAggregationResult(1)),
- newGroup(4, 411, new CountAggregationResult(1)),
- newGroup(4, 412, new CountAggregationResult(1))),
- newGroup(3, 304,
- newGroup(4, 413, new CountAggregationResult(1)),
- newGroup(4, 414, new CountAggregationResult(1)),
- newGroup(4, 415, new CountAggregationResult(1)),
- newGroup(4, 416, new CountAggregationResult(1)))),
- newGroup(2, 202,
- newGroup(3, 305,
- newGroup(4, 417, new CountAggregationResult(1)),
- newGroup(4, 418, new CountAggregationResult(1)),
- newGroup(4, 419, new CountAggregationResult(1)),
- newGroup(4, 420, new CountAggregationResult(1))),
- newGroup(3, 306,
- newGroup(4, 421, new CountAggregationResult(1)),
- newGroup(4, 422, new CountAggregationResult(1)),
- newGroup(4, 423, new CountAggregationResult(1)),
- newGroup(4, 424, new CountAggregationResult(1))),
- newGroup(3, 307,
- newGroup(4, 425, new CountAggregationResult(1)),
- newGroup(4, 426, new CountAggregationResult(1)),
- newGroup(4, 427, new CountAggregationResult(1)),
- newGroup(4, 428, new CountAggregationResult(1))),
- newGroup(3, 308,
- newGroup(4, 429, new CountAggregationResult(1)),
- newGroup(4, 430, new CountAggregationResult(1)),
- newGroup(4, 431, new CountAggregationResult(1)),
- newGroup(4, 432, new CountAggregationResult(1)))));
+ newGroup(3, 301,
+ newGroup(4, 401, new CountAggregationResult(1)),
+ newGroup(4, 402, new CountAggregationResult(1)),
+ newGroup(4, 403, new CountAggregationResult(1)),
+ newGroup(4, 404, new CountAggregationResult(1))),
+ newGroup(3, 302,
+ newGroup(4, 405, new CountAggregationResult(1)),
+ newGroup(4, 406, new CountAggregationResult(1)),
+ newGroup(4, 407, new CountAggregationResult(1)),
+ newGroup(4, 408, new CountAggregationResult(1))),
+ newGroup(3, 303,
+ newGroup(4, 409, new CountAggregationResult(1)),
+ newGroup(4, 410, new CountAggregationResult(1)),
+ newGroup(4, 411, new CountAggregationResult(1)),
+ newGroup(4, 412, new CountAggregationResult(1))),
+ newGroup(3, 304,
+ newGroup(4, 413, new CountAggregationResult(1)),
+ newGroup(4, 414, new CountAggregationResult(1)),
+ newGroup(4, 415, new CountAggregationResult(1)),
+ newGroup(4, 416, new CountAggregationResult(1)))),
+ newGroup(2, 202,
+ newGroup(3, 305,
+ newGroup(4, 417, new CountAggregationResult(1)),
+ newGroup(4, 418, new CountAggregationResult(1)),
+ newGroup(4, 419, new CountAggregationResult(1)),
+ newGroup(4, 420, new CountAggregationResult(1))),
+ newGroup(3, 306,
+ newGroup(4, 421, new CountAggregationResult(1)),
+ newGroup(4, 422, new CountAggregationResult(1)),
+ newGroup(4, 423, new CountAggregationResult(1)),
+ newGroup(4, 424, new CountAggregationResult(1))),
+ newGroup(3, 307,
+ newGroup(4, 425, new CountAggregationResult(1)),
+ newGroup(4, 426, new CountAggregationResult(1)),
+ newGroup(4, 427, new CountAggregationResult(1)),
+ newGroup(4, 428, new CountAggregationResult(1))),
+ newGroup(3, 308,
+ newGroup(4, 429, new CountAggregationResult(1)),
+ newGroup(4, 430, new CountAggregationResult(1)),
+ newGroup(4, 431, new CountAggregationResult(1)),
+ newGroup(4, 432, new CountAggregationResult(1)))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
- "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
+ "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2),
- newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
- "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
- "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }, " +
- "{ 'group:307', {}, [{ 'grouplist:c', {next=2}, [{ 'group:425', {}, [] }, { 'group:426', {}, [] }] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2),
+ newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
+ "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
+ "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }, " +
+ "{ 'group:307', {}, [{ 'grouplist:c', {next=2}, [{ 'group:425', {}, [] }, { 'group:426', {}, [] }] }] }] }] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsAffectAllDecendants() {
+ void requireThatUnstableContinuationsAffectAllDecendants() {
String request = "all(group(a) each(group(b) max(1) each(group(c) max(1) each(group(d) max(1) each(output(count()))))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301,
- newGroup(4, 401,
- newGroup(5, 501, new CountAggregationResult(1)),
- newGroup(5, 502, new CountAggregationResult(1))),
- newGroup(4, 402,
- newGroup(5, 503, new CountAggregationResult(1)),
- newGroup(5, 504, new CountAggregationResult(1)))),
- newGroup(3, 302,
- newGroup(4, 403,
- newGroup(5, 505, new CountAggregationResult(1)),
- newGroup(5, 506, new CountAggregationResult(1))),
- newGroup(4, 404,
- newGroup(5, 507, new CountAggregationResult(1)),
- newGroup(5, 508, new CountAggregationResult(1))))));
+ newGroup(3, 301,
+ newGroup(4, 401,
+ newGroup(5, 501, new CountAggregationResult(1)),
+ newGroup(5, 502, new CountAggregationResult(1))),
+ newGroup(4, 402,
+ newGroup(5, 503, new CountAggregationResult(1)),
+ newGroup(5, 504, new CountAggregationResult(1)))),
+ newGroup(3, 302,
+ newGroup(4, 403,
+ newGroup(5, 505, new CountAggregationResult(1)),
+ newGroup(5, 506, new CountAggregationResult(1))),
+ newGroup(4, 404,
+ newGroup(5, 507, new CountAggregationResult(1)),
+ newGroup(5, 508, new CountAggregationResult(1))))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:401', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:501', {}, [] }] }] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:401', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:501', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:401', {}, [{ 'grouplist:d', {prev=0}, [" +
- "{ 'group:502', {}, [] }] }] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:401', {}, [{ 'grouplist:d', {prev=0}, [" +
+ "{ 'group:502', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1),
- newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {prev=0}, [" +
- "{ 'group:402', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:503', {}, [] }] }] }] }] }] }] }] }] }");
+ newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {prev=0}, [" +
+ "{ 'group:402', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:503', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1),
- newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1),
- newUnstableOffset(newResultId(0, 0, 0), 3, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:403', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:505', {}, [] }] }] }] }] }] }] }] }] }");
+ newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1),
+ newUnstableOffset(newResultId(0, 0, 0), 3, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:403', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:505', {}, [] }] }] }] }] }] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsAreNotCreatedUnlessMaxIsSet() {
+ void requireThatHitListContinuationsAreNotCreatedUnlessMaxIsSet() {
assertContinuation("all(group(a) each(each(output(summary()))))",
- newGrouping(newGroup(2, newHitList(3, 4))),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {}, [hit:1, hit:2, hit:3, hit:4] }] }] }] }");
+ newGrouping(newGroup(2, newHitList(3, 4))),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {}, [hit:1, hit:2, hit:3, hit:4] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSet() {
+ void requireThatHitListContinuationsCanBeSet() {
String request = "all(group(a) each(max(2) each(output(summary()))))";
Grouping result = newGrouping(newGroup(2, newHitList(3, 4)));
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 0),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 1),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 2),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 3),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 4),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 5),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSetInSiblingGroups() {
+ void requireThatHitListContinuationsCanBeSetInSiblingGroups() {
String request = "all(group(a) each(max(2) each(output(summary()))))";
Grouping result = newGrouping(newGroup(2, 201, newHitList(3, 4)),
- newGroup(2, 202, newHitList(3, 4)));
+ newGroup(2, 202, newHitList(3, 4)));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 0),
- newOffset(newResultId(0, 1, 0), 3, 5)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 5)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 1),
- newOffset(newResultId(0, 1, 0), 3, 4)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 4)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(0, 1, 0), 3, 3)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 3)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 3),
- newOffset(newResultId(0, 1, 0), 3, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 4),
- newOffset(newResultId(0, 1, 0), 3, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 5),
- newOffset(newResultId(0, 1, 0), 3, 0)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 0)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSetInSiblingHitLists() {
+ void requireThatHitListContinuationsCanBeSetInSiblingHitLists() {
String request = "all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))";
+ " each(max(2) each(output(summary()))) as(bar))";
List<Grouping> result = Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4))));
+ newGrouping(newGroup(4, newHitList(5, 4))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 0),
- newOffset(newResultId(1, 0, 0), 5, 5)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 5)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 1),
- newOffset(newResultId(1, 0, 0), 5, 4)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 4)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(1, 0, 0), 5, 3)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 3)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 3),
- newOffset(newResultId(1, 0, 0), 5, 2)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 2)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 4),
- newOffset(newResultId(1, 0, 0), 5, 1)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 1)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 5),
- newOffset(newResultId(1, 0, 0), 5, 0)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 0)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectSiblingHitLists() {
+ void requireThatUnstableContinuationsDoNotAffectSiblingHitLists() {
String request = "all(group(a) each(group(b) max(2) each(max(2) each(output(summary())))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301, newHitList(4, 4)),
- newGroup(3, 302, newHitList(4, 4)),
- newGroup(3, 303, newHitList(4, 4)),
- newGroup(3, 304, newHitList(4, 4))),
- newGroup(2, 202,
- newGroup(3, 305, newHitList(4, 4)),
- newGroup(3, 306, newHitList(4, 4)),
- newGroup(3, 307, newHitList(4, 4)),
- newGroup(3, 308, newHitList(4, 4))));
+ newGroup(3, 301, newHitList(4, 4)),
+ newGroup(3, 302, newHitList(4, 4)),
+ newGroup(3, 303, newHitList(4, 4)),
+ newGroup(3, 304, newHitList(4, 4))),
+ newGroup(2, 202,
+ newGroup(3, 305, newHitList(4, 4)),
+ newGroup(3, 306, newHitList(4, 4)),
+ newGroup(3, 307, newHitList(4, 4)),
+ newGroup(3, 308, newHitList(4, 4))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2),
- newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
- "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:307', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2),
+ newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:307', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
}
// --------------------------------------------------------------------------------
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java
index 8afaa4922ec..0e38e688258 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class ResultIdTestCase {
@Test
- public void requireThatStartsWithWorks() {
+ void requireThatStartsWithWorks() {
assertFalse(ResultId.valueOf().startsWith(1, 1, 2, 3));
assertFalse(ResultId.valueOf(1).startsWith(1, 1, 2, 3));
assertFalse(ResultId.valueOf(1, 1).startsWith(1, 1, 2, 3));
@@ -26,32 +24,32 @@ public class ResultIdTestCase {
}
@Test
- public void requireThatChildIdStartsWithParentId() {
+ void requireThatChildIdStartsWithParentId() {
ResultId parentId = ResultId.valueOf(1, 1, 2);
ResultId childId = parentId.newChildId(3);
assertTrue(childId.startsWith(1, 1, 2));
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(ResultId.valueOf(1, 1, 2, 3).hashCode(), ResultId.valueOf(1, 1, 2, 3).hashCode());
- assertFalse(ResultId.valueOf(1, 1, 2, 3).hashCode() == ResultId.valueOf(5, 8, 13, 21).hashCode());
+ assertNotNull(ResultId.valueOf(5, 8, 13, 21).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
assertEquals(ResultId.valueOf(1, 1, 2, 3), ResultId.valueOf(1, 1, 2, 3));
- assertFalse(ResultId.valueOf(1, 1, 2, 3).equals(ResultId.valueOf(5, 8, 13, 21)));
+ assertNotEquals(ResultId.valueOf(1, 1, 2, 3), ResultId.valueOf(5, 8, 13, 21));
}
@Test
- public void requireThatResultIdCanBeEncoded() {
+ void requireThatResultIdCanBeEncoded() {
assertEncode("BIBCBCBEBG", ResultId.valueOf(1, 1, 2, 3));
assertEncode("BIBKCBACBKCCK", ResultId.valueOf(5, 8, 13, 21));
}
@Test
- public void requireThatResultIdCanBeDecoded() {
+ void requireThatResultIdCanBeDecoded() {
assertDecode(ResultId.valueOf(1, 1, 2, 3), "BIBCBCBEBG");
assertDecode(ResultId.valueOf(5, 8, 13, 21), "BIBKCBACBKCCK");
}
diff --git a/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java b/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
index b0b88bf8190..83022ccf3ff 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
@@ -17,12 +17,11 @@ import com.yahoo.slime.Inspector;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.test.json.JsonTestHelper;
import org.assertj.core.api.Assertions;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -32,12 +31,12 @@ import java.util.Map;
import java.util.Random;
import static com.yahoo.jdisc.http.HttpRequest.Method.GET;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests submitting the query as JSON.
@@ -56,16 +55,16 @@ public class JSONSearchHandlerTestCase {
private static final String uri = "http://localhost?";
private static final String JSON_CONTENT_TYPE = "application/json";
- @Rule
- public TemporaryFolder tempfolder = new TemporaryFolder();
+ @TempDir
+ public File tempfolder;
private RequestHandlerTestDriver driver = null;
private HandlersConfigurerTestWrapper configurer = null;
private SearchHandler searchHandler;
- @Before
+ @BeforeEach
public void startUp() throws IOException {
- File cfgDir = tempfolder.newFolder("SearchHandlerTestCase");
+ File cfgDir = newFolder(tempfolder, "SearchHandlerTestCase");
tempDir = cfgDir.getAbsolutePath();
String configId = "dir:" + tempDir;
@@ -77,7 +76,7 @@ public class JSONSearchHandlerTestCase {
driver = new RequestHandlerTestDriver(searchHandler);
}
- @After
+ @AfterEach
public void shutDown() {
if (configurer != null) configurer.shutdown();
if (driver != null) driver.close();
@@ -96,7 +95,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testBadJSON() {
+ void testBadJSON() {
String json = "Not a valid JSON-string";
RequestHandlerTestDriver.MockResponseHandler responseHandler = driver.sendRequest(uri, com.yahoo.jdisc.http.HttpRequest.Method.POST, json, JSON_CONTENT_TYPE);
String response = responseHandler.readAll();
@@ -106,7 +105,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testFailing() {
+ void testFailing() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "test");
json.put("searchChain", "classLoadingError");
@@ -115,7 +114,7 @@ public class JSONSearchHandlerTestCase {
@Test
- public synchronized void testPluginError() {
+ synchronized void testPluginError() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "test");
json.put("searchChain", "exceptionInPlugin");
@@ -123,7 +122,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public synchronized void testWorkingReconfiguration() throws IOException {
+ synchronized void testWorkingReconfiguration() throws IOException {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertJsonResult(json, driver);
@@ -135,22 +134,22 @@ public class JSONSearchHandlerTestCase {
// ...and check the resulting config
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
- assertNotNull("Have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"));
- assertNull("Don't have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"));
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
+ assertNotNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"), "Have the new search chain");
+ assertNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"), "Don't have the new search chain");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
assertJsonResult(json, newDriver);
}
}
@Test
- public void testInvalidYqlQuery() throws IOException {
+ void testInvalidYqlQuery() throws IOException {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertTrue("Do I have a new instance of the search handler?", searchHandler != newSearchHandler);
+ assertTrue(searchHandler != newSearchHandler, "Do I have a new instance of the search handler?");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
ObjectNode json = jsonMapper.createObjectNode();
json.put("yql", "selectz * from foo where bar > 1453501295");
@@ -162,7 +161,7 @@ public class JSONSearchHandlerTestCase {
// Query handling takes a different code path when a query profile is active, so we test both paths.
@Test
- public void testInvalidQueryParamWithQueryProfile() throws IOException {
+ void testInvalidQueryParamWithQueryProfile() throws IOException {
try (RequestHandlerTestDriver newDriver = driverWithConfig("config_invalid_param")) {
testInvalidQueryParam(newDriver);
}
@@ -182,7 +181,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultJsonAliasRendering() {
+ void testNormalResultJsonAliasRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("format", "json");
json.put("query", "abc");
@@ -190,7 +189,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("format", "xml");
@@ -204,7 +203,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testWebServiceStatus() {
+ void testWebServiceStatus() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "web_service_status_code");
RequestHandlerTestDriver.MockResponseHandler responseHandler =
@@ -215,14 +214,14 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultImplicitDefaultRendering() {
+ void testNormalResultImplicitDefaultRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertJsonResult(json, driver);
}
@Test
- public void testNormalResultExplicitDefaultRendering() {
+ void testNormalResultExplicitDefaultRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "default");
@@ -230,7 +229,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultXmlAliasRendering() {
+ void testNormalResultXmlAliasRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "xml");
@@ -238,7 +237,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName1() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName1() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "XmlRenderer");
@@ -246,7 +245,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName2() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName2() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "JsonRenderer");
@@ -303,12 +302,12 @@ public class JSONSearchHandlerTestCase {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertTrue("Do I have a new instance of the search handler?", searchHandler != newSearchHandler);
+ assertTrue(searchHandler != newSearchHandler, "Do I have a new instance of the search handler?");
return new RequestHandlerTestDriver(newSearchHandler);
}
@Test
- public void testSelectParameters() throws IOException {
+ void testSelectParameters() throws IOException {
ObjectNode json = jsonMapper.createObjectNode();
ObjectNode select = jsonMapper.createObjectNode();
@@ -335,7 +334,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonQueryWithSelectWhere() {
+ void testJsonQueryWithSelectWhere() {
ObjectNode root = jsonMapper.createObjectNode();
ObjectNode select = jsonMapper.createObjectNode();
ObjectNode where = jsonMapper.createObjectNode();
@@ -349,28 +348,28 @@ public class JSONSearchHandlerTestCase {
// Run query
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, root.toString(), JSON_CONTENT_TYPE).readAll();
assertEquals("{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where default contains \\\"bad\\\"\"}}]}}",
- result);
+ result);
}
@Test
- public void testJsonWithWhereAndGroupingUnderSelect() {
+ void testJsonWithWhereAndGroupingUnderSelect() {
String query = "{\n" +
- " \"select\": {\n" +
- " \"where\": {\n" +
- " \"contains\": [\n" +
- " \"field\",\n" +
- " \"term\"\n" +
- " ]\n" +
- " },\n" +
- " \"grouping\":[\n" +
- " {\n" +
- " \"all\": {\n" +
- " \"output\": \"count()\"\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- "}\n";
+ " \"select\": {\n" +
+ " \"where\": {\n" +
+ " \"contains\": [\n" +
+ " \"field\",\n" +
+ " \"term\"\n" +
+ " ]\n" +
+ " },\n" +
+ " \"grouping\":[\n" +
+ " {\n" +
+ " \"all\": {\n" +
+ " \"output\": \"count()\"\n" +
+ " }\n" +
+ " }\n" +
+ " ]\n" +
+ " }\n" +
+ "}\n";
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, query, JSON_CONTENT_TYPE).readAll();
String expected = "{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where field contains \\\"term\\\" | all(output(count()))\"}}]}}";
@@ -378,22 +377,22 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonWithWhereAndGroupingSeparate() {
+ void testJsonWithWhereAndGroupingSeparate() {
String query = "{\n" +
- " \"select.where\": {\n" +
- " \"contains\": [\n" +
- " \"field\",\n" +
- " \"term\"\n" +
- " ]\n" +
- " },\n" +
- " \"select.grouping\":[\n" +
- " {\n" +
- " \"all\": {\n" +
- " \"output\": \"count()\"\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- "}\n";
+ " \"select.where\": {\n" +
+ " \"contains\": [\n" +
+ " \"field\",\n" +
+ " \"term\"\n" +
+ " ]\n" +
+ " },\n" +
+ " \"select.grouping\":[\n" +
+ " {\n" +
+ " \"all\": {\n" +
+ " \"output\": \"count()\"\n" +
+ " }\n" +
+ " }\n" +
+ " ]\n" +
+ "}\n";
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, query, JSON_CONTENT_TYPE).readAll();
String expected = "{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where field contains \\\"term\\\" | all(output(count()))\"}}]}}";
@@ -401,18 +400,18 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonQueryWithYQL() {
+ void testJsonQueryWithYQL() {
ObjectNode root = jsonMapper.createObjectNode();
root.put("yql", "select * from sources * where default contains 'bad';");
// Run query
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, root.toString(), JSON_CONTENT_TYPE).readAll();
assertEquals("{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where default contains \\\"bad\\\"\"}}]}}",
- result);
+ result);
}
@Test
- public void testRequestMapping() {
+ void testRequestMapping() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("yql", "select * from sources * where sddocname contains \"blog_post\" limit 0 | all(group(date) max(3) order(-count())each(output(count())))");
json.put("hits", 10);
@@ -529,7 +528,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testContentTypeParsing() {
+ void testContentTypeParsing() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertOkResult(driver.sendRequest(uri, com.yahoo.jdisc.http.HttpRequest.Method.POST, json.toString(), "Application/JSON; charset=utf-8"), jsonResult);
@@ -546,7 +545,7 @@ public class JSONSearchHandlerTestCase {
sb.append("]}");
return sb.toString();
}
- @Ignore
+ @Disabled
public void benchmarkJsonParsing() {
String request = createBenchmarkRequest(768);
for (int i=0; i < 10000; i++) {
@@ -558,4 +557,13 @@ public class JSONSearchHandlerTestCase {
}
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
diff --git a/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java b/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
index d8db88323c7..e421365b541 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
@@ -1,17 +1,17 @@
package com.yahoo.search.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class Json2SinglelevelMapTestCase {
@Test
- public void testDecodeString() {
+ void testDecodeString() {
Map<String, String> m = new Json2SingleLevelMap(new ByteArrayInputStream("{\"yql\":\"text\", \"f1\":7.3, \"i1\":7, \"t\":true, \"f\":false, \"n\":null, \"a\":[0.786, 0.193]}".getBytes(StandardCharsets.UTF_8))).parse();
assertEquals(7, m.size());
assertTrue(m.containsKey("yql"));
@@ -29,4 +29,11 @@ public class Json2SinglelevelMapTestCase {
assertEquals("null", m.get("n"));
assertEquals("[0.786, 0.193]", m.get("a"));
}
+
+ @Test
+ void testThatWeAllowSingleQuotes() {
+ Map<String, String> m = new Json2SingleLevelMap(new ByteArrayInputStream("{'yql':'text'}".getBytes(StandardCharsets.UTF_8))).parse();
+ assertTrue(m.containsKey("yql"));
+ assertEquals("text", m.get("yql"));
+ }
}
diff --git a/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java b/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
index a0374570b69..eb461d6211f 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
@@ -23,12 +23,11 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.config.test.SearchChainConfigurerTestCase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -37,13 +36,7 @@ import java.net.URI;
import java.util.concurrent.Executors;
import static com.yahoo.yolean.Exceptions.uncheckInterrupted;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -56,17 +49,17 @@ public class SearchHandlerTest {
private static String tempDir = "";
- @Rule
- public TemporaryFolder tempfolder = new TemporaryFolder();
+ @TempDir
+ public File tempfolder;
private RequestHandlerTestDriver driver = null;
private HandlersConfigurerTestWrapper configurer = null;
private MockMetric metric;
private SearchHandler searchHandler;
- @Before
+ @BeforeEach
public void startUp() throws IOException {
- File cfgDir = tempfolder.newFolder("SearchHandlerTestCase");
+ File cfgDir = newFolder(tempfolder, "SearchHandlerTestCase");
tempDir = cfgDir.getAbsolutePath();
String configId = "dir:" + tempDir;
@@ -79,7 +72,7 @@ public class SearchHandlerTest {
driver = new RequestHandlerTestDriver(searchHandler);
}
- @After
+ @AfterEach
public void shutDown() {
if (configurer != null) configurer.shutdown();
if (driver != null) driver.close();
@@ -98,30 +91,30 @@ public class SearchHandlerTest {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\">\n" +
- " <hit relevancy=\"1.0\">\n" +
- " <field name=\"relevancy\">1.0</field>\n" +
- " <field name=\"uri\">testHit</field>\n" +
- " </hit>\n" +
- "</result>\n",
- driver.sendRequest("http://localhost?format=xml").readAll()
- );
+ "<result total-hit-count=\"0\">\n" +
+ " <hit relevancy=\"1.0\">\n" +
+ " <field name=\"relevancy\">1.0</field>\n" +
+ " <field name=\"uri\">testHit</field>\n" +
+ " </hit>\n" +
+ "</result>\n",
+ driver.sendRequest("http://localhost?format=xml").readAll()
+ );
}
@Test
- public void testFailing() {
- assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=classLoadingError").readAll().contains("NoClassDefFoundError"));
+ void testFailing() {
+ assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=classLoadingError").readAll().contains("NoClassDefFoundError"));
}
@Test
- public synchronized void testPluginError() {
+ synchronized void testPluginError() {
assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=exceptionInPlugin").readAll().contains("NullPointerException"));
}
@Test
- public synchronized void testWorkingReconfiguration() throws Exception {
+ synchronized void testWorkingReconfiguration() throws Exception {
assertJsonResult("http://localhost?query=abc", driver);
// reconfiguration
@@ -131,17 +124,17 @@ public class SearchHandlerTest {
// ...and check the resulting config
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
- assertNotNull("Have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"));
- assertNull("Don't have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"));
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
+ assertNotNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"), "Have the new search chain");
+ assertNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"), "Don't have the new search chain");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
assertJsonResult("http://localhost?query=abc", newDriver);
}
}
@Test
- @Ignore //TODO: Must be done at the ConfiguredApplication level, not handlers configurer? Also, this must be rewritten as the above
- public synchronized void testFailedReconfiguration() throws Exception {
+ @Disabled //TODO: Must be done at the ConfiguredApplication level, not handlers configurer? Also, this must be rewritten as the above
+ synchronized void testFailedReconfiguration() throws Exception {
assertXmlResult(driver);
// attempt reconfiguration
@@ -150,15 +143,15 @@ public class SearchHandlerTest {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
RequestHandler newMockHandler = configurer.getRequestHandlerRegistry().getComponent("com.yahoo.search.handler.test.MockHandler");
- assertSame("Reconfiguration failed: Kept the existing instance of the search handler", searchHandler, newSearchHandler);
- assertNull("Reconfiguration failed: No mock handler", newMockHandler);
+ assertSame(searchHandler, newSearchHandler, "Reconfiguration failed: Kept the existing instance of the search handler");
+ assertNull(newMockHandler, "Reconfiguration failed: No mock handler");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(searchHandler)) {
assertXmlResult(newDriver);
}
}
@Test
- public void testResponseBasics() {
+ void testResponseBasics() {
Query q = new Query("?query=dummy&tracelevel=3");
q.trace("nalle", 1);
Result r = new Result(q);
@@ -172,13 +165,13 @@ public class SearchHandlerTest {
}
@Test
- public void testInvalidYqlQuery() throws Exception {
+ void testInvalidYqlQuery() throws Exception {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
RequestHandlerTestDriver.MockResponseHandler responseHandler = newDriver.sendRequest(
"http://localhost/search/?yql=select%20*%20from%20foo%20where%20bar%20%3E%201453501295%27%3B");
@@ -189,7 +182,7 @@ public class SearchHandlerTest {
}
@Test
- public void testRequestType() throws Exception {
+ void testRequestType() throws Exception {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
@@ -205,14 +198,14 @@ public class SearchHandlerTest {
// Query handling takes a different code path when a query profile is active, so we test both paths.
@Test
- public void testInvalidQueryParamWithQueryProfile() throws Exception {
+ void testInvalidQueryParamWithQueryProfile() throws Exception {
try (RequestHandlerTestDriver newDriver = driverWithConfig("config_invalid_param")) {
testInvalidQueryParam(newDriver);
}
}
@Test
- public void testInvalidQueryParamWithoutQueryProfile() {
+ void testInvalidQueryParamWithoutQueryProfile() {
testInvalidQueryParam(driver);
}
private void testInvalidQueryParam(final RequestHandlerTestDriver testDriver) {
@@ -225,7 +218,7 @@ public class SearchHandlerTest {
}
@Test
- public void testResultStatus() {
+ void testResultStatus() {
assertEquals(200, httpStatus(result().build()));
assertEquals(200, httpStatus(result().withHit().build()));
assertEquals(200, httpStatus(result().withGroups().build()));
@@ -238,7 +231,7 @@ public class SearchHandlerTest {
}
@Test
- public void testWebServiceStatus() {
+ void testWebServiceStatus() {
RequestHandlerTestDriver.MockResponseHandler responseHandler =
driver.sendRequest("http://localhost/search/?query=web_service_status_code");
String response = responseHandler.readAll();
@@ -247,32 +240,32 @@ public class SearchHandlerTest {
}
@Test
- public void testNormalResultImplicitDefaultRendering() {
+ void testNormalResultImplicitDefaultRendering() {
assertJsonResult("http://localhost?query=abc", driver);
}
@Test
- public void testNormalResultExplicitDefaultRendering() {
+ void testNormalResultExplicitDefaultRendering() {
assertJsonResult("http://localhost?query=abc&format=default", driver);
}
@Test
- public void testNormalResultXmlAliasRendering() {
+ void testNormalResultXmlAliasRendering() {
assertXmlResult("http://localhost?query=abc&format=xml", driver);
}
@Test
- public void testNormalResultJsonAliasRendering() {
+ void testNormalResultJsonAliasRendering() {
assertJsonResult("http://localhost?query=abc&format=json", driver);
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName1() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName1() {
assertXmlResult("http://localhost?query=abc&format=XmlRenderer", driver);
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName2() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName2() {
assertJsonResult("http://localhost?query=abc&format=JsonRenderer", driver);
}
@@ -319,7 +312,7 @@ public class SearchHandlerTest {
}
@Test
- public void testFaultyHandlers() throws Exception {
+ void testFaultyHandlers() throws Exception {
assertHandlerResponse(500, null, "NullReturning");
assertHandlerResponse(500, null, "NullReturningAsync");
assertHandlerResponse(500, null, "Throwing");
@@ -327,7 +320,7 @@ public class SearchHandlerTest {
}
@Test
- public void testForwardingHandlers() throws Exception {
+ void testForwardingHandlers() throws Exception {
assertHandlerResponse(200, jsonResult, "ForwardingAsync");
// Fails because we are forwarding from a sync to an async handler -
@@ -341,9 +334,9 @@ public class SearchHandlerTest {
try (RequestHandlerTestDriver forwardingDriver = new RequestHandlerTestDriver(forwardingHandler)) {
RequestHandlerTestDriver.MockResponseHandler response = forwardingDriver.sendRequest("http://localhost/" + handlerName + "?query=test");
response.awaitResponse();
- assertEquals("Expected HTTP status", status, response.getStatus());
+ assertEquals(status, response.getStatus(), "Expected HTTP status");
if (responseData == null)
- assertNull("Connection closed with no data", response.read());
+ assertNull(response.read(), "Connection closed with no data");
else
assertEquals(responseData, response.readAll());
}
@@ -355,7 +348,7 @@ public class SearchHandlerTest {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Should have a new instance of the search handler", searchHandler, newSearchHandler);
+ assertNotSame(searchHandler, newSearchHandler, "Should have a new instance of the search handler");
return new RequestHandlerTestDriver(newSearchHandler);
}
@@ -387,6 +380,15 @@ public class SearchHandlerTest {
return result;
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
/** Referenced from config */
@@ -396,6 +398,15 @@ public class SearchHandlerTest {
public Result search(Query query, Execution execution) {
throw new NoClassDefFoundError(); // Simulate typical OSGi problem
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
/** Referenced from config */
@@ -411,6 +422,15 @@ public class SearchHandlerTest {
}
return result;
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
/** Referenced from config */
@@ -422,6 +442,15 @@ public class SearchHandlerTest {
result.hits().add(new Hit("HelloWorld"));
return result;
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
/** Referenced from config */
@@ -435,6 +464,15 @@ public class SearchHandlerTest {
result.hits().add(hit);
return result;
}
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
}
/** Referenced from config */
@@ -459,6 +497,15 @@ public class SearchHandlerTest {
}
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
/** Referenced from config */
@@ -483,6 +530,15 @@ public class SearchHandlerTest {
}
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
/** Referenced from config */
@@ -497,6 +553,15 @@ public class SearchHandlerTest {
return null;
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
/** Referenced from config */
@@ -511,6 +576,15 @@ public class SearchHandlerTest {
return null;
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
/** Referenced from config */
@@ -525,6 +599,15 @@ public class SearchHandlerTest {
throw new RuntimeException();
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
/** Referenced from config */
@@ -539,6 +622,15 @@ public class SearchHandlerTest {
throw new RuntimeException();
}
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
}
private ResultBuilder result() { return new ResultBuilder(); }
@@ -564,6 +656,24 @@ public class SearchHandlerTest {
public Result build() { return result; }
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
+ }
+
+ }
+
+ private static File newFolder(File root, String... subDirs) throws IOException {
+ String subFolder = String.join("/", subDirs);
+ File result = new File(root, subFolder);
+ if (!result.mkdirs()) {
+ throw new IOException("Couldn't create folders " + root);
+ }
+ return result;
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java b/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
index eff9c2f558f..4df45b26191 100644
--- a/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
+++ b/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
@@ -6,17 +6,16 @@ import com.yahoo.document.datatypes.WeightedSet;
import com.yahoo.search.Result;
import com.yahoo.search.match.DocumentDb;
import com.yahoo.text.MapParser;
-import org.junit.Ignore;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
public class DocumentDbTest {
@Test
- @Ignore
- public void testWand() {
+ @Disabled
+ void testWand() {
DocumentDb db = new DocumentDb();
- db.put(createFeatureDocument("1","[a:7, b:5, c:3]"));
+ db.put(createFeatureDocument("1", "[a:7, b:5, c:3]"));
db.put(createFeatureDocument("2", "[a:2, b:1, c:4]"));
//Result r = execute(createWandQuery("[a:1, b:3, c:5]"));
//assertEquals(67,r.hits().get(0).getRelevance());
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
index b8457344944..5b4f4e82221 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
@@ -8,13 +8,11 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.Placeholder;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.pagetemplates.model.Source;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -24,13 +22,13 @@ public class MapPageTemplateXMLReadingTestCase {
private String root="src/test/java/com/yahoo/search/pagetemplates/config/test/examples/mapexamples/";
@Test
- public void testMap1() {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root);
+ void testMap1() {
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root);
assertCorrectMap1(registry.getComponent("map1"));
}
private void assertCorrectMap1(PageTemplate page) {
- assertNotNull("map1 was read",page);
+ assertNotNull(page,"map1 was read");
Section root=page.getSection();
assertTrue(((Section)((Section)root.elements(Section.class).get(0)).elements(Section.class).get(0)).elements().get(0) instanceof Placeholder);
assertTrue(((Section)((Section)root.elements(Section.class).get(0)).elements(Section.class).get(1)).elements().get(0) instanceof Placeholder);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
index 1b845802ec3..5994cad468d 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
@@ -13,15 +13,12 @@ import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Renderer;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.pagetemplates.model.Source;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -31,8 +28,8 @@ public class PageTemplateXMLReadingTestCase {
private String root="src/test/java/com/yahoo/search/pagetemplates/config/test/";
@Test
- public void testExamples() {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root + "examples");
+ void testExamples() {
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root + "examples");
assertCorrectSerp(registry.getComponent("serp"));
assertCorrectSlottingSerp(registry.getComponent("slottingSerp"));
assertCorrectRichSerp(registry.getComponent("richSerp"));
@@ -42,7 +39,7 @@ public class PageTemplateXMLReadingTestCase {
}
@Test
- public void testConfigReading() {
+ void testConfigReading() {
PageTemplatesConfig config = new PageTemplatesConfig(new PageTemplatesConfig.Builder()
.page("<page id=\"slottingSerp\" layout=\"mainAndRight\">\n <section layout=\"column\" region=\"main\" source=\"*\" order=\"-[rank]\"/>\n <section layout=\"column\" region=\"right\" source=\"ads\"/>\n</page>\n")
.page("<page id=\"richSerp\" layout=\"mainAndRight\">\n <section layout=\"row\" region=\"main\">\n <section layout=\"column\" description=\"left main pane\">\n <section layout=\"row\" max=\"5\" description=\"Bar of images, from one of two possible sources\">\n <choice method=\"annealing\">\n <source name=\"images\"/>\n <source name=\"flickr\"/>\n </choice>\n </section>\n <section max=\"1\" source=\"local map video ticker weather\" description=\"A single relevant graphically rich element\"/>\n <section order=\"-[rank]\" max=\"10\" source=\"web news\" description=\"Various kinds of traditional search results\"/>\n </section>\n <section layout=\"column\" order=\"[source]\" source=\"answers blogs twitter\" description=\"right main pane, ugc stuff, grouped by source\"/>\n </section>\n <section layout=\"column\" source=\"ads\" region=\"right\"/>\n</page>\n")
@@ -57,19 +54,19 @@ public class PageTemplateXMLReadingTestCase {
}
@Test
- public void testInvalidFilename() {
+ void testInvalidFilename() {
try {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root + "examples/invalidfilename");
- assertEquals(0,registry.allComponents().size());
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root + "examples/invalidfilename");
+ assertEquals(0, registry.allComponents().size());
fail("Should have caused an exception");
}
catch (IllegalArgumentException e) {
- assertEquals("The file name of page template 'notinvalid' must be 'notinvalid.xml' but was 'invalid.xml'",e.getMessage());
+ assertEquals("The file name of page template 'notinvalid' must be 'notinvalid.xml' but was 'invalid.xml'", e.getMessage());
}
}
protected void assertCorrectSerp(PageTemplate page) {
- assertNotNull("'serp' was read",page);
+ assertNotNull(page,"'serp' was read");
Section rootSection=page.getSection();
assertNotNull(rootSection);
assertEquals("mainAndRight",rootSection.getLayout().getName());
@@ -84,7 +81,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectSlottingSerp(PageTemplate page) {
- assertNotNull("'slotting serp' was read",page);
+ assertNotNull(page,"'slotting serp' was read");
Section rootSection=page.getSection();
Section main=(Section)rootSection.elements(Section.class).get(0);
assertEquals("-[rank]",main.getOrder().toString());
@@ -94,7 +91,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectRichSerp(PageTemplate page) {
- assertNotNull("'rich serp' was read",page);
+ assertNotNull(page,"'rich serp' was read");
Section rootSection=page.getSection();
assertNotNull(rootSection);
assertEquals("mainAndRight",rootSection.getLayout().getName());
@@ -129,7 +126,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectRicherSerp(PageTemplate page) {
- assertNotNull("'richer serp' was read",page);
+ assertNotNull(page,"'richer serp' was read");
// Check resolution as we go
Resolver resolver=new DeterministicResolver();
@@ -139,7 +136,7 @@ public class PageTemplateXMLReadingTestCase {
assertNotNull(root);
assertEquals("column",root.getLayout().getName());
- assertEquals("Sections was correctly imported and combined with the section in this",4,root.elements(Section.class).size());
+ assertEquals(4,root.elements(Section.class).size(),"Sections was correctly imported and combined with the section in this");
assertCorrectHeader((Section)root.elements(Section.class).get(0));
@@ -218,14 +215,13 @@ public class PageTemplateXMLReadingTestCase {
Set<String> sourceNames=new HashSet<>();
for (Source source : page.getSources())
sourceNames.add(source.getName());
- assertEquals("Expected " + expectedSourceNames.length + " elements in " + sourceNames,
- expectedSourceNames.length,sourceNames.size());
+ assertEquals(expectedSourceNames.length,sourceNames.size(),"Expected " + expectedSourceNames.length + " elements in " + sourceNames);
for (String expectedSourceName : expectedSourceNames)
- assertTrue("Sources did not include '" + expectedSourceName+ "'",sourceNames.contains(expectedSourceName));
+ assertTrue(sourceNames.contains(expectedSourceName),"Sources did not include '" + expectedSourceName+ "'");
}
protected void assertCorrectIncluder(PageTemplate page) {
- assertNotNull("'includer' was read",page);
+ assertNotNull(page,"'includer' was read");
Resolution resolution=new DeterministicResolver().resolve(Choice.createSingleton(page),null,null);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
index 4ee07db691b..7e72a57b1dc 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
@@ -9,9 +9,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -19,41 +19,41 @@ import static org.junit.Assert.assertEquals;
public class AnySourceTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("AnySource.xml"));
+ Choice page = Choice.createSingleton(importPage("AnySource.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve (noop here)
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// all three sources, ordered by relevance, source 3 first in each relevance group
- HitGroup hits=result.hits();
- assertEquals(9,hits.size());
- assertEquals("source3-1",hits.get(0).getId().stringValue());
- assertEquals("source1-1",hits.get(1).getId().stringValue());
- assertEquals("source2-1",hits.get(2).getId().stringValue());
- assertEquals("source3-2",hits.get(3).getId().stringValue());
- assertEquals("source1-2",hits.get(4).getId().stringValue());
- assertEquals("source2-2",hits.get(5).getId().stringValue());
- assertEquals("source3-3",hits.get(6).getId().stringValue());
- assertEquals("source1-3",hits.get(7).getId().stringValue());
- assertEquals("source2-3",hits.get(8).getId().stringValue());
+ HitGroup hits = result.hits();
+ assertEquals(9, hits.size());
+ assertEquals("source3-1", hits.get(0).getId().stringValue());
+ assertEquals("source1-1", hits.get(1).getId().stringValue());
+ assertEquals("source2-1", hits.get(2).getId().stringValue());
+ assertEquals("source3-2", hits.get(3).getId().stringValue());
+ assertEquals("source1-2", hits.get(4).getId().stringValue());
+ assertEquals("source2-2", hits.get(5).getId().stringValue());
+ assertEquals("source3-3", hits.get(6).getId().stringValue());
+ assertEquals("source1-3", hits.get(7).getId().stringValue());
+ assertEquals("source2-3", hits.get(8).getId().stringValue());
// Check rendering
- assertRendered(result,"AnySourceResult.xml");
+ assertRendered(result, "AnySourceResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
index b495f68464e..227afbce9dc 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
@@ -10,9 +10,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Renderer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -21,31 +21,31 @@ public class ChoiceOfRenderersTestCase extends ExecutionAbstractTestCase {
//This test is order dependent. Fix this!!
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("ChoiceOfRenderers.xml"));
+ Choice page = Choice.createSingleton(importPage("ChoiceOfRenderers.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
- assertEquals(1,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Renderer.class).get(0)));
- assertEquals(2,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Renderer.class).get(1)));
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
+ assertEquals(1, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Renderer.class).get(0)));
+ assertEquals(2, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Renderer.class).get(1)));
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
- assertEquals(6,result.getConcreteHitCount());
- assertEquals(6,result.getHitCount());
+ assertEquals(6, result.getConcreteHitCount());
+ assertEquals(6, result.getHitCount());
// Check rendering
- assertRendered(result,"ChoiceOfRenderersResult.xml");
+ assertRendered(result, "ChoiceOfRenderersResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
index 332d8612954..50db2810630 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class ChoiceOfSubsectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("ChoiceOfSubsections.xml"));
@@ -38,8 +38,8 @@ public class ChoiceOfSubsectionsTestCase extends ExecutionAbstractTestCase {
// Check execution:
// Two subsections with one source each
assertEquals(2, result.hits().size());
- HitGroup section1 = (HitGroup)result.hits().get(0);
- HitGroup section2 = (HitGroup)result.hits().get(1);
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertEquals("section", section1.types().stream().collect(Collectors.joining(", ")));
assertEquals("section", section2.types().stream().collect(Collectors.joining(", ")));
assertEqualHitGroups(createHits("source2", 3), section1);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
index b7fb22713f2..8849f73cfb6 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
@@ -10,9 +10,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Source;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -20,32 +20,32 @@ import static org.junit.Assert.assertEquals;
public class ChoiceOfTwoSourcesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("ChoiceOfTwoSources.xml"));
+ Choice page = Choice.createSingleton(importPage("ChoiceOfTwoSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
- assertEquals(1,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Source.class).get(0)));
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
+ assertEquals(1, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Source.class).get(0)));
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// No subsections: Last choice (source2) used
- assertEqualHitGroups(createHits("source2",3),result.hits());
+ assertEqualHitGroups(createHits("source2", 3), result.hits());
// Check rendering
- assertRendered(result,"ChoiceOfTwoSourcesResult.xml");
+ assertRendered(result, "ChoiceOfTwoSourcesResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
index 629d690fda2..17d59b3e22f 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
@@ -9,7 +9,7 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.PageElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -20,31 +20,31 @@ import java.util.List;
public class ChoicesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template (second alternative will be chosen)
- List<PageElement> pages=new ArrayList<>();
+ List<PageElement> pages = new ArrayList<>();
pages.add(importPage("AnySource.xml"));
pages.add(importPage("Choices.xml"));
- Choice page=Choice.createSingletons(pages);
+ Choice page = Choice.createSingletons(pages);
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("news",3));
- result.hits().add(createHits("web",3));
- result.hits().add(createHits("blog",3));
- result.hits().add(createHits("images",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("news", 3));
+ result.hits().add(createHits("web", 3));
+ result.hits().add(createHits("blog", 3));
+ result.hits().add(createHits("images", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check rendering
- assertRendered(result,"ChoicesResult.xml");
+ assertRendered(result, "ChoicesResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
index 5a8a4dfa9d2..3645b0efe37 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
@@ -14,7 +14,7 @@ import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,7 +25,7 @@ public class ExecutionAbstractTestCase {
protected PageTemplate importPage(String name) {
PageTemplate template=new PageTemplateXMLReader().readFile(root + name);
- assertNotNull("Could look up page template '" + name + "'",template);
+ assertNotNull(template,"Could look up page template '" + name + "'");
return template;
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
index 770e7f524e8..284c719b05e 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
@@ -13,13 +13,13 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.PageElement;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -27,52 +27,52 @@ import static org.junit.Assert.assertNotNull;
public class MapSectionsToSectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("MapSectionsToSections.xml"));
+ Choice page = Choice.createSingleton(importPage("MapSectionsToSections.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",5));
- result.hits().add(createHits("source4",6));
- result.hits().add(createHits("source5",7));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 5));
+ result.hits().add(createHits("source4", 6));
+ result.hits().add(createHits("source5", 7));
// Resolve
- Resolver resolver=new DeterministicResolverAssertingMethod();
- Resolution resolution=resolver.resolve(page,query,result);
- Map<String, List<PageElement>> mapping=
- resolution.getResolution((MapChoice)((PageTemplate)page.get(0).get(0)).getSection().elements().get(2));
+ Resolver resolver = new DeterministicResolverAssertingMethod();
+ Resolution resolution = resolver.resolve(page, query, result);
+ Map<String, List<PageElement>> mapping =
+ resolution.getResolution((MapChoice) ((PageTemplate) page.get(0).get(0)).getSection().elements().get(2));
assertNotNull(mapping);
- assertEquals("box1",((Section)mapping.get("box1holder").get(0)).getId());
- assertEquals("box2",((Section)mapping.get("box2holder").get(0)).getId());
- assertEquals("box3",((Section)mapping.get("box3holder").get(0)).getId());
- assertEquals("box4",((Section)mapping.get("box4holder").get(0)).getId());
+ assertEquals("box1", ((Section) mapping.get("box1holder").get(0)).getId());
+ assertEquals("box2", ((Section) mapping.get("box2holder").get(0)).getId());
+ assertEquals("box3", ((Section) mapping.get("box3holder").get(0)).getId());
+ assertEquals("box4", ((Section) mapping.get("box4holder").get(0)).getId());
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// Two subsections, each containing two sub-subsections with one source each
- assertEquals(2,result.hits().size());
- HitGroup row1=(HitGroup)result.hits().get(0);
- HitGroup column11=(HitGroup)row1.get(0);
- HitGroup column12=(HitGroup)row1.get(1);
- HitGroup row2=(HitGroup)result.hits().get(1);
- HitGroup column21a=(HitGroup)row2.get(0);
- HitGroup column21b=(HitGroup)row2.get(1);
- HitGroup column22=(HitGroup)row2.get(2);
- assertEqualHitGroups(createHits("source1",3),column11);
- assertEqualHitGroups(createHits("source2",4),column12);
- assertEqualHitGroups(createHits("source3",5),column21a);
- assertEqualHitGroups(createHits("source5",7),column21b);
- assertEqualHitGroups(createHits("source4",6),column22);
+ assertEquals(2, result.hits().size());
+ HitGroup row1 = (HitGroup) result.hits().get(0);
+ HitGroup column11 = (HitGroup) row1.get(0);
+ HitGroup column12 = (HitGroup) row1.get(1);
+ HitGroup row2 = (HitGroup) result.hits().get(1);
+ HitGroup column21a = (HitGroup) row2.get(0);
+ HitGroup column21b = (HitGroup) row2.get(1);
+ HitGroup column22 = (HitGroup) row2.get(2);
+ assertEqualHitGroups(createHits("source1", 3), column11);
+ assertEqualHitGroups(createHits("source2", 4), column12);
+ assertEqualHitGroups(createHits("source3", 5), column21a);
+ assertEqualHitGroups(createHits("source5", 7), column21b);
+ assertEqualHitGroups(createHits("source4", 6), column22);
// Check rendering
- assertRendered(result,"MapSectionsToSectionsResult.xml");
+ assertRendered(result, "MapSectionsToSectionsResult.xml");
}
/** Same as deterministic resolver, but asserts that it received the correct method names for each map choice */
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
index 8d8e39bd934..4d844c50cc9 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
@@ -13,13 +13,13 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.PageElement;
import com.yahoo.search.pagetemplates.model.Source;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -27,50 +27,50 @@ import static org.junit.Assert.assertNotNull;
public class MapSourcesToSectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("MapSourcesToSections.xml"));
+ Choice page = Choice.createSingleton(importPage("MapSourcesToSections.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",5));
- result.hits().add(createHits("source4",6));
- result.hits().add(createHits("source5",7));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 5));
+ result.hits().add(createHits("source4", 6));
+ result.hits().add(createHits("source5", 7));
// Resolve
- Resolver resolver=new DeterministicResolverAssertingMethod();
- Resolution resolution=resolver.resolve(page,query,result);
- Map<String, List<PageElement>> mapping=
- resolution.getResolution((MapChoice)((PageTemplate)page.get(0).get(0)).getSection().elements().get(2));
+ Resolver resolver = new DeterministicResolverAssertingMethod();
+ Resolution resolution = resolver.resolve(page, query, result);
+ Map<String, List<PageElement>> mapping =
+ resolution.getResolution((MapChoice) ((PageTemplate) page.get(0).get(0)).getSection().elements().get(2));
assertNotNull(mapping);
- assertEquals("source1",((Source)mapping.get("box1source").get(0)).getName());
- assertEquals("source2",((Source)mapping.get("box2source").get(0)).getName());
- assertEquals("source3",((Source)mapping.get("box3source").get(0)).getName());
- assertEquals("source4",((Source)mapping.get("box4source").get(0)).getName());
+ assertEquals("source1", ((Source) mapping.get("box1source").get(0)).getName());
+ assertEquals("source2", ((Source) mapping.get("box2source").get(0)).getName());
+ assertEquals("source3", ((Source) mapping.get("box3source").get(0)).getName());
+ assertEquals("source4", ((Source) mapping.get("box4source").get(0)).getName());
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// Two subsections, each containing two sub-subsections with one source each
- assertEquals(2,result.hits().size());
- HitGroup row1=(HitGroup)result.hits().get(0);
- HitGroup column11=(HitGroup)row1.get(0);
- HitGroup column12=(HitGroup)row1.get(1);
- HitGroup row2=(HitGroup)result.hits().get(1);
- HitGroup column21=(HitGroup)row2.get(0);
- HitGroup column22=(HitGroup)row2.get(1);
- assertEqualHitGroups(createHits("source1",3),column11);
- assertEqualHitGroups(createHits("source2",4),column12);
- assertEqualHitGroups(createHits("source3",5),column21);
- assertEqualHitGroups(createHits("source4",6),column22);
+ assertEquals(2, result.hits().size());
+ HitGroup row1 = (HitGroup) result.hits().get(0);
+ HitGroup column11 = (HitGroup) row1.get(0);
+ HitGroup column12 = (HitGroup) row1.get(1);
+ HitGroup row2 = (HitGroup) result.hits().get(1);
+ HitGroup column21 = (HitGroup) row2.get(0);
+ HitGroup column22 = (HitGroup) row2.get(1);
+ assertEqualHitGroups(createHits("source1", 3), column11);
+ assertEqualHitGroups(createHits("source2", 4), column12);
+ assertEqualHitGroups(createHits("source3", 5), column21);
+ assertEqualHitGroups(createHits("source4", 6), column22);
// Check rendering
- assertRendered(result,"MapSourcesToSectionsResult.xml");
+ assertRendered(result, "MapSourcesToSectionsResult.xml");
}
/** Same as deterministic resolver, but asserts that it received the correct method names for each map choice */
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
index 6a86f4f81aa..a985c7435d8 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an example page.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("Page.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
index 69d35eb2b69..a4166b6d90f 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an expanded example.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageWithBlendingTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("PageWithBlending.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
index 8cb35bf5e4f..7becf7f1895 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an example with two data sources with a renderer each.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageWithSourceRendererTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("PageWithSourceRenderer.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
index bcd6a462a62..349c39514ba 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -16,7 +16,7 @@ import org.junit.Test;
public class SourceChoiceTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("SourceChoice.xml"));
@@ -29,14 +29,14 @@ public class SourceChoiceTestCase extends ExecutionAbstractTestCase {
// Resolve (noop here)
Resolver resolver = new DeterministicResolver();
- Resolution resolution = resolver.resolve(page,query,result);
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
Organizer organizer = new Organizer();
organizer.organize(page, resolution, result);
// Check rendering
- assertRendered(result,"SourceChoiceResult.xml", false);
+ assertRendered(result, "SourceChoiceResult.xml", false);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
index 8413b43e662..43bb16f8b14 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
@@ -8,11 +8,11 @@ import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -20,95 +20,95 @@ import static org.junit.Assert.assertEquals;
public class TwoSectionsFourSourcesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",12));
- result.hits().add(createHits("source4",13));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 12));
+ result.hits().add(createHits("source4", 13));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
assertBlendedSource4Source2(section2.asList());
// Check rendering
- assertRendered(result,"TwoSectionsFourSourcesResult.xml");
+ assertRendered(result, "TwoSectionsFourSourcesResult.xml");
}
@Test
- public void testExecutionMissingOneSource() {
+ void testExecutionMissingOneSource() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source3",12));
- result.hits().add(createHits("source4",13));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source3", 12));
+ result.hits().add(createHits("source4", 13));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
- assertEqualHitGroups(createHits("source4",10),section2);
+ assertEqualHitGroups(createHits("source4", 10), section2);
}
@Test
- public void testExecutionMissingTwoSources() {
+ void testExecutionMissingTwoSources() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source3",12));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source3", 12));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
- assertEquals(0,section2.size());
+ assertEquals(0, section2.size());
}
@Test
- public void testExecutionMissingAllSources() {
+ void testExecutionMissingAllSources() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
+ Query query = new Query();
+ Result result = new Result(query);
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
- assertEquals(0,section1.size());
- assertEquals(0,section2.size());
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
+ assertEquals(0, section1.size());
+ assertEquals(0, section2.size());
}
private void assertGroupedSource3Source1(List<Hit> hits) {
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
index 7b10966a675..a38c3f164b9 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
@@ -18,15 +18,11 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.text.interpretation.Interpretation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -34,50 +30,50 @@ import static org.junit.Assert.fail;
public class PageTemplateSearcherTestCase {
@Test
- public void testSearcher() {
+ void testSearcher() {
PageTemplateSearcher s = new PageTemplateSearcher(createPageTemplateRegistry(), new FirstChoiceResolver());
- Chain<Searcher> chain = new Chain<>(s,new MockFederator());
+ Chain<Searcher> chain = new Chain<>(s, new MockFederator());
{
// No template specified, should use default
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.resolver=native.deterministic"));
- assertSources("source1 source2",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.resolver=native.deterministic"));
+ assertSources("source1 source2", result);
}
{
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=oneSource&page.resolver=native.deterministic"));
- assertSources("source1",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=oneSource&page.resolver=native.deterministic"));
+ assertSources("source1", result);
}
{
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=twoSources&model.sources=source1&page.resolver=native.deterministic"));
- assertSources("source1",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=twoSources&model.sources=source1&page.resolver=native.deterministic"));
+ assertSources("source1", result);
}
{
- Query query=new Query("?query=foo&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", result);
}
{
- Query query=new Query("?query=foo&page.id=twoSourcesAndAny&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.id=twoSourcesAndAny&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", result);
}
{
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source3",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source3", result);
}
{
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
assertTrue(query.getModel().getSources().isEmpty());
assertNotNull(result.hits().get("source1"));
assertNotNull(result.hits().get("source2"));
@@ -85,38 +81,38 @@ public class PageTemplateSearcherTestCase {
}
{
- Query query=new Query("?query=foo&page.id=choiceOfSources&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2","source2",result);
+ Query query = new Query("?query=foo&page.id=choiceOfSources&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", "source2", result);
}
{
- Query query=new Query("?query=foo&page.id=choiceOfSources&page.resolver=test.firstChoice");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2","source1",result);
+ Query query = new Query("?query=foo&page.id=choiceOfSources&page.resolver=test.firstChoice");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", "source1", result);
}
{ // Specifying two templates, should pick the last
- Query query=new Query("?query=foo&page.id=threeSources+oneSource&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3","source1",result);
+ Query query = new Query("?query=foo&page.id=threeSources+oneSource&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", "source1", result);
}
{ // Specifying two templates as a list, should override the page.id setting
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
- query.properties().set("page.idList",Arrays.asList("oneSource","threeSources"));
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3","source1 source2 source3",result);
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ query.properties().set("page.idList", Arrays.asList("oneSource", "threeSources"));
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", "source1 source2 source3", result);
}
{
try {
- Query query=new Query("?query=foo&page.id=oneSource+choiceOfSources&page.resolver=noneSuch");
+ Query query = new Query("?query=foo&page.id=oneSource+choiceOfSources&page.resolver=noneSuch");
new Execution(chain, Execution.Context.createContextStub()).search(query);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
- assertEquals("No page template resolver 'noneSuch'",e.getMessage());
+ assertEquals("No page template resolver 'noneSuch'", e.getMessage());
}
}
@@ -182,9 +178,9 @@ public class PageTemplateSearcherTestCase {
Set<String> expectedResultSources=new HashSet<>(Arrays.asList(expectedResultSourceString.split(" ")));
for (String sourceName : Arrays.asList("source1 source2 source3".split(" "))) {
if (expectedResultSources.contains(sourceName))
- assertNotNull("Result contains '" + sourceName + "'",result.hits().get(sourceName));
+ assertNotNull(result.hits().get(sourceName),"Result contains '" + sourceName + "'");
else
- assertNull("Result does not contain '" + sourceName + "'",result.hits().get(sourceName));
+ assertNull(result.hits().get(sourceName),"Result does not contain '" + sourceName + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
index 0606636d0cb..50a19753e0c 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.search.pagetemplates.PageTemplateRegistry;
import com.yahoo.search.pagetemplates.PageTemplateSearcher;
import com.yahoo.search.pagetemplates.config.PageTemplateXMLReader;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -20,40 +20,40 @@ public class SourceParametersTestCase {
private static final String root="src/test/java/com/yahoo/search/pagetemplates/test/";
@Test
- public void testSourceParametersWithSourcesDeterminedByTemplate() {
+ void testSourceParametersWithSourcesDeterminedByTemplate() {
// Create the page template
- PageTemplateRegistry pageTemplateRegistry=new PageTemplateRegistry();
- PageTemplate page=importPage("SourceParameters.xml");
+ PageTemplateRegistry pageTemplateRegistry = new PageTemplateRegistry();
+ PageTemplate page = importPage("SourceParameters.xml");
pageTemplateRegistry.register(page);
- PageTemplateSearcher s=new PageTemplateSearcher(pageTemplateRegistry);
- Query query=new Query("?query=foo&page.id=SourceParameters&page.resolver=native.deterministic");
+ PageTemplateSearcher s = new PageTemplateSearcher(pageTemplateRegistry);
+ Query query = new Query("?query=foo&page.id=SourceParameters&page.resolver=native.deterministic");
new Execution(s, Execution.Context.createContextStub()).search(query);
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source2p1Value",query.properties().get("source.source2.p1"));
- assertEquals("source2p3Value",query.properties().get("source.source2.p3"));
- assertEquals("source3p1Value",query.properties().get("source.source3.p1"));
- assertEquals("We get the correct number of parameters",5,query.properties().listProperties("source").size());
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source2p1Value", query.properties().get("source.source2.p1"));
+ assertEquals("source2p3Value", query.properties().get("source.source2.p3"));
+ assertEquals("source3p1Value", query.properties().get("source.source3.p1"));
+ assertEquals(5, query.properties().listProperties("source").size(), "We get the correct number of parameters");
}
@Test
- public void testSourceParametersWithSourcesDeterminedByParameter() {
+ void testSourceParametersWithSourcesDeterminedByParameter() {
// Create the page template
- PageTemplateRegistry pageTemplateRegistry=new PageTemplateRegistry();
- PageTemplate page=importPage("SourceParameters.xml");
+ PageTemplateRegistry pageTemplateRegistry = new PageTemplateRegistry();
+ PageTemplate page = importPage("SourceParameters.xml");
pageTemplateRegistry.register(page);
- PageTemplateSearcher s=new PageTemplateSearcher(pageTemplateRegistry);
- Query query=new Query("?query=foo&page.id=SourceParameters&model.sources=source1,source3&page.resolver=native.deterministic");
+ PageTemplateSearcher s = new PageTemplateSearcher(pageTemplateRegistry);
+ Query query = new Query("?query=foo&page.id=SourceParameters&model.sources=source1,source3&page.resolver=native.deterministic");
new Execution(s, Execution.Context.createContextStub()).search(query);
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source3p1Value",query.properties().get("source.source3.p1"));
- assertEquals("We get the correct number of parameters",3,query.properties().listProperties("source").size());
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source3p1Value", query.properties().get("source.source3.p1"));
+ assertEquals(3, query.properties().listProperties("source").size(), "We get the correct number of parameters");
}
protected PageTemplate importPage(String name) {
PageTemplate template=new PageTemplateXMLReader().readFile(root + name);
- assertNotNull("Could look up read template '" + name + "'",template);
+ assertNotNull(template,"Could look up read template '" + name + "'");
return template;
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
index 9eb44eb0dc4..e3a1eb18a33 100644
--- a/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
@@ -2,10 +2,9 @@
package com.yahoo.search.query;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -13,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class MatchingTestCase {
@Test
- public void testDefaultsInQuery() {
+ void testDefaultsInQuery() {
Query query = new Query("?query=test");
assertNull(query.getRanking().getMatching().getTermwiseLimit());
assertNull(query.getRanking().getMatching().getNumThreadsPerSearch());
@@ -24,7 +23,7 @@ public class MatchingTestCase {
}
@Test
- public void testQueryOverrides() {
+ void testQueryOverrides() {
Query query = new Query("?query=test" +
"&ranking.matching.termwiseLimit=0.7" +
"&ranking.matching.numThreadsPerSearch=17" +
@@ -49,7 +48,7 @@ public class MatchingTestCase {
}
@Test
- public void testBackwardsCompatibleQueryOverrides() {
+ void testBackwardsCompatibleQueryOverrides() {
// The lowercase aliases are supported to provide backwards compatibility of the properties that was wrongly named in the first place.
Query query = new Query("?query=test" +
"&ranking.matching.termwiselimit=0.7" +
@@ -73,7 +72,7 @@ public class MatchingTestCase {
}
@Test
- public void testLimits() {
+ void testLimits() {
verifyException("termwiselimit", "-0.1");
verifyException("termwiselimit", "1.1");
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java b/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
index 6c73937f4fa..4badb16f20c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
@@ -4,9 +4,9 @@ package com.yahoo.search.query;
import com.yahoo.prelude.query.NotItem;
import com.yahoo.prelude.query.NullItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Assert;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -14,53 +14,53 @@ import static org.junit.Assert.assertEquals;
public class QueryTreeTest {
@Test
- public void testAddQueryItemWithRoot() {
- Assert.assertEquals("AND a b",
- new QueryTree(new WordItem("a")).and(new WordItem("b")).toString());
+ void testAddQueryItemWithRoot() {
+ assertEquals("AND a b",
+ new QueryTree(new WordItem("a")).and(new WordItem("b")).toString());
NotItem not = new NotItem();
not.addNegativeItem(new WordItem("b"));
assertEquals("+a -b",
- new QueryTree(new WordItem("a")).and(not).toString());
- }
+ new QueryTree(new WordItem("a")).and(not).toString());
+ }
- @Test
- public void addNotToNot() {
- NotItem not1 = new NotItem();
- not1.addPositiveItem(new WordItem("p1"));
- not1.addNegativeItem(new WordItem("n1.1"));
- not1.addNegativeItem(new WordItem("n1.2"));
+ @Test
+ void addNotToNot() {
+ NotItem not1 = new NotItem();
+ not1.addPositiveItem(new WordItem("p1"));
+ not1.addNegativeItem(new WordItem("n1.1"));
+ not1.addNegativeItem(new WordItem("n1.2"));
- NotItem not2 = new NotItem();
- not2.addPositiveItem(new WordItem("p2"));
- not2.addNegativeItem(new WordItem("n2.1"));
- not2.addNegativeItem(new WordItem("n2.2"));
+ NotItem not2 = new NotItem();
+ not2.addPositiveItem(new WordItem("p2"));
+ not2.addNegativeItem(new WordItem("n2.1"));
+ not2.addNegativeItem(new WordItem("n2.2"));
- QueryTree tree = new QueryTree(not1);
- tree.and(not2);
+ QueryTree tree = new QueryTree(not1);
+ tree.and(not2);
- assertEquals("+(AND p1 p2) -n1.1 -n1.2 -n2.1 -n2.2", tree.toString());
- }
+ assertEquals("+(AND p1 p2) -n1.1 -n1.2 -n2.1 -n2.2", tree.toString());
+ }
- @Test
- public void getCorrectTreeSize() {
+ @Test
+ void getCorrectTreeSize() {
QueryTree nullTree = new QueryTree(new NullItem());
assertEquals(0, nullTree.treeSize());
- NotItem not1 = new NotItem();
- not1.addPositiveItem(new WordItem("p1"));
- not1.addNegativeItem(new WordItem("n1.1"));
- not1.addNegativeItem(new WordItem("n1.2"));
+ NotItem not1 = new NotItem();
+ not1.addPositiveItem(new WordItem("p1"));
+ not1.addNegativeItem(new WordItem("n1.1"));
+ not1.addNegativeItem(new WordItem("n1.2"));
- NotItem not2 = new NotItem();
- not2.addPositiveItem(new WordItem("p2"));
- not2.addNegativeItem(new WordItem("n2.1"));
- not2.addNegativeItem(new WordItem("n2.2"));
+ NotItem not2 = new NotItem();
+ not2.addPositiveItem(new WordItem("p2"));
+ not2.addNegativeItem(new WordItem("n2.1"));
+ not2.addNegativeItem(new WordItem("n2.2"));
- QueryTree tree = new QueryTree(not1);
- tree.and(not2);
+ QueryTree tree = new QueryTree(not1);
+ tree.and(not2);
- assertEquals(8, tree.treeSize());
- }
+ assertEquals(8, tree.treeSize());
+ }
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java b/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
index e30e8bf119a..da1d09fec1e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
@@ -14,7 +14,7 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -23,9 +23,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests queries towards rank profiles using input declarations.
@@ -35,7 +33,7 @@ import static org.junit.Assert.fail;
public class RankProfileInputTest {
@Test
- public void testTensorRankFeatureInRequest() {
+ void testTensorRankFeatureInRequest() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
{
@@ -55,13 +53,12 @@ public class RankProfileInputTest {
{ // Resolution is limited to the correct sources
Query query = createTensor1Query(tensorString, "bOnly", "sources=a");
assertEquals(0, query.errors().size());
- assertEquals("Not converted to tensor",
- tensorString, query.properties().get("ranking.features.query(myTensor1)"));
+ assertEquals(tensorString, query.properties().get("ranking.features.query(myTensor1)"), "Not converted to tensor");
}
}
@Test
- public void testTensorRankFeatureInRequestInconsistentInput() {
+ void testTensorRankFeatureInRequestInconsistentInput() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
try {
createTensor1Query(tensorString, "inconsistent", "");
@@ -69,14 +66,14 @@ public class RankProfileInputTest {
}
catch (IllegalArgumentException e) {
assertEquals("Conflicting input type declarations for 'query(myTensor1)': " +
- "Declared as tensor(a{},b{}) in rank profile 'inconsistent' in schema 'a', " +
- "and as tensor(x[10]) in rank profile 'inconsistent' in schema 'b'",
- Exceptions.toMessageString(e));
+ "Declared as tensor(a{},b{}) in rank profile 'inconsistent' in schema 'a', " +
+ "and as tensor(x[10]) in rank profile 'inconsistent' in schema 'b'",
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testTensorRankFeatureWithSourceResolution() {
+ void testTensorRankFeatureWithSourceResolution() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
{
@@ -99,14 +96,14 @@ public class RankProfileInputTest {
}
@Test
- public void testTensorRankFeatureSetProgrammatically() {
+ void testTensorRankFeatureSetProgrammatically() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query.Builder()
.setSchemaInfo(createSchemaInfo())
.setQueryProfile(createQueryProfile()) // Use the instantiation path with query profiles
.setRequest(HttpRequest.createTestRequest("?" +
- "&ranking=commonProfile",
- com.yahoo.jdisc.http.HttpRequest.Method.GET))
+ "&ranking=commonProfile",
+ com.yahoo.jdisc.http.HttpRequest.Method.GET))
.build();
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -114,24 +111,24 @@ public class RankProfileInputTest {
}
@Test
- public void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
+ void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
Query query = new Query.Builder()
.setSchemaInfo(createSchemaInfo())
.setQueryProfile(createQueryProfile()) // Use the instantiation path with query profiles
.setRequest(HttpRequest.createTestRequest("?" +
- "&ranking=commonProfile",
- com.yahoo.jdisc.http.HttpRequest.Method.GET))
+ "&ranking=commonProfile",
+ com.yahoo.jdisc.http.HttpRequest.Method.GET))
.build();
String tensorString = "tensor(x[3]):[0.1, 0.2, 0.3]";
try {
- query.getRanking().getFeatures().put("query(myTensor1)",Tensor.from(tensorString));
+ query.getRanking().getFeatures().put("query(myTensor1)", Tensor.from(tensorString));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "This input is declared in rank profile 'commonProfile' as tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "This input is declared in rank profile 'commonProfile' as tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
try {
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -139,13 +136,13 @@ public class RankProfileInputTest {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testUnembeddedTensorRankFeatureInRequest() {
+ void testUnembeddedTensorRankFeatureInRequest() {
String text = "text to embed into a tensor";
Tensor embedding1 = Tensor.from("tensor<float>(x[5]):[3,7,4,0,0]]");
Tensor embedding2 = Tensor.from("tensor<float>(x[5]):[1,2,3,4,0]]");
@@ -159,7 +156,7 @@ public class RankProfileInputTest {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb1, \"" + text + "\")", embedding1, embedders);
assertEmbedQueryFails("embed(emb2, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb2'. Valid embedders are emb1");
+ "Can't find embedder 'emb2'. Valid embedders are emb1");
embedders = Map.of(
"emb1", new MockEmbedder(text, Language.UNKNOWN, embedding1),
@@ -168,7 +165,7 @@ public class RankProfileInputTest {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb2, '" + text + "')", embedding2, embedders);
assertEmbedQueryFails("embed(emb3, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb3'. Valid embedders are emb1,emb2");
+ "Can't find embedder 'emb3'. Valid embedders are emb1,emb2");
// And with specified language
embedders = Map.of(
diff --git a/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java b/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
index f8874040cb2..2decb3fb26a 100644
--- a/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
@@ -2,8 +2,9 @@
package com.yahoo.search.query;
import com.yahoo.search.Query;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -11,7 +12,7 @@ import static org.junit.Assert.*;
public class SoftTimeoutTestCase {
@Test
- public void testDefaultsInQuery() {
+ void testDefaultsInQuery() {
Query query = new Query("?query=test");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
assertNull(query.getRanking().getSoftTimeout().getFactor());
@@ -19,7 +20,7 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testQueryOverride() {
+ void testQueryOverride() {
Query query = new Query("?query=test&ranking.softtimeout.factor=0.7&ranking.softtimeout.tailcost=0.3");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
assertEquals(Double.valueOf(0.7), query.getRanking().getSoftTimeout().getFactor());
@@ -31,16 +32,16 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testDisable() {
- Query query=new Query("?query=test&ranking.softtimeout.enable=false");
+ void testDisable() {
+ Query query = new Query("?query=test&ranking.softtimeout.enable=false");
assertFalse(query.getRanking().getSoftTimeout().getEnable());
query.prepare();
assertEquals("false", query.getRanking().getProperties().get("vespa.softtimeout.enable").get(0));
}
@Test
- public void testEnable() {
- Query query=new Query("?query=test&ranking.softtimeout.enable=true");
+ void testEnable() {
+ Query query = new Query("?query=test&ranking.softtimeout.enable=true");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
query.prepare();
assertEquals("true", query.getRanking().getProperties().get("vespa.softtimeout.enable").get(0));
@@ -57,7 +58,7 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testLimits() {
+ void testLimits() {
verifyException("factor", "-0.1");
verifyException("factor", "1.1");
verifyException("tailcost", "-0.1");
diff --git a/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
index 4f14ae066cb..facb620b63b 100644
--- a/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
@@ -5,20 +5,19 @@ import com.ibm.icu.lang.UScript;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.RuleBasedCollator;
import com.ibm.icu.util.ULocale;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
*/
public class SortingTestCase {
@Test
- public void validAttributeName() {
+ void validAttributeName() {
assertNotNull(Sorting.fromString("a"));
assertNotNull(Sorting.fromString("_a"));
assertNotNull(Sorting.fromString("+a"));
@@ -33,8 +32,9 @@ public class SortingTestCase {
fail("I only expect 'IllegalArgumentException', not: + " + e.toString());
}
}
+
@Test
- public void requireThatChineseSortCorrect() {
+ void requireThatChineseSortCorrect() {
requireThatChineseHasCorrectRules(Collator.getInstance(new ULocale("zh")));
Sorting ch = Sorting.fromString("uca(a,zh)");
assertEquals(1, ch.fieldOrders().size());
@@ -69,9 +69,10 @@ public class SortingTestCase {
assertNotEquals("", ((RuleBasedCollator) col).getRules());
}
+
@Test
- @Ignore
- public void requireThatArabicSortCorrect() {
+ @Disabled
+ void requireThatArabicSortCorrect() {
requireThatArabicHasCorrectRules(Collator.getInstance(new ULocale("ar")));
Sorting ar = Sorting.fromString("uca(a,ar)");
assertEquals(1, ar.fieldOrders().size());
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
index 0152367915a..d4f1e814980 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
@@ -8,10 +8,10 @@ import java.util.Set;
import com.yahoo.processing.execution.Execution;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -19,34 +19,34 @@ import static org.junit.Assert.assertTrue;
public class LoggingTestCase {
@Test
- public void testLogging() {
- Query query=new Query();
+ void testLogging() {
+ Query query = new Query();
QueryContext queryContext = query.getContext(true);
- queryContext.logValue("a","a1");
+ queryContext.logValue("a", "a1");
queryContext.trace("first message", 2);
- queryContext.logValue("a","a2");
- queryContext.logValue("b","b1");
+ queryContext.logValue("a", "a2");
+ queryContext.logValue("b", "b1");
QueryContext h2 = query.clone().getContext(true);
- h2.logValue("b","b2");
+ h2.logValue("b", "b2");
h2.trace("second message", 2);
- h2.logValue("b","b3");
- queryContext.logValue("b","b4");
+ h2.logValue("b", "b3");
+ queryContext.logValue("b", "b4");
QueryContext h3 = query.clone().getContext(true);
- h3.logValue("b","b5");
- h3.logValue("c","c1");
+ h3.logValue("b", "b5");
+ h3.logValue("c", "c1");
h3.trace("third message", 2);
- h2.logValue("c","c2");
+ h2.logValue("c", "c2");
queryContext.trace("fourth message", 2);
- queryContext.logValue("d","d1");
+ queryContext.logValue("d", "d1");
h2.trace("fifth message", 2);
- h2.logValue("c","c3");
- queryContext.logValue("c","c4");
+ h2.logValue("c", "c3");
+ queryContext.logValue("c", "c4");
// Assert that all of the above is in the log, in some undefined order
- Set<String> logValues=new HashSet<>();
- for (Iterator<Execution.Trace.LogValue> logValueIterator=queryContext.logValueIterator(); logValueIterator.hasNext(); )
+ Set<String> logValues = new HashSet<>();
+ for (Iterator<Execution.Trace.LogValue> logValueIterator = queryContext.logValueIterator(); logValueIterator.hasNext(); )
logValues.add(logValueIterator.next().toString());
- assertEquals(12,logValues.size());
+ assertEquals(12, logValues.size());
assertTrue(logValues.contains("a=a1"));
assertTrue(logValues.contains("a=a2"));
assertTrue(logValues.contains("b=b1"));
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
index 61e1f06ed28..8505da0e814 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.query.context.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author bratseth
@@ -14,34 +14,34 @@ import static org.junit.Assert.assertNull;
public class PropertiesTestCase {
@Test
- public void testProperties() {
- Query query=new Query();
+ void testProperties() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
- h.setProperty("a","a1");
+ h.setProperty("a", "a1");
h.trace("first message", 2);
- h.setProperty("a","a2");
- h.setProperty("b","b1");
+ h.setProperty("a", "a2");
+ h.setProperty("b", "b1");
query.clone();
QueryContext h2 = query.clone().getContext(true);
- h2.setProperty("b","b2");
+ h2.setProperty("b", "b2");
h2.trace("second message", 2);
- h2.setProperty("b","b3");
- h.setProperty("b","b4");
+ h2.setProperty("b", "b3");
+ h.setProperty("b", "b4");
QueryContext h3 = query.clone().getContext(true);
- h3.setProperty("b","b5");
- h3.setProperty("c","c1");
+ h3.setProperty("b", "b5");
+ h3.setProperty("c", "c1");
h3.trace("third message", 2);
- h2.setProperty("c","c2");
+ h2.setProperty("c", "c2");
h.trace("fourth message", 2);
- h.setProperty("d","d1");
+ h.setProperty("d", "d1");
h2.trace("fifth message", 2);
- h2.setProperty("c","c3");
- h.setProperty("c","c4");
+ h2.setProperty("c", "c3");
+ h.setProperty("c", "c4");
- assertEquals("a2",h.getProperty("a"));
- assertEquals("b5",h.getProperty("b"));
- assertEquals("c4",h.getProperty("c"));
- assertEquals("d1",h.getProperty("d"));
+ assertEquals("a2", h.getProperty("a"));
+ assertEquals("b5", h.getProperty("b"));
+ assertEquals("c4", h.getProperty("c"));
+ assertEquals("d1", h.getProperty("d"));
assertNull(h.getProperty("e"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
index 76f243e4592..a340e83a77c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.search.query.context.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Steinar Knutsen
@@ -19,8 +19,8 @@ import static org.junit.Assert.assertTrue;
public class TraceTestCase {
@Test
- public void testBasicTracing() {
- Query query=new Query();
+ void testBasicTracing() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
h.trace("first message", 0);
h.trace("second message", 0);
@@ -28,8 +28,8 @@ public class TraceTestCase {
}
@Test
- public void testCloning() throws IOException {
- Query query=new Query();
+ void testCloning() throws IOException {
+ Query query = new Query();
QueryContext h = query.getContext(true);
h.trace("first message", 0);
QueryContext h2 = query.clone().getContext(true);
@@ -49,19 +49,19 @@ public class TraceTestCase {
assertEquals(toplevel, finishedBelow);
// basic sanity test
assertEquals("trace: [ [ " +
- "first message second message third message " +
- "fourth message fifth message ] ]",h.toString());
+ "first message second message third message " +
+ "fourth message fifth message ] ]", h.toString());
Iterator<String> i = h.getTrace().traceNode().root().descendants(String.class).iterator();
- assertEquals("first message",i.next());
- assertEquals("second message",i.next());
- assertEquals("third message",i.next());
- assertEquals("fourth message",i.next());
- assertEquals("fifth message",i.next());
+ assertEquals("first message", i.next());
+ assertEquals("second message", i.next());
+ assertEquals("third message", i.next());
+ assertEquals("fourth message", i.next());
+ assertEquals("fifth message", i.next());
}
@Test
- public void testEmpty() throws IOException {
- Query query=new Query();
+ void testEmpty() throws IOException {
+ Query query = new Query();
QueryContext h = query.getContext(true);
Writer w = new StringWriter();
h.render(w);
@@ -69,20 +69,20 @@ public class TraceTestCase {
}
@Test
- public void testEmptySubSequence() {
- Query query=new Query();
+ void testEmptySubSequence() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
query.clone().getContext(true);
Writer w = new StringWriter();
try {
h.render(w);
} catch (IOException e) {
- assertTrue("rendering empty subsequence crashed", false);
+ assertTrue(false, "rendering empty subsequence crashed");
}
}
@Test
- public void testAttachedTraces() throws IOException {
+ void testAttachedTraces() throws IOException {
String needle0 = "nalle";
String needle1 = "tralle";
String needle2 = "trolle";
@@ -101,10 +101,10 @@ public class TraceTestCase {
int tralle = trace.indexOf(needle1);
int trolle = trace.indexOf(needle2);
int bamse = trace.indexOf(needle3);
- assertTrue("Could not find first manual context to main query.", nalle > 0);
- assertTrue("Could not find second manual context to main query.", bamse > 0);
- assertTrue("Could not find first manual context to attached query.", tralle > 0);
- assertTrue("Could not find second manual context to attached query.", trolle > 0);
+ assertTrue(nalle > 0, "Could not find first manual context to main query.");
+ assertTrue(bamse > 0, "Could not find second manual context to main query.");
+ assertTrue(tralle > 0, "Could not find first manual context to attached query.");
+ assertTrue(trolle > 0, "Could not find second manual context to attached query.");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java
new file mode 100644
index 00000000000..a73d12a5a4e
--- /dev/null
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java
@@ -0,0 +1,66 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.search.query.profile;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * @author baldersheim
+ */
+public class ChainedMapTestCase {
+ @Test
+ void testIsEmpty() {
+ assertTrue(new ChainedMap<String, String>(Map.of(), Map.of()).isEmpty());
+ assertFalse(new ChainedMap<>(Map.of("k", "v"), Map.of()).isEmpty());
+ assertFalse(new ChainedMap<>(Map.of(), Map.of("k", "v")).isEmpty());
+ assertFalse(new ChainedMap<>(Map.of("k", "v"), Map.of("k", "v")).isEmpty());
+ }
+
+ @Test
+ void testSize() {
+ assertEquals(0, new ChainedMap<String, String>(Map.of(), Map.of()).size());
+ assertEquals(1, new ChainedMap<>(Map.of("k", "v"), Map.of()).size());
+ assertEquals(1, new ChainedMap<>(Map.of(), Map.of("k", "v")).size());
+ assertEquals(1, new ChainedMap<>(Map.of("k", "v"), Map.of("k", "v")).size());
+ assertEquals(2, new ChainedMap<>(Map.of("k", "v"), Map.of("K", "v")).size());
+ assertEquals(2, new ChainedMap<>(Map.of("k", "v"), Map.of("K", "v", "k", "v")).size());
+ }
+
+ @Test
+ void testGetUsesBoth() {
+ Map<String, String> a = Map.of("a", "a_1");
+ Map<String, String> b = Map.of("b", "b_1");
+ Map<String, String> ab = Map.of("a", "a_2", "b", "b_2");
+ Map<String, String> a_b = new ChainedMap<>(a, b);
+ assertEquals("a_1", a_b.get("a"));
+ assertEquals("b_1", a_b.get("b"));
+
+ Map<String, String> b_a = new ChainedMap<>(a, b);
+ assertEquals("a_1", b_a.get("a"));
+ assertEquals("b_1", b_a.get("b"));
+
+ Map<String, String> a_ab = new ChainedMap<>(a, ab);
+ assertEquals("a_1", a_ab.get("a"));
+ assertEquals("b_2", a_ab.get("b"));
+
+ Map<String, String> ab_a = new ChainedMap<>(ab, a);
+ assertEquals("a_2", ab_a.get("a"));
+ assertEquals("b_2", ab_a.get("b"));
+ }
+
+ @Test
+ void testKeySet() {
+ assertTrue(new ChainedMap<String, String>(Map.of(), Map.of()).keySet().isEmpty());
+ Map<String, String> a = Map.of("a", "a_1");
+ Map<String, String> b = Map.of("b", "b_1");
+ Map<String, String> ab = Map.of("a", "a_2", "b", "b_2");
+ assertEquals(Set.of("a"), new ChainedMap<>(a, Map.of()).keySet());
+ assertEquals(Set.of("a"), new ChainedMap<>(Map.of(), a).keySet());
+ assertEquals(Set.of("a", "b"), new ChainedMap<>(a, b).keySet());
+ assertEquals(Set.of("a", "b"), new ChainedMap<>(ab, b).keySet());
+ }
+}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
index bebdda15983..013de292cb7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
@@ -2,13 +2,13 @@
package com.yahoo.search.query.profile.compiled;
import com.yahoo.search.query.profile.DimensionBinding;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue;
public class BindingTestCase {
@Test
- public void testGeneralizes() {
+ void testGeneralizes() {
Map<String, String> m1 = new HashMap<>();
m1.put("a", "a1");
m1.put("b", "b1");
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
index 511921ac047..c2faeb899c9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
@@ -2,12 +2,12 @@
package com.yahoo.search.query.profile.compiled;
import com.yahoo.search.query.profile.config.QueryProfilesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -15,13 +15,13 @@ import static org.junit.Assert.assertTrue;
public class CompiledQueryProfileRegistryTest {
@Test
- public void registry_can_be_created_from_config() {
+ void registry_can_be_created_from_config() {
var config = new QueryProfilesConfig.Builder()
.queryprofile(new QueryProfilesConfig.Queryprofile.Builder()
- .id("profile1")
- .property(new QueryProfilesConfig.Queryprofile.Property.Builder()
- .name("hits")
- .value("5")))
+ .id("profile1")
+ .property(new QueryProfilesConfig.Queryprofile.Property.Builder()
+ .name("hits")
+ .value("5")))
.build();
var executor = Executors.newCachedThreadPool();
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
index 21f20e70ddb..ebe9c9d3c04 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
@@ -7,10 +7,10 @@ import java.util.Map;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -18,31 +18,31 @@ import static org.junit.Assert.assertNotNull;
public class MultiProfileTestCase {
@Test
- public void testValid() {
- QueryProfileRegistry registry=
+ void testValid() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/multiprofile");
- QueryProfile multiprofile1=registry.getComponent("multiprofile1");
+ QueryProfile multiprofile1 = registry.getComponent("multiprofile1");
assertNotNull(multiprofile1);
- assertGet("general-a","a",new String[] {null,null,null},multiprofile1);
- assertGet("us-nokia-test1-a","a",new String[] {"us","nok ia","test1"},multiprofile1);
- assertGet("us-nokia-b","b",new String[] {"us","nok ia","test1"},multiprofile1);
- assertGet("us-a","a",new String[] {"us",null,null},multiprofile1);
- assertGet("us-b","b",new String[] {"us",null,null},multiprofile1);
- assertGet("us-nokia-a","a",new String[] {"us","nok ia",null},multiprofile1);
- assertGet("us-test1-a","a",new String[] {"us",null,"test1"},multiprofile1);
- assertGet("us-test1-b","b",new String[] {"us",null,"test1"},multiprofile1);
+ assertGet("general-a", "a", new String[]{null, null, null}, multiprofile1);
+ assertGet("us-nokia-test1-a", "a", new String[]{"us", "nok ia", "test1"}, multiprofile1);
+ assertGet("us-nokia-b", "b", new String[]{"us", "nok ia", "test1"}, multiprofile1);
+ assertGet("us-a", "a", new String[]{"us", null, null}, multiprofile1);
+ assertGet("us-b", "b", new String[]{"us", null, null}, multiprofile1);
+ assertGet("us-nokia-a", "a", new String[]{"us", "nok ia", null}, multiprofile1);
+ assertGet("us-test1-a", "a", new String[]{"us", null, "test1"}, multiprofile1);
+ assertGet("us-test1-b", "b", new String[]{"us", null, "test1"}, multiprofile1);
- assertGet("us-a","a",new String[] {"us","unspecified","unspecified"},multiprofile1);
- assertGet("us-nokia-a","a",new String[] {"us","nok ia","unspecified"},multiprofile1);
- assertGet("us-test1-a","a",new String[] {"us","unspecified","test1"},multiprofile1);
- assertGet("us-nokia-b","b",new String[] {"us","nok ia","test1"},multiprofile1);
+ assertGet("us-a", "a", new String[]{"us", "unspecified", "unspecified"}, multiprofile1);
+ assertGet("us-nokia-a", "a", new String[]{"us", "nok ia", "unspecified"}, multiprofile1);
+ assertGet("us-test1-a", "a", new String[]{"us", "unspecified", "test1"}, multiprofile1);
+ assertGet("us-nokia-b", "b", new String[]{"us", "nok ia", "test1"}, multiprofile1);
// ...inherited
- assertGet("parent1-value","parent1",new String[] { "us","nok ia","-" }, multiprofile1);
- assertGet("parent2-value","parent2",new String[] { "us","nok ia","-" }, multiprofile1);
- assertGet(null,"parent1",new String[] { "us","-","-" }, multiprofile1);
- assertGet(null,"parent2",new String[] { "us","-","-" }, multiprofile1);
+ assertGet("parent1-value", "parent1", new String[]{"us", "nok ia", "-"}, multiprofile1);
+ assertGet("parent2-value", "parent2", new String[]{"us", "nok ia", "-"}, multiprofile1);
+ assertGet(null, "parent1", new String[]{"us", "-", "-"}, multiprofile1);
+ assertGet(null, "parent2", new String[]{"us", "-", "-"}, multiprofile1);
}
private void assertGet(String expectedValue,String parameter,String[] dimensionValues,QueryProfile profile) {
@@ -50,7 +50,7 @@ public class MultiProfileTestCase {
context.put("region",dimensionValues[0]);
context.put("model",dimensionValues[1]);
context.put("bucket",dimensionValues[2]);
- assertEquals("Looking up '" + parameter + "' for '" + toString(dimensionValues) + "'",expectedValue,profile.get(parameter,context,null));
+ assertEquals(expectedValue,profile.get(parameter,context,null),"Looking up '" + parameter + "' for '" + toString(dimensionValues) + "'");
}
private String toString(String[] array) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
index 29a8969233b..bf3afecc115 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
@@ -7,15 +7,13 @@ import com.yahoo.search.query.profile.QueryProfileProperties;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.config.QueryProfileConfigurer;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,9 +23,9 @@ public class QueryProfileConfigurationTestCase {
public final String CONFIG_DIR ="src/test/java/com/yahoo/search/query/profile/config/test/";
@Test
- public void testConfiguration() {
+ void testConfiguration() {
var profile = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profiles-configuration.cfg")
- .getComponent("default");
+ .getComponent("default");
assertEquals("a-value", profile.get("a"));
assertEquals("b-value", profile.get("b"));
@@ -43,9 +41,9 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testBug3197426() {
+ void testBug3197426() {
var profile = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "bug3197426.cfg")
- .getComponent("default").compile(null);
+ .getComponent("default").compile(null);
Map<String, Object> properties = new QueryProfileProperties(profile).listProperties("source.image");
assertEquals("yes", properties.get("mlr"));
@@ -63,42 +61,42 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testVariantConfiguration() {
+ void testVariantConfiguration() {
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants-configuration.cfg");
// Variant 1
QueryProfile variants1 = registry.getComponent("variants1");
- assertGet("x1.y1.a", "a", new String[] { "x1","y1" }, variants1);
- assertGet("x1.y1.b", "b", new String[] { "x1","y1" }, variants1);
- assertGet("x1.y?.a", "a", new String[] { "x1","zz" }, variants1);
- assertGet("x?.y1.a", "a", new String[] { "zz","y1" }, variants1);
- assertGet("a-deflt", "a", new String[] { "z1","z2" }, variants1);
+ assertGet("x1.y1.a", "a", new String[]{"x1", "y1"}, variants1);
+ assertGet("x1.y1.b", "b", new String[]{"x1", "y1"}, variants1);
+ assertGet("x1.y?.a", "a", new String[]{"x1", "zz"}, variants1);
+ assertGet("x?.y1.a", "a", new String[]{"zz", "y1"}, variants1);
+ assertGet("a-deflt", "a", new String[]{"z1", "z2"}, variants1);
// ...inherited
- assertGet("parent1-value", "parent1", new String[] { "x1","y1" }, variants1);
- assertGet("parent2-value", "parent2", new String[] { "x1","y1" }, variants1);
- assertGet(null, "parent1", new String[] { "x1","y2" }, variants1);
- assertGet(null, "parent2", new String[] { "x1","y2" }, variants1);
+ assertGet("parent1-value", "parent1", new String[]{"x1", "y1"}, variants1);
+ assertGet("parent2-value", "parent2", new String[]{"x1", "y1"}, variants1);
+ assertGet(null, "parent1", new String[]{"x1", "y2"}, variants1);
+ assertGet(null, "parent2", new String[]{"x1", "y2"}, variants1);
// Variant 2
QueryProfile variants2 = registry.getComponent("variants2");
- assertGet("variant2:y1.c", "c", new String[] { "*","y1" }, variants2);
- assertGet("variant2:y2.c", "c", new String[] { "*","y2" }, variants2);
- assertGet("variant2:c-df", "c", new String[] { "*","z1" }, variants2);
- assertGet("variant2:c-df", "c", new String[] { }, variants2);
- assertGet("variant2:c-df", "c", new String[] { "*" }, variants2);
- assertGet(null, "d", new String[] { "*","y1" }, variants2);
+ assertGet("variant2:y1.c", "c", new String[]{"*", "y1"}, variants2);
+ assertGet("variant2:y2.c", "c", new String[]{"*", "y2"}, variants2);
+ assertGet("variant2:c-df", "c", new String[]{"*", "z1"}, variants2);
+ assertGet("variant2:c-df", "c", new String[]{ }, variants2);
+ assertGet("variant2:c-df", "c", new String[]{"*" }, variants2);
+ assertGet(null, "d", new String[]{"*", "y1"}, variants2);
// Reference following from variant 1
- assertGet("variant2:y1.c", "toVariants.c", new String[] { "**", "y1" } , variants1);
- assertGet("variant3:c-df", "toVariants.c", new String[] { "x1", "**" } , variants1);
- assertGet("variant3:y1.c", "toVariants.c", new String[] { "x1", "y1" } , variants1); // variant3 by order priority
- assertGet("variant3:y2.c", "toVariants.c", new String[] { "x1", "y2" } , variants1);
+ assertGet("variant2:y1.c", "toVariants.c", new String[]{"**", "y1"}, variants1);
+ assertGet("variant3:c-df", "toVariants.c", new String[]{"x1", "**"}, variants1);
+ assertGet("variant3:y1.c", "toVariants.c", new String[]{"x1", "y1"}, variants1); // variant3 by order priority
+ assertGet("variant3:y2.c", "toVariants.c", new String[]{"x1", "y2"}, variants1);
}
@Test
- public void testVariantConfigurationThroughQueryLookup() {
+ void testVariantConfigurationThroughQueryLookup() {
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants-configuration.cfg")
- .compile();
+ .compile();
CompiledQueryProfile variants1 = registry.getComponent("variants1");
@@ -107,7 +105,7 @@ public class QueryProfileConfigurationTestCase {
assertEquals("x1.y1.b", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=y1"), variants1).properties().get("b"));
assertEquals("x1.y1.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=y1"), variants1).getModel().getDefaultIndex());
assertEquals("x1.y?.a", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"), variants1).properties().get("a"));
- assertEquals("x1.y?.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"),variants1).getModel().getDefaultIndex());
+ assertEquals("x1.y?.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"), variants1).getModel().getDefaultIndex());
assertEquals("x?.y1.a", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).properties().get("a"));
assertEquals("x?.y1.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).getModel().getDefaultIndex());
assertEquals("x?.y1.filter", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).getModel().getFilter());
@@ -130,14 +128,14 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testVariant2ConfigurationThroughQueryLookup() {
+ void testVariant2ConfigurationThroughQueryLookup() {
final double delta = 0.0000001;
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants2.cfg")
- .compile();
+ .compile();
Query query = new Query(QueryTestCase.httpEncode("?query=heh&queryProfile=multi&myindex=default&myquery=lo ve&tracelevel=5"),
- registry.findQueryProfile("multi"));
+ registry.findQueryProfile("multi"));
assertEquals("love", query.properties().get("model.queryString"));
assertEquals("default", query.properties().get("model.defaultIndex"));
@@ -152,8 +150,7 @@ public class QueryProfileConfigurationTestCase {
Map<String, String> context = new HashMap<>();
for (int i = 0; i<dimensionValues.length; i++)
context.put(profile.getVariants().getDimensions().get(i), dimensionValues[i]); // Lookup dim. names to ease test...
- assertEquals("Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'",
- expectedValue, profile.get(parameter, context, null));
+ assertEquals(expectedValue, profile.get(parameter, context, null), "Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
index c64d5df64f9..ce6f6264623 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.search.handler.HttpSearchResponse;
import com.yahoo.search.handler.SearchHandler;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests using query profiles in searches
@@ -26,13 +26,13 @@ import static org.junit.Assert.assertNotNull;
*/
public class QueryProfileIntegrationTestCase {
- @org.junit.After
+ @org.junit.jupiter.api.AfterEach
public void tearDown() {
System.getProperties().remove("config.id");
}
@Test
- public void testUntyped() {
+ void testUntyped() {
String configId = "dir:src/test/java/com/yahoo/search/query/profile/config/test/untyped";
System.setProperty("config.id", configId);
Container container = new Container();
@@ -41,79 +41,79 @@ public class QueryProfileIntegrationTestCase {
// Should get "default" query profile containing the "test" search chain containing the "test" searcher
HttpRequest request = HttpRequest.createTestRequest("search", Method.GET);
- HttpSearchResponse response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ HttpSearchResponse response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:test"));
// Should get the "test' query profile containing the "default" search chain containing the "default" searcher
request = HttpRequest.createTestRequest("search?queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Should get "default" query profile, but override the search chain to default
request = HttpRequest.createTestRequest("search?searchChain=default", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Tests a profile setting hits and offset
request = HttpRequest.createTestRequest("search?queryProfile=hitsoffset", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertEquals(20, response.getQuery().getHits());
assertEquals(80, response.getQuery().getOffset());
// Tests a non-resolved profile request
request = HttpRequest.createTestRequest("search?queryProfile=none", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertNotNull("Got an error", response.getResult().hits().getError());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertNotNull(response.getResult().hits().getError(), "Got an error");
assertEquals("Could not resolve query profile 'none'", response.getResult().hits().getError().getDetailedMessage());
// Tests that properties in objects owned by query is handled correctly
request = HttpRequest.createTestRequest("search?query=word&queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals("index" ,response.getQuery().getModel().getDefaultIndex());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals("index", response.getQuery().getModel().getDefaultIndex());
assertEquals("WEAKAND(100) index:word", response.getQuery().getModel().getQueryTree().toString());
configurer.shutdown();
}
@Test
- public void testTyped() {
+ void testTyped() {
String configId = "dir:src/test/java/com/yahoo/search/query/profile/config/test/typed";
System.setProperty("config.id", configId);
Container container = new Container();
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper(container, configId);
- SearchHandler searchHandler = (SearchHandler)configurer.getRequestHandlerRegistry().getComponent(SearchHandler.class.getName());
+ SearchHandler searchHandler = (SearchHandler) configurer.getRequestHandlerRegistry().getComponent(SearchHandler.class.getName());
// Should get "default" query profile containing the "test" search chain containing the "test" searcher
HttpRequest request = HttpRequest.createTestRequest("search", Method.GET);
- HttpSearchResponse response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ HttpSearchResponse response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:test"));
// Should get the "test' query profile containing the "default" search chain containing the "default" searcher
request = HttpRequest.createTestRequest("search?queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Should get "default" query profile, but override the search chain to default
request = HttpRequest.createTestRequest("search?searchChain=default", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Tests a profile setting hits and offset
request = HttpRequest.createTestRequest("search?queryProfile=hitsoffset", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals(22,response.getQuery().getHits());
- assertEquals(80,response.getQuery().getOffset());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals(22, response.getQuery().getHits());
+ assertEquals(80, response.getQuery().getOffset());
// Tests a non-resolved profile request
request = HttpRequest.createTestRequest("search?queryProfile=none", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertNotNull("Got an error",response.getResult().hits().getError());
- assertEquals("Could not resolve query profile 'none'",response.getResult().hits().getError().getDetailedMessage());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertNotNull(response.getResult().hits().getError(), "Got an error");
+ assertEquals("Could not resolve query profile 'none'", response.getResult().hits().getError().getDetailedMessage());
// Test overriding a sub-profile in the request
request = HttpRequest.createTestRequest("search?queryProfile=root&sub=newsub", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals("newsubvalue1",response.getQuery().properties().get("sub.value1"));
- assertEquals("newsubvalue2",response.getQuery().properties().get("sub.value2"));
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals("newsubvalue1", response.getQuery().properties().get("sub.value1"));
+ assertEquals("newsubvalue2", response.getQuery().properties().get("sub.value2"));
configurer.shutdown();
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
index 944ee6d79ef..de46e6ee77c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.search.query.profile.config.test;
import com.yahoo.search.query.profile.config.QueryProfileConfigurer;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -17,7 +15,7 @@ public class TypedProfilesConfigurationTestCase {
/** Asserts that everything is read correctly from this configuration */
@Test
- public void testIt() {
+ void testIt() {
var registry = QueryProfileConfigurer.createFromConfigId("file:src/test/java/com/yahoo/search/query/profile/config/test/typed-profiles.cfg");
var types = registry.getTypeRegistry();
@@ -33,19 +31,19 @@ public class TypedProfilesConfigurationTestCase {
assertTrue(testType.getField("myString").isOverridable());
assertFalse(testType.getField("myInteger").isMandatory());
assertFalse(testType.getField("myInteger").isOverridable());
- FieldDescription field= testType.getField("myUserQueryProfile");
+ FieldDescription field = testType.getField("myUserQueryProfile");
assertEquals("reference to a query profile of type 'user'", field.getType().toInstanceDescription());
assertTrue(field.getAliases().contains("myqp"));
assertTrue(field.getAliases().contains("user-profile"));
- QueryProfileType testTypeStrict=types.getComponent("testtypestrict");
+ QueryProfileType testTypeStrict = types.getComponent("testtypestrict");
assertTrue(testTypeStrict.isStrict());
assertTrue(testTypeStrict.getMatchAsPath());
assertEquals(7, testTypeStrict.fields().size());
assertEquals("reference to a query profile of type 'userstrict'",
- testTypeStrict.getField("myUserQueryProfile").getType().toInstanceDescription());
+ testTypeStrict.getField("myUserQueryProfile").getType().toInstanceDescription());
- QueryProfileType user=types.getComponent("user");
+ QueryProfileType user = types.getComponent("user");
assertFalse(user.isStrict());
assertFalse(user.getMatchAsPath());
assertEquals(2, user.fields().size());
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
index 62bc89c8453..dcb41dc5e31 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
@@ -19,17 +19,13 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -37,7 +33,7 @@ import static org.junit.Assert.fail;
public class XmlReadingTestCase {
@Test
- public void testInheritance() {
+ void testInheritance() {
QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/inheritance");
@@ -48,7 +44,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testValid() {
+ void testValid() {
QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/validxml");
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -106,8 +102,8 @@ public class XmlReadingTestCase {
assertEquals(3, query.getTrace().getLevel());
QueryProfile someUser = registry.getComponent("someUser");
- assertEquals("5",someUser.get("sub.test"));
- assertEquals(18,someUser.get("age"));
+ assertEquals("5", someUser.get("sub.test"));
+ assertEquals(18, someUser.get("age"));
// aliases
assertEquals(18, someUser.get("alder"));
@@ -129,19 +125,19 @@ public class XmlReadingTestCase {
}
@Test
- public void testBasicsNoProfile() {
- Query q=new Query(HttpRequest.createTestRequest("?query=test", Method.GET));
- assertEquals("test",q.properties().get("query"));
- assertEquals("test",q.properties().get("QueRY"));
- assertEquals("test",q.properties().get("model.queryString"));
- assertEquals("test",q.getModel().getQueryString());
+ void testBasicsNoProfile() {
+ Query q = new Query(HttpRequest.createTestRequest("?query=test", Method.GET));
+ assertEquals("test", q.properties().get("query"));
+ assertEquals("test", q.properties().get("QueRY"));
+ assertEquals("test", q.properties().get("model.queryString"));
+ assertEquals("test", q.getModel().getQueryString());
}
@Test
- public void testBasicsWithProfile() {
+ void testBasicsWithProfile() {
QueryProfile p = new QueryProfile("default");
p.set("a", "foo", null);
- Query q=new Query(HttpRequest.createTestRequest("?query=test", Method.GET), p.compile(null));
+ Query q = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), p.compile(null));
assertEquals("test", q.properties().get("query"));
assertEquals("test", q.properties().get("QueRY"));
assertEquals("test", q.properties().get("model.queryString"));
@@ -150,7 +146,7 @@ public class XmlReadingTestCase {
/** Tests a subset of the configuration in the system test of this */
@Test
- public void testSystemtest() {
+ void testSystemtest() {
String queryString = "?query=test";
QueryProfileXMLReader reader = new QueryProfileXMLReader();
@@ -170,7 +166,7 @@ public class XmlReadingTestCase {
assertEquals("le", p.get("subst.end"));
assertEquals("title", p.get("model.defaultIndex"));
- Map<String,Object> ps = p.listProperties();
+ Map<String, Object> ps = p.listProperties();
assertEquals("bar", ps.get("foo"));
assertEquals(5, ps.get("hits"));
assertEquals("tit", ps.get("subst"));
@@ -180,7 +176,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid1() {
+ void testInvalid1() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml1");
fail("Should have failed");
@@ -191,7 +187,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid2() {
+ void testInvalid2() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml2");
fail("Should have failed");
@@ -202,7 +198,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid3() {
+ void testInvalid3() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml3");
fail("Should have failed");
@@ -213,7 +209,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testQueryProfileVariants() {
+ void testQueryProfileVariants() {
String query = "?query=test&dim1=yahoo&dim2=uk&dim3=test";
QueryProfileXMLReader reader = new QueryProfileXMLReader();
@@ -227,7 +223,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testQueryProfileVariantsWithOverridableFalse() {
+ void testQueryProfileVariantsWithOverridableFalse() {
QueryProfileXMLReader reader = new QueryProfileXMLReader();
CompiledQueryProfileRegistry registry = reader.read("src/test/java/com/yahoo/search/query/profile/config/test/variants/").compile();
CompiledQueryProfile profile = registry.findQueryProfile("default");
@@ -240,156 +236,156 @@ public class XmlReadingTestCase {
}
@Test
- public void testNewsFE1() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe").compile();
+ void testNewsFE1() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe").compile();
- String queryString="tiled?vertical=news&query=barack&intl=us&resulttypes=article&testid=&clientintl=us&SpellState=&rss=0&tracelevel=5";
+ String queryString = "tiled?vertical=news&query=barack&intl=us&resulttypes=article&testid=&clientintl=us&SpellState=&rss=0&tracelevel=5";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
- assertEquals("13",query.properties().listProperties().get("source.news.discovery.sources.count"));
- assertEquals("13",query.properties().get("source.news.discovery.sources.count"));
- assertEquals("sources",query.properties().listProperties().get("source.news.discovery"));
- assertEquals("sources",query.properties().get("source.news.discovery"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
+ assertEquals("13", query.properties().listProperties().get("source.news.discovery.sources.count"));
+ assertEquals("13", query.properties().get("source.news.discovery.sources.count"));
+ assertEquals("sources", query.properties().listProperties().get("source.news.discovery"));
+ assertEquals("sources", query.properties().get("source.news.discovery"));
}
@Test
- public void testQueryProfileVariants2() {
+ void testQueryProfileVariants2() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/queryprofilevariants2").compile();
CompiledQueryProfile multi = registry.getComponent("multi");
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi", Method.GET), multi);
query.validate();
- assertEquals("best",query.properties().get("model.queryString"));
- assertEquals("best",query.getModel().getQueryString());
+ assertEquals("best", query.properties().get("model.queryString"));
+ assertEquals("best", query.getModel().getQueryString());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default", Method.GET), multi);
query.validate();
assertEquals("best", query.properties().get("model.queryString"));
assertEquals("best", query.getModel().getQueryString());
assertEquals("default", query.getModel().getDefaultIndex());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default&myquery=love", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default&myquery=love", Method.GET), multi);
query.validate();
assertEquals("love", query.properties().get("model.queryString"));
assertEquals("love", query.getModel().getQueryString());
assertEquals("default", query.getModel().getDefaultIndex());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?model=querybest", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?model=querybest", Method.GET), multi);
query.validate();
- assertEquals("best",query.getModel().getQueryString());
- assertEquals("title",query.properties().get("model.defaultIndex"));
- assertEquals("title",query.getModel().getDefaultIndex());
+ assertEquals("best", query.getModel().getQueryString());
+ assertEquals("title", query.properties().get("model.defaultIndex"));
+ assertEquals("title", query.getModel().getDefaultIndex());
}
}
@Test
- public void testKlee() {
- QueryProfileRegistry registry=
+ void testKlee() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/klee");
- QueryProfile pv=registry.getComponent("twitter_dd-us:0.2.4");
- assertEquals("0.2.4",pv.getId().getVersion().toString());
- assertEquals("[query profile 'production']",pv.inherited().toString());
+ QueryProfile pv = registry.getComponent("twitter_dd-us:0.2.4");
+ assertEquals("0.2.4", pv.getId().getVersion().toString());
+ assertEquals("[query profile 'production']", pv.inherited().toString());
- QueryProfile p=registry.getComponent("twitter_dd-us:0.0.0");
- assertEquals("",p.getId().getVersion().toString()); // that is 0.0.0
- assertEquals("[query profile 'twitter_dd']",p.inherited().toString());
+ QueryProfile p = registry.getComponent("twitter_dd-us:0.0.0");
+ assertEquals("", p.getId().getVersion().toString()); // that is 0.0.0
+ assertEquals("[query profile 'twitter_dd']", p.inherited().toString());
}
@Test
- public void testVersions() {
- QueryProfileRegistry registry=
+ void testVersions() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/versions");
registry.freeze();
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1.20.100").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1.20").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1.20.100").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1.20").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile").getId().getVersion().toString());
}
@Test
- public void testNewsFE2() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe2").compile();
+ void testNewsFE2() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe2").compile();
- String queryString="tiled?query=a&intl=tw&mode=adv&mode=adv";
+ String queryString = "tiled?query=a&intl=tw&mode=adv&mode=adv";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET),registry.getComponent("default"));
- assertEquals("news_adv",query.properties().listProperties().get("provider"));
- assertEquals("news_adv",query.properties().get("provider"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
+ assertEquals("news_adv", query.properties().listProperties().get("provider"));
+ assertEquals("news_adv", query.properties().get("provider"));
}
@Test
- public void testSourceProvider() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/sourceprovider").compile();
+ void testSourceProvider() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/sourceprovider").compile();
- String queryString="tiled?query=india&queryProfile=myprofile&source.common.intl=tw&source.common.mode=adv";
+ String queryString = "tiled?query=india&queryProfile=myprofile&source.common.intl=tw&source.common.mode=adv";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("myprofile"));
- assertEquals("news",query.properties().listProperties().get("source.common.provider"));
- assertEquals("news",query.properties().get("source.common.provider"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("myprofile"));
+ assertEquals("news", query.properties().listProperties().get("source.common.provider"));
+ assertEquals("news", query.properties().get("source.common.provider"));
}
@Test
- public void testNewsCase1() {
+ void testNewsCase1() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase1").compile();
Query query;
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.0, query.properties().get("ranking.features.b"));
assertEquals("0.0", query.properties().listProperties().get("ranking.features.b"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.1, query.properties().get("ranking.features.b"));
assertEquals("0.1", query.properties().listProperties().get("ranking.features.b"));
}
@Test
- public void testNewsCase2() {
+ void testNewsCase2() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase2").compile();
Query query;
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("0.0", query.properties().get("a.features.b"));
assertEquals("0.0", query.properties().listProperties().get("a.features.b"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("0.1", query.properties().get("a.features.b"));
assertEquals("0.1", query.properties().listProperties().get("a.features.b"));
}
@Test
- public void testNewsCase3() {
+ void testNewsCase3() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase3").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
- assertEquals("0.0",query.properties().get("a.features"));
+ registry.getComponent("default"));
+ assertEquals("0.0", query.properties().get("a.features"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
- assertEquals("0.1",query.properties().get("a.features"));
+ registry.getComponent("default"));
+ assertEquals("0.1", query.properties().get("a.features"));
}
@Test
- public void testNewsCase4() {
+ void testNewsCase4() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase4").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.0, query.properties().get("ranking.features.foo"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.1, query.properties().get("ranking.features.foo"));
}
@Test
- public void testVersionRefs() {
+ void testVersionRefs() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/versionrefs").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), registry.getComponent("default"));
@@ -397,14 +393,14 @@ public class XmlReadingTestCase {
}
@Test
- public void testRefOverride() {
+ void testRefOverride() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/refoverride").compile();
{
// Original reference
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET),
- registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ registry.getComponent("default"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile1", query.properties().get("profileRef.name"));
assertEquals("myProfile1Only", query.properties().get("profileRef.myProfile1Only"));
assertNull(query.properties().get("profileRef.myProfile2Only"));
@@ -412,8 +408,8 @@ public class XmlReadingTestCase {
{
// Overridden reference
- Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET),registry.getComponent("default"));
- assertEquals(null,query.properties().get("profileRef"));
+ Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET), registry.getComponent("default"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
assertEquals("myProfile2Only", query.properties().get("profileRef.myProfile2Only"));
assertNull(query.properties().get("profileRef.myProfile1Only"));
@@ -423,20 +419,20 @@ public class XmlReadingTestCase {
assertEquals("newName", query.properties().get("profileRef.name"));
// ...will not impact others
query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
}
}
@Test
- public void testRefOverrideTyped() {
+ void testRefOverrideTyped() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/refoverridetyped").compile();
{
// Original reference
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile1", query.properties().get("profileRef.name"));
assertEquals("myProfile1Only", query.properties().get("profileRef.myProfile1Only"));
assertNull(query.properties().get("profileRef.myProfile2Only"));
@@ -445,7 +441,7 @@ public class XmlReadingTestCase {
{
// Overridden reference
Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=MyProfile2", Method.GET), registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
assertEquals("myProfile2Only", query.properties().get("profileRef.myProfile2Only"));
assertNull(query.properties().get("profileRef.myProfile1Only"));
@@ -461,7 +457,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testAnonymousIdsAreStableBetweenImports() {
+ void testAnonymousIdsAreStableBetweenImports() {
QueryProfileRegistry registry1 = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/typedinheritance");
var childIn1 = registry1.findQueryProfile("child");
var childTypeIn1 = registry1.getType("childType");
@@ -470,50 +466,50 @@ public class XmlReadingTestCase {
var childIn2 = registry2.findQueryProfile("child");
var childTypeIn2 = registry2.getType("childType");
- assertEquals(((QueryProfile)childIn1.lookup("a", Map.of())).getId().stringValue(),
- ((QueryProfile)childIn2.lookup("a", Map.of())).getId().stringValue());
+ assertEquals(((QueryProfile) childIn1.lookup("a", Map.of())).getId().stringValue(),
+ ((QueryProfile) childIn2.lookup("a", Map.of())).getId().stringValue());
assertEquals(childTypeIn1.getType("a").getId().stringValue(),
- childTypeIn2.getType("a").getId().stringValue());
+ childTypeIn2.getType("a").getId().stringValue());
}
@Test
- public void testTensorTypes() {
+ void testTensorTypes() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/tensortypes").compile();
QueryProfileType type1 = registry.getTypeRegistry().getComponent("type1");
assertEquals(TensorType.fromSpec("tensor<float>(x[1])"),
- type1.getFieldType(new CompoundName("ranking.features.query(tensor_1)")).asTensorType());
+ type1.getFieldType(new CompoundName("ranking.features.query(tensor_1)")).asTensorType());
assertNull(type1.getFieldType(new CompoundName("ranking.features.query(tensor_2)")));
assertNull(type1.getFieldType(new CompoundName("ranking.features.query(tensor_3)")));
assertEquals(TensorType.fromSpec("tensor(key{})"),
- type1.getFieldType(new CompoundName("ranking.features.query(tensor_4)")).asTensorType());
+ type1.getFieldType(new CompoundName("ranking.features.query(tensor_4)")).asTensorType());
QueryProfileType type2 = registry.getTypeRegistry().getComponent("type2");
assertNull(type2.getFieldType(new CompoundName("ranking.features.query(tensor_1)")));
assertEquals(TensorType.fromSpec("tensor<float>(x[2])"),
- type2.getFieldType(new CompoundName("ranking.features.query(tensor_2)")).asTensorType());
+ type2.getFieldType(new CompoundName("ranking.features.query(tensor_2)")).asTensorType());
assertEquals(TensorType.fromSpec("tensor<float>(x[3])"),
- type2.getFieldType(new CompoundName("ranking.features.query(tensor_3)")).asTensorType());
+ type2.getFieldType(new CompoundName("ranking.features.query(tensor_3)")).asTensorType());
Query queryProfile1 = new Query.Builder().setQueryProfile(registry.getComponent("profile1"))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
- assertEquals("tensor_1 received as a tensor tensor",
- Tensor.from("tensor<float>(x[1]):[1.2]"),
- queryProfile1.properties().get("ranking.features.query(tensor_1)"));
- assertEquals("tensor_4 contained in the profile is a tensor",
- Tensor.from("tensor(key{}):{pre_key1_post:1.0}"),
- queryProfile1.properties().get("ranking.features.query(tensor_4)"));
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
+ assertEquals(Tensor.from("tensor<float>(x[1]):[1.2]"),
+ queryProfile1.properties().get("ranking.features.query(tensor_1)"),
+ "tensor_1 received as a tensor tensor");
+ assertEquals(Tensor.from("tensor(key{}):{pre_key1_post:1.0}"),
+ queryProfile1.properties().get("ranking.features.query(tensor_4)"),
+ "tensor_4 contained in the profile is a tensor");
Query queryProfile2 = new Query.Builder().setQueryProfile(registry.getComponent("profile2"))
- .setEmbedder(new MockEmbedder("text-to-embed",
- Tensor.from("tensor(x[3]):[1, 2, 3]")))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
- assertEquals("tensor_1 received as a string as it is not in type2",
- "[1.200]",
- queryProfile2.properties().get("ranking.features.query(tensor_1)"));
+ .setEmbedder(new MockEmbedder("text-to-embed",
+ Tensor.from("tensor(x[3]):[1, 2, 3]")))
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
+ assertEquals("[1.200]",
+ queryProfile2.properties().get("ranking.features.query(tensor_1)"),
+ "tensor_1 received as a string as it is not in type2");
//assertEquals(Tensor.from("tensor(x[3]):[1, 2, 3]"),
// queryProfile2.properties().get("ranking.features.query(tensor_3)"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
index 433b87363b3..437d5e3b943 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
@@ -6,9 +6,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.jdisc.http.HttpRequest.Method;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -16,185 +16,185 @@ import static org.junit.Assert.assertEquals;
public class CloningTestCase {
@Test
- public void testCloningWithVariants() {
+ void testCloningWithVariants() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a","a1");
+ q1.properties().set("a", "a1");
Query q2 = q1.clone();
- q2.properties().set("a","a2");
- assertEquals("a1",q1.properties().get("a"));
- assertEquals("a2",q2.properties().get("a"));
+ q2.properties().set("a", "a2");
+ assertEquals("a1", q1.properties().get("a"));
+ assertEquals("a2", q2.properties().get("a"));
}
@Test
- public void testShallowCloning() {
+ void testShallowCloning() {
QueryProfile test = new QueryProfile("test");
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a",new MutableString("a1"));
+ q1.properties().set("a", new MutableString("a1"));
Query q2 = q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a2",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a2", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testShallowCloningWithVariants() {
+ void testShallowCloningWithVariants() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a",new MutableString("a1"));
+ q1.properties().set("a", new MutableString("a1"));
Query q2 = q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a2",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a2", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testDeepCloning() {
- QueryProfile test=new QueryProfile("test");
+ void testDeepCloning() {
+ QueryProfile test = new QueryProfile("test");
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a",new CloneableMutableString("a1"));
- Query q2=q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a1",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ q1.properties().set("a", new CloneableMutableString("a1"));
+ Query q2 = q1.clone();
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a1", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testDeepCloningWithVariants() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ void testDeepCloningWithVariants() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a",new CloneableMutableString("a1"));
- Query q2=q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a1",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ q1.properties().set("a", new CloneableMutableString("a1"));
+ Query q2 = q1.clone();
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a1", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testReAssignment() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ void testReAssignment() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a","a1");
- q1.properties().set("a","a2");
- assertEquals("a2",q1.properties().get("a"));
+ q1.properties().set("a", "a1");
+ q1.properties().set("a", "a2");
+ assertEquals("a2", q1.properties().get("a"));
}
@Test
- public void testThreeLevelsOfCloning() {
+ void testThreeLevelsOfCloning() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a","q1-a");
- Query q2=q1.clone();
- q2.properties().set("a","q2-a");
- Query q31=q2.clone();
- q31.properties().set("a","q31-a");
- Query q32=q2.clone();
- q32.properties().set("a","q32-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ q1.properties().set("a", "q1-a");
+ Query q2 = q1.clone();
+ q2.properties().set("a", "q2-a");
+ Query q31 = q2.clone();
+ q31.properties().set("a", "q31-a");
+ Query q32 = q2.clone();
+ q32.properties().set("a", "q32-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningReverseSetOrder() {
+ void testThreeLevelsOfCloningReverseSetOrder() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q32.properties().set("a","q32-a");
- q31.properties().set("a","q31-a");
- q2.properties().set("a","q2-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q32.properties().set("a", "q32-a");
+ q31.properties().set("a", "q31-a");
+ q2.properties().set("a", "q2-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningMiddleFirstSetOrder1() {
+ void testThreeLevelsOfCloningMiddleFirstSetOrder1() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q2.properties().set("a","q2-a");
- q32.properties().set("a","q32-a");
- q31.properties().set("a","q31-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q2.properties().set("a", "q2-a");
+ q32.properties().set("a", "q32-a");
+ q31.properties().set("a", "q31-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningMiddleFirstSetOrder2() {
+ void testThreeLevelsOfCloningMiddleFirstSetOrder2() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q2.properties().set("a","q2-a");
- q31.properties().set("a","q31-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
- q1.properties().set("a","q1-a-2");
- assertEquals("q1-a-2",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a-2",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q2.properties().set("a", "q2-a");
+ q31.properties().set("a", "q31-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
+ q1.properties().set("a", "q1-a-2");
+ assertEquals("q1-a-2", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a-2", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
}
public static class MutableString {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
index 0fca7a566e2..62ed8413d92 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
@@ -2,14 +2,14 @@
package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DimensionBinding;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -17,47 +17,47 @@ import static org.junit.Assert.*;
public class DimensionBindingTestCase {
@Test
- public void testCombining() {
+ void testCombining() {
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("c", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("c", "c=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("a, c", "a=1", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("a, c", "a=1", "c=1")));
assertEquals(binding("c, a, b", "c=1", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("c, a", "a=1", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("c, a", "a=1", "c=1")));
assertEquals(binding("a, b", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("a, b", "a=1", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("a, b", "a=1", "b=1")));
assertEquals(DimensionBinding.invalidBinding,
- binding("a, b", "a=1", "b=1").combineWith(binding("b, a", "a=1", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("b, a", "a=1", "b=1")));
assertEquals(binding("a, b", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("b", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("b", "b=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
+ binding("a, b, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
+ binding("a, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
}
// found DimensionBinding [custid_1=yahoo, custid_2=ca, custid_3=sc, custid_4=null, custid_5=null, custid_6=null], combined with DimensionBinding [custid_1=yahoo, custid_2=null, custid_3=sc, custid_4=null, custid_5=null, custid_6=null] to Invalid DimensionBinding
@Test
- public void testCombiningBindingsWithNull() {
+ void testCombiningBindingsWithNull() {
List<String> dimensions = list("a,b");
Map<String, String> map1 = new HashMap<>();
- map1.put("a","a1");
- map1.put("b","b1");
+ map1.put("a", "a1");
+ map1.put("b", "b1");
Map<String, String> map2 = new HashMap<>();
- map2.put("a","a1");
- map2.put("b",null);
+ map2.put("a", "a1");
+ map2.put("b", null);
assertEquals(DimensionBinding.createFrom(dimensions, map1),
- DimensionBinding.createFrom(dimensions, map1).combineWith(DimensionBinding.createFrom(dimensions, map2)));
+ DimensionBinding.createFrom(dimensions, map1).combineWith(DimensionBinding.createFrom(dimensions, map2)));
}
private DimensionBinding binding(String dimensions, String ... dimensionPoints) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
index 3ed044601f0..00e48a639c1 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DumpTool;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -14,28 +14,28 @@ public class DumpToolTestCase {
private final String profileDir = "src/test/java/com/yahoo/search/query/profile/config/test/multiprofile";
@Test
- public void testNoParameters() {
+ void testNoParameters() {
assertTrue(new DumpTool().resolveAndDump().startsWith("Dumps all resolved"));
}
@Test
- public void testHelpParameter() {
+ void testHelpParameter() {
assertTrue(new DumpTool().resolveAndDump("-help").startsWith("Dumps all resolved"));
}
@Test
- public void testNoDimensionValues() {
+ void testNoDimensionValues() {
System.out.println(new DumpTool().resolveAndDump("multiprofile1", profileDir));
assertTrue(new DumpTool().resolveAndDump("multiprofile1", profileDir).contains("a=general-a\n"));
}
@Test
- public void testAllParametersSet() {
+ void testAllParametersSet() {
assertTrue(new DumpTool().resolveAndDump("multiprofile1", profileDir, "").contains("a=general-a\n"));
}
@Test
- public void testVariant() {
+ void testVariant() {
String result = new DumpTool().resolveAndDump("multiprofile1", profileDir, "region=us");
assertTrue(result.contains("a=us-a"));
assertTrue(result.contains("b=us-b"));
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
index 7a92aa8081b..6a9896188f9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
@@ -8,9 +8,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test using the profile to set the query to execute
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class QueryFromProfileTestCase {
@Test
- public void testQueryFromProfile1() {
+ void testQueryFromProfile1() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile topLevel = new QueryProfile("topLevel");
topLevel.setType(registry.getTypeRegistry().getComponent("native"));
@@ -39,7 +39,7 @@ public class QueryFromProfileTestCase {
}
@Test
- public void testQueryFromProfile2() {
+ void testQueryFromProfile2() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType rootType = new QueryProfileType("root");
rootType.inherited().add(registry.getTypeRegistry().getComponent("native"));
@@ -49,7 +49,7 @@ public class QueryFromProfileTestCase {
root.setType(rootType);
registry.register(root);
- QueryProfile queryBest=new QueryProfile("querybest");
+ QueryProfile queryBest = new QueryProfile("querybest");
queryBest.setType(registry.getTypeRegistry().getComponent("model"));
queryBest.set("queryString", "best", registry);
registry.register(queryBest);
@@ -62,7 +62,7 @@ public class QueryFromProfileTestCase {
}
@Test
- public void testQueryFromProfile3() {
+ void testQueryFromProfile3() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType rootType = new QueryProfileType("root");
rootType.inherited().add(registry.getTypeRegistry().getComponent("native"));
@@ -72,7 +72,7 @@ public class QueryFromProfileTestCase {
root.setType(rootType);
registry.register(root);
- QueryProfile queryBest=new QueryProfile("querybest");
+ QueryProfile queryBest = new QueryProfile("querybest");
queryBest.setType(registry.getTypeRegistry().getComponent("model"));
queryBest.set("queryString", "best", registry);
registry.register(queryBest);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
index 2173d72cab9..9c162df02bf 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.yolean.Exceptions;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileProperties;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -17,17 +17,17 @@ import static org.junit.Assert.fail;
public class QueryProfileSubstitutionTestCase {
@Test
- public void testSubstitutionOnly() {
+ void testSubstitutionOnly() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{world}", null);
+ p.set("message", "%{world}", null);
p.set("world", "world", null);
assertEquals("world", p.compile(null).get("message"));
}
@Test
- public void testSingleSubstitution() {
+ void testSingleSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
+ p.set("message", "Hello %{world}!", null);
p.set("world", "world", null);
assertEquals("Hello world!", p.compile(null).get("message"));
@@ -38,15 +38,15 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testRelativeSubstitution() {
+ void testRelativeSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{.world}!", null);
+ p.set("message", "Hello %{.world}!", null);
p.set("world", "world", null);
assertEquals("Hello world!", p.compile(null).get("message"));
}
@Test
- public void testRelativeSubstitutionNotFound() {
+ void testRelativeSubstitutionNotFound() {
try {
QueryProfile p = new QueryProfile("test");
p.set("message", "Hello %{.world}!", null);
@@ -55,80 +55,80 @@ public class QueryProfileSubstitutionTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Invalid query profile 'test': Could not resolve local substitution 'world' in variant []",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testMultipleSubstitutions() {
+ void testMultipleSubstitutions() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{greeting} %{entity}%{exclamation}", null);
- p.set("greeting","Hola", null);
- p.set("entity","local group", null);
- p.set("exclamation","?", null);
+ p.set("message", "%{greeting} %{entity}%{exclamation}", null);
+ p.set("greeting", "Hola", null);
+ p.set("entity", "local group", null);
+ p.set("exclamation", "?", null);
assertEquals("Hola local group?", p.compile(null).get("message"));
QueryProfile p2 = new QueryProfile("test2");
p2.addInherited(p);
- p2.set("entity","milky way", null);
+ p2.set("entity", "milky way", null);
assertEquals("Hola milky way?", p2.compile(null).get("message"));
}
@Test
- public void testUnclosedSubstitution1() {
+ void testUnclosedSubstitution1() {
try {
QueryProfile p = new QueryProfile("test");
- p.set("message1","%{greeting} %{entity}%{exclamation", null);
+ p.set("message1", "%{greeting} %{entity}%{exclamation", null);
fail("Should have produced an exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'message1' to '%{greeting} %{entity}%{exclamation': Unterminated value substitution '%{exclamation'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testUnclosedSubstitution2() {
+ void testUnclosedSubstitution2() {
try {
QueryProfile p = new QueryProfile("test");
- p.set("message1","%{greeting} %{entity%{exclamation}", null);
+ p.set("message1", "%{greeting} %{entity%{exclamation}", null);
fail("Should have produced an exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'message1' to '%{greeting} %{entity%{exclamation}': Unterminated value substitution '%{entity%{exclamation}'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testNullSubstitution() {
+ void testNullSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{greeting} %{entity}%{exclamation}", null);
- p.set("greeting","Hola", null);
+ p.set("message", "%{greeting} %{entity}%{exclamation}", null);
+ p.set("greeting", "Hola", null);
assertEquals("Hola ", p.compile(null).get("message"));
QueryProfile p2 = new QueryProfile("test2");
p2.addInherited(p);
- p2.set("greeting","Hola", null);
+ p2.set("greeting", "Hola", null);
p2.set("exclamation", "?", null);
assertEquals("Hola ?", p2.compile(null).get("message"));
}
@Test
- public void testNoOverridingOfPropertiesSetAtRuntime() {
+ void testNoOverridingOfPropertiesSetAtRuntime() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","world", null);
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "world", null);
p.freeze();
Properties runtime = new QueryProfileProperties(p.compile(null));
- runtime.set("runtimeMessage","Hello %{world}!");
+ runtime.set("runtimeMessage", "Hello %{world}!");
assertEquals("Hello world!", runtime.get("message"));
- assertEquals("Hello %{world}!",runtime.get("runtimeMessage"));
+ assertEquals("Hello %{world}!", runtime.get("runtimeMessage"));
}
@Test
- public void testButPropertiesSetAtRuntimeAreUsedInSubstitutions() {
+ void testButPropertiesSetAtRuntimeAreUsedInSubstitutions() {
QueryProfile p = new QueryProfile("test");
p.set("message", "Hello %{world}!", null);
p.set("world", "world", null);
@@ -139,21 +139,22 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testInspection() {
+ void testInspection() {
QueryProfile p = new QueryProfile("test");
p.set("message", "%{greeting} %{entity}%{exclamation}", null);
- assertEquals("message","%{greeting} %{entity}%{exclamation}",
- p.declaredContent().entrySet().iterator().next().getValue().toString());
+ assertEquals("%{greeting} %{entity}%{exclamation}",
+ p.declaredContent().entrySet().iterator().next().getValue().toString(),
+ "message");
}
@Test
- public void testVariants() {
+ void testVariants() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","world", null);
- p.setDimensions(new String[] {"x"});
- p.set("message","Halo %{world}!",new String[] {"x1"}, null);
- p.set("world","Europe",new String[] {"x2"}, null);
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "world", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("message", "Halo %{world}!", new String[]{"x1"}, null);
+ p.set("world", "Europe", new String[]{"x2"}, null);
CompiledQueryProfile cp = p.compile(null);
assertEquals("Hello world!", cp.get("message", QueryProfileVariantsTestCase.toMap("x=x?")));
@@ -162,12 +163,12 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testRecursion() {
+ void testRecursion() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","sol planet number %{number}", null);
- p.set("number",3, null);
- assertEquals("Hello sol planet number 3!",p.compile(null).get("message"));
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "sol planet number %{number}", null);
+ p.set("number", 3, null);
+ assertEquals("Hello sol planet number 3!", p.compile(null).get("message"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
index 39ed9b829d2..7a4247f2584 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.ValueWithSource;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -21,11 +21,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests untyped query profiles
@@ -35,60 +31,60 @@ import static org.junit.Assert.fail;
public class QueryProfileTestCase {
@Test
- public void testBasics() {
+ void testBasics() {
QueryProfile profile = new QueryProfile("test");
- profile.set("a","a-value", null);
- profile.set("b.c","b.c-value", null);
- profile.set("d.e.f","d.e.f-value", null);
+ profile.set("a", "a-value", null);
+ profile.set("b.c", "b.c-value", null);
+ profile.set("d.e.f", "d.e.f-value", null);
CompiledQueryProfile cprofile = profile.compile(null);
- assertEquals("a-value",cprofile.get("a"));
- assertEquals("b.c-value",cprofile.get("b.c"));
- assertEquals("d.e.f-value",cprofile.get("d.e.f"));
+ assertEquals("a-value", cprofile.get("a"));
+ assertEquals("b.c-value", cprofile.get("b.c"));
+ assertEquals("d.e.f-value", cprofile.get("d.e.f"));
assertNull(cprofile.get("nonexistent"));
assertNull(cprofile.get("nested.nonexistent"));
- assertTrue(profile.lookup("b",null).getClass()==QueryProfile.class);
- assertTrue(profile.lookup("b",null).getClass()==QueryProfile.class);
+ assertEquals(profile.lookup("b", null).getClass(), QueryProfile.class);
+ assertEquals(profile.lookup("b", null).getClass(), QueryProfile.class);
}
/** Tests cloning, with wrappers used in production in place */
@Test
- public void testCloning() {
+ void testCloning() {
QueryProfile classProfile = new QueryProfile("test");
- classProfile.set("a","aValue", null);
- classProfile.set("b",3, null);
+ classProfile.set("a", "aValue", null);
+ classProfile.set("b", 3, null);
Properties properties = new QueryProfileProperties(classProfile.compile(null));
- Properties propertiesClone=properties.clone();
- assertEquals("aValue",propertiesClone.get("a"));
- assertEquals(3,propertiesClone.get("b"));
- properties.set("a","aNewValue");
- assertEquals("aNewValue",properties.get("a"));
- assertEquals("aValue",propertiesClone.get("a"));
+ Properties propertiesClone = properties.clone();
+ assertEquals("aValue", propertiesClone.get("a"));
+ assertEquals(3, propertiesClone.get("b"));
+ properties.set("a", "aNewValue");
+ assertEquals("aNewValue", properties.get("a"));
+ assertEquals("aValue", propertiesClone.get("a"));
}
@Test
- public void testFreezing() {
+ void testFreezing() {
QueryProfile profile = new QueryProfile("test");
- profile.set("a","a-value", null);
- profile.set("b.c","b.c-value", null);
- profile.set("d.e.f","d.e.f-value", null);
+ profile.set("a", "a-value", null);
+ profile.set("b.c", "b.c-value", null);
+ profile.set("d.e.f", "d.e.f-value", null);
assertFalse(profile.isFrozen());
- assertEquals("a-value",profile.get("a"));
+ assertEquals("a-value", profile.get("a"));
profile.freeze();
assertTrue(profile.isFrozen());
- assertTrue(((QueryProfile)profile.lookup("b",null)).isFrozen());
- assertTrue(((QueryProfile)profile.lookup("d.e",null)).isFrozen());
+ assertTrue(((QueryProfile) profile.lookup("b", null)).isFrozen());
+ assertTrue(((QueryProfile) profile.lookup("d.e", null)).isFrozen());
try {
- profile.set("a","value", null);
+ profile.set("a", "value", null);
fail("Expected exception");
}
catch (IllegalStateException e) {
@@ -97,15 +93,15 @@ public class QueryProfileTestCase {
private void assertSameObjects(CompiledQueryProfile profile, String path, List<String> expectedKeys) {
Map<String, Object> subObjects = profile.listValues(path);
- assertEquals("Sub-objects list equal for path " + path, new HashSet<>(expectedKeys), subObjects.keySet());
+ assertEquals(new HashSet<>(expectedKeys), subObjects.keySet(), "Sub-objects list equal for path " + path);
for(String key : expectedKeys) {
- assertEquals("Equal for key " + key, profile.get(key),subObjects.get(path + "." + key));
+ assertEquals(profile.get(key),subObjects.get(path + "." + key),"Equal for key " + key);
}
}
@Test
- public void testGetSubObjects() {
+ void testGetSubObjects() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -117,21 +113,21 @@ public class QueryProfileTestCase {
far.addInherited(farfar);
barn.addInherited(mor);
barn.addInherited(far);
- mormor.set("a.mormor","a.mormor", null);
- barn.set("a.barn","a.barn", null);
+ mormor.set("a.mormor", "a.mormor", null);
+ barn.set("a.barn", "a.barn", null);
mor.set("b.mor", "b.mor", null);
far.set("b.far", "b.far", null);
- far.set("a.far","a.far", null);
+ far.set("a.far", "a.far", null);
CompiledQueryProfile cbarn = barn.compile(null);
- assertSameObjects(cbarn, "a", Arrays.asList("mormor","far","barn"));
+ assertSameObjects(cbarn, "a", Arrays.asList("mormor", "far", "barn"));
assertEquals("b.mor", cbarn.get("b.mor"));
assertEquals("b.far", cbarn.get("b.far"));
}
@Test
- public void testInheritance() {
+ void testInheritance() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -144,24 +140,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a","morfar-a", null);
- mormor.set("a","mormor-a", null);
- farfar.set("a","farfar-a", null);
- mor.set("a","mor-a", null);
- far.set("a","far-a", null);
- barn.set("a","barn-a", null);
+ morfar.set("a", "morfar-a", null);
+ mormor.set("a", "mormor-a", null);
+ farfar.set("a", "farfar-a", null);
+ mor.set("a", "mor-a", null);
+ far.set("a", "far-a", null);
+ barn.set("a", "barn-a", null);
- mormor.set("b","mormor-b", null);
- far.set("b","far-b", null);
+ mormor.set("b", "mormor-b", null);
+ far.set("b", "far-b", null);
- mor.set("c","mor-c", null);
- far.set("c","far-c", null);
+ mor.set("c", "mor-c", null);
+ far.set("c", "far-c", null);
- mor.set("d.a","mor-d.a", null);
- barn.set("d.b","barn-d.b", null);
+ mor.set("d.a", "mor-d.a", null);
+ barn.set("d.b", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -179,7 +175,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testInheritance2Level() {
+ void testInheritance2Level() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -192,24 +188,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a.x","morfar-a", null);
- mormor.set("a.x","mormor-a", null);
- farfar.set("a.x","farfar-a", null);
- mor.set("a.x","mor-a", null);
- far.set("a.x","far-a", null);
- barn.set("a.x","barn-a", null);
+ morfar.set("a.x", "morfar-a", null);
+ mormor.set("a.x", "mormor-a", null);
+ farfar.set("a.x", "farfar-a", null);
+ mor.set("a.x", "mor-a", null);
+ far.set("a.x", "far-a", null);
+ barn.set("a.x", "barn-a", null);
- mormor.set("b.x","mormor-b", null);
- far.set("b.x","far-b", null);
+ mormor.set("b.x", "mormor-b", null);
+ far.set("b.x", "far-b", null);
- mor.set("c.x","mor-c", null);
- far.set("c.x","far-c", null);
+ mor.set("c.x", "mor-c", null);
+ far.set("c.x", "far-c", null);
- mor.set("d.a.x","mor-d.a", null);
- barn.set("d.b.x","barn-d.b", null);
+ mor.set("d.a.x", "mor-d.a", null);
+ barn.set("d.b.x", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -227,7 +223,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testInheritance3Level() {
+ void testInheritance3Level() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -240,24 +236,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("y.a.x","morfar-a", null);
- mormor.set("y.a.x","mormor-a", null);
- farfar.set("y.a.x","farfar-a", null);
- mor.set("y.a.x","mor-a", null);
- far.set("y.a.x","far-a", null);
- barn.set("y.a.x","barn-a", null);
+ morfar.set("y.a.x", "morfar-a", null);
+ mormor.set("y.a.x", "mormor-a", null);
+ farfar.set("y.a.x", "farfar-a", null);
+ mor.set("y.a.x", "mor-a", null);
+ far.set("y.a.x", "far-a", null);
+ barn.set("y.a.x", "barn-a", null);
- mormor.set("y.b.x","mormor-b", null);
- far.set("y.b.x","far-b", null);
+ mormor.set("y.b.x", "mormor-b", null);
+ far.set("y.b.x", "far-b", null);
- mor.set("y.c.x","mor-c", null);
- far.set("y.c.x","far-c", null);
+ mor.set("y.c.x", "mor-c", null);
+ far.set("y.c.x", "far-c", null);
- mor.set("y.d.a.x","mor-d.a", null);
- barn.set("y.d.b.x","barn-d.b", null);
+ mor.set("y.d.a.x", "mor-d.a", null);
+ barn.set("y.d.b.x", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -275,7 +271,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testListProperties() {
+ void testListProperties() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -288,18 +284,18 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a","morfar-a", null);
- morfar.set("model.b","morfar-model.b", null);
- mormor.set("a","mormor-a", null);
- mormor.set("model.b","mormor-model.b", null);
- farfar.set("a","farfar-a", null);
- mor.set("a","mor-a", null);
- far.set("a","far-a", null);
- barn.set("a","barn-a", null);
- mormor.set("b","mormor-b", null);
- far.set("b","far-b", null);
- mor.set("c","mor-c", null);
- far.set("c","far-c", null);
+ morfar.set("a", "morfar-a", null);
+ morfar.set("model.b", "morfar-model.b", null);
+ mormor.set("a", "mormor-a", null);
+ mormor.set("model.b", "mormor-model.b", null);
+ farfar.set("a", "farfar-a", null);
+ mor.set("a", "mor-a", null);
+ far.set("a", "far-a", null);
+ barn.set("a", "barn-a", null);
+ mormor.set("b", "mormor-b", null);
+ far.set("b", "far-b", null);
+ mor.set("c", "mor-c", null);
+ far.set("c", "far-c", null);
CompiledQueryProfile cbarn = barn.compile(null);
@@ -316,8 +312,8 @@ public class QueryProfileTestCase {
Map<String, Object> modelMap = properties.listProperties("model");
assertEquals("mormor-model.b", modelMap.get("b"));
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn", barn, (QueryProfileRegistry)null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, (QueryProfileRegistry) null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
Map<String, Object> annetBarnMap = new QueryProfileProperties(cannetBarn).listProperties();
@@ -329,12 +325,12 @@ public class QueryProfileTestCase {
/** Dots are followed when setting overridability */
@Test
- public void testInstanceOverridable() {
+ void testInstanceOverridable() {
QueryProfile profile = new QueryProfile("root/unoverridableIndex");
- profile.set("model.defaultIndex","default", null);
+ profile.set("model.defaultIndex", "default", null);
profile.setOverridable("model.defaultIndex", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("model.defaultIndex",null));
+ assertFalse(profile.isDeclaredOverridable("model.defaultIndex", null));
// Parameters should be ignored
Query query = new Query(HttpRequest.createTestRequest("?model.defaultIndex=title", Method.GET), profile.compile(null));
@@ -348,13 +344,13 @@ public class QueryProfileTestCase {
/** Dots are followed when setting overridability, also with variants */
@Test
- public void testInstanceOverridableWithVariants() {
+ void testInstanceOverridableWithVariants() {
QueryProfile profile = new QueryProfile("root/unoverridableIndex");
- profile.setDimensions(new String[] {"x"});
- profile.set("model.defaultIndex","default", null);
+ profile.setDimensions(new String[]{"x"});
+ profile.set("model.defaultIndex", "default", null);
profile.setOverridable("model.defaultIndex", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("model.defaultIndex",null));
+ assertFalse(profile.isDeclaredOverridable("model.defaultIndex", null));
// Parameters should be ignored
Query query = new Query(HttpRequest.createTestRequest("?x=x1&model.defaultIndex=title", Method.GET), profile.compile(null));
@@ -367,47 +363,47 @@ public class QueryProfileTestCase {
}
@Test
- public void testSimpleInstanceOverridableWithVariants1() {
- QueryProfile profile=new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
- profile.set("a","original", null);
+ void testSimpleInstanceOverridableWithVariants1() {
+ QueryProfile profile = new QueryProfile("test");
+ profile.setDimensions(new String[]{"x"});
+ profile.set("a", "original", null);
profile.setOverridable("a", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("a",null));
+ assertFalse(profile.isDeclaredOverridable("a", null));
Query query = new Query(HttpRequest.createTestRequest("?x=x1&a=overridden", Method.GET), profile.compile(null));
assertEquals("original", query.properties().get("a"));
}
@Test
- public void testSimpleInstanceOverridableWithVariants2() {
+ void testSimpleInstanceOverridableWithVariants2() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
- profile.set("a", "original", new String[] {"x1"}, null);
+ profile.setDimensions(new String[]{"x"});
+ profile.set("a", "original", new String[]{"x1"}, null);
profile.setOverridable("a", false, DimensionValues.empty);
assertFalse(profile.isDeclaredOverridable("a", null));
Query query = new Query(HttpRequest.createTestRequest("?x=x1&a=overridden", Method.GET), profile.compile(null));
- assertEquals("original",query.properties().get("a"));
+ assertEquals("original", query.properties().get("a"));
}
/** Tests having both an explicit reference and an override */
@Test
- public void testExplicitReferenceOverride() {
+ void testExplicitReferenceOverride() {
QueryProfile a1 = new QueryProfile("a1");
- a1.set("b","a1.b", null);
+ a1.set("b", "a1.b", null);
QueryProfile profile = new QueryProfile("test");
- profile.set("a",a1, null);
- profile.set("a.b","a.b", null);
+ profile.set("a", a1, null);
+ profile.set("a.b", "a.b", null);
assertEquals("a.b", profile.compile(null).get("a.b"));
}
@Test
- public void testSettingNonLeaf1() {
- QueryProfile p=new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ void testSettingNonLeaf1() {
+ QueryProfile p = new QueryProfile("test");
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
@@ -415,10 +411,10 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf2() {
+ void testSettingNonLeaf2() {
QueryProfile p = new QueryProfile("test");
- p.set("a.b","a.b-value", null);
- p.set("a","a-value", null);
+ p.set("a.b", "a.b-value", null);
+ p.set("a", "a-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
@@ -426,48 +422,48 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf3a() {
+ void testSettingNonLeaf3a() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value", null);
- p.set("a","a-value",new String[] {"x1"}, null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", null);
+ p.set("a", "a-value", new String[]{"x1"}, null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(p.get("a"));
assertEquals("a.b-value", cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b", new String[] {"x1"}));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", new String[]{"x1"}));
}
@Test
- public void testSettingNonLeaf3b() {
+ void testSettingNonLeaf3b() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a","a-value",new String[] {"x1"}, null);
- p.set("a.b","a.b-value", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a", "a-value", new String[]{"x1"}, null);
+ p.set("a.b", "a.b-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(cp.get("a"));
assertEquals("a.b-value", cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b",new String[] {"x1"}));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", new String[]{"x1"}));
}
@Test
- public void testSettingNonLeaf4a() {
+ void testSettingNonLeaf4a() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value",new String[] {"x1"}, null);
- p.set("a","a-value", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", new String[]{"x1"}, null);
+ p.set("a", "a-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
assertNull(cp.get("a.b"));
- assertEquals("a-value", cp.get("a",new String[] {"x1"}));
- assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
+ assertEquals("a-value", cp.get("a", new String[]{"x1"}));
+ assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
}
public void testSettingNonLeaf4b() {
@@ -485,36 +481,36 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf5() {
+ void testSettingNonLeaf5() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value",new String[] {"x1"}, null);
- p.set("a","a-value",new String[] {"x1"}, null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", new String[]{"x1"}, null);
+ p.set("a", "a-value", new String[]{"x1"}, null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(cp.get("a"));
assertNull(cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
}
@Test
- public void testListingWithNonLeafs() {
+ void testListingWithNonLeafs() {
QueryProfile p = new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
Map<String, Object> values = p.compile(null).listValues("a");
assertEquals(2, values.size());
- p.set("a","a-value", null);
+ p.set("a", "a-value", null);
assertEquals("a.b-value", values.get("b"));
}
@Test
- public void testListingSources() {
+ void testListingSources() {
QueryProfile p = new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
{
Map<String, ValueWithSource> values = p.compile(null).listValuesWithSources(new CompoundName(""), new HashMap<>(), null);
@@ -534,30 +530,30 @@ public class QueryProfileTestCase {
}
@Test
- public void testRankTypeNames() {
- QueryProfile p = new QueryProfile("test");
- p.set("a.$b","foo", null);
- p.set("a.query(b)", "bar", null);
- p.set("a.b.default-index", "fuu", null);
- CompiledQueryProfile cp = p.compile(null);
-
- assertEquals("foo", cp.get("a.$b"));
- assertEquals("bar", cp.get("a.query(b)"));
- assertEquals("fuu", cp.get("a.b.default-index"));
-
- Map<String,Object> p1 = cp.listValues("");
- assertEquals("foo", p1.get("a.$b"));
- assertEquals("bar", p1.get("a.query(b)"));
- assertEquals("fuu", p1.get("a.b.default-index"));
-
- Map<String,Object> p2 = cp.listValues("a");
- assertEquals("foo", p2.get("$b"));
- assertEquals("bar", p2.get("query(b)"));
- assertEquals("fuu", p2.get("b.default-index"));
+ void testRankTypeNames() {
+ QueryProfile p = new QueryProfile("test");
+ p.set("a.$b", "foo", null);
+ p.set("a.query(b)", "bar", null);
+ p.set("a.b.default-index", "fuu", null);
+ CompiledQueryProfile cp = p.compile(null);
+
+ assertEquals("foo", cp.get("a.$b"));
+ assertEquals("bar", cp.get("a.query(b)"));
+ assertEquals("fuu", cp.get("a.b.default-index"));
+
+ Map<String, Object> p1 = cp.listValues("");
+ assertEquals("foo", p1.get("a.$b"));
+ assertEquals("bar", p1.get("a.query(b)"));
+ assertEquals("fuu", p1.get("a.b.default-index"));
+
+ Map<String, Object> p2 = cp.listValues("a");
+ assertEquals("foo", p2.get("$b"));
+ assertEquals("bar", p2.get("query(b)"));
+ assertEquals("fuu", p2.get("b.default-index"));
}
@Test
- public void testQueryProfileInlineValueReassignment() {
+ void testQueryProfileInlineValueReassignment() {
QueryProfile p = new QueryProfile("test");
p.set("source.rel.params.query", "%{model.queryString}", null);
p.freeze();
@@ -570,9 +566,9 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileInlineValueReassignmentSimpleName() {
+ void testQueryProfileInlineValueReassignmentSimpleName() {
QueryProfile p = new QueryProfile("test");
- p.set("key","%{model.queryString}", null);
+ p.set("key", "%{model.queryString}", null);
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?query=foo", Method.GET), p.compile(null));
assertEquals("foo", q.properties().get("key"));
@@ -583,7 +579,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileInlineValueReassignmentSimpleNameGenericProperty() {
+ void testQueryProfileInlineValueReassignmentSimpleNameGenericProperty() {
QueryProfile p = new QueryProfile("test");
p.set("key", "%{value}", null);
p.freeze();
@@ -596,7 +592,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileModelValueListing() {
+ void testQueryProfileModelValueListing() {
QueryProfile p = new QueryProfile("test");
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?query=bar", Method.GET), p.compile(null));
@@ -608,21 +604,21 @@ public class QueryProfileTestCase {
}
@Test
- public void testEmptyBoolean() {
+ void testEmptyBoolean() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x","y"});
- p.set("clustering.something","bar", null);
- p.set("clustering.something","bar", new String[] {"x1","y1"}, null);
+ p.setDimensions(new String[]{"x", "y"});
+ p.set("clustering.something", "bar", null);
+ p.set("clustering.something", "bar", new String[]{"x1", "y1"}, null);
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?x=x1&y=y1&query=bar&clustering.timeline.kano=tur&" +
- "clustering.enable=true&clustering.timeline.bucketspec=-" +
- "7d/3h&clustering.timeline.tophit=false&clustering.timeli" +
- "ne=true", Method.GET), p.compile(null));
+ "clustering.enable=true&clustering.timeline.bucketspec=-" +
+ "7d/3h&clustering.timeline.tophit=false&clustering.timeli" +
+ "ne=true", Method.GET), p.compile(null));
assertTrue(q.properties().getBoolean("clustering.timeline", false));
}
@Test
- public void testSubstitutionInTrace() {
+ void testSubstitutionInTrace() {
QueryProfile profile = new QueryProfile("test");
profile.set("property", "%{foo}", null);
CompiledQueryProfile cProfile = profile.compile(null);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
index 3e1a101628c..43078db66d0 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
@@ -5,13 +5,13 @@ package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DimensionValues;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class QueryProfileVariantsCloneTestCase {
@Test
- public void test_that_interior_and_leaf_values_on_a_path_are_preserved_when_cloning() {
+ void test_that_interior_and_leaf_values_on_a_path_are_preserved_when_cloning() {
Map<String, String> dimensionBinding = createDimensionBinding("location", "norway");
QueryProfile profile = new QueryProfile("profile");
@@ -32,10 +32,10 @@ public class QueryProfileVariantsCloneTestCase {
CompiledQueryProfile clone = profile.compile(null).clone();
assertEquals(profile.get("interior", dimensionBinding, null),
- clone.get("interior", dimensionBinding));
+ clone.get("interior", dimensionBinding));
assertEquals(profile.get("interior.leaf", dimensionBinding, null),
- clone.get("interior.leaf", dimensionBinding));
+ clone.get("interior.leaf", dimensionBinding));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
index 3cf2949f33c..1a6cfee75a5 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
@@ -19,8 +19,8 @@ import com.yahoo.search.query.profile.QueryProfileVariant;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.ValueWithSource;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -28,9 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -38,75 +36,75 @@ import static org.junit.Assert.assertTrue;
public class QueryProfileVariantsTestCase {
@Test
- public void testSimple() {
+ void testSimple() {
QueryProfile profile = new QueryProfile("a");
- profile.set("a","a.deflt", null);
- profile.setDimensions(new String[] {"x","y","z"});
- profile.set("a","a.1.*.*", new String[] {"x1",null,null}, null);
- profile.set("a","a.1.*.1", new String[] {"x1",null,"z1"}, null);
- profile.set("a","a.1.*.5", new String[] {"x1",null,"z5"}, null);
- profile.set("a","a.1.1.*", new String[] {"x1","y1",null}, null);
- profile.set("a","a.1.5.*", new String[] {"x1","y5",null}, null);
- profile.set("a","a.1.1.1", new String[] {"x1","y1","z1"}, null);
- profile.set("a","a.2.1.1", new String[] {"x2","y1","z1"}, null);
- profile.set("a","a.1.2.2", new String[] {"x1","y2","z2"}, null);
- profile.set("a","a.1.2.3", new String[] {"x1","y2","z3"}, null);
- profile.set("a","a.2.*.*", new String[] {"x2" }, null); // Same as ,null,null
+ profile.set("a", "a.deflt", null);
+ profile.setDimensions(new String[]{"x", "y", "z"});
+ profile.set("a", "a.1.*.*", new String[]{"x1", null, null}, null);
+ profile.set("a", "a.1.*.1", new String[]{"x1", null, "z1"}, null);
+ profile.set("a", "a.1.*.5", new String[]{"x1", null, "z5"}, null);
+ profile.set("a", "a.1.1.*", new String[]{"x1", "y1", null}, null);
+ profile.set("a", "a.1.5.*", new String[]{"x1", "y5", null}, null);
+ profile.set("a", "a.1.1.1", new String[]{"x1", "y1", "z1"}, null);
+ profile.set("a", "a.2.1.1", new String[]{"x2", "y1", "z1"}, null);
+ profile.set("a", "a.1.2.2", new String[]{"x1", "y2", "z2"}, null);
+ profile.set("a", "a.1.2.3", new String[]{"x1", "y2", "z3"}, null);
+ profile.set("a", "a.2.*.*", new String[]{"x2" }, null); // Same as ,null,null
CompiledQueryProfile cprofile = profile.compile(null);
// Perfect matches
- assertGet("a.deflt","a", new String[] {null,null,null}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1",null,null}, profile, cprofile);
- assertGet("a.1.1.*","a", new String[] {"x1","y1",null}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5",null}, profile, cprofile);
- assertGet("a.1.*.1","a", new String[] {"x1",null,"z1"}, profile, cprofile);
- assertGet("a.1.*.5","a", new String[] {"x1",null,"z5"}, profile, cprofile);
- assertGet("a.1.1.1","a", new String[] {"x1","y1","z1"}, profile, cprofile);
- assertGet("a.2.1.1","a", new String[] {"x2","y1","z1"}, profile, cprofile);
- assertGet("a.1.2.2","a", new String[] {"x1","y2","z2"}, profile, cprofile);
- assertGet("a.1.2.3","a", new String[] {"x1","y2","z3"}, profile, cprofile);
- assertGet("a.2.*.*","a", new String[] {"x2",null,null}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{null, null, null}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", null, null}, profile, cprofile);
+ assertGet("a.1.1.*", "a", new String[]{"x1", "y1", null}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", null}, profile, cprofile);
+ assertGet("a.1.*.1", "a", new String[]{"x1", null, "z1"}, profile, cprofile);
+ assertGet("a.1.*.5", "a", new String[]{"x1", null, "z5"}, profile, cprofile);
+ assertGet("a.1.1.1", "a", new String[]{"x1", "y1", "z1"}, profile, cprofile);
+ assertGet("a.2.1.1", "a", new String[]{"x2", "y1", "z1"}, profile, cprofile);
+ assertGet("a.1.2.2", "a", new String[]{"x1", "y2", "z2"}, profile, cprofile);
+ assertGet("a.1.2.3", "a", new String[]{"x1", "y2", "z3"}, profile, cprofile);
+ assertGet("a.2.*.*", "a", new String[]{"x2", null, null}, profile, cprofile);
// Wildcard matches
- assertGet("a.deflt","a", new String[] {"x?","y?","z?"}, profile, cprofile);
- assertGet("a.deflt","a", new String[] {"x?","y1","z1"}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1","y?","z?"}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1","y?","z?"}, profile, cprofile);
- assertGet("a.1.1.*","a", new String[] {"x1","y1","z?"}, profile, cprofile);
- assertGet("a.1.*.1","a", new String[] {"x1","y?","z1"}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5","z?"}, profile, cprofile);
- assertGet("a.1.*.5","a", new String[] {"x1","y?","z5"}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5","z5"}, profile, cprofile); // Left dimension gets precedence
- assertGet("a.2.*.*","a", new String[] {"x2","y?","z?"}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{"x?", "y?", "z?"}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{"x?", "y1", "z1"}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", "y?", "z?"}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", "y?", "z?"}, profile, cprofile);
+ assertGet("a.1.1.*", "a", new String[]{"x1", "y1", "z?"}, profile, cprofile);
+ assertGet("a.1.*.1", "a", new String[]{"x1", "y?", "z1"}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", "z?"}, profile, cprofile);
+ assertGet("a.1.*.5", "a", new String[]{"x1", "y?", "z5"}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", "z5"}, profile, cprofile); // Left dimension gets precedence
+ assertGet("a.2.*.*", "a", new String[]{"x2", "y?", "z?"}, profile, cprofile);
}
@Test
- public void testReferenceInVariant() {
+ void testReferenceInVariant() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] { "d1" });
+ test.setDimensions(new String[]{"d1"});
registry.register(test);
QueryProfile references = new QueryProfile("referenced");
- references.setDimensions(new String[] { "d1" });
+ references.setDimensions(new String[]{"d1"});
registry.register(references);
QueryProfile other = new QueryProfile("other");
- other.setDimensions(new String[] { "d1" });
+ other.setDimensions(new String[]{"d1"});
registry.register(other);
- test.set( "a", references, new String[] { "d1v"}, registry);
- test.set( "a.b", "test-value", new String[] { "d1v"}, registry);
- other.set( "a", references, new String[] { "d1v"}, registry);
- other.set("a.b", "other-value", new String[] { "d1v"}, registry);
+ test.set("a", references, new String[]{"d1v"}, registry);
+ test.set("a.b", "test-value", new String[]{"d1v"}, registry);
+ other.set("a", references, new String[]{"d1v"}, registry);
+ other.set("a.b", "other-value", new String[]{"d1v"}, registry);
- assertEquals("test-value", test.get("a.b", new String[] { "d1v"}));
- assertEquals("other-value", other.get("a.b", new String[] { "d1v"}));
- assertNull(references.get("b", new String[] { "d1v"}));
+ assertEquals("test-value", test.get("a.b", new String[]{"d1v"}));
+ assertEquals("other-value", other.get("a.b", new String[]{"d1v"}));
+ assertNull(references.get("b", new String[]{"d1v"}));
var cRegistry = registry.compile();
assertEquals("test-value",
- cRegistry.getComponent("test").get("a.b", Map.of("d1", "d1v")));
+ cRegistry.getComponent("test").get("a.b", Map.of("d1", "d1v")));
}
/**
@@ -114,7 +112,7 @@ public class QueryProfileVariantsTestCase {
* and also setting a value within that variants subspace.
*/
@Test
- public void testVariantReference() {
+ void testVariantReference() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile parent = new QueryProfile("parent");
@@ -123,24 +121,24 @@ public class QueryProfileVariantsTestCase {
QueryProfile referenced = new QueryProfile("referenced");
referenced.addInherited(parent);
- referenced.setDimensions(new String[] {"d2", "d3"});
+ referenced.setDimensions(new String[]{"d2", "d3"});
registry.register(referenced);
QueryProfile base = new QueryProfile("base");
base.setDimensions(new String[]{"d1", "d2", "d3"});
- base.set("a", referenced, new String[] {null, null, "d3-val"}, registry);
- assertEquals("Variant dimensions are not overridden by the referenced dimensions",
- "[d1, d2, d3]",
- ((QueryProfile)base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString());
- base.set("a.b", 1, new String[] {null, null, "d3-val"}, registry);
+ base.set("a", referenced, new String[]{null, null, "d3-val"}, registry);
+ assertEquals("[d1, d2, d3]",
+ ((QueryProfile) base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString(),
+ "Variant dimensions are not overridden by the referenced dimensions");
+ base.set("a.b", 1, new String[]{null, null, "d3-val"}, registry);
QueryProfileVariant aVariants = base.getVariants().getVariants().get(0);
- assertEquals("Variant dimensions are not overridden by the referenced dimensions",
- "[d1, d2, d3]",
- ((QueryProfile)base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString());
+ assertEquals("[d1, d2, d3]",
+ ((QueryProfile) base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString(),
+ "Variant dimensions are not overridden by the referenced dimensions");
}
@Test
- public void testReference() {
+ void testReference() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
registry.register(test);
@@ -151,9 +149,9 @@ public class QueryProfileVariantsTestCase {
QueryProfile other = new QueryProfile("other");
registry.register(other);
- test.set( "a", references, registry);
- test.set( "a.b", "test-value", registry);
- other.set( "a", references, registry);
+ test.set("a", references, registry);
+ test.set("a.b", "test-value", registry);
+ other.set("a", references, registry);
other.set("a.b", "other-value", registry);
assertEquals("test-value", test.get("a.b"));
@@ -162,21 +160,21 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantInReferencedAndParentWithOtherMatchingVariant() {
+ void testVariantInReferencedAndParentWithOtherMatchingVariant() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "x", "y" } );
- parent.set("other", "otherValue", new String[] { "x1", "y1" }, registry );
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("other", "otherValue", new String[]{"x1", "y1"}, registry);
QueryProfile profile = new QueryProfile("test");
profile.addInherited(parent);
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "x", "y", "z" });
+ referenced.setDimensions(new String[]{"x", "y", "z"});
registry.register(parent);
registry.register(profile);
registry.register(referenced);
profile.set("a.b", referenced, registry);
referenced.set("c", "default_value", registry);
- referenced.set("c", "variant_value", new String[] { "x1", null, "z1" }, registry);
+ referenced.set("c", "variant_value", new String[]{"x1", null, "z1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -186,9 +184,9 @@ public class QueryProfileVariantsTestCase {
{
Map<String, ValueWithSource> values = cRegistry.findQueryProfile("test")
- .listValuesWithSources(new CompoundName(""),
- new HashMap<>(),
- null);
+ .listValuesWithSources(new CompoundName(""),
+ new HashMap<>(),
+ null);
assertEquals(1, values.size());
assertEquals("default_value", values.get("a.b.c").value());
assertEquals("referenced", values.get("a.b.c").source());
@@ -197,9 +195,9 @@ public class QueryProfileVariantsTestCase {
{
Map<String, ValueWithSource> values = cRegistry.findQueryProfile("test")
- .listValuesWithSources(new CompoundName(""),
- toMap("x=x1", "y=y1", "z=z1"),
- null);
+ .listValuesWithSources(new CompoundName(""),
+ toMap("x=x1", "y=y1", "z=z1"),
+ null);
assertEquals(2, values.size());
assertEquals("variant_value", values.get("a.b.c").value());
assertEquals("referenced", values.get("a.b.c").source());
@@ -212,16 +210,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testSwitchingDimensionOrderInReferencedVariantWithFullOverlap() {
+ void testSwitchingDimensionOrderInReferencedVariantWithFullOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "y", "x" });
+ referenced.setDimensions(new String[]{"y", "x"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1", "y1" }, registry);
- referenced.set("c", "variant_value", new String[] { "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1", "y1"}, registry);
+ referenced.set("c", "variant_value", new String[]{"y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -230,16 +228,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testSameDimensionOrderInReferencedVariantWithPartialOverlap() {
+ void testSameDimensionOrderInReferencedVariantWithPartialOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "x", "y" });
+ referenced.setDimensions(new String[]{"x", "y"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1" }, registry);
- referenced.set("c", "variant_value", new String[] { null, "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1"}, registry);
+ referenced.set("c", "variant_value", new String[]{null, "y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -247,18 +245,19 @@ public class QueryProfileVariantsTestCase {
assertEquals("variant_value", new Query("?x=x1&i=i1&j=j1&y=y1", cTest).properties().get("a.b.c"));
}
+ // Switching order is not supported
@Test
- @Ignore // Switching order is not supported
- public void testSwitchingDimensionOrderInReferencedVariantWithPartialOverlap() {
+ @Disabled
+ void testSwitchingDimensionOrderInReferencedVariantWithPartialOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "y", "x" });
+ referenced.setDimensions(new String[]{"y", "x"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1" }, registry);
- referenced.set("c", "variant_value", new String[] { "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1"}, registry);
+ referenced.set("c", "variant_value", new String[]{"y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -267,12 +266,12 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testMultipleMatchingVariantsAndDefault() {
+ void testMultipleMatchingVariantsAndDefault() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "a", "b" });
+ profile.setDimensions(new String[]{"a", "b"});
profile.set("property1", "property1_default", null);
- profile.set("property1", "property1_variantB", new String[] { null, "b1" }, null);
- profile.set("property2", "property2_variantA", new String[] { "a1", null }, null);
+ profile.set("property1", "property1_variantB", new String[]{null, "b1"}, null);
+ profile.set("property2", "property2_variantA", new String[]{"a1", null}, null);
CompiledQueryProfile cProfile = profile.compile(null);
Query query = new Query("?a=a1&b=b1&b=b1", cProfile);
@@ -281,16 +280,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testInheritedVariants() {
+ void testInheritedVariants() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "parentDim" });
+ parent.setDimensions(new String[]{"parentDim"});
parent.set("property", "defaultValue", null);
- parent.set("property", "variantValue", new String[] { "V2" }, null);
+ parent.set("property", "variantValue", new String[]{"V2"}, null);
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
- child.setDimensions(new String[] { "childDim" });
- child.set("otherProperty", "otherPropertyValue", new String[] { "V1" }, null);
+ child.setDimensions(new String[]{"childDim"});
+ child.set("otherProperty", "otherPropertyValue", new String[]{"V1"}, null);
CompiledQueryProfile cchild = child.compile(null);
assertEquals("defaultValue", new Query("?query=test", cchild).properties().get("property"));
@@ -301,19 +300,19 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testInheritedVariantsMultipleInheritance() {
+ void testInheritedVariantsMultipleInheritance() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "parentDim" });
+ parent.setDimensions(new String[]{"parentDim"});
parent.set("property", "defaultValue", null);
- parent.set("property", "variantValue", new String[] { "V2" }, null);
+ parent.set("property", "variantValue", new String[]{"V2"}, null);
QueryProfile otherParent = new QueryProfile("otherParent");
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.addInherited(otherParent);
- child.setDimensions(new String[] { "childDim" });
- child.set("otherProperty", "otherPropertyValue", new String[] { "V1" }, null);
+ child.setDimensions(new String[]{"childDim"});
+ child.set("otherProperty", "otherPropertyValue", new String[]{"V1"}, null);
CompiledQueryProfile cchild = child.compile(null);
assertEquals("defaultValue", new Query("?query=test", cchild).properties().get("property"));
@@ -324,12 +323,12 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsOfInlineCompound() {
+ void testVariantsOfInlineCompound() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a.b", "a.b", null);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, null);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, null);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, null);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -339,13 +338,13 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testOverlappingProfiles() {
+ void testOverlappingProfiles() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"region", "model", "bucket"});
- profile.set("a", "us,nokia,* : a", new String[] {"us", "nokia", null }, null);
- profile.set("b", "us,nokia,* : b", new String[] {"us", "nokia", null }, null);
- profile.set("c", "us,*,bucket1: c", new String[] {"us", null, "bucket1"}, null);
- profile.set("d", "us,*,bucket1: d", new String[] {"us", null, "bucket1"}, null);
+ profile.setDimensions(new String[]{"region", "model", "bucket"});
+ profile.set("a", "us,nokia,* : a", new String[]{"us", "nokia", null }, null);
+ profile.set("b", "us,nokia,* : b", new String[]{"us", "nokia", null }, null);
+ profile.set("c", "us,*,bucket1: c", new String[]{"us", null, "bucket1"}, null);
+ profile.set("d", "us,*,bucket1: d", new String[]{"us", null, "bucket1"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
var parameters = toMap("region=us", "model=nokia", "bucket=bucket1");
@@ -360,15 +359,15 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsOfExplicitCompound() {
+ void testVariantsOfExplicitCompound() {
QueryProfile a1 = new QueryProfile("a1");
a1.set("b", "a.b", null);
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a", a1, null);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, null);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, null);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, null);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -378,11 +377,11 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testCompound() {
+ void testCompound() {
// Configuration phase
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x","y"});
+ profile.setDimensions(new String[]{"x", "y"});
QueryProfile a1 = new QueryProfile("a1");
a1.set("b", "a1.b.default", null);
@@ -396,23 +395,23 @@ public class QueryProfileVariantsTestCase {
a2.set("d", "a2.d.default", null);
a2.set("e", "a2.e.default", null);
- profile.set("a",a1, null); // Must set profile references before overrides
+ profile.set("a", a1, null); // Must set profile references before overrides
profile.set("a.b", "a.b.default-override", null);
profile.set("a.c", "a.c.default-override", null);
profile.set("a.d", "a.d.default-override", null);
profile.set("a.g", "a.g.default-override", null);
- String[] d1 = new String[] { "x1","y1" };
+ String[] d1 = new String[]{"x1", "y1"};
profile.set("a", a1, d1, null);
profile.set("a.b", "x1.y1.a.b.default-override", d1, null);
profile.set("a.c", "x1.y1.a.c.default-override", d1, null);
profile.set("a.g", "x1.y1.a.g.default-override", d1, null); // This value is never manifest because the runtime override overrides all variants
- String[] d2 = new String[] { "x1","y2" };
- profile.set("a.b","x1.y2.a.b.default-override", d2, null);
- profile.set("a.c","x1.y2.a.c.default-override", d2, null);
+ String[] d2 = new String[]{"x1", "y2"};
+ profile.set("a.b", "x1.y2.a.b.default-override", d2, null);
+ profile.set("a.c", "x1.y2.a.c.default-override", d2, null);
- String[] d3 = new String[] { "x2","y1" };
+ String[] d3 = new String[]{"x2", "y1"};
profile.set("a", a2, d3, null);
profile.set("a.b", "x2.y1.a.b.default-override", d3, null);
profile.set("a.c", "x2.y1.a.c.default-override", d3, null);
@@ -466,39 +465,39 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantNotInBase() {
+ void testVariantNotInBase() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("InX1Only", "x1", new String[] { "x1" }, null);
+ test.setDimensions(new String[]{"x"});
+ test.set("InX1Only", "x1", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals("x1", ctest.get("InX1Only", toMap("x=x1")));
- assertEquals(null, ctest.get("InX1Only", toMap("x=x2")));
- assertEquals(null, ctest.get("InX1Only"));
+ assertNull(ctest.get("InX1Only", toMap("x=x2")));
+ assertNull(ctest.get("InX1Only"));
}
@Test
- public void testVariantNotInBaseSpaceVariantValue() {
+ void testVariantNotInBaseSpaceVariantValue() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] { "x" });
- test.set("InX1Only", "x1", new String[] { "x 1" }, null);
+ test.setDimensions(new String[]{"x"});
+ test.set("InX1Only", "x1", new String[]{"x 1"}, null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals("x1", ctest.get("InX1Only", toMap("x=x 1")));
- assertEquals(null, ctest.get("InX1Only", toMap("x=x 2")));
- assertEquals(null, ctest.get("InX1Only"));
+ assertNull(ctest.get("InX1Only", toMap("x=x 2")));
+ assertNull(ctest.get("InX1Only"));
}
@Test
- public void testDimensionsInSuperType() {
+ void testDimensionsInSuperType() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] {"x", "y"});
+ parent.setDimensions(new String[]{"x", "y"});
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.set("a", "a.default", null);
- child.set("a", "a.x1.y1", new String[] {"x1", "y1"}, null);
- child.set("a", "a.x1.y2", new String[] {"x1", "y2"}, null);
+ child.set("a", "a.x1.y1", new String[]{"x1", "y1"}, null);
+ child.set("a", "a.x1.y2", new String[]{"x1", "y2"}, null);
CompiledQueryProfile cchild = child.compile(null);
@@ -508,15 +507,15 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testDimensionsInSuperTypeRuntime() {
+ void testDimensionsInSuperTypeRuntime() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "x", "y" });
+ parent.setDimensions(new String[]{"x", "y"});
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.set("a", "a.default", null);
child.set("a", "a.x1.y1", new String[]{"x1", "y1"}, null);
child.set("a", "a.x1.y2", new String[]{"x1", "y2"}, null);
- Properties overridable=new QueryProfileProperties(child.compile(null));
+ Properties overridable = new QueryProfileProperties(child.compile(null));
assertEquals("a.default", child.get("a"));
assertEquals("a.x1.y1", overridable.get("a", toMap("x=x1", "y=y1")));
@@ -524,220 +523,220 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsAreResolvedBeforeInheritance() {
- QueryProfile parent=new QueryProfile("parent");
- parent.setDimensions(new String[] {"x","y"});
- parent.set("a","p.a.default", null);
- parent.set("a","p.a.x1.y1",new String[] {"x1","y1"}, null);
- parent.set("a","p.a.x1.y2",new String[] {"x1","y2"}, null);
- parent.set("b","p.b.default", null);
- parent.set("b","p.b.x1.y1",new String[] {"x1","y1"}, null);
- parent.set("b","p.b.x1.y2",new String[] {"x1","y2"}, null);
- QueryProfile child=new QueryProfile("child");
- child.setDimensions(new String[] {"x","y"});
+ void testVariantsAreResolvedBeforeInheritance() {
+ QueryProfile parent = new QueryProfile("parent");
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("a", "p.a.default", null);
+ parent.set("a", "p.a.x1.y1", new String[]{"x1", "y1"}, null);
+ parent.set("a", "p.a.x1.y2", new String[]{"x1", "y2"}, null);
+ parent.set("b", "p.b.default", null);
+ parent.set("b", "p.b.x1.y1", new String[]{"x1", "y1"}, null);
+ parent.set("b", "p.b.x1.y2", new String[]{"x1", "y2"}, null);
+ QueryProfile child = new QueryProfile("child");
+ child.setDimensions(new String[]{"x", "y"});
child.addInherited(parent);
- child.set("a","c.a.default", null);
- child.set("a","c.a.x1.y1",new String[] {"x1","y1"}, null);
+ child.set("a", "c.a.default", null);
+ child.set("a", "c.a.x1.y1", new String[]{"x1", "y1"}, null);
CompiledQueryProfile cchild = child.compile(null);
- assertEquals("c.a.default",cchild.get("a"));
- assertEquals("c.a.x1.y1",cchild.get("a", toMap("x=x1", "y=y1")));
- assertEquals("c.a.default",cchild.get("a", toMap("x=x1", "y=y2")));
- assertEquals("p.b.default",cchild.get("b"));
- assertEquals("p.b.x1.y1",cchild.get("b", toMap("x=x1", "y=y1")));
- assertEquals("p.b.x1.y2",cchild.get("b", toMap("x=x1", "y=y2")));
+ assertEquals("c.a.default", cchild.get("a"));
+ assertEquals("c.a.x1.y1", cchild.get("a", toMap("x=x1", "y=y1")));
+ assertEquals("c.a.default", cchild.get("a", toMap("x=x1", "y=y2")));
+ assertEquals("p.b.default", cchild.get("b"));
+ assertEquals("p.b.x1.y1", cchild.get("b", toMap("x=x1", "y=y1")));
+ assertEquals("p.b.x1.y2", cchild.get("b", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantsAreResolvedBeforeInheritanceSimplified() {
- QueryProfile parent=new QueryProfile("parent");
- parent.setDimensions(new String[] {"x","y"});
- parent.set("a","p.a.x1.y2",new String[] {"x1","y2"}, null);
+ void testVariantsAreResolvedBeforeInheritanceSimplified() {
+ QueryProfile parent = new QueryProfile("parent");
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("a", "p.a.x1.y2", new String[]{"x1", "y2"}, null);
- QueryProfile child=new QueryProfile("child");
- child.setDimensions(new String[] {"x","y"});
+ QueryProfile child = new QueryProfile("child");
+ child.setDimensions(new String[]{"x", "y"});
child.addInherited(parent);
- child.set("a","c.a.default", null);
+ child.set("a", "c.a.default", null);
- assertEquals("c.a.default",child.compile(null).get("a", toMap("x=x1", "y=y2")));
+ assertEquals("c.a.default", child.compile(null).get("a", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritance() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x","y"});
- QueryProfile defaultParent=new QueryProfile("defaultParent");
- defaultParent.set("a","a-default", null);
- QueryProfile x1Parent=new QueryProfile("x1Parent");
- x1Parent.set("a","a-x1", null);
- x1Parent.set("d","d-x1", null);
- x1Parent.set("e","e-x1", null);
- QueryProfile x1y1Parent=new QueryProfile("x1y1Parent");
- x1y1Parent.set("a","a-x1y1", null);
- QueryProfile x1y2Parent=new QueryProfile("x1y2Parent");
- x1y2Parent.set("a","a-x1y2", null);
- x1y2Parent.set("b","b-x1y2", null);
- x1y2Parent.set("c","c-x1y2", null);
+ void testVariantInheritance() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x", "y"});
+ QueryProfile defaultParent = new QueryProfile("defaultParent");
+ defaultParent.set("a", "a-default", null);
+ QueryProfile x1Parent = new QueryProfile("x1Parent");
+ x1Parent.set("a", "a-x1", null);
+ x1Parent.set("d", "d-x1", null);
+ x1Parent.set("e", "e-x1", null);
+ QueryProfile x1y1Parent = new QueryProfile("x1y1Parent");
+ x1y1Parent.set("a", "a-x1y1", null);
+ QueryProfile x1y2Parent = new QueryProfile("x1y2Parent");
+ x1y2Parent.set("a", "a-x1y2", null);
+ x1y2Parent.set("b", "b-x1y2", null);
+ x1y2Parent.set("c", "c-x1y2", null);
test.addInherited(defaultParent);
- test.addInherited(x1Parent,new String[] {"x1"});
- test.addInherited(x1y1Parent,new String[] {"x1","y1"});
- test.addInherited(x1y2Parent,new String[] {"x1","y2"});
- test.set("c","c-x1",new String[] {"x1"}, null);
- test.set("e","e-x1y2",new String[] {"x1","y2"}, null);
+ test.addInherited(x1Parent, new String[]{"x1"});
+ test.addInherited(x1y1Parent, new String[]{"x1", "y1"});
+ test.addInherited(x1y2Parent, new String[]{"x1", "y2"});
+ test.set("c", "c-x1", new String[]{"x1"}, null);
+ test.set("e", "e-x1y2", new String[]{"x1", "y2"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("a-default",ctest.get("a"));
- assertEquals("a-x1",ctest.get("a", toMap("x=x1")));
- assertEquals("a-x1y1",ctest.get("a", toMap("x=x1", "y=y1")));
- assertEquals("a-x1y2",ctest.get("a", toMap("x=x1", "y=y2")));
+ assertEquals("a-default", ctest.get("a"));
+ assertEquals("a-x1", ctest.get("a", toMap("x=x1")));
+ assertEquals("a-x1y1", ctest.get("a", toMap("x=x1", "y=y1")));
+ assertEquals("a-x1y2", ctest.get("a", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("b"));
- assertEquals(null,ctest.get("b", toMap("x=x1")));
- assertEquals(null,ctest.get("b", toMap("x=x1", "y=y1")));
- assertEquals("b-x1y2",ctest.get("b", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("b"));
+ assertNull(ctest.get("b", toMap("x=x1")));
+ assertNull(ctest.get("b", toMap("x=x1", "y=y1")));
+ assertEquals("b-x1y2", ctest.get("b", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("c"));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1")));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1", "y=y1")));
- assertEquals("c-x1y2",ctest.get("c", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("c"));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1")));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1", "y=y1")));
+ assertEquals("c-x1y2", ctest.get("c", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("d"));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1")));
+ assertNull(ctest.get("d"));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1")));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1", "y=y1")));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1", "y=y2")));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1", "y=y1")));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("d"));
- assertEquals("e-x1",ctest.get("e", toMap("x=x1")));
- assertEquals("e-x1",ctest.get("e", toMap("x=x1", "y=y1")));
- assertEquals("e-x1y2",ctest.get("e", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("d"));
+ assertEquals("e-x1", ctest.get("e", toMap("x=x1")));
+ assertEquals("e-x1", ctest.get("e", toMap("x=x1", "y=y1")));
+ assertEquals("e-x1y2", ctest.get("e", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritanceSimplified() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x","y"});
- QueryProfile x1y2Parent=new QueryProfile("x1y2Parent");
- x1y2Parent.set("c","c-x1y2", null);
- test.addInherited(x1y2Parent,new String[] {"x1","y2"});
- test.set("c","c-x1",new String[] {"x1"}, null);
+ void testVariantInheritanceSimplified() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x", "y"});
+ QueryProfile x1y2Parent = new QueryProfile("x1y2Parent");
+ x1y2Parent.set("c", "c-x1y2", null);
+ test.addInherited(x1y2Parent, new String[]{"x1", "y2"});
+ test.set("c", "c-x1", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals(null,ctest.get("c"));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1")));
+ assertNull(ctest.get("c"));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1")));
assertEquals("c-x1", ctest.get("c", toMap("x=x1", "y=y1")));
- assertEquals("c-x1y2",ctest.get("c", toMap("x=x1", "y=y2")));
+ assertEquals("c-x1y2", ctest.get("c", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritanceWithCompoundReferences() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("a.b","default-a.b", null);
+ void testVariantInheritanceWithCompoundReferences() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ test.set("a.b", "default-a.b", null);
- QueryProfile ac=new QueryProfile("ac");
- ac.set("a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("a.b", "x1-a.b", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("Basic functionality","default-a.b",ctest.get("a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctest.get("a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference overriding works","x1-a.b",ctest.get("a.b", toMap("x=x1")));
+ assertEquals("default-a.b", ctest.get("a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctest.get("a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("x1-a.b", ctest.get("a.b", toMap("x=x1")), "Inherited variance reference overriding works");
}
@Test
- public void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtFirstLevel() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("o.a.b","default-a.b", null);
+ void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtFirstLevel() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ test.set("o.a.b", "default-a.b", null);
- QueryProfile ac=new QueryProfile("ac");
- ac.set("o.a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("o.a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("o.a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("o.a.b", "x1-a.b", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("Basic functionality","default-a.b",ctest.get("o.a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctest.get("o.a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference overriding works","x1-a.b",ctest.get("o.a.b", toMap("x=x1")));
+ assertEquals("default-a.b", ctest.get("o.a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctest.get("o.a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("x1-a.b", ctest.get("o.a.b", toMap("x=x1")), "Inherited variance reference overriding works");
}
@Test
- public void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtSecondLevel() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtSecondLevel() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
- QueryProfile ac=new QueryProfile("ac");
- ac.set("a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("a.b", "x1-a.b", new String[]{"x1"}, null);
- QueryProfile top=new QueryProfile("top");
- top.set("o.a.b","default-a.b", null);
- top.set("o",test, null);
+ QueryProfile top = new QueryProfile("top");
+ top.set("o.a.b", "default-a.b", null);
+ top.set("o", test, null);
CompiledQueryProfile ctop = top.compile(null);
- assertEquals("Basic functionality","default-a.b",ctop.get("o.a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctop.get("o.a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference does not override value set in referent","default-a.b",ctop.get("o.a.b", toMap("x=x1"))); // Note: Changed from x1-a.b in 4.2.3
+ assertEquals("default-a.b", ctop.get("o.a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctop.get("o.a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("default-a.b", ctop.get("o.a.b", toMap("x=x1")), "Inherited variance reference does not override value set in referent"); // Note: Changed from x1-a.b in 4.2.3
}
@Test
- public void testVariantInheritanceOverridesBaseInheritance1() {
- QueryProfile test=new QueryProfile("test");
- QueryProfile baseInherited=new QueryProfile("baseInherited");
- baseInherited.set("a.b","baseInherited-a.b", null);
- QueryProfile variantInherited=new QueryProfile("variantInherited");
- variantInherited.set("a.b","variantInherited-a.b", null);
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceOverridesBaseInheritance1() {
+ QueryProfile test = new QueryProfile("test");
+ QueryProfile baseInherited = new QueryProfile("baseInherited");
+ baseInherited.set("a.b", "baseInherited-a.b", null);
+ QueryProfile variantInherited = new QueryProfile("variantInherited");
+ variantInherited.set("a.b", "variantInherited-a.b", null);
+ test.setDimensions(new String[]{"x"});
test.addInherited(baseInherited);
- test.addInherited(variantInherited,new String[] {"x1"});
+ test.addInherited(variantInherited, new String[]{"x1"});
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("baseInherited-a.b",ctest.get("a.b"));
- assertEquals("variantInherited-a.b",ctest.get("a.b",toMap("x=x1")));
+ assertEquals("baseInherited-a.b", ctest.get("a.b"));
+ assertEquals("variantInherited-a.b", ctest.get("a.b", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritance2() {
- QueryProfile test=new QueryProfile("test");
- QueryProfile baseInherited=new QueryProfile("baseInherited");
- baseInherited.set("a.b","baseInherited-a.b", null);
- QueryProfile variantInherited=new QueryProfile("variantInherited");
- variantInherited.set("a.b","variantInherited-a.b", null);
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceOverridesBaseInheritance2() {
+ QueryProfile test = new QueryProfile("test");
+ QueryProfile baseInherited = new QueryProfile("baseInherited");
+ baseInherited.set("a.b", "baseInherited-a.b", null);
+ QueryProfile variantInherited = new QueryProfile("variantInherited");
+ variantInherited.set("a.b", "variantInherited-a.b", null);
+ test.setDimensions(new String[]{"x"});
test.addInherited(baseInherited);
- test.addInherited(variantInherited,new String[] {"x1"});
- test.set("a.c","variant-a.c",new String[] {"x1"}, null);
+ test.addInherited(variantInherited, new String[]{"x1"});
+ test.set("a.c", "variant-a.c", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("baseInherited-a.b",ctest.get("a.b"));
- assertEquals("variantInherited-a.b",ctest.get("a.b", toMap("x=x1")));
- assertEquals("variant-a.c",ctest.get("a.c", toMap("x=x1")));
+ assertEquals("baseInherited-a.b", ctest.get("a.b"));
+ assertEquals("variantInherited-a.b", ctest.get("a.b", toMap("x=x1")));
+ assertEquals("variant-a.c", ctest.get("a.c", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceComplex() {
- QueryProfile defaultQP=new QueryProfile("default");
- defaultQP.set("model.defaultIndex","title", null);
+ void testVariantInheritanceOverridesBaseInheritanceComplex() {
+ QueryProfile defaultQP = new QueryProfile("default");
+ defaultQP.set("model.defaultIndex", "title", null);
- QueryProfile root=new QueryProfile("root");
+ QueryProfile root = new QueryProfile("root");
root.addInherited(defaultQP);
- root.set("model.defaultIndex","default", null);
+ root.set("model.defaultIndex", "default", null);
- QueryProfile querybest=new QueryProfile("querybest");
- querybest.set("defaultIndex","title", null);
- querybest.set("queryString","best", null);
+ QueryProfile querybest = new QueryProfile("querybest");
+ querybest.set("defaultIndex", "title", null);
+ querybest.set("queryString", "best", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
multi.addInherited(defaultQP);
- multi.set("model",querybest, null);
- multi.addInherited(root,new String[] {"x1"});
- multi.set("model.queryString","love",new String[] {"x1"}, null);
+ multi.set("model", querybest, null);
+ multi.addInherited(root, new String[]{"x1"});
+ multi.set("model.queryString", "love", new String[]{"x1"}, null);
// Rumtimize
defaultQP.freeze();
@@ -746,461 +745,461 @@ public class QueryProfileVariantsTestCase {
multi.freeze();
Properties runtime = new QueryProfileProperties(multi.compile(null));
- assertEquals("default",runtime.get("model.defaultIndex", toMap("x=x1")));
- assertEquals("love",runtime.get("model.queryString", toMap("x=x1")));
+ assertEquals("default", runtime.get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("love", runtime.get("model.queryString", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceComplexSimplified() {
- QueryProfile root=new QueryProfile("root");
- root.set("model.defaultIndex","default", null);
+ void testVariantInheritanceOverridesBaseInheritanceComplexSimplified() {
+ QueryProfile root = new QueryProfile("root");
+ root.set("model.defaultIndex", "default", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
- multi.set("model.defaultIndex","title", null);
- multi.addInherited(root,new String[] {"x1"});
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
+ multi.set("model.defaultIndex", "title", null);
+ multi.addInherited(root, new String[]{"x1"});
- assertEquals("default",multi.compile(null).get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("default", multi.compile(null).get("model.defaultIndex", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceMixed() {
- QueryProfile root=new QueryProfile("root");
- root.set("model.defaultIndex","default", null);
+ void testVariantInheritanceOverridesBaseInheritanceMixed() {
+ QueryProfile root = new QueryProfile("root");
+ root.set("model.defaultIndex", "default", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
- multi.set("model.defaultIndex","title", null);
- multi.set("model.queryString","modelQuery", null);
- multi.addInherited(root,new String[] {"x1"});
- multi.set("model.queryString","modelVariantQuery",new String[] {"x1"}, null);
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
+ multi.set("model.defaultIndex", "title", null);
+ multi.set("model.queryString", "modelQuery", null);
+ multi.addInherited(root, new String[]{"x1"});
+ multi.set("model.queryString", "modelVariantQuery", new String[]{"x1"}, null);
CompiledQueryProfile cmulti = multi.compile(null);
- assertEquals("default",cmulti.get("model.defaultIndex", toMap("x=x1")));
- assertEquals("modelVariantQuery",cmulti.get("model.queryString", toMap("x=x1")));
+ assertEquals("default", cmulti.get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("modelVariantQuery", cmulti.get("model.queryString", toMap("x=x1")));
}
@Test
- public void testListVariantPropertiesNoCompounds() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("a","parent1-a", null); // Defined everywhere
- parent1.set("b","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("c","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("a","parent2-a", null);
- parent2.set("b","parent2-b", null);
- parent2.set("c","parent2-c", null);
- parent2.set("d","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesNoCompounds() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("a", "parent1-a", null); // Defined everywhere
+ parent1.set("b", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("c", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("a", "parent2-a", null);
+ parent2.set("b", "parent2-b", null);
+ parent2.set("c", "parent2-c", null);
+ parent2.set("d", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("a","main-a", null);
- main.set("a","main-a-x1",new String[] {"x1"}, null);
- main.set("e","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("f","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("a","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("a","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("e","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("g","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("b","main-b", null);
-
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a","inheritedVariant1-a", null);
- inheritedVariant1.set("h","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("a","inheritedVariant2-a", null);
- inheritedVariant2.set("h","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("i","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("j","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
-
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
+ main.set("a", "main-a", null);
+ main.set("a", "main-a-x1", new String[]{"x1"}, null);
+ main.set("e", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("f", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("a", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("a", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("e", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("g", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("b", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a", "inheritedVariant1-a", null);
+ inheritedVariant1.set("h", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("a", "inheritedVariant2-a", null);
+ inheritedVariant2.set("h", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("i", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("j", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
// Runtime-ify
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
// Context x=x1
- listed=properties.listProperties(toMap(main, new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main, new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main, new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1.y2",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("main-g-x1.y2",listed.get("g"));
- assertEquals("inheritedVariant2-h",listed.get("h"));
- assertEquals("inheritedVariant2-i",listed.get("i"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1.y2", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("main-g-x1.y2", listed.get("g"));
+ assertEquals("inheritedVariant2-h", listed.get("h"));
+ assertEquals("inheritedVariant2-i", listed.get("i"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main, new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main, new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
}
@Test
- public void testListVariantPropertiesCompounds1Simplified() {
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
- main.set("a.p1","main-a-x1",new String[] {"x1"}, null);
+ void testListVariantPropertiesCompounds1Simplified() {
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
+ main.set("a.p1", "main-a-x1", new String[]{"x1"}, null);
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a.p1","inheritedVariant1-a", null);
- main.addInherited(inheritedVariant1,new String[] {"x1"});
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a.p1", "inheritedVariant1-a", null);
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
// Context x=x1
- Map<String,Object> listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals("main-a-x1",listed.get("a.p1"));
+ Map<String, Object> listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals("main-a-x1", listed.get("a.p1"));
}
@Test
- public void testListVariantPropertiesCompounds1() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("a.p1","parent1-a", null); // Defined everywhere
- parent1.set("b.p1","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("c.p1","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("a.p1","parent2-a", null);
- parent2.set("b.p1","parent2-b", null);
- parent2.set("c.p1","parent2-c", null);
- parent2.set("d.p1","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesCompounds1() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("a.p1", "parent1-a", null); // Defined everywhere
+ parent1.set("b.p1", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("c.p1", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("a.p1", "parent2-a", null);
+ parent2.set("b.p1", "parent2-b", null);
+ parent2.set("c.p1", "parent2-c", null);
+ parent2.set("d.p1", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("a.p1","main-a", null);
- main.set("a.p1","main-a-x1",new String[] {"x1"}, null);
- main.set("e.p1","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("f.p1","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("a.p1","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("a.p1","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("e.p1","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("g.p1","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("b.p1","main-b", null);
+ main.set("a.p1", "main-a", null);
+ main.set("a.p1", "main-a-x1", new String[]{"x1"}, null);
+ main.set("e.p1", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("f.p1", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("a.p1", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("a.p1", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("e.p1", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("g.p1", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("b.p1", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a.p1", "inheritedVariant1-a", null);
+ inheritedVariant1.set("h.p1", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("a.p1", "inheritedVariant2-a", null);
+ inheritedVariant2.set("h.p1", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("i.p1", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("j.p1", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a.p1","inheritedVariant1-a", null);
- inheritedVariant1.set("h.p1","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("a.p1","inheritedVariant2-a", null);
- inheritedVariant2.set("h.p1","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("i.p1","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("j.p1","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
-
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
-
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main,new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1.y2",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("main-g-x1.y2",listed.get("g.p1"));
- assertEquals("inheritedVariant2-h",listed.get("h.p1"));
- assertEquals("inheritedVariant2-i",listed.get("i.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1.y2", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("main-g-x1.y2", listed.get("g.p1"));
+ assertEquals("inheritedVariant2-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant2-i", listed.get("i.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main,new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
}
@Test
- public void testListVariantPropertiesCompounds2() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("p1.a","parent1-a", null); // Defined everywhere
- parent1.set("p1.b","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("p1.c","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("p1.a","parent2-a", null);
- parent2.set("p1.b","parent2-b", null);
- parent2.set("p1.c","parent2-c", null);
- parent2.set("p1.d","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesCompounds2() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("p1.a", "parent1-a", null); // Defined everywhere
+ parent1.set("p1.b", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("p1.c", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("p1.a", "parent2-a", null);
+ parent2.set("p1.b", "parent2-b", null);
+ parent2.set("p1.c", "parent2-c", null);
+ parent2.set("p1.d", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("p1.a","main-a", null);
- main.set("p1.a","main-a-x1",new String[] {"x1"}, null);
- main.set("p1.e","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("p1.f","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("p1.a","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("p1.a","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("p1.e","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("p1.g","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("p1.b","main-b", null);
-
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("p1.a","inheritedVariant1-a", null);
- inheritedVariant1.set("p1.h","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("p1.a","inheritedVariant2-a", null);
- inheritedVariant2.set("p1.h","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("p1.i","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("p1.j","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+ main.set("p1.a", "main-a", null);
+ main.set("p1.a", "main-a-x1", new String[]{"x1"}, null);
+ main.set("p1.e", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("p1.f", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("p1.a", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("p1.a", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("p1.e", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("p1.g", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("p1.b", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("p1.a", "inheritedVariant1-a", null);
+ inheritedVariant1.set("p1.h", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("p1.a", "inheritedVariant2-a", null);
+ inheritedVariant2.set("p1.h", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("p1.i", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("p1.j", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
-
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main,new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1.y2",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("main-g-x1.y2",listed.get("p1.g"));
- assertEquals("inheritedVariant2-h",listed.get("p1.h"));
- assertEquals("inheritedVariant2-i",listed.get("p1.i"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1.y2", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("main-g-x1.y2", listed.get("p1.g"));
+ assertEquals("inheritedVariant2-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant2-i", listed.get("p1.i"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main,new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
}
@Test
- public void testQueryProfileReferences() {
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x1"});
- QueryProfile referencedMain=new QueryProfile("referencedMain");
- referencedMain.set("r1","mainReferenced-r1", null); // In both
- referencedMain.set("r2","mainReferenced-r2", null); // Only in this
- QueryProfile referencedVariant=new QueryProfile("referencedVariant");
- referencedVariant.set("r1","variantReferenced-r1", null); // In both
- referencedVariant.set("r3","variantReferenced-r3", null); // Only in this
+ void testQueryProfileReferences() {
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x1"});
+ QueryProfile referencedMain = new QueryProfile("referencedMain");
+ referencedMain.set("r1", "mainReferenced-r1", null); // In both
+ referencedMain.set("r2", "mainReferenced-r2", null); // Only in this
+ QueryProfile referencedVariant = new QueryProfile("referencedVariant");
+ referencedVariant.set("r1", "variantReferenced-r1", null); // In both
+ referencedVariant.set("r3", "variantReferenced-r3", null); // Only in this
- main.set("a",referencedMain, null);
- main.set("a",referencedVariant,new String[] {"x1"}, null);
+ main.set("a", referencedMain, null);
+ main.set("a", referencedVariant, new String[]{"x1"}, null);
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(2,listed.size());
- assertEquals("mainReferenced-r1",listed.get("a.r1"));
- assertEquals("mainReferenced-r2",listed.get("a.r2"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(2, listed.size());
+ assertEquals("mainReferenced-r1", listed.get("a.r1"));
+ assertEquals("mainReferenced-r2", listed.get("a.r2"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(3,listed.size());
- assertEquals("variantReferenced-r1",listed.get("a.r1"));
- assertEquals("mainReferenced-r2",listed.get("a.r2"));
- assertEquals("variantReferenced-r3",listed.get("a.r3"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(3, listed.size());
+ assertEquals("variantReferenced-r1", listed.get("a.r1"));
+ assertEquals("mainReferenced-r2", listed.get("a.r2"));
+ assertEquals("variantReferenced-r3", listed.get("a.r3"));
}
@Test
- public void testQueryProfileReferencesWithSubstitution() {
+ void testQueryProfileReferencesWithSubstitution() {
QueryProfile main = new QueryProfile("main");
- main.setDimensions(new String[] {"x1"});
+ main.setDimensions(new String[]{"x1"});
QueryProfile referencedMain = new QueryProfile("referencedMain");
- referencedMain.set("r1","%{prefix}mainReferenced-r1", null); // In both
- referencedMain.set("r2","%{prefix}mainReferenced-r2", null); // Only in this
+ referencedMain.set("r1", "%{prefix}mainReferenced-r1", null); // In both
+ referencedMain.set("r2", "%{prefix}mainReferenced-r2", null); // Only in this
QueryProfile referencedVariant = new QueryProfile("referencedVariant");
- referencedVariant.set("r1","%{prefix}variantReferenced-r1", null); // In both
- referencedVariant.set("r3","%{prefix}variantReferenced-r3", null); // Only in this
+ referencedVariant.set("r1", "%{prefix}variantReferenced-r1", null); // In both
+ referencedVariant.set("r3", "%{prefix}variantReferenced-r3", null); // Only in this
referencedVariant.set("inthis", "local value", null);
- referencedVariant.set("r4","This has %{.inthis}", null); // Relative
+ referencedVariant.set("r4", "This has %{.inthis}", null); // Relative
main.set("a", referencedMain, null);
- main.set("a", referencedVariant,new String[] {"x1"}, null);
+ main.set("a", referencedVariant, new String[]{"x1"}, null);
main.set("prefix", "mainPrefix:", null);
- main.set("prefix", "variantPrefix:", new String[] {"x1"}, null);
+ main.set("prefix", "variantPrefix:", new String[]{"x1"}, null);
Properties properties = new QueryProfileProperties(main.compile(null));
// No context
- Map<String,Object> listed = properties.listProperties();
+ Map<String, Object> listed = properties.listProperties();
assertEquals(3, listed.size());
assertEquals("mainPrefix:mainReferenced-r1", listed.get("a.r1"));
assertEquals("mainPrefix:mainReferenced-r2", listed.get("a.r2"));
// Context x=x1
- listed = properties.listProperties(toMap(main, new String[] {"x1"}));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
assertEquals(6, listed.size());
assertEquals("variantPrefix:variantReferenced-r1", listed.get("a.r1"));
assertEquals("variantPrefix:mainReferenced-r2", listed.get("a.r2"));
@@ -1209,17 +1208,17 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testNewsCase1() {
+ void testNewsCase1() {
QueryProfile shortcuts = new QueryProfile("shortcuts");
- shortcuts.setDimensions(new String[] {"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
+ shortcuts.setDimensions(new String[]{"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
shortcuts.set("testout", "outside", null);
shortcuts.set("test.out", "dotoutside", null);
- shortcuts.set("testin", "inside", new String[] {"yahoo","ca","sc"}, null);
- shortcuts.set("test.in", "dotinside", new String[] {"yahoo","ca","sc"}, null);
+ shortcuts.set("testin", "inside", new String[]{"yahoo", "ca", "sc"}, null);
+ shortcuts.set("test.in", "dotinside", new String[]{"yahoo", "ca", "sc"}, null);
- QueryProfile profile=new QueryProfile("default");
- profile.setDimensions(new String[] {"custid_1","custid_2","custid_3","custid_4","custid_5","custid_6"});
- profile.addInherited(shortcuts, new String[] {"yahoo",null,"sc"});
+ QueryProfile profile = new QueryProfile("default");
+ profile.setDimensions(new String[]{"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
+ profile.addInherited(shortcuts, new String[]{"yahoo", null, "sc"});
profile.freeze();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=yahoo&custid_2=ca&custid_3=sc", Method.GET), profile.compile(null));
@@ -1231,103 +1230,103 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testNewsCase2() {
- QueryProfile test=new QueryProfile("test");
+ void testNewsCase2() {
+ QueryProfile test = new QueryProfile("test");
test.setDimensions("sort,resulttypes,rss,age,intl,testid".split(","));
- String[] dimensionValues=new String[] {null,null,"0"};
- test.set("discovery","sources",dimensionValues, null);
- test.set("discoverytypes","article",dimensionValues, null);
- test.set("discovery.sources.count","10",dimensionValues, null);
+ String[] dimensionValues = new String[]{null, null, "0"};
+ test.set("discovery", "sources", dimensionValues, null);
+ test.set("discoverytypes", "article", dimensionValues, null);
+ test.set("discovery.sources.count", "10", dimensionValues, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("sources",ctest.get("discovery", toMap(test, dimensionValues)));
- assertEquals("article",ctest.get("discoverytypes", toMap(test, dimensionValues)));
- assertEquals("10",ctest.get("discovery.sources.count", toMap(test, dimensionValues)));
+ assertEquals("sources", ctest.get("discovery", toMap(test, dimensionValues)));
+ assertEquals("article", ctest.get("discoverytypes", toMap(test, dimensionValues)));
+ assertEquals("10", ctest.get("discovery.sources.count", toMap(test, dimensionValues)));
- Map<String,Object> values=ctest.listValues("",toMap(test,dimensionValues));
- assertEquals(3,values.size());
- assertEquals("sources",values.get("discovery"));
- assertEquals("article",values.get("discoverytypes"));
- assertEquals("10",values.get("discovery.sources.count"));
+ Map<String, Object> values = ctest.listValues("", toMap(test, dimensionValues));
+ assertEquals(3, values.size());
+ assertEquals("sources", values.get("discovery"));
+ assertEquals("article", values.get("discoverytypes"));
+ assertEquals("10", values.get("discovery.sources.count"));
- Map<String,Object> sourceValues=ctest.listValues("discovery.sources",toMap(test,dimensionValues));
- assertEquals(1,sourceValues.size());
- assertEquals("10",sourceValues.get("count"));
+ Map<String, Object> sourceValues = ctest.listValues("discovery.sources", toMap(test, dimensionValues));
+ assertEquals(1, sourceValues.size());
+ assertEquals("10", sourceValues.get("count"));
}
@Test
- public void testRuntimeAssignmentInClone() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- String[] x1=new String[] {"x1"};
- Map<String,String> x1m=toMap(test,x1);
- test.set("a","30",x1, null);
- test.set("a.b","20",x1, null);
- test.set("a.b.c","10",x1, null);
+ void testRuntimeAssignmentInClone() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ String[] x1 = new String[]{"x1"};
+ Map<String, String> x1m = toMap(test, x1);
+ test.set("a", "30", x1, null);
+ test.set("a.b", "20", x1, null);
+ test.set("a.b.c", "10", x1, null);
// Setting in one profile works
Query qMain = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), test.compile(null));
- qMain.properties().set("a.b","50",x1m);
- assertEquals("50",qMain.properties().get("a.b",x1m));
+ qMain.properties().set("a.b", "50", x1m);
+ assertEquals("50", qMain.properties().get("a.b", x1m));
// Cloning
- Query qBranch=qMain.clone();
+ Query qBranch = qMain.clone();
// Setting in main still works
- qMain.properties().set("a.b","51",x1m);
- assertEquals("51",qMain.properties().get("a.b",x1m));
+ qMain.properties().set("a.b", "51", x1m);
+ assertEquals("51", qMain.properties().get("a.b", x1m));
// Clone is not affected by change in original
- assertEquals("50",qBranch.properties().get("a.b",x1m));
+ assertEquals("50", qBranch.properties().get("a.b", x1m));
// Setting in clone works
- qBranch.properties().set("a.b","70",x1m);
- assertEquals("70",qBranch.properties().get("a.b",x1m));
+ qBranch.properties().set("a.b", "70", x1m);
+ assertEquals("70", qBranch.properties().get("a.b", x1m));
// Setting in clone does not affect original
- assertEquals("51",qMain.properties().get("a.b",x1m));
+ assertEquals("51", qMain.properties().get("a.b", x1m));
}
@Test
- public void testIncompatibleDimensions() {
+ void testIncompatibleDimensions() {
QueryProfile alert = new QueryProfile("alert");
QueryProfile backendBase = new QueryProfile("backendBase");
- backendBase.setDimensions(new String[] { "sort", "resulttypes", "rss" });
+ backendBase.setDimensions(new String[]{"sort", "resulttypes", "rss"});
backendBase.set("custid", "s", null);
QueryProfile backend = new QueryProfile("backend");
- backend.setDimensions(new String[] { "sort", "offset", "resulttypes", "rss", "age", "lang", "fr", "entry" });
+ backend.setDimensions(new String[]{"sort", "offset", "resulttypes", "rss", "age", "lang", "fr", "entry"});
backend.addInherited(backendBase);
QueryProfile web = new QueryProfile("web");
- web.setDimensions(new String[] { "entry", "recency" });
- web.set("fr", "alerts", new String[] { "alert" }, null);
+ web.setDimensions(new String[]{"entry", "recency"});
+ web.set("fr", "alerts", new String[]{"alert"}, null);
alert.set("config.backend.vertical.news", backend, null);
alert.set("config.backend.multimedia", web, null);
- backend.set("custid", "yahoo/alerts", new String[] { null, null, null, null, null, "en-US", null, "alert"}, null);
+ backend.set("custid", "yahoo/alerts", new String[]{null, null, null, null, null, "en-US", null, "alert"}, null);
CompiledQueryProfile cAlert = alert.compile(null);
assertEquals("yahoo/alerts", cAlert.get("config.backend.vertical.news.custid", toMap("entry=alert", "intl=us", "lang=en-US")));
}
@Test
- public void testIncompatibleDimensionsSimplified() {
+ void testIncompatibleDimensionsSimplified() {
QueryProfile alert = new QueryProfile("alert");
QueryProfile backendBase = new QueryProfile("backendBase");
backendBase.set("custid", "s", null);
QueryProfile backend = new QueryProfile("backend");
- backend.setDimensions(new String[] { "sort", "lang", "fr", "entry" });
- backend.set("custid", "yahoo/alerts", new String[] { null, "en-US", null, "alert"}, null);
+ backend.setDimensions(new String[]{"sort", "lang", "fr", "entry"});
+ backend.set("custid", "yahoo/alerts", new String[]{null, "en-US", null, "alert"}, null);
backend.addInherited(backendBase);
QueryProfile web = new QueryProfile("web");
- web.setDimensions(new String[] { "entry", "recency" });
- web.set("fr", "alerts", new String[] { "alert" }, null);
+ web.setDimensions(new String[]{"entry", "recency"});
+ web.set("fr", "alerts", new String[]{"alert"}, null);
alert.set("vertical", backend, null);
alert.set("multimedia", web, null);
@@ -1337,23 +1336,23 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testZoneInfoInContext() {
+ void testZoneInfoInContext() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "environment", "region", "instance" });
+ profile.setDimensions(new String[]{"environment", "region", "instance"});
profile.set("value", "default", registry);
profile.set("value", "prod-region1-instance1",
- toMap("environment=prod", "region=region1", "instance=instance1"),
- registry);
+ toMap("environment=prod", "region=region1", "instance=instance1"),
+ registry);
profile.set("value", "prod-instance2",
- toMap("environment=prod", "instance=instance2"),
- registry);
+ toMap("environment=prod", "instance=instance2"),
+ registry);
profile.set("value", "prod-region3",
- toMap("environment=prod", "region=region3"),
- registry);
+ toMap("environment=prod", "region=region3"),
+ registry);
profile.set("value", "dev",
- toMap("environment=dev"),
- registry);
+ toMap("environment=dev"),
+ registry);
registry.register(profile);
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -1361,36 +1360,36 @@ public class QueryProfileVariantsTestCase {
assertValueForZone("default", ZoneInfo.defaultInfo(), null, cTest);
assertValueForZone("prod-region1-instance1",
- new ZoneInfo(new ApplicationId("tenant1", "application1", "instance1"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "instance1"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
assertValueForZone("prod-instance2",
- new ZoneInfo(new ApplicationId("tenant2", "application2", "instance2"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant2", "application2", "instance2"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
assertValueForZone("prod-region3",
- new ZoneInfo(new ApplicationId("tenant3", "application3", "instance3"),
- new Zone(Environment.prod, "region3")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant3", "application3", "instance3"),
+ new Zone(Environment.prod, "region3")),
+ null,
+ cTest);
assertValueForZone("dev",
- new ZoneInfo(new ApplicationId("tenant4", "application4", "instance4"),
- new Zone(Environment.dev, "region4")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant4", "application4", "instance4"),
+ new Zone(Environment.dev, "region4")),
+ null,
+ cTest);
}
@Test
- public void testZoneInfoInContextWithUnoverridability() {
+ void testZoneInfoInContextWithUnoverridability() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "instance", "environment", "region" });
+ profile.setDimensions(new String[]{"instance", "environment", "region"});
profile.set("value", "default", registry);
profile.set("value", "prod-beta",
- toMap("environment=prod", "instance=beta"),
- registry);
+ toMap("environment=prod", "instance=beta"),
+ registry);
profile.setOverridable("value", false, toMap("environment=prod", "instance=beta"));
registry.register(profile);
@@ -1398,10 +1397,10 @@ public class QueryProfileVariantsTestCase {
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
assertValueForZone("prod-beta",
- new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
- new Zone(Environment.prod, "region1")),
- "fromRequest",
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
+ new Zone(Environment.prod, "region1")),
+ "fromRequest",
+ cTest);
}
@@ -1413,23 +1412,23 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testZoneInfoInContextSettingNativeProperty() {
+ void testZoneInfoInContextSettingNativeProperty() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "instance", "environment", "region" });
+ profile.setDimensions(new String[]{"instance", "environment", "region"});
profile.set("timeout", "0.3",
- toMap("environment=prod", "instance=beta"),
- registry);
+ toMap("environment=prod", "instance=beta"),
+ registry);
registry.register(profile);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
assertTimeoutForZone(300,
- new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
}
private void assertTimeoutForZone(int expected, ZoneInfo zoneInfo, String requestValue, CompiledQueryProfile cTest) {
@@ -1441,8 +1440,7 @@ public class QueryProfileVariantsTestCase {
private void assertGet(String expectedValue, String parameter, String[] dimensionValues, QueryProfile profile, CompiledQueryProfile cprofile) {
Map<String, String> context = toMap(profile,dimensionValues);
- assertEquals("Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'",
- expectedValue, cprofile.get(parameter,context));
+ assertEquals(expectedValue, cprofile.get(parameter,context), "Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'");
}
public static Map<String,String> toMap(QueryProfile profile, String[] dimensionValues) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
index 0ace8f93f1d..b245648b861 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.search.query.profile.types.test;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class FieldTypeTestCase {
@Test
- public void testConvertToFromString() {
- QueryProfileTypeRegistry registry=new QueryProfileTypeRegistry();
+ void testConvertToFromString() {
+ QueryProfileTypeRegistry registry = new QueryProfileTypeRegistry();
registry.register(new QueryProfileType("foo"));
- assertEquals("string", FieldType.fromString("string",registry).stringValue());
- assertEquals("boolean", FieldType.fromString("boolean",registry).stringValue());
- assertEquals("query-profile", FieldType.fromString("query-profile",registry).stringValue());
- assertEquals("query-profile:foo", FieldType.fromString("query-profile:foo",registry).stringValue());
+ assertEquals("string", FieldType.fromString("string", registry).stringValue());
+ assertEquals("boolean", FieldType.fromString("boolean", registry).stringValue());
+ assertEquals("query-profile", FieldType.fromString("query-profile", registry).stringValue());
+ assertEquals("query-profile:foo", FieldType.fromString("query-profile:foo", registry).stringValue());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
index dfe4b24e256..5bde89d0282 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
@@ -13,9 +13,9 @@ import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -55,18 +55,18 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryFullySpecifiedQueryProfile() {
+ void testMandatoryFullySpecifiedQueryProfile() {
Fixture1 fixture = new Fixture1();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(fixture.type);
test.set("myString", "aString", fixture.registry);
fixture.registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(fixture.user);
- myUser.set("myUserInteger",1, fixture.registry);
- myUser.set("myUserString",1, fixture.registry);
+ myUser.set("myUserInteger", 1, fixture.registry);
+ myUser.set("myUserString", 1, fixture.registry);
test.set("myUserQueryProfile", myUser, fixture.registry);
fixture.registry.register(myUser);
@@ -77,7 +77,7 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryRequestPropertiesNeeded() {
+ void testMandatoryRequestPropertiesNeeded() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -94,11 +94,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'myString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("test")));
// Underspecified request 2
assertError("Incomplete query: Parameter 'myUserQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -106,7 +106,7 @@ public class MandatoryTestCase {
/** Same as above except the whole thing is nested in maps */
@Test
- public void testMandatoryNestedInMaps() {
+ void testMandatoryNestedInMaps() {
Fixture1 fixture = new Fixture1();
QueryProfile topMap = new QueryProfile("topMap");
@@ -123,7 +123,7 @@ public class MandatoryTestCase {
QueryProfile myUser = new QueryProfile("user");
myUser.setType(fixture.user);
- myUser.set("myUserInteger",1, fixture.registry);
+ myUser.set("myUserInteger", 1, fixture.registry);
test.set("myUserQueryProfile", myUser, fixture.registry);
fixture.registry.register(myUser);
@@ -132,11 +132,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'subMap.test.myString' is mandatory in query profile 'topMap' but is not set",
- new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("topMap")));
+ new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("topMap")));
// Underspecified request 2
assertError("Incomplete query: Parameter 'subMap.test.myUserQueryProfile.myUserString' is mandatory in query profile 'topMap' but is not set",
- new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString", Method.GET), cRegistry.getComponent("topMap")));
+ new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString", Method.GET), cRegistry.getComponent("topMap")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString&subMap.test.myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("topMap")));
@@ -144,7 +144,7 @@ public class MandatoryTestCase {
/** Here, no user query profile is referenced in the query profile, but one is chosen in the request */
@Test
- public void testMandatoryUserProfileSetInRequest() {
+ void testMandatoryUserProfileSetInRequest() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -161,11 +161,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'myUserQueryProfile' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
// Underspecified request 1
assertError("Incomplete query: Parameter 'myUserQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user", Method.GET), cRegistry.getComponent("test")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user&myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -173,7 +173,7 @@ public class MandatoryTestCase {
/** Here, a partially specified query profile is added to a non-mandatory field, making the request underspecified */
@Test
- public void testNonMandatoryUnderspecifiedUserProfileSetInRequest() {
+ void testNonMandatoryUnderspecifiedUserProfileSetInRequest() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -199,7 +199,7 @@ public class MandatoryTestCase {
// Underspecified because an underspecified profile is added
assertError("Incomplete query: Parameter 'myQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser", Method.GET), cRegistry.getComponent("test")));
// Back to fully specified
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser&myQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -223,7 +223,7 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryInParentType() {
+ void testMandatoryInParentType() {
Fixture2 fixture = new Fixture2();
QueryProfile defaultProfile = new QueryProfile("default");
@@ -237,11 +237,11 @@ public class MandatoryTestCase {
CompiledQueryProfileRegistry cRegistry = fixture.registry.compile();
assertError("Incomplete query: Parameter 'foobar' is mandatory in query profile 'mandatory' of type 'mandatory-type' but is not set",
- new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
+ new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
}
@Test
- public void testMandatoryInParentTypeWithInheritance() {
+ void testMandatoryInParentTypeWithInheritance() {
Fixture2 fixture = new Fixture2();
QueryProfile defaultProfile = new QueryProfile("default");
@@ -256,7 +256,7 @@ public class MandatoryTestCase {
CompiledQueryProfileRegistry cRegistry = fixture.registry.compile();
assertError("Incomplete query: Parameter 'foobar' is mandatory in query profile 'mandatory' of type 'mandatory-type' but is not set",
- new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
+ new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
}
private void assertError(String message,Query query) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
index fa7508ea5ac..37991f7f14f 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
@@ -8,10 +8,10 @@ import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* tests creating invalid names
@@ -21,7 +21,7 @@ import static org.junit.Assert.fail;
public class NameTestCase {
@Test
- public void testNames() {
+ void testNames() {
assertLegalName("aB");
assertIllegalName("a.");
assertLegalName("_a_b");
@@ -33,11 +33,11 @@ public class NameTestCase {
}
@Test
- public void testFieldNames() {
+ void testFieldNames() {
assertLegalFieldName("aB");
try {
- QueryProfile profile=new QueryProfile("test");
- profile.set("a.","anyValue", (QueryProfileRegistry)null);
+ QueryProfile profile = new QueryProfile("test");
+ profile.set("a.", "anyValue", (QueryProfileRegistry) null);
fail("Should have failed");
} catch (IllegalArgumentException e) {
assertEquals("'a.' is not a legal compound name. Names can not end with a dot.", e.getMessage());
@@ -48,12 +48,12 @@ public class NameTestCase {
assertLegalFieldName("/a/b");
assertLegalFieldName("/a/b/");
assertIllegalFieldName("aBc.dooEee.ce_d.-some-other.moreHere",
- "Could not set 'aBc.dooEee.ce_d.-some-other.moreHere' to 'anyValue'",
- "Illegal name '-some-other'");
+ "Could not set 'aBc.dooEee.ce_d.-some-other.moreHere' to 'anyValue'",
+ "Illegal name '-some-other'");
}
@Test
- public void testComponentIdAsCompoundName() {
+ void testComponentIdAsCompoundName() {
String name = "a/b";
assertEquals(new CompoundName(name), new QueryProfileType(name).getComponentIdAsCompoundName());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
index 6f884650b5d..72499002ba9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests that properties can not be set even if they are native, if declared not settable in the query profile
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class NativePropertiesTestCase {
@Test
- public void testNativeInStrict() {
+ void testNativeInStrict() {
QueryProfileType strictType = new QueryProfileType("strict");
strictType.setStrict(true);
QueryProfile strict = new QueryProfile("profile");
@@ -39,7 +39,7 @@ public class NativePropertiesTestCase {
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'notnative' to '5':"
+ "Could not set 'notnative' to '5':"
+ " 'notnative' is not declared in query profile type 'strict', and the type is strict"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
index 906d43790bd..69d577719c5 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
@@ -13,10 +13,10 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests overriding of field values
@@ -29,7 +29,7 @@ public class OverrideTestCase {
private QueryProfileType type, user;
- @Before
+ @BeforeEach
public void setUp() {
type=new QueryProfileType(new ComponentId("testtype"));
user=new QueryProfileType(new ComponentId("user"));
@@ -60,38 +60,38 @@ public class OverrideTestCase {
/** Check that a simple non-overridable string cannot be overridden */
@Test
- public void testSimpleUnoverridable() {
+ void testSimpleUnoverridable() {
QueryProfileRegistry registry = new QueryProfileRegistry();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myString","finalString", (QueryProfileRegistry)null);
+ test.set("myString", "finalString", (QueryProfileRegistry) null);
registry.register(test);
registry.freeze();
// Assert request assignment does not work
Query query = new Query(HttpRequest.createTestRequest("?myString=newValue", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals("finalString",query.properties().get("myString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalString", query.properties().get("myString"));
// Assert direct assignment does not work
- query.properties().set("myString","newValue");
- assertEquals("finalString",query.properties().get("myString"));
+ query.properties().set("myString", "newValue");
+ assertEquals("finalString", query.properties().get("myString"));
}
/** Check that a query profile cannot be overridden */
@Test
- public void testUnoverridableQueryProfile() {
+ void testUnoverridableQueryProfile() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
test.setType(type);
registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(user);
- myUser.set("myUserInteger",1, registry);
- myUser.set("myUserString","userValue", registry);
- test.set("myUserQueryProfile",myUser, registry);
+ myUser.set("myUserInteger", 1, registry);
+ myUser.set("myUserString", "userValue", registry);
+ test.set("myUserQueryProfile", myUser, registry);
registry.register(myUser);
QueryProfile otherUser = new QueryProfile("otherUser");
@@ -102,52 +102,52 @@ public class OverrideTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryprofile=otherUser", Method.GET), cRegistry.getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals(1,query.properties().get("myUserQueryProfile.myUserInteger"));
+ assertEquals(0, query.errors().size());
+ assertEquals(1, query.properties().get("myUserQueryProfile.myUserInteger"));
}
/** Check that non-overridables are protected also in nested untyped references */
@Test
- public void testUntypedNestedUnoverridable() {
+ void testUntypedNestedUnoverridable() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile topMap = new QueryProfile("topMap");
registry.register(topMap);
- QueryProfile subMap=new QueryProfile("topSubMap");
- topMap.set("subMap",subMap, registry);
+ QueryProfile subMap = new QueryProfile("topSubMap");
+ topMap.set("subMap", subMap, registry);
registry.register(subMap);
QueryProfile test = new QueryProfile("test");
test.setType(type);
- subMap.set("test",test, registry);
+ subMap.set("test", test, registry);
registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(user);
- myUser.set("myUserString","finalValue", registry);
- test.set("myUserQueryProfile",myUser, registry);
+ myUser.set("myUserString", "finalValue", registry);
+ test.set("myUserQueryProfile", myUser, registry);
registry.register(myUser);
registry.freeze();
Query query = new Query(HttpRequest.createTestRequest("?subMap.test.myUserQueryProfile.myUserString=newValue", Method.GET), registry.compile().getComponent("topMap"));
- assertEquals(0,query.errors().size());
- assertEquals("finalValue",query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalValue", query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
- query.properties().set("subMap.test.myUserQueryProfile.myUserString","newValue");
- assertEquals("finalValue",query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
+ query.properties().set("subMap.test.myUserQueryProfile.myUserString", "newValue");
+ assertEquals("finalValue", query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
}
/** Tests overridability in an inherited field */
@Test
- public void testInheritedNonOverridableInType() {
+ void testInheritedNonOverridableInType() {
QueryProfileRegistry registry = new QueryProfileRegistry();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myString","finalString", (QueryProfileRegistry)null);
+ test.set("myString", "finalString", (QueryProfileRegistry) null);
registry.register(test);
- QueryProfile profile=new QueryProfile("profile");
+ QueryProfile profile = new QueryProfile("profile");
profile.addInherited(test);
registry.register(profile);
@@ -155,16 +155,16 @@ public class OverrideTestCase {
Query query = new Query(HttpRequest.createTestRequest("?myString=newString", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals("finalString",query.properties().get("myString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalString", query.properties().get("myString"));
- query.properties().set("myString","newString");
- assertEquals("finalString",query.properties().get("myString"));
+ query.properties().set("myString", "newString");
+ assertEquals("finalString", query.properties().get("myString"));
}
/** Tests overridability in an inherited field */
@Test
- public void testInheritedNonOverridableInProfile() {
+ void testInheritedNonOverridableInProfile() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
test.setType(type);
@@ -172,7 +172,7 @@ public class OverrideTestCase {
test.setOverridable("myInteger", false, DimensionValues.empty);
registry.register(test);
- QueryProfile profile=new QueryProfile("profile");
+ QueryProfile profile = new QueryProfile("profile");
profile.addInherited(test);
registry.register(profile);
@@ -180,11 +180,11 @@ public class OverrideTestCase {
Query query = new Query(HttpRequest.createTestRequest("?myInteger=32", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals(1,query.properties().get("myInteger"));
+ assertEquals(0, query.errors().size());
+ assertEquals(1, query.properties().get("myInteger"));
- query.properties().set("myInteger",32);
- assertEquals(1,query.properties().get("myInteger"));
+ query.properties().set("myInteger", 32);
+ assertEquals(1, query.properties().get("myInteger"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
index d39bfa13126..58d92d84e94 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.search.query.profile.types.test;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests that matching query profiles by path name works
@@ -17,62 +17,62 @@ import static org.junit.Assert.assertNull;
public class PatchMatchingTestCase {
@Test
- public void testPatchMatching() {
- QueryProfileType type=new QueryProfileType("type");
+ void testPatchMatching() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee/cede").getId().getName());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
@Test
- public void testNoPatchMatching() {
- QueryProfileType type=new QueryProfileType("type");
+ void testNoPatchMatching() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(false); // Default, but set here for clarity
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
assertNull(registry.findQueryProfile("a/bee/ce/dee")); // Different from test above
assertNull(registry.findQueryProfile("a/bee/ce/dee/eee/")); // Different from test above
assertNull(registry.findQueryProfile("a/bee/cede")); // Different from test above
@@ -82,59 +82,59 @@ public class PatchMatchingTestCase {
/** Check that the path matching property is inherited to subtypes */
@Test
- public void testPatchMatchingInheritance() {
- QueryProfileType type=new QueryProfileType("type");
- QueryProfileType subType=new QueryProfileType("subType");
+ void testPatchMatchingInheritance() {
+ QueryProfileType type = new QueryProfileType("type");
+ QueryProfileType subType = new QueryProfileType("subType");
subType.inherited().add(type);
type.setMatchAsPath(true); // Supertype only
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(subType);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(subType);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee/cede").getId().getName());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
/** Check that the path matching works with versioned profiles */
@Test
- public void testPatchMatchingVersions() {
- QueryProfileType type=new QueryProfileType("type");
+ void testPatchMatchingVersions() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee11=new QueryProfile("a/bee:1.1");
+ QueryProfile abee11 = new QueryProfile("a/bee:1.1");
abee11.setType(type);
abee11.addInherited(a);
- QueryProfile abee13=new QueryProfile("a/bee:1.3");
+ QueryProfile abee13 = new QueryProfile("a/bee:1.3");
abee13.setType(type);
abee13.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee13);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee11);
registry.register(abee13);
@@ -142,52 +142,52 @@ public class PatchMatchingTestCase {
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee:1.1",registry.findQueryProfile("a/bee:1.1").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee:1").getId().toString());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee:1.1",registry.findQueryProfile("a/bee/cede:1.1").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee/cede").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee/cede:1").getId().toString());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee:1.1", registry.findQueryProfile("a/bee:1.1").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee:1").getId().toString());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee:1.1", registry.findQueryProfile("a/bee/cede:1.1").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee/cede").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee/cede:1").getId().toString());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
@Test
- public void testQuirkyNames() {
- QueryProfileType type=new QueryProfileType("type");
+ void testQuirkyNames() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("/a");
+ QueryProfile a = new QueryProfile("/a");
a.setType(type);
- QueryProfile abee=new QueryProfile("/a//bee");
+ QueryProfile abee = new QueryProfile("/a//bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("/a//bee/ce/");
+ QueryProfile abeece = new QueryProfile("/a//bee/ce/");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("/a",registry.findQueryProfile("/a").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a").getId().getName());
assertNull(registry.findQueryProfile("a"));
- assertEquals("/a//bee",registry.findQueryProfile("/a//bee").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/dee").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/dee/eee/").getId().getName());
- assertEquals("/a//bee",registry.findQueryProfile("/a//bee/cede").getId().getName());
- assertEquals("/a",registry.findQueryProfile("/a/foo/bee/cede").getId().getName());
- assertEquals("/a",registry.findQueryProfile("/a/bee").getId().getName());
+ assertEquals("/a//bee", registry.findQueryProfile("/a//bee").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/dee").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/dee/eee/").getId().getName());
+ assertEquals("/a//bee", registry.findQueryProfile("/a//bee/cede").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a/foo/bee/cede").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a/bee").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
index 62551447017..cc7b5c4d666 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
@@ -9,13 +9,10 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -26,7 +23,7 @@ public class QueryProfileTypeInheritanceTestCase {
private QueryProfileType type, typeStrict, user, userStrict;
- @Before
+ @BeforeEach
public void setUp() {
type=new QueryProfileType(new ComponentId("testtype"));
typeStrict=new QueryProfileType(new ComponentId("testtypeStrict"));
@@ -63,7 +60,7 @@ public class QueryProfileTypeInheritanceTestCase {
}
@Test
- public void testInheritance() {
+ void testInheritance() {
type.inherited().add(user);
type.freeze();
user.freeze();
@@ -71,11 +68,11 @@ public class QueryProfileTypeInheritanceTestCase {
assertFalse(type.isOverridable("myUserString"));
assertEquals("myUserInteger", type.getField("myUserInteger").getName());
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals(37, ctest.get("myUserInteger"));
@@ -83,45 +80,45 @@ public class QueryProfileTypeInheritanceTestCase {
}
@Test
- public void testInheritanceStrict() {
+ void testInheritanceStrict() {
typeStrict.inherited().add(userStrict);
typeStrict.freeze();
userStrict.freeze();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(typeStrict);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
try {
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
fail("Should have failed");
}
catch (IllegalArgumentException e) {
assertEquals("'myUnknownInteger' is not declared in query profile type 'testtypeStrict', and the type is strict",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
- assertEquals(37,test.get("myUserInteger"));
+ assertEquals(37, test.get("myUserInteger"));
assertNull(test.get("myUnknownInteger"));
}
@Test
- public void testStrictIsInherited() {
+ void testStrictIsInherited() {
type.inherited().add(userStrict);
type.freeze();
userStrict.freeze();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
try {
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
fail("Should have failed");
}
catch (IllegalArgumentException e) {
assertEquals("'myUnknownInteger' is not declared in query profile type 'testtype', and the type is strict",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
CompiledQueryProfile ctest = test.compile(null);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
index a77de954b3a..21a9b2fe399 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
@@ -19,19 +19,15 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* tests query profiles with/and types
@@ -44,7 +40,7 @@ public class QueryProfileTypeTestCase {
private QueryProfileType testtype, emptyInheritingTesttype, testtypeStrict, user, userStrict;
- @Before
+ @BeforeEach
public void setUp() {
registry = new QueryProfileRegistry();
@@ -95,24 +91,24 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testTypedOfPrimitivesAssignmentNonStrict() {
+ void testTypedOfPrimitivesAssignmentNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
profile.set("myString", "anyValue", registry);
profile.set("nontypedString", "anyValueToo", registry); // legal because this is not strict
- assertWrongType(profile,"integer", "myInteger","notInteger");
+ assertWrongType(profile, "integer", "myInteger", "notInteger");
assertWrongType(profile, "integer", "myInteger", "1.5");
profile.set("myInteger", 3, registry);
- assertWrongType(profile,"long","myLong","notLong");
+ assertWrongType(profile, "long", "myLong", "notLong");
assertWrongType(profile, "long", "myLong", "1.5");
profile.set("myLong", 4000000000000L, registry);
assertWrongType(profile, "float", "myFloat", "notFloat");
profile.set("myFloat", 3.14f, registry);
assertWrongType(profile, "double", "myDouble", "notDouble");
- profile.set("myDouble",2.18, registry);
- profile.set("myBoolean",true, registry);
+ profile.set("myDouble", 2.18, registry);
+ profile.set("myBoolean", true, registry);
String tensorString1 = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
profile.set("ranking.features.query(myTensor1)", tensorString1, registry);
@@ -122,12 +118,12 @@ public class QueryProfileTypeTestCase {
profile.set("ranking.features.query(myTensor3)", tensorString3, registry);
profile.set("myQuery", "...", registry); // TODO
- profile.set("myQueryProfile.anyString","value1", registry);
- profile.set("myQueryProfile.anyDouble",8.76, registry);
- profile.set("myUserQueryProfile.myUserString","value2", registry);
+ profile.set("myQueryProfile.anyString", "value1", registry);
+ profile.set("myQueryProfile.anyDouble", 8.76, registry);
+ profile.set("myUserQueryProfile.myUserString", "value2", registry);
profile.set("myUserQueryProfile.anyString", "value3", registry); // Legal because user is not strict
assertWrongType(profile, "integer", "myUserQueryProfile.myUserInteger", "notInteger");
- profile.set("myUserQueryProfile.uint",1337, registry); // Set using alias
+ profile.set("myUserQueryProfile.uint", 1337, registry); // Set using alias
profile.set("myUserQueryProfile.anyDouble", 9.13, registry); // Legal because user is not strict
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -162,22 +158,22 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testTypedOfPrimitivesAssignmentStrict() {
+ void testTypedOfPrimitivesAssignmentStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
profile.set("myString", "anyValue", registry);
assertNotPermitted(profile, "nontypedString", "anyValueToo"); // Illegal because this is strict
- assertWrongType(profile,"integer","myInteger","notInteger");
+ assertWrongType(profile, "integer", "myInteger", "notInteger");
assertWrongType(profile, "integer", "myInteger", "1.5");
profile.set("myInteger", 3, registry);
- assertWrongType(profile,"long","myLong","notLong");
+ assertWrongType(profile, "long", "myLong", "notLong");
assertWrongType(profile, "long", "myLong", "1.5");
profile.set("myLong", 4000000000000L, registry);
assertWrongType(profile, "float", "myFloat", "notFloat");
profile.set("myFloat", 3.14f, registry);
assertWrongType(profile, "double", "myDouble", "notDouble");
- profile.set("myDouble",2.18, registry);
+ profile.set("myDouble", 2.18, registry);
profile.set("myQueryProfile.anyString", "value1", registry);
profile.set("myQueryProfile.anyDouble", 8.76, registry);
profile.set("myUserQueryProfile.myUserString", "value2", registry);
@@ -204,22 +200,22 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile directly */
@Test
- public void testTypedAssignmentOfQueryProfilesNonStrict() {
+ void testTypedAssignmentOfQueryProfilesNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
- QueryProfile map1=new QueryProfile("myMap1");
+ QueryProfile map1 = new QueryProfile("myMap1");
map1.set("key1", "value1", registry);
- QueryProfile map2=new QueryProfile("myMap2");
+ QueryProfile map2 = new QueryProfile("myMap2");
map2.set("key2", "value2", registry);
- QueryProfile myUser=new QueryProfile("myUser");
+ QueryProfile myUser = new QueryProfile("myUser");
myUser.setType(user);
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
- assertWrongType(profile,"reference to a query profile","myQueryProfile","aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
profile.set("myQueryProfile", map1, registry);
profile.set("someMap", map2, registry); // Legal because this is not strict
assertWrongType(profile, "reference to a query profile of type 'user'", "myUserQueryProfile", map1);
@@ -235,14 +231,14 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile directly */
@Test
- public void testTypedAssignmentOfQueryProfilesStrict() {
+ void testTypedAssignmentOfQueryProfilesStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
- QueryProfile map1=new QueryProfile("myMap1");
+ QueryProfile map1 = new QueryProfile("myMap1");
map1.set("key1", "value1", registry);
- QueryProfile map2=new QueryProfile("myMap2");
+ QueryProfile map2 = new QueryProfile("myMap2");
map2.set("key2", "value2", registry);
QueryProfile myUser = new QueryProfile("myUser");
@@ -250,10 +246,10 @@ public class QueryProfileTypeTestCase {
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
- assertWrongType(profile,"reference to a query profile","myQueryProfile","aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
profile.set("myQueryProfile", map1, registry);
- assertNotPermitted(profile,"someMap", map2);
- assertWrongType(profile,"reference to a query profile of type 'userStrict'", "myUserQueryProfile", map1);
+ assertNotPermitted(profile, "someMap", map2);
+ assertWrongType(profile, "reference to a query profile of type 'userStrict'", "myUserQueryProfile", map1);
profile.set("myUserQueryProfile", myUser, registry);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -266,7 +262,7 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile as an id string */
@Test
- public void testTypedAssignmentOfQueryProfileReferencesNonStrict() {
+ void testTypedAssignmentOfQueryProfileReferencesNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
@@ -286,21 +282,21 @@ public class QueryProfileTypeTestCase {
registry.register(map2);
registry.register(myUser);
- assertWrongType(profile,"reference to a query profile", "myQueryProfile", "aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
registry.register(map1);
profile.set("myQueryProfile", "myMap1", registry);
registry.register(map2);
profile.set("someMap", "myMap2", registry); // NOTICE: Will set as a string because we cannot know this is a reference
assertWrongType(profile, "reference to a query profile of type 'user'", "myUserQueryProfile", "myMap1");
registry.register(myUser);
- profile.set("myUserQueryProfile","myUser", registry);
+ profile.set("myUserQueryProfile", "myUser", registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
assertEquals("value1", cprofile.get("myQueryProfile.key1"));
assertEquals("myMap2", cprofile.get("someMap"));
- assertNull("Asking for an value which cannot be completely resolved returns null", cprofile.get("someMap.key2"));
+ assertNull(cprofile.get("someMap.key2"), "Asking for an value which cannot be completely resolved returns null");
assertEquals("userValue1", cprofile.get("myUserQueryProfile.myUserString"));
assertEquals(442, cprofile.get("myUserQueryProfile.myUserInteger"));
}
@@ -310,11 +306,11 @@ public class QueryProfileTypeTestCase {
* Here there exists a user profile already, and then a new one is overwritten
*/
@Test
- public void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQuery() {
+ void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
- QueryProfile myUser=new QueryProfile("myUser");
+ QueryProfile myUser = new QueryProfile("myUser");
myUser.setType(user);
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
@@ -332,8 +328,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cprofile);
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cprofile);
assertEquals(0, query.errors().size());
@@ -346,7 +342,7 @@ public class QueryProfileTypeTestCase {
* Here no user profile is set before it is assigned in the query
*/
@Test
- public void testTypedAssignmentOfQueryProfileReferencesNonStrictThroughQuery() {
+ void testTypedAssignmentOfQueryProfileReferencesNonStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
@@ -361,8 +357,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cprofile);
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cprofile);
assertEquals(0, query.errors().size());
@@ -375,7 +371,7 @@ public class QueryProfileTypeTestCase {
* Here no user profile is set before it is assigned in the query
*/
@Test
- public void testTypedAssignmentOfQueryProfileReferencesStrictThroughQuery() {
+ void testTypedAssignmentOfQueryProfileReferencesStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
@@ -401,13 +397,13 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'myUserQueryProfile.someKey' to 'value': 'someKey' is not declared in query profile type 'userStrict', and the type is strict",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testTensorRankFeatureInRequest() {
+ void testTensorRankFeatureInRequest() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -415,16 +411,16 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?" + urlEncode("ranking.features.query(myTensor1)") +
- "=" + urlEncode(tensorString),
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ "=" + urlEncode(tensorString),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("test"));
assertEquals(0, query.errors().size());
assertEquals(Tensor.from(tensorString), query.properties().get("ranking.features.query(myTensor1)"));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testTensorRankFeatureSetProgrammatically() {
+ void testTensorRankFeatureSetProgrammatically() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -432,13 +428,13 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?", com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ cRegistry.getComponent("test"));
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
+ void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -446,15 +442,15 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "tensor(x[3]):[0.1, 0.2, 0.3]";
Query query = new Query(HttpRequest.createTestRequest("?", com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ cRegistry.getComponent("test"));
try {
- query.getRanking().getFeatures().put("query(myTensor1)",Tensor.from(tensorString));
+ query.getRanking().getFeatures().put("query(myTensor1)", Tensor.from(tensorString));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
try {
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -462,14 +458,14 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
}
// Expected to work exactly as testTensorRankFeatureInRequest
@Test
- public void testTensorRankFeatureInRequestWithInheritedQueryProfileType() {
+ void testTensorRankFeatureInRequestWithInheritedQueryProfileType() {
QueryProfile profile = new QueryProfile("test");
profile.setType(emptyInheritingTesttype);
registry.register(profile);
@@ -477,16 +473,16 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?" + urlEncode("ranking.features.query(myTensor1)") +
- "=" + urlEncode(tensorString),
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ "=" + urlEncode(tensorString),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("test"));
assertEquals(0, query.errors().size());
assertEquals(Tensor.from(tensorString), query.properties().get("ranking.features.query(myTensor1)"));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testUnembeddedTensorRankFeatureInRequest() {
+ void testUnembeddedTensorRankFeatureInRequest() {
String text = "text to embed into a tensor";
Tensor embedding1 = Tensor.from("tensor<float>(x[5]):[3,7,4,0,0]]");
Tensor embedding2 = Tensor.from("tensor<float>(x[5]):[1,2,3,4,0]]");
@@ -500,7 +496,7 @@ public class QueryProfileTypeTestCase {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb1, \"" + text + "\")", embedding1, embedders);
assertEmbedQueryFails("embed(emb2, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb2'. Valid embedders are emb1");
+ "Can't find embedder 'emb2'. Valid embedders are emb1");
embedders = Map.of(
"emb1", new MockEmbedder(text, Language.UNKNOWN, embedding1),
@@ -530,7 +526,7 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testIllegalStrictAssignmentFromRequest() {
+ void testIllegalStrictAssignmentFromRequest() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
@@ -541,13 +537,13 @@ public class QueryProfileTypeTestCase {
try {
new Query(HttpRequest.createTestRequest("?myUserQueryProfile.nondeclared=someValue",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- profile.compile(null));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ profile.compile(null));
fail("Above statement should throw");
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'myUserQueryProfile.nondeclared' to 'someValue': 'nondeclared' is not declared in query profile type 'userStrict', and the type is strict"));
+ "Could not set 'myUserQueryProfile.nondeclared' to 'someValue': 'nondeclared' is not declared in query profile type 'userStrict', and the type is strict"));
}
}
@@ -557,7 +553,7 @@ public class QueryProfileTypeTestCase {
* The whole thing is accessed through a two levels of nontyped top-level profiles
*/
@Test
- public void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -586,8 +582,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("topMap"));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
@@ -599,7 +595,7 @@ public class QueryProfileTypeTestCase {
* Same as previous test but using the untyped myQueryProfile reference instead of the typed myUserQueryProfile
*/
@Test
- public void testAnonTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testAnonTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -630,15 +626,15 @@ public class QueryProfileTypeTestCase {
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myQueryProfile=newUser", com.yahoo.jdisc.http.HttpRequest.Method.GET), cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
- assertEquals("newUserValue1",query.properties().get("subMap.typeProfile.myQueryProfile.myUserString"));
- assertEquals(845,query.properties().get("subMap.typeProfile.myQueryProfile.myUserInteger"));
+ assertEquals("newUserValue1", query.properties().get("subMap.typeProfile.myQueryProfile.myUserString"));
+ assertEquals(845, query.properties().get("subMap.typeProfile.myQueryProfile.myUserInteger"));
}
/**
* Tests setting a illegal value in a strict profile nested under untyped maps
*/
@Test
- public void testSettingValueInStrictTypeNestedUnderUntypedMaps() {
+ void testSettingValueInStrictTypeNestedUnderUntypedMaps() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -656,13 +652,13 @@ public class QueryProfileTypeTestCase {
try {
new Query(
HttpRequest.createTestRequest("?subMap.typeProfile.someValue=value",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
cRegistry.getComponent("topMap"));
fail("Above statement should throw");
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'subMap.typeProfile.someValue' to 'value': 'someValue' is not declared in query profile type 'testtypeStrict', and the type is strict"));
+ "Could not set 'subMap.typeProfile.someValue' to 'value': 'someValue' is not declared in query profile type 'testtypeStrict', and the type is strict"));
}
}
@@ -672,15 +668,15 @@ public class QueryProfileTypeTestCase {
* The whole thing is accessed through a two levels of nontyped top-level profiles
*/
@Test
- public void testTypedSettingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testTypedSettingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
- topMap.set("subMap",subMap, registry);
+ topMap.set("subMap", subMap, registry);
QueryProfile test = new QueryProfile("test");
test.setType(testtype);
- subMap.set("typeProfile",test, registry);
+ subMap.set("typeProfile", test, registry);
QueryProfile newUser = new QueryProfile("newUser");
newUser.setType(user);
@@ -694,8 +690,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("topMap"));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
assertEquals("newUserValue1", query.properties().get("subMap.typeProfile.myUserQueryProfile.myUserString"));
@@ -703,14 +699,14 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testNestedTypeName() {
+ void testNestedTypeName() {
ComponentId.resetGlobalCountersForTests();
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("testType");
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding_profile)",
- "tensor<float>(model{},x[128])"),
- registry.getTypeRegistry());
+ "tensor<float>(model{},x[128])"),
+ registry.getTypeRegistry());
QueryProfile test = new QueryProfile("test");
registry.register(test);
test.setType(type);
@@ -723,15 +719,15 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testNestedTypeNameUsingBuiltInTypes() {
+ void testNestedTypeNameUsingBuiltInTypes() {
ComponentId.resetGlobalCountersForTests();
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("testType");
type.inherited().add(Query.getArgumentType()); // Include native type checking
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding_profile)",
- "tensor<float>(model{},x[128])"),
- registry.getTypeRegistry());
+ "tensor<float>(model{},x[128])"),
+ registry.getTypeRegistry());
QueryProfile test = new QueryProfile("test");
registry.register(test);
test.setType(type);
@@ -745,7 +741,7 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("'foo' is not a valid property in 'ranking'. See the query api for valid keys starting by 'ranking'.",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
// With a prefix we're not in the built-in type space
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
index 5fbe8858186..46859ab1cbe 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
@@ -2,13 +2,12 @@
package com.yahoo.search.query.properties.test;
import com.yahoo.processing.request.properties.PropertyMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -16,24 +15,24 @@ import static org.junit.Assert.assertTrue;
public class PropertyMapTestCase {
@Test
- public void testCloning() {
+ void testCloning() {
PropertyMap map = new PropertyMap();
map.set("clonable", new ClonableObject());
map.set("nonclonable", new NonClonableObject());
- map.set("clonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("nonclonableArray", new NonClonableObject[] {new NonClonableObject()});
+ map.set("clonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()});
map.set("clonableList", Collections.singletonList(new ClonableObject()));
map.set("nonclonableList", Collections.singletonList(new NonClonableObject()));
assertNotNull(map.get("clonable"));
assertNotNull(map.get("nonclonable"));
- PropertyMap mapClone=map.clone();
+ PropertyMap mapClone = map.clone();
assertTrue(map.get("clonable") != mapClone.get("clonable"));
- assertTrue(map.get("nonclonable") == mapClone.get("nonclonable"));
+ assertEquals(map.get("nonclonable"), mapClone.get("nonclonable"));
assertTrue(map.get("clonableArray") != mapClone.get("clonableArray"));
assertTrue(first(map.get("clonableArray")) != first(mapClone.get("clonableArray")));
- assertTrue(first(map.get("nonclonableArray")) == first(mapClone.get("nonclonableArray")));
+ assertEquals(first(map.get("nonclonableArray")), first(mapClone.get("nonclonableArray")));
}
private Object first(Object object) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
index 2a123b4bbda..23b41092660 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
@@ -5,9 +5,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests that dimension arguments in queries are transferred correctly to dimension values
@@ -17,18 +17,18 @@ import static org.junit.Assert.assertEquals;
public class RequestContextPropertiesTestCase {
@Test
- public void testIt() {
- QueryProfile p=new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a","a-default", (QueryProfileRegistry)null);
- p.set("a","a-x1",new String[] {"x1"}, null);
- p.set("a","a-+x1",new String[] {"+x1"}, null);
+ void testIt() {
+ QueryProfile p = new QueryProfile("test");
+ p.setDimensions(new String[]{"x"});
+ p.set("a", "a-default", (QueryProfileRegistry) null);
+ p.set("a", "a-x1", new String[]{"x1"}, null);
+ p.set("a", "a-+x1", new String[]{"+x1"}, null);
Query q1 = new Query(QueryTestCase.httpEncode("?query=foo"), p.compile(null));
- assertEquals("a-default",q1.properties().get("a"));
- Query q2 = new Query(QueryTestCase.httpEncode("?query=foo&x=x1"),p.compile(null));
- assertEquals("a-x1",q2.properties().get("a"));
- Query q3 = new Query(QueryTestCase.httpEncode("?query=foo&x=+x1"),p.compile(null));
- assertEquals("a-+x1",q3.properties().get("a"));
+ assertEquals("a-default", q1.properties().get("a"));
+ Query q2 = new Query(QueryTestCase.httpEncode("?query=foo&x=x1"), p.compile(null));
+ assertEquals("a-x1", q2.properties().get("a"));
+ Query q3 = new Query(QueryTestCase.httpEncode("?query=foo&x=+x1"), p.compile(null));
+ assertEquals("a-+x1", q3.properties().get("a"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
index 11c249c5cdb..0e9bf8d41ec 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
@@ -1,15 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.properties.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Arrays;
import java.util.HashSet;
import com.yahoo.processing.request.properties.PropertyMap;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.search.query.properties.SubProperties;
/**
@@ -18,19 +17,21 @@ import com.yahoo.search.query.properties.SubProperties;
public class SubPropertiesTestCase {
@Test
- public void testSubProperties() {
- PropertyMap map = new PropertyMap() {{
- set("a.e","1");
- set("a.f",2);
- set("b.e","3");
- set("f",3);
- set("e","2");
- set("d","a");
- }};
+ void testSubProperties() {
+ PropertyMap map = new PropertyMap() {
+ {
+ set("a.e", "1");
+ set("a.f", 2);
+ set("b.e", "3");
+ set("f", 3);
+ set("e", "2");
+ set("d", "a");
+ }
+ };
SubProperties sub = new SubProperties("a", map);
- assertEquals("1",sub.get("e"));
- assertEquals(2,sub.get("f"));
+ assertEquals("1", sub.get("e"));
+ assertEquals(2, sub.get("f"));
assertNull(sub.get("d"));
assertEquals(new HashSet<>(Arrays.asList("e", "f")), sub.listProperties("").keySet());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
index 72b77377bf2..e502cf538aa 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
@@ -1,12 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.rewrite;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
import com.yahoo.prelude.query.WeakAndItem;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.AndItem;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.CompositeItem;
import com.yahoo.prelude.query.Item;
import com.yahoo.language.process.SpecialTokenRegistry;
@@ -25,7 +26,7 @@ public class RewriterFeaturesTestCase {
private static final String ASCII_ELLIPSIS = "...";
@Test
- public final void testConvertStringToQTree() {
+ final void testConvertStringToQTree() {
Execution placeholder = new Execution(Context.createContextStub());
SpecialTokenRegistry tokenRegistry = new SpecialTokenRegistry(
new SpecialtokensConfig(
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
index d9a3603bdaf..668d070b3e2 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
@@ -8,8 +8,8 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for GenericExpansionRewriter
@@ -29,7 +29,7 @@ public class GenericExpansionRewriterTestCase {
* Load the GenericExpansionRewriterSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -44,149 +44,149 @@ public class GenericExpansionRewriterTestCase {
* MaxRewrites=3, PartialPhraseMatch is on, type=adv case
*/
@Test
- public void testPartialPhraseMaxRewriteAdvType() {
+ void testPartialPhraseMaxRewriteAdvType() {
utils.assertRewrittenQuery("?query=(modern new york city travel phone number) OR (travel agency) OR travel&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=3",
- "query 'OR (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
- "(AND new york city travel)) (OR pn (AND phone number))) ta (AND travel agency) " +
- "tr travel'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=3",
+ "query 'OR (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
+ "(AND new york city travel)) (OR pn (AND phone number))) ta (AND travel agency) " +
+ "tr travel'");
}
/**
* PartialPhraseMatch is off, type=adv case
*/
@Test
- public void testPartialPhraseNoMaxRewriteAdvType() {
+ void testPartialPhraseNoMaxRewriteAdvType() {
utils.assertRewrittenQuery("?query=(modern new york city travel phone number) OR (travel agency) OR travel&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR (AND modern new york city travel phone number) " +
- "ta (AND travel agency) tr travel'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR (AND modern new york city travel phone number) " +
+ "ta (AND travel agency) tr travel'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, type=adv, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteAdvTypeFilter() {
+ void testFullPhraseNoMaxRewriteAdvTypeFilter() {
utils.assertRewrittenQuery("?query=ca OR (modern new york city travel phone number) OR (travel agency) OR travel&" +
- "type=adv&filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR california ca (AND modern new york city travel phone number) " +
- "ta (AND travel agency) tr travel) |citystate:santa |clara |ca'");
+ "type=adv&filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR california ca (AND modern new york city travel phone number) " +
+ "ta (AND travel agency) tr travel) |citystate:santa |clara |ca'");
}
/**
* MaxRewrites=0 (i.e No MaxRewrites), PartialPhraseMatch is on, type=adv, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteAdvTypeFilter() {
+ void testPartialPhraseNoMaxRewriteAdvTypeFilter() {
utils.assertRewrittenQuery("?query=ca OR (modern new york city travel phone number) OR (travel agency) OR travel&" +
- "type=adv&filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=0",
- "query 'RANK (OR california ca (AND modern (OR \"rewrite11 rewrite12\" " +
- "rewrite2 rewrite3 rewrite4 rewrite5 (AND new york city travel)) " +
- "(OR pn (AND phone number))) ta (AND travel agency) tr travel) " +
- "|citystate:santa |clara |ca'");
+ "type=adv&filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=0",
+ "query 'RANK (OR california ca (AND modern (OR \"rewrite11 rewrite12\" " +
+ "rewrite2 rewrite3 rewrite4 rewrite5 (AND new york city travel)) " +
+ "(OR pn (AND phone number))) ta (AND travel agency) tr travel) " +
+ "|citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, single word, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteSingleWordFilter() {
+ void testFullPhraseNoMaxRewriteSingleWordFilter() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, single word, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteSingleWordFilter() {
+ void testPartialPhraseNoMaxRewriteSingleWordFilter() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWordFilter() {
+ void testFullPhraseNoMaxRewriteMultiWordFilter() {
utils.assertRewrittenQuery("?query=travel agency&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR ta (AND travel agency)) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR ta (AND travel agency)) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, multi word, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteMultiWordFilter() {
+ void testPartialPhraseNoMaxRewriteMultiWordFilter() {
utils.assertRewrittenQuery("?query=modern new york city travel phone number&" +
- "filter=citystate:santa clara ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
- "rewrite4 rewrite5 (AND new york city travel)) (OR pn (AND phone number))) " +
- "|citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&type=all&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
+ "rewrite4 rewrite5 (AND new york city travel)) (OR pn (AND phone number))) " +
+ "|citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, single word
*/
@Test
- public void testFullPhraseNoMaxRewriteSingleWord() {
+ void testFullPhraseNoMaxRewriteSingleWord() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR california ca'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR california ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, single word
*/
@Test
- public void testPartialPhraseNoMaxRewriteSingleWord() {
+ void testPartialPhraseNoMaxRewriteSingleWord() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'OR california ca'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'OR california ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWord() {
+ void testFullPhraseNoMaxRewriteMultiWord() {
utils.assertRewrittenQuery("?query=travel agency&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR ta (AND travel agency)'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR ta (AND travel agency)'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word, no full match
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWordNoMatch() {
+ void testFullPhraseNoMaxRewriteMultiWordNoMatch() {
utils.assertRewrittenQuery("?query=nyc travel agency&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'AND nyc travel agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'AND nyc travel agency'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, multi word
*/
@Test
- public void testPartialPhraseNoMaxRewriteMultiWord() {
+ void testPartialPhraseNoMaxRewriteMultiWord() {
utils.assertRewrittenQuery("?query=modern new york city travel phone number&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 rewrite4 rewrite5 "+
- "(AND new york city travel)) (OR pn (AND phone number))'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 rewrite4 rewrite5 " +
+ "(AND new york city travel)) (OR pn (AND phone number))'");
}
/**
@@ -195,10 +195,10 @@ public class GenericExpansionRewriterTestCase {
* Should rewrite travel but not travel agency in this case
*/
@Test
- public void testPartialPhraseMultiWordRankTree() {
+ void testPartialPhraseMultiWordRankTree() {
utils.assertRewrittenQuery("?query=travel RANK agency&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR tr travel) agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR tr travel) agency'");
}
/**
@@ -207,10 +207,10 @@ public class GenericExpansionRewriterTestCase {
* Should rewrite travel but not travel agency in this case
*/
@Test
- public void testFullPhraseMultiWordRankTree() {
+ void testFullPhraseMultiWordRankTree() {
utils.assertRewrittenQuery("?query=travel RANK agency&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR tr travel) agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR tr travel) agency'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
index 6c9f9c248ea..36eb06a3a92 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.intent.model.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test Cases for MisspellRewriter
@@ -25,7 +25,7 @@ public class MisspellRewriterTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
MisspellRewriter searcher = new MisspellRewriter();
Execution execution = QueryRewriteSearcherTestUtils.createExecutionObj(searcher);
@@ -37,18 +37,18 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=0.9 qss_sugg=1.0
*/
@Test
- public void testQSSRewriteQSSSuggestWithRewrite() {
+ void testQSSRewriteQSSSuggestWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 0.9,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw", 0.9,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg)'",
+ intentModel);
}
/**
@@ -56,19 +56,19 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=0.9 qss_rw=0.9 qss_sugg=1.0
*/
@Test
- public void testQSSRewriteWithRewrite() {
+ void testQSSRewriteWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw1", 0.9,
- true, false),
- utils.createInterpretation("will smith rw2", 0.9,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw1", 0.9,
+ true, false),
+ utils.createInterpretation("will smith rw2", 0.9,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith rw1)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith rw1)'",
+ intentModel);
}
/**
@@ -76,19 +76,19 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=1.0 qss_sugg=0.9 qss_sugg=0.8
*/
@Test
- public void testQSSSuggWithRewrite() {
+ void testQSSSuggWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 1.0,
- true, false),
- utils.createInterpretation("will smith sugg1", 0.9,
- false, true),
- utils.createInterpretation("will smith sugg2", 0.8,
- false, true));
+ utils.createInterpretation("will smith rw", 1.0,
+ true, false),
+ utils.createInterpretation("will smith sugg1", 0.9,
+ false, true),
+ utils.createInterpretation("will smith sugg2", 0.8,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg1)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg1)'",
+ intentModel);
}
/**
@@ -96,16 +96,16 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=1.0 qss_sugg=1.0
*/
@Test
- public void testFeautureOffWithRewrite() {
+ void testFeautureOffWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 1.0,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw", 1.0,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith",
- "query 'WEAKAND(100) willl smith'",
- intentModel);
+ "query 'WEAKAND(100) willl smith'",
+ intentModel);
}
/**
@@ -113,18 +113,18 @@ public class MisspellRewriterTestCase {
* QLAS returns no spell correction
*/
@Test
- public void testQSSRewriteQSSSuggWithoutRewrite() {
+ void testQSSRewriteQSSSuggWithoutRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("use diff query for testing", 1.0,
- false, false),
- utils.createInterpretation("use diff query for testing", 1.0,
- false, false));
+ utils.createInterpretation("use diff query for testing", 1.0,
+ false, false),
+ utils.createInterpretation("use diff query for testing", 1.0,
+ false, false));
utils.assertRewrittenQuery("?query=will+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'WEAKAND(100) will smith'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'WEAKAND(100) will smith'",
+ intentModel);
}
/**
@@ -132,7 +132,7 @@ public class MisspellRewriterTestCase {
* It should throw exception
*/
@Test
- public void testNullIntentModelException() {
+ void testNullIntentModelException() {
try {
RewriterUtils.getSpellCorrected(new Query("willl smith"), true, true);
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
index c99ddcd6c62..98a93a572e9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
@@ -8,8 +8,8 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for NameRewriter
@@ -29,7 +29,7 @@ public class NameRewriterTestCase {
* Load the NameRewriterSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -44,29 +44,29 @@ public class NameRewriterTestCase {
* RewritesAsEquiv and OriginalAsUnit are on
*/
@Test
- public void testRewritesAsEquivAndOriginalAsUnit() {
+ void testRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'OR \"will smith\" (AND will smith movies) " +
- "(AND will smith news) (AND will smith imdb) " +
- "(AND will smith lyrics) (AND will smith dead) " +
- "(AND will smith nfl) (AND will smith new movie hancock) " +
- "(AND will smith biography)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'OR \"will smith\" (AND will smith movies) " +
+ "(AND will smith news) (AND will smith imdb) " +
+ "(AND will smith lyrics) (AND will smith dead) " +
+ "(AND will smith nfl) (AND will smith new movie hancock) " +
+ "(AND will smith biography)'");
}
/**
* RewritesAsEquiv is on
*/
@Test
- public void testRewritesAsEquiv() {
+ void testRewritesAsEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
- "query 'OR (AND will smith) (AND will smith movies) " +
- "(AND will smith news) (AND will smith imdb) " +
- "(AND will smith lyrics) (AND will smith dead) " +
- "(AND will smith nfl) (AND will smith new movie hancock) " +
- "(AND will smith biography)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
+ "query 'OR (AND will smith) (AND will smith movies) " +
+ "(AND will smith news) (AND will smith imdb) " +
+ "(AND will smith lyrics) (AND will smith dead) " +
+ "(AND will smith nfl) (AND will smith new movie hancock) " +
+ "(AND will smith biography)'");
}
/**
@@ -74,57 +74,57 @@ public class NameRewriterTestCase {
* Should not rewrite
*/
@Test
- public void testComplextQueryRewritesAsEquiv() {
+ void testComplextQueryRewritesAsEquiv() {
utils.assertRewrittenQuery("?query=((will smith) OR (willl smith)) AND (tom cruise)&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
- "query 'AND (OR (AND will smith) (AND willl smith)) (AND tom cruise)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
+ "query 'AND (OR (AND will smith) (AND willl smith)) (AND tom cruise)'");
}
/**
* Single word query for RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testSingleWordForRewritesAsEquivAndOriginalAsUnit() {
+ void testSingleWordForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=obama&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'OR obama (AND obama \"nobel peace prize\") " +
- "(AND obama wiki) (AND obama nobel prize) " +
- "(AND obama nobel peace prize) (AND obama wears mom jeans) " +
- "(AND obama sucks) (AND obama news) (AND malia obama) " +
- "(AND obama speech) (AND obama nobel) (AND obama wikipedia) " +
- "(AND barack obama biography) (AND obama snl) " +
- "(AND obama peace prize) (AND michelle obama) (AND barack obama)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'OR obama (AND obama \"nobel peace prize\") " +
+ "(AND obama wiki) (AND obama nobel prize) " +
+ "(AND obama nobel peace prize) (AND obama wears mom jeans) " +
+ "(AND obama sucks) (AND obama news) (AND malia obama) " +
+ "(AND obama speech) (AND obama nobel) (AND obama wikipedia) " +
+ "(AND barack obama biography) (AND obama snl) " +
+ "(AND obama peace prize) (AND michelle obama) (AND barack obama)'");
}
/**
* RewritesAsUnitEquiv and OriginalAsUnitEquiv are on
*/
@Test
- public void testRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
+ void testRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
- "=true",
- "query 'OR (AND will smith) \"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR (AND will smith) \"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
* Single word query for RewritesAsUnitEquiv and OriginalAsUnitEquiv on case
*/
@Test
- public void testSingleWordForRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
+ void testSingleWordForRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
utils.assertRewrittenQuery("?query=obama&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
- "=true",
- "query 'OR obama \"obama nobel peace prize\" \"obama wiki\" \"obama nobel prize\" \"obama nobel peace prize\" \"obama wears mom jeans\" \"obama sucks\" \"obama news\" \"malia obama\" \"obama speech\" \"obama nobel\" \"obama wikipedia\" \"barack obama biography\" \"obama snl\" \"obama peace prize\" \"michelle obama\" \"barack obama\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR obama \"obama nobel peace prize\" \"obama wiki\" \"obama nobel prize\" \"obama nobel peace prize\" \"obama wears mom jeans\" \"obama sucks\" \"obama news\" \"malia obama\" \"obama speech\" \"obama nobel\" \"obama wikipedia\" \"barack obama biography\" \"obama snl\" \"obama peace prize\" \"michelle obama\" \"barack obama\"'");
}
/**
@@ -132,11 +132,11 @@ public class NameRewriterTestCase {
* for RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testBoostingQueryForRewritesAsEquivAndOriginalAsUnit() {
+ void testBoostingQueryForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=angelina jolie&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query '\"angelina jolie\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query '\"angelina jolie\"'");
}
/**
@@ -144,39 +144,39 @@ public class NameRewriterTestCase {
* RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testFSANoMatchForRewritesAsEquivAndOriginalAsUnit() {
+ void testFSANoMatchForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=tom cruise&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'AND tom cruise'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'AND tom cruise'");
}
/**
* RewritesAsUnitEquiv is on
*/
@Test
- public void testRewritesAsUnitEquiv() {
+ void testRewritesAsUnitEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'OR (AND will smith) \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR (AND will smith) \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
* RewritesAsUnitEquiv is on and MaxRewrites is set to 2
*/
@Test
- public void testRewritesAsUnitEquivAndMaxRewrites() {
+ void testRewritesAsUnitEquivAndMaxRewrites() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=2",
- "query 'OR (AND will smith) \"will smith movies\" " +
- "\"will smith news\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=2",
+ "query 'OR (AND will smith) \"will smith movies\" " +
+ "\"will smith news\"'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
index 8906dbfa386..4848483688e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
@@ -10,8 +10,8 @@ import com.yahoo.search.intent.model.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Generic Test Cases for QueryRewriteSearcher
@@ -36,7 +36,7 @@ public class QueryRewriteSearcherTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
@@ -61,7 +61,7 @@ public class QueryRewriteSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testInvalidFSAConfigPath() {
+ void testInvalidFSAConfigPath() {
// Instantiate Name Rewriter with fake FSA path
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(FAKE_FSA_CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -80,9 +80,9 @@ public class QueryRewriteSearcherTestCase {
QueryRewriteSearcherTestUtils utilsWithFakePath = new QueryRewriteSearcherTestUtils(execution);
utilsWithFakePath.assertRewrittenQuery("?query=will smith&type=all&" +
- NAME_REWRITER_NAME + "." +
- RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true",
- "query 'AND will smith'");
+ NAME_REWRITER_NAME + "." +
+ RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true",
+ "query 'AND will smith'");
}
/**
@@ -90,19 +90,19 @@ public class QueryRewriteSearcherTestCase {
* It should skip to the next rewriter
*/
@Test
- public void testExceptionInRewriter() {
+ void testExceptionInRewriter() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
@@ -110,26 +110,26 @@ public class QueryRewriteSearcherTestCase {
* Query will be rewritten twice
*/
@Test
- public void testTwoRewritersInChain() {
+ void testTwoRewritersInChain() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
index da005871539..960eea5bba7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
@@ -13,10 +13,11 @@ import com.yahoo.text.interpretation.Interpretation;
import com.yahoo.text.interpretation.Annotations;
import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.component.chain.Chain;
-import org.junit.Assert;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Test utilities for QueryRewriteSearcher
*
@@ -40,6 +41,7 @@ public class QueryRewriteSearcherTestUtils {
*
* @param configPath path for the searcher config
*/
+ @SuppressWarnings("deprecation")
public static RewritesConfig createConfigObj(String configPath) {
return new ConfigGetter<>(RewritesConfig.class).getConfig(configPath);
}
@@ -72,7 +74,7 @@ public class QueryRewriteSearcherTestUtils {
public void assertRewrittenQuery(String origQuery, String finalQuery) {
Query query = new Query(QueryTestCase.httpEncode(origQuery));
Result result = execution.search(query);
- Assert.assertEquals(finalQuery, result.getQuery().toString());
+ assertEquals(finalQuery, result.getQuery().toString());
}
/**
@@ -88,7 +90,7 @@ public class QueryRewriteSearcherTestUtils {
Query query = new Query(origQuery);
intentModel.setTo(query);
Result result = execution.search(query);
- Assert.assertEquals(finalQuery, result.getQuery().toString());
+ assertEquals(finalQuery, result.getQuery().toString());
}
/**
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
index 96626738c35..56797768f56 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
@@ -12,8 +12,8 @@ import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.query.rewrite.RewritesConfig;
import com.yahoo.search.intent.model.*;
import com.yahoo.component.chain.Chain;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for SearchChainDispatcherSearcher
@@ -35,7 +35,7 @@ public class SearchChainDispatcherSearcherTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
@@ -70,26 +70,26 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be rewritten twice
*/
@Test
- public void testMarketChain() {
+ void testMarketChain() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&QRWChain=" + US_MARKET_SEARCH_CHAIN + "&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
/**
@@ -97,13 +97,13 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testInvalidMarketChain() {
+ void testInvalidMarketChain() {
utils.assertRewrittenQuery("?query=will smith&type=all&QRWChain=abc&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'AND will smith'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'AND will smith'");
}
/**
@@ -111,13 +111,13 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testEmptyMarketChain() {
+ void testEmptyMarketChain() {
utils.assertRewrittenQuery("?query=will smith&type=all&QRWChain=&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'AND will smith'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'AND will smith'");
}
/**
@@ -125,7 +125,7 @@ public class SearchChainDispatcherSearcherTestCase {
* should be executed
*/
@Test
- public void testChainContinuation() {
+ void testChainContinuation() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -156,24 +156,24 @@ public class SearchChainDispatcherSearcherTestCase {
new QueryRewriteSearcherTestUtils(execution);
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&QRWChain=" + US_MARKET_SEARCH_CHAIN + "&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
index 6f856144b8a..49d43bdc4c2 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
@@ -4,18 +4,16 @@ package com.yahoo.search.query.test;
import com.yahoo.prelude.query.Item;
import com.yahoo.search.Query;
import com.yahoo.search.query.Model;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedHashSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -25,13 +23,13 @@ public class ModelTestCase {
String oldConfigId;
- @Before
+ @BeforeEach
public void setUp() {
oldConfigId = System.getProperty("config.id");
System.setProperty("config.id", "file:src/test/java/com/yahoo/prelude/test/fieldtypes/field-info.cfg");
}
- @After
+ @AfterEach
public void tearDown() {
if (oldConfigId == null)
System.getProperties().remove("config.id");
@@ -40,30 +38,30 @@ public class ModelTestCase {
}
@Test
- public void testCopyParameters() {
+ void testCopyParameters() {
Query q1 = new Query("?query=test1&filter=test2&default-index=content&default-index=lala&encoding=iso8859-1");
Query q2 = q1.clone();
Model r1 = q1.getModel();
Model r2 = q2.getModel();
assertTrue(r1 != r2);
- assertEquals(r1,r2);
- assertEquals("test1",r2.getQueryString());
+ assertEquals(r1, r2);
+ assertEquals("test1", r2.getQueryString());
}
@Test
- public void testSetQuery() {
+ void testSetQuery() {
Query q1 = new Query("?query=test1");
Item r1 = q1.getModel().getQueryTree();
- q1.properties().set("query","test2");
+ q1.properties().set("query", "test2");
q1.getModel().setQueryString(q1.getModel().getQueryString()); // Force reparse
- assertNotSame(r1,q1.getModel().getQueryTree());
- q1.properties().set("query","test1");
+ assertNotSame(r1, q1.getModel().getQueryTree());
+ q1.properties().set("query", "test1");
q1.getModel().setQueryString(q1.getModel().getQueryString()); // Force reparse
- assertEquals(r1,q1.getModel().getQueryTree());
+ assertEquals(r1, q1.getModel().getQueryTree());
}
@Test
- public void testSetofSetters() {
+ void testSetofSetters() {
Query q1 = new Query("?query=test1&encoding=iso-8859-1&language=en&default-index=subject&filter=" + enc("\u00C5"));
Model r1 = q1.getModel();
assertEquals(r1.getQueryString(), "test1");
@@ -82,23 +80,23 @@ public class ModelTestCase {
}
@Test
- public void testSearchPath() {
- assertEquals("c6/r8",new Query("?query=test1&model.searchPath=c6/r8").getModel().getSearchPath());
- assertEquals("c6/r8",new Query("?query=test1&searchpath=c6/r8").getModel().getSearchPath());
+ void testSearchPath() {
+ assertEquals("c6/r8", new Query("?query=test1&model.searchPath=c6/r8").getModel().getSearchPath());
+ assertEquals("c6/r8", new Query("?query=test1&searchpath=c6/r8").getModel().getSearchPath());
}
@Test
- public void testClone() {
- Query q= new Query();
+ void testClone() {
+ Query q = new Query();
Model sr = new Model(q);
sr.setRestrict("music, cheese,other");
sr.setSources("cluster1");
assertEquals(sr.getSources(), new LinkedHashSet<>(Arrays.asList(new String[]{"cluster1"})));
- assertEquals(sr.getRestrict(),new LinkedHashSet<>(Arrays.asList(new String[]{"cheese","music","other"})));
+ assertEquals(sr.getRestrict(), new LinkedHashSet<>(Arrays.asList(new String[]{"cheese", "music", "other"})));
}
@Test
- public void testEquals() {
+ void testEquals() {
Query q = new Query();
Model sra = new Model(q);
sra.setRestrict("music,cheese");
@@ -107,20 +105,20 @@ public class ModelTestCase {
Model srb = new Model(q);
srb.setRestrict(" cheese , music");
srb.setSources("cluster1,cluster2");
- assertEquals(sra,srb);
+ assertEquals(sra, srb);
srb.setRestrict("music,cheese");
- assertNotSame(sra,srb);
+ assertNotSame(sra, srb);
}
@Test
- public void testSearchRestrictQueryParameters() {
- Query query=new Query("?query=test&search=news,archive&restrict=fish,bird");
+ void testSearchRestrictQueryParameters() {
+ Query query = new Query("?query=test&search=news,archive&restrict=fish,bird");
assertTrue(query.getModel().getSources().contains("news"));
assertTrue(query.getModel().getSources().contains("archive"));
- assertEquals(2,query.getModel().getSources().size());
+ assertEquals(2, query.getModel().getSources().size());
assertTrue(query.getModel().getRestrict().contains("fish"));
assertTrue(query.getModel().getRestrict().contains("bird"));
- assertEquals(2,query.getModel().getRestrict().size());
+ assertEquals(2, query.getModel().getRestrict().size());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
index c28e64196a2..df97c03ae68 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.jdisc.http.HttpRequest.Method;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -19,49 +19,49 @@ public class ParametersTestCase {
private final double delta = 0.000001;
@Test
- public void testSettingRankProperty() {
+ void testSettingRankProperty() {
Query query = new Query("?query=test&ranking.properties.dotProduct.X=(a:1,b:2)");
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankPropertyAsAlias() {
+ void testSettingRankPropertyAsAlias() {
Query query = new Query("?query=test&rankproperty.dotProduct.X=(a:1,b:2)");
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankFeature() {
+ void testSettingRankFeature() {
Query query = new Query("?query=test&ranking.features.matches=3");
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankFeatureAsAlias() {
+ void testSettingRankFeatureAsAlias() {
Query query = new Query("?query=test&rankfeature.matches=3");
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankPropertyWithQueryProfile() {
+ void testSettingRankPropertyWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&ranking.properties.dotProduct.X=(a:1,b:2)", Method.GET), createProfile());
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankPropertyAsAliasWithQueryProfile() {
+ void testSettingRankPropertyAsAliasWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&rankproperty.dotProduct.X=(a:1,b:2)", Method.GET), createProfile());
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankFeatureWithQueryProfile() {
+ void testSettingRankFeatureWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&ranking.features.matches=3", Method.GET), createProfile());
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankFeatureAsAliasWithQueryProfile() {
+ void testSettingRankFeatureAsAliasWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&rankfeature.matches=3", Method.GET), createProfile());
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
index aafbeaf5825..4aefd3c82e0 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.search.query.test;
import com.yahoo.prelude.query.Highlight;
import com.yahoo.search.Query;
import com.yahoo.search.query.Presentation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -16,20 +14,20 @@ import static org.junit.Assert.assertTrue;
public class PresentationTestCase {
@Test
- public void testClone() {
- Query q= new Query("");
+ void testClone() {
+ Query q = new Query("");
Presentation p = new Presentation(q);
p.setBolding(true);
Highlight h = new Highlight();
- h.addHighlightTerm("date","today");
+ h.addHighlightTerm("date", "today");
p.setHighlight(h);
- Presentation pc = (Presentation)p.clone();
- h.addHighlightTerm("title","Hello");
+ Presentation pc = (Presentation) p.clone();
+ h.addHighlightTerm("title", "Hello");
assertTrue(pc.getBolding());
pc.getHighlight().getHighlightItems();
assertTrue(pc.getHighlight().getHighlightItems().containsKey("date"));
assertFalse(pc.getHighlight().getHighlightItems().containsKey("title"));
- assertEquals(p,pc);
+ assertEquals(p, pc);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
index 0644a2b02e8..b1e406c47d7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -19,7 +19,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertEquals;
public class RankFeaturesTestCase {
@Test
- public void requireThatRankPropertiesTakesBothStringAndObject() {
+ void requireThatRankPropertiesTakesBothStringAndObject() {
RankProperties p = new RankProperties();
p.put("string", "b");
p.put("object", 7);
@@ -37,7 +37,7 @@ public class RankFeaturesTestCase {
@Test
@SuppressWarnings("deprecation")
- public void requireThatRankFeaturesUsingDoubleAndDoubleToStringEncodeTheSameWay() {
+ void requireThatRankFeaturesUsingDoubleAndDoubleToStringEncodeTheSameWay() {
RankFeatures withDouble = new RankFeatures(new Ranking(new Query()));
withDouble.put("query(myDouble)", 3.8);
assertEquals(3.8, withDouble.getDouble("query(myDouble)").getAsDouble(), 0.000001);
@@ -56,7 +56,7 @@ public class RankFeaturesTestCase {
}
@Test
- public void requireThatSingleTensorIsBinaryEncoded() {
+ void requireThatSingleTensorIsBinaryEncoded() {
TensorType type = new TensorType.Builder().mapped("x").mapped("y").mapped("z").build();
Tensor tensor = Tensor.from(type, "{ {x:a, y:b, z:c}:2.0, {x:a, y:b, z:c2}:3.0 }");
assertTensorEncodingAndDecoding(type, "query(my_tensor)", "my_tensor", tensor);
@@ -64,7 +64,7 @@ public class RankFeaturesTestCase {
}
@Test
- public void requireThatMultipleTensorsAreBinaryEncoded() {
+ void requireThatMultipleTensorsAreBinaryEncoded() {
TensorType type = new TensorType.Builder().mapped("x").mapped("y").mapped("z").build();
Tensor tensor1 = Tensor.from(type, "{ {x:a, y:b, z:c}:2.0, {x:a, y:b, z:c2}:3.0 }");
Tensor tensor2 = Tensor.from(type, "{ {x:a, y:b, z:c}:5.0 }");
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
index 7a9080f46db..a6bc7460f2e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.query.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.Sorting;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Arne Bergene Fossaa
@@ -17,7 +17,7 @@ public class RankingTestCase {
/** Tests setting rank feature values */
@Test
- public void testRankFeatures() {
+ void testRankFeatures() {
// Check initializing from query
Query query = new Query("?query=test&ranking.features.query(name)=0.1&ranking.features.fieldMatch(foo)=0.2");
assertEquals(0.1, query.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
@@ -30,8 +30,8 @@ public class RankingTestCase {
assertEquals(0.2, query.getRanking().getFeatures().getDouble("fieldMatch(foo)").getAsDouble(), delta);
// Check programmatic setting + that the clone really has a separate object
- assertFalse(clone.getRanking().getFeatures() == query.getRanking().getFeatures());
- clone.properties().set("ranking.features.query(name)","0.3");
+ assertNotNull(query.getRanking().getFeatures());
+ clone.properties().set("ranking.features.query(name)", "0.3");
assertEquals(0.3, clone.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
assertEquals(0.1, query.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
@@ -47,7 +47,7 @@ public class RankingTestCase {
// This test is order dependent. Fix this!!
@Test
- public void test_setting_rank_feature_values() {
+ void test_setting_rank_feature_values() {
// Check initializing from query
Query query = new Query("?query=test&ranking.properties.foo=bar1&ranking.properties.foo2=bar2&ranking.properties.other=10");
assertEquals("bar1", query.getRanking().getProperties().get("foo").get(0));
@@ -57,13 +57,13 @@ public class RankingTestCase {
// Test cloning
Query clone = query.clone();
- assertFalse(clone.getRanking().getProperties() == query.getRanking().getProperties());
+ assertNotNull(query.getRanking().getProperties());
assertEquals("bar1", clone.getRanking().getProperties().get("foo").get(0));
assertEquals("bar2", clone.getRanking().getProperties().get("foo2").get(0));
assertEquals("10", clone.getRanking().getProperties().get("other").get(0));
// Check programmatic setting mean addition
- clone.properties().set("ranking.properties.other","12");
+ clone.properties().set("ranking.properties.other", "12");
assertEquals("[10, 12]", clone.getRanking().getProperties().get("other").toString());
assertEquals("[10]", query.getRanking().getProperties().get("other").toString());
@@ -74,14 +74,14 @@ public class RankingTestCase {
/** Test setting sorting to null does not cause an exception. */
@Test
- public void testResetSorting() {
+ void testResetSorting() {
Query q = new Query();
- q.getRanking().setSorting((Sorting)null);
- q.getRanking().setSorting((String)null);
+ q.getRanking().setSorting((Sorting) null);
+ q.getRanking().setSorting((String) null);
}
@Test
- public void testStructuredRankProperty() {
+ void testStructuredRankProperty() {
Query query = new Query("?query=abc&rankproperty.distanceToPath(gps_position).path=(0,0,10,0,10,5,20,5)");
assertEquals("(0,0,10,0,10,5,20,5)", query.getRanking().getProperties().get("distanceToPath(gps_position).path").get(0));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java b/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
index b351bfb927a..07beabe14f3 100644
--- a/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
@@ -19,13 +19,11 @@ import com.yahoo.search.query.textserialize.item.ItemContext;
import com.yahoo.search.query.textserialize.item.ItemFormHandler;
import com.yahoo.search.query.textserialize.parser.ParseException;
import com.yahoo.search.query.textserialize.parser.Parser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.StringReader;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -40,12 +38,12 @@ public class ParseItemTestCase {
}
@Test
- public void parse_and() throws ParseException {
+ void parse_and() throws ParseException {
assertTrue(parse("(AND)") instanceof AndItem);
}
@Test
- public void parse_and_with_children() throws ParseException {
+ void parse_and_with_children() throws ParseException {
AndItem andItem = (AndItem) parse("(AND (WORD 'first') (WORD 'second'))");
assertEquals(2, andItem.getItemCount());
@@ -53,116 +51,120 @@ public class ParseItemTestCase {
}
@Test
- public void parse_or() throws ParseException {
+ void parse_or() throws ParseException {
assertTrue(parse("(OR)") instanceof OrItem);
}
@Test
- public void parse_and_not_rest() throws ParseException {
+ void parse_and_not_rest() throws ParseException {
assertTrue(parse("(AND-NOT-REST)") instanceof NotItem);
}
@Test
- public void parse_and_not_rest_with_children() throws ParseException {
+ void parse_and_not_rest_with_children() throws ParseException {
NotItem notItem = (NotItem) parse("(AND-NOT-REST (WORD 'positive') (WORD 'negative'))");
assertEquals("positive", getWord(notItem.getPositiveItem()));
assertEquals("negative", getWord(notItem.getItem(1)));
}
@Test
- public void parse_and_not_rest_with_only_negated_children() throws ParseException {
+ void parse_and_not_rest_with_only_negated_children() throws ParseException {
NotItem notItem = (NotItem) parse("(AND-NOT-REST null (WORD 'negated-item'))");
assertTrue(notItem.getPositiveItem() instanceof TrueItem);
assertTrue(notItem.getItem(1) instanceof WordItem);
}
@Test
- public void parse_rank() throws ParseException {
+ void parse_rank() throws ParseException {
assertTrue(parse("(RANK (WORD 'first'))") instanceof RankItem);
}
@Test
- public void parse_word() throws ParseException {
+ void parse_word() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD 'text')");
assertEquals("text", wordItem.getWord());
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_when_word_given_multiple_strings() throws ParseException {
- parse("(WORD 'one' 'invalid')");
+ @Test
+ void fail_when_word_given_multiple_strings() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ parse("(WORD 'one' 'invalid')");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_when_word_given_no_string() throws ParseException {
- parse("(WORD)");
+ @Test
+ void fail_when_word_given_no_string() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ parse("(WORD)");
+ });
}
@Test
- public void parse_int() throws ParseException {
+ void parse_int() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;]')");
assertEquals("[42;]", intItem.getNumber());
}
@Test
- public void parse_range() throws ParseException {
+ void parse_range() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;73]')");
assertEquals("[42;73]", intItem.getNumber());
}
@Test
- public void parse_range_withlimit() throws ParseException {
+ void parse_range_withlimit() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;73;32]')");
assertEquals("[42;73;32]", intItem.getNumber());
}
@Test
- public void parse_prefix() throws ParseException {
+ void parse_prefix() throws ParseException {
PrefixItem prefixItem = (PrefixItem) parse("(PREFIX 'word')");
assertEquals("word", prefixItem.getWord());
}
@Test
- public void parse_subString() throws ParseException {
+ void parse_subString() throws ParseException {
SubstringItem subStringItem = (SubstringItem) parse("(SUBSTRING 'word')");
assertEquals("word", subStringItem.getWord());
}
@Test
- public void parse_exactString() throws ParseException {
+ void parse_exactString() throws ParseException {
ExactStringItem subStringItem = (ExactStringItem) parse("(EXACT 'word')");
assertEquals("word", subStringItem.getWord());
}
@Test
- public void parse_suffix() throws ParseException {
+ void parse_suffix() throws ParseException {
SuffixItem suffixItem = (SuffixItem) parse("(SUFFIX 'word')");
assertEquals("word", suffixItem.getWord());
}
@Test
- public void parse_phrase() throws ParseException {
+ void parse_phrase() throws ParseException {
PhraseItem phraseItem = (PhraseItem) parse("(PHRASE (WORD 'word'))");
assertTrue(phraseItem.getItem(0) instanceof WordItem);
}
@Test
- public void parse_near() throws ParseException {
+ void parse_near() throws ParseException {
assertTrue(parse("(NEAR)") instanceof NearItem);
}
@Test
- public void parse_onear() throws ParseException {
+ void parse_onear() throws ParseException {
assertTrue(parse("(ONEAR)") instanceof ONearItem);
}
@Test
- public void parse_near_with_distance() throws ParseException {
+ void parse_near_with_distance() throws ParseException {
NearItem nearItem = (NearItem) parse("(NEAR {'distance' 42} (WORD 'first'))");
assertEquals(42, nearItem.getDistance());
}
@Test
- public void parse_items_with_connectivity() throws ParseException {
+ void parse_items_with_connectivity() throws ParseException {
AndItem andItem = (AndItem) parse("(AND (WORD {'id' '1'} 'first') (WORD {'connectivity' ['1' 23.5]} 'second'))");
WordItem secondItem = (WordItem) andItem.getItem(1);
@@ -171,13 +173,13 @@ public class ParseItemTestCase {
}
@Test
- public void parse_word_with_index() throws ParseException {
+ void parse_word_with_index() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD {'index' 'someIndex'} 'text')");
assertEquals("someIndex", wordItem.getIndexName());
}
@Test
- public void parse_unicode_word() throws ParseException {
+ void parse_unicode_word() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD 'trăm')");
assertEquals("trăm", wordItem.getWord());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java b/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
index 133382cbe91..65458cfb8ee 100644
--- a/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
@@ -11,12 +11,12 @@ import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.query.textserialize.parser.ParseException;
import com.yahoo.search.query.textserialize.serializer.QueryTreeSerializer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.search.query.textserialize.item.test.ParseItemTestCase.parse;
import static com.yahoo.search.query.textserialize.item.test.ParseItemTestCase.getWord;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue;
public class SerializeItemTestCase {
@Test
- public void serialize_word_item() {
+ void serialize_word_item() {
WordItem item = new WordItem("test that \" and \\ works");
item.setIndexName("index\"Name");
@@ -34,7 +34,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_and_item() {
+ void serialize_and_item() {
AndItem andItem = new AndItem();
andItem.addItem(new WordItem("first"));
andItem.addItem(new WordItem("second"));
@@ -46,12 +46,12 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_or_item() {
+ void serialize_or_item() {
assertTrue(serializeThenParse(new OrItem()) instanceof OrItem);
}
@Test
- public void serialize_not_item() {
+ void serialize_not_item() {
NotItem notItem = new NotItem();
{
notItem.addItem(new WordItem("first"));
@@ -62,7 +62,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_near_item() {
+ void serialize_near_item() {
int distance = 23;
NearItem nearItem = new NearItem(distance);
{
@@ -77,8 +77,8 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_phrase_item() throws ParseException {
- PhraseItem phraseItem = new PhraseItem(new String[] {"first", "second"});
+ void serialize_phrase_item() throws ParseException {
+ PhraseItem phraseItem = new PhraseItem(new String[]{"first", "second"});
phraseItem.setIndexName("indexName");
PhraseItem deSerialized = serializeThenParse(phraseItem);
@@ -88,7 +88,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_equiv_item() {
+ void serialize_equiv_item() {
EquivItem equivItem = new EquivItem();
equivItem.addItem(new WordItem("first"));
@@ -97,7 +97,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_connectivity() {
+ void serialize_connectivity() {
OrItem orItem = new OrItem();
{
WordItem first = new WordItem("first");
@@ -117,7 +117,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_significance() {
+ void serialize_significance() {
EquivItem equivItem = new EquivItem();
equivItem.setSignificance(24.2);
@@ -126,7 +126,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_unique_id() {
+ void serialize_unique_id() {
EquivItem equivItem = new EquivItem();
equivItem.setUniqueID(42);
@@ -135,7 +135,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_weight() {
+ void serialize_weight() {
EquivItem equivItem = new EquivItem();
equivItem.setWeight(42);
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
index 66fdbdcb267..9889c479b84 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.querytransform;
import com.yahoo.prelude.query.PredicateQueryItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author magnarn
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class BooleanAttributeParserTest {
@Test
- public void requireThatParseHandlesAllFormats() {
+ void requireThatParseHandlesAllFormats() {
assertParse(null, 0);
assertParse("{}", 0);
assertParse("{foo:bar}", 1);
@@ -37,7 +37,7 @@ public class BooleanAttributeParserTest {
}
@Test
- public void requireThatIllegalStringsFail() {
+ void requireThatIllegalStringsFail() {
assertException("{foo:[bar:[baz]}");
assertException("{foo:[bar:baz}");
assertException("{foo:bar:[0,1,2}");
@@ -60,7 +60,7 @@ public class BooleanAttributeParserTest {
}
@Test
- public void requireThatTermsCanHaveBitmaps() {
+ void requireThatTermsCanHaveBitmaps() {
PredicateQueryItem q = assertParse("{foo:bar:0x1}", 1);
PredicateQueryItem.Entry[] features = new PredicateQueryItem.Entry[q.getFeatures().size()];
q.getFeatures().toArray(features);
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
index 599b0ca4443..247c96f0676 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test BooleanSearcher
@@ -27,13 +27,13 @@ public class BooleanSearcherTestCase {
Execution.Context.createContextStub());
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
exec = buildExec();
}
@Test
- public void requireThatAttributeMapToSingleFeature() {
+ void requireThatAttributeMapToSingleFeature() {
PredicateQueryItem item = buildPredicateQueryItem("{gender:female}", null);
assertEquals(1, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
@@ -43,7 +43,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatAttributeListMapToMultipleFeatures() {
+ void requireThatAttributeListMapToMultipleFeatures() {
PredicateQueryItem item = buildPredicateQueryItem("{gender:[female,male]}", null);
assertEquals(2, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
@@ -51,7 +51,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatRangeAttributesMapToRangeTerm() {
+ void requireThatRangeAttributesMapToRangeTerm() {
PredicateQueryItem item = buildPredicateQueryItem(null, "{age:25}");
assertEquals(0, item.getFeatures().size());
assertEquals(1, item.getRangeFeatures().size());
@@ -63,17 +63,17 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatQueryWithoutBooleanPropertiesIsUnchanged() {
+ void requireThatQueryWithoutBooleanPropertiesIsUnchanged() {
Query q = new Query("");
q.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(q);
- WordItem root = (WordItem)r.getQuery().getModel().getQueryTree().getRoot();
+ WordItem root = (WordItem) r.getQuery().getModel().getQueryTree().getRoot();
assertEquals("foo", root.getWord());
}
@Test
- public void requireThatBooleanSearcherCanBuildPredicateQueryItem() {
+ void requireThatBooleanSearcherCanBuildPredicateQueryItem() {
PredicateQueryItem root = buildPredicateQueryItem("{gender:female}", "{age:23:[2, 3, 5]}");
Collection<PredicateQueryItem.Entry> features = root.getFeatures();
@@ -92,7 +92,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatKeysAndValuesCanContainSpaces() {
+ void requireThatKeysAndValuesCanContainSpaces() {
PredicateQueryItem item = buildPredicateQueryItem("{'My Key':'My Value'}", null);
assertEquals(1, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
index 025c3ff7a32..3a8442bc12d 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
@@ -2,19 +2,16 @@
package com.yahoo.search.querytransform;
-import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.yahoo.prelude.IndexModel;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.prelude.query.SameElementItem;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.Index;
import com.yahoo.prelude.IndexFacts;
@@ -69,7 +66,7 @@ public class LowercasingTestCase {
}
@Test
- public void simple() {
+ void simple() {
Query q = new Query();
AndItem root = new AndItem();
WordItem tmp;
@@ -92,7 +89,7 @@ public class LowercasingTestCase {
}
@Test
- public void slightlyMoreComplexTree() {
+ void slightlyMoreComplexTree() {
Query q = new Query();
AndItem a0 = new AndItem();
OrItem o0 = new OrItem();
@@ -148,7 +145,7 @@ public class LowercasingTestCase {
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
Query q = new Query();
AndItem root = new AndItem();
WeightedSetItem tmp;
@@ -170,11 +167,11 @@ public class LowercasingTestCase {
}
@Test
- public void testDisableLowercasingWeightedSet() {
+ void testDisableLowercasingWeightedSet() {
Execution execution = new Execution(new Chain<Searcher>(
- new VespaLowercasingSearcher(new LowercasingConfig(
- new LowercasingConfig.Builder()
- .transform_weighted_sets(false)))),
+ new VespaLowercasingSearcher(new LowercasingConfig(
+ new LowercasingConfig.Builder()
+ .transform_weighted_sets(false)))),
Execution.Context.createContextStub(createIndexFacts()));
Query q = new Query();
@@ -198,7 +195,7 @@ public class LowercasingTestCase {
}
@Test
- public void testLowercasingWordAlternatives() {
+ void testLowercasingWordAlternatives() {
Execution execution = new Execution(new Chain<Searcher>(new VespaLowercasingSearcher(new LowercasingConfig(
new LowercasingConfig.Builder().transform_weighted_sets(false)))), Execution.Context.createContextStub(createIndexFacts()));
@@ -221,7 +218,7 @@ public class LowercasingTestCase {
}
@Test
- public void testLowercasingSameElement() {
+ void testLowercasingSameElement() {
Query q = new Query();
SameElementItem root = new SameElementItem(SARR);
root.addItem(new WordItem("ABC", BAMSE, true));
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
index d2010ec852e..438f36b32a6 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
@@ -19,17 +19,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.ListIterator;
import static com.yahoo.container.protect.Error.INVALID_QUERY_PARAMETER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Testing of WandSearcher.
@@ -88,17 +85,17 @@ public class WandSearcherTestCase {
assertEquals(expWeight, wordItem.getWeight());
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
exec = buildExec();
}
@Test
- public void requireThatVespaWandCanBeSpecified() {
+ void requireThatVespaWandCanBeSpecified() {
Query q = buildDefaultQuery();
Result r = exec.search(q);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(100, root.getN());
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
@@ -109,21 +106,21 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatVespaWandHeapSizeCanBeSpecified() {
+ void requireThatVespaWandHeapSizeCanBeSpecified() {
Query q = buildDefaultQuery(VESPA_FIELD, "50");
Result r = exec.search(q);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(50, root.getN());
}
@Test
- public void requireThatWandCanBeSpecifiedTogetherWithNonAndQueryRoot() {
+ void requireThatWandCanBeSpecifiedTogetherWithNonAndQueryRoot() {
Query q = buildDefaultQuery();
q.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(q);
- AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
+ AndItem root = (AndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(2, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
@@ -132,7 +129,7 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatWandCanBeSpecifiedTogetherWithAndQueryRoot() {
+ void requireThatWandCanBeSpecifiedTogetherWithAndQueryRoot() {
Query q = buildDefaultQuery();
{
AndItem root = new AndItem();
@@ -142,7 +139,7 @@ public class WandSearcherTestCase {
}
Result r = exec.search(q);
- AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
+ AndItem root = (AndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
@@ -153,42 +150,42 @@ public class WandSearcherTestCase {
@Test
- public void requireThatNothingIsAddedWithoutWandPropertiesSet() {
+ void requireThatNothingIsAddedWithoutWandPropertiesSet() {
Query foo = new Query("");
foo.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(foo);
- WordItem root = (WordItem)TestUtils.getQueryTreeRoot(r);
+ WordItem root = (WordItem) TestUtils.getQueryTreeRoot(r);
assertEquals("foo", root.getWord());
}
@Test
- public void requireThatErrorIsReturnedOnInvalidTokenList() {
+ void requireThatErrorIsReturnedOnInvalidTokenList() {
Query q = buildQuery(VESPA_FIELD, "{a1,b:1}", null, null, null, null);
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
- assertEquals("'{a1,b:1}' is not a legal sparse vector string: Expected ':' starting at position 3 but was ','",msg.getDetailedMessage());
+ assertEquals("'{a1,b:1}' is not a legal sparse vector string: Expected ':' starting at position 3 but was ','", msg.getDetailedMessage());
}
@Test
- public void requireThatErrorIsReturnedOnUnknownField() {
+ void requireThatErrorIsReturnedOnUnknownField() {
Query q = buildDefaultQuery("unknown", "50");
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
- assertEquals("Field 'unknown' was not found in index facts for search definitions [test]",msg.getDetailedMessage());
+ assertEquals("Field 'unknown' was not found in index facts for search definitions [test]", msg.getDetailedMessage());
}
@Test
- public void requireThatVespaOrCanBeSpecified() {
+ void requireThatVespaOrCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "or", null, null);
Result r = exec.search(q);
- OrItem root = (OrItem)TestUtils.getQueryTreeRoot(r);
+ OrItem root = (OrItem) TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertWordItem("a", VESPA_FIELD, 1, itr.next());
@@ -205,11 +202,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatDefaultParallelWandCanBeSpecified() {
+ void requireThatDefaultParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "parallel", null, null);
Result r = exec.search(q);
- WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
+ WandItem root = (WandItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(100, root.getTargetNumHits());
assertEquals(0.0, root.getScoreThreshold(), delta);
@@ -218,11 +215,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatParallelWandCanBeSpecified() {
+ void requireThatParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", "50", "parallel", "70.5", "2.3");
Result r = exec.search(q);
- WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
+ WandItem root = (WandItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(50, root.getTargetNumHits());
assertEquals(70.5, root.getScoreThreshold(), delta);
@@ -231,11 +228,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatDotProductCanBeSpecified() {
+ void requireThatDotProductCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "dotProduct", null, null);
Result r = exec.search(q);
- DotProductItem root = (DotProductItem)TestUtils.getQueryTreeRoot(r);
+ DotProductItem root = (DotProductItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertWeightedSetItem(root);
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
index 54f6bcd4c23..97e37c2f40c 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
@@ -2,21 +2,30 @@
package com.yahoo.search.querytransform;
import com.yahoo.component.chain.Chain;
-import com.yahoo.prelude.query.*;
-import com.yahoo.processing.request.CompoundName;
+import com.yahoo.prelude.query.AndItem;
+import com.yahoo.prelude.query.CompositeItem;
+import com.yahoo.prelude.query.IntItem;
+import com.yahoo.prelude.query.Item;
+import com.yahoo.prelude.query.NotItem;
+import com.yahoo.prelude.query.OrItem;
+import com.yahoo.prelude.query.WeakAndItem;
+import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.stream.IntStream;
-import static org.junit.Assert.*;
+import static com.yahoo.search.querytransform.WeakAndReplacementSearcher.WEAKAND_REPLACE;
+import static com.yahoo.search.querytransform.WeakAndReplacementSearcher.WAND_HITS;
-public class WeakAndReplacementSearcherTestCase {
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
- private static final CompoundName WEAKAND_REPLACE = new CompoundName("weakAnd.replace");
+public class WeakAndReplacementSearcherTestCase {
private static final int N = 99;
@@ -27,7 +36,7 @@ public class WeakAndReplacementSearcherTestCase {
private Query buildDefaultQuery(boolean searcherEnabled) {
Query query = new Query();
- query.properties().set("wand.hits", N);
+ query.properties().set(WAND_HITS, N);
query.properties().set(WEAKAND_REPLACE, searcherEnabled);
OrItem root = new OrItem();
root.addItem(new WordItem("text"));
@@ -42,20 +51,18 @@ public class WeakAndReplacementSearcherTestCase {
}
-
-
@Test
- public void requireOrItemsToBeReplaced() {
+ void requireOrItemsToBeReplaced() {
Query query = buildDefaultQuery(true);
Result result = buildExec().search(query);
Item root = TestUtils.getQueryTreeRoot(result);
assertFalse(orItemsExist(root));
assertTrue(root instanceof WeakAndItem);
- assertEquals(N, ((WeakAndItem)root).getN());
+ assertEquals(N, ((WeakAndItem) root).getN());
}
@Test
- public void requireQueryPropertyToWork() {
+ void requireQueryPropertyToWork() {
Query query = buildDefaultQuery(false);
Item preRoot = query.getModel().getQueryTree().getRoot();
Result result = buildExec().search(query);
@@ -65,7 +72,7 @@ public class WeakAndReplacementSearcherTestCase {
}
@Test
- public void requireDoNothingOnNoOrItems() {
+ void requireDoNothingOnNoOrItems() {
Query query = new Query();
query.properties().set(WEAKAND_REPLACE, true);
AndItem andItem = new AndItem();
@@ -78,7 +85,7 @@ public class WeakAndReplacementSearcherTestCase {
}
@Test
- public void requireChildrenAreTheSame() {
+ void requireChildrenAreTheSame() {
Query query = new Query();
query.properties().set(WEAKAND_REPLACE, true);
OrItem preRoot = new OrItem();
@@ -87,7 +94,7 @@ public class WeakAndReplacementSearcherTestCase {
query.getModel().getQueryTree().setRoot(preRoot);
Result result = buildExec().search(query);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(result);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(result);
assertEquals(preRoot.getItem(0), root.getItem(0));
assertEquals(preRoot.getItem(1), root.getItem(1));
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
index 460ae1f641c..8dccf7d0f38 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
@@ -33,12 +33,10 @@ import com.yahoo.search.querytransform.NGramSearcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.search.searchchain.Execution.Context.createContextStub;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -103,7 +101,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testMixedDocTypes() {
+ void testMixedDocTypes() {
{
Query q = new Query("?query=abc&restrict=song");
createMixedSetupExecution().search(q);
@@ -127,7 +125,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testMixedClusters() {
+ void testMixedClusters() {
{
Query q = new Query("?query=abc&search=songOnly");
createMixedSetupExecution().search(q);
@@ -151,42 +149,42 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRewritingMixedQuery() {
+ void testNGramRewritingMixedQuery() {
Query q = new Query("?query=foo+gram3:engul+test:bar");
createExecution().search(q);
assertEquals("WEAKAND(100) foo (AND gram3:eng gram3:ngu gram3:gul) test:bar", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingNGramOnly() {
+ void testNGramRewritingNGramOnly() {
Query q = new Query("?query=gram3:engul");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewriting2NGramsOnly() {
+ void testNGramRewriting2NGramsOnly() {
Query q = new Query("?query=gram3:engul+gram2:123");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul) (AND gram2:12 gram2:23)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingShortOnly() {
+ void testNGramRewritingShortOnly() {
Query q = new Query("?query=gram3:en");
createExecution().search(q);
assertEquals("WEAKAND(100) gram3:en", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingShortInMixes() {
+ void testNGramRewritingShortInMixes() {
Query q = new Query("?query=test:a+gram3:en");
createExecution().search(q);
assertEquals("WEAKAND(100) test:a gram3:en", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingPhrase() {
+ void testNGramRewritingPhrase() {
Query q = new Query("?query=gram3:%22engul+a+holi%22");
createExecution().search(q);
assertEquals("WEAKAND(100) gram3:\"eng ngu gul a hol oli\"", q.getModel().getQueryTree().toString());
@@ -197,19 +195,19 @@ public class NGramSearcherTestCase {
* so the ngram rewriter cannot know to keep the grams as a phrase in this case.
*/
@Test
- public void testNGramRewritingPhraseSingleTerm() {
+ void testNGramRewritingPhraseSingleTerm() {
Query q = new Query("?query=gram3:%22engul%22");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingAdditionalTermInfo() {
+ void testNGramRewritingAdditionalTermInfo() {
Query q = new Query("?query=gram3:engul!50+foo+gram2:123!150");
createExecution().search(q);
- WeakAndItem root = (WeakAndItem)q.getModel().getQueryTree().getRoot();
- AndItem gram3And = (AndItem)root.getItem(0);
- AndItem gram2And = (AndItem)root.getItem(2);
+ WeakAndItem root = (WeakAndItem) q.getModel().getQueryTree().getRoot();
+ AndItem gram3And = (AndItem) root.getItem(0);
+ AndItem gram2And = (AndItem) root.getItem(2);
assertExtraTermInfo(50, "engul", gram3And.getItem(0));
assertExtraTermInfo(50, "engul", gram3And.getItem(1));
@@ -227,21 +225,21 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRewritingExplicitDefault() {
+ void testNGramRewritingExplicitDefault() {
Query q = new Query("?query=default:engul");
createExecution().search(q);
- assertEquals("WEAKAND(100) (AND default:eng default:ngu default:gul)" ,q.getModel().getQueryTree().toString());
+ assertEquals("WEAKAND(100) (AND default:eng default:ngu default:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingImplicitDefault() {
+ void testNGramRewritingImplicitDefault() {
Query q = new Query("?query=engul");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND eng ngu gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testGramsWithSegmentation() {
+ void testGramsWithSegmentation() {
Searcher searcher = createSearcher();
assertGramsWithSegmentation(new Chain<>(searcher));
assertGramsWithSegmentation(new Chain<>(new CJKSearcher(), searcher));
@@ -259,7 +257,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationSingleSegment() {
+ void testGramsWithSegmentationSingleSegment() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationSingleSegment(new Chain<>(searcher));
assertGramsWithSegmentationSingleSegment(new Chain<>(new CJKSearcher(), searcher));
@@ -277,7 +275,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationSubstringSegmented() {
+ void testGramsWithSegmentationSubstringSegmented() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationSubstringSegmented(new Chain<>(searcher));
assertGramsWithSegmentationSubstringSegmented(new Chain<>(new CJKSearcher(), searcher));
@@ -296,7 +294,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationMixed() {
+ void testGramsWithSegmentationMixed() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationMixed(new Chain<>(searcher));
assertGramsWithSegmentationMixed(new Chain<>(new CJKSearcher(), searcher));
@@ -315,7 +313,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationMixedAndPhrases() {
+ void testGramsWithSegmentationMixedAndPhrases() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationMixedAndPhrases(new Chain<>(searcher));
assertGramsWithSegmentationMixedAndPhrases(new Chain<>(new CJKSearcher(), searcher));
@@ -334,19 +332,20 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRecombining() {
+ void testNGramRecombining() {
Query q = new Query("?query=ignored");
Result r = new Execution(new Chain<>(createSearcher(), new MockBackend1()), createContextStub(createIndexFacts())).search(q);
Hit h1 = r.hits().get("hit1");
assertEquals("Should be untouched,\u001feven if containing \u001f",
- h1.getField("test").toString());
+ h1.getField("test").toString());
assertTrue(h1.getField("test") instanceof String);
- assertEquals("Blue red Ed A",h1.getField("gram2").toString());
+ assertEquals("Blue red Ed A", h1.getField("gram2").toString());
assertTrue(h1.getField("gram2") instanceof XMLString);
- assertEquals("Separators on borders work","Blue red ed a\u001f",
- h1.getField("gram3").toString());
+ assertEquals("Blue red ed a\u001f",
+ h1.getField("gram3").toString(),
+ "Separators on borders work");
assertTrue(h1.getField("gram3") instanceof String);
Hit h2 = r.hits().get("hit2");
@@ -356,7 +355,7 @@ public class NGramSearcherTestCase {
Hit h3 = r.hits().get("hit3");
assertEquals("\u001ffin\u001f \u001fen\u001f \u001fa\u001f", h3.getField("gram2").toString());
assertEquals("#Logging in #Java is like that \"Judean P\u001fopul\u001far Front\" scene from \"Life of Brian\".",
- h3.getField("gram3").toString());
+ h3.getField("gram3").toString());
}
private Item parseQuery(String query, Query.Type type) {
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
index df6cd046b74..927a891a797 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
@@ -19,12 +19,12 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
import com.yahoo.search.querytransform.RangeQueryOptimizer;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Iterator;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -35,9 +35,9 @@ public class RangeQueryOptimizerTestCase {
private static IndexFacts indexFacts = createIndexFacts();
@Test
- public void testRangeOptimizing() {
+ void testRangeOptimizing() {
assertOptimized("s:<15", "s:<15");
- assertOptimized("AND a s:[1999;2002]","a AND s:[1999;2002]");
+ assertOptimized("AND a s:[1999;2002]", "a AND s:[1999;2002]");
assertOptimized("AND s:<10;15>", "s:<15 AND s:>10");
assertOptimized("AND s:give s:5 s:me", "s:give s:5 s:me");
assertOptimized("AND s:[;15> b:<10;]", "s:<15 AND b:>10");
@@ -59,7 +59,7 @@ public class RangeQueryOptimizerTestCase {
}
@Test
- public void testRangeOptimizingCarriesOverItemAttributesWhenNotOptimized() {
+ void testRangeOptimizingCarriesOverItemAttributesWhenNotOptimized() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -69,14 +69,14 @@ public class RangeQueryOptimizerTestCase {
intItem.setRanked(false);
root.addItem(intItem);
assertOptimized("Not optimized", "AND |s:<15;]!500", query);
- IntItem transformedIntItem = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem.getWeight());
+ IntItem transformedIntItem = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem.getWeight(), "Weight was carried over");
}
@Test
- public void testRangeOptimizingCarriesOverItemAttributesWhenOptimized() {
+ void testRangeOptimizingCarriesOverItemAttributesWhenOptimized() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -94,14 +94,14 @@ public class RangeQueryOptimizerTestCase {
root.addItem(intItem2);
assertOptimized("Optimized", "AND |s:<15;30>!500", query);
- IntItem transformedIntItem = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem.getWeight());
+ IntItem transformedIntItem = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem.getWeight(), "Weight was carried over");
}
@Test
- public void testNoRangeOptimizingWhenAttributesAreIncompatible() {
+ void testNoRangeOptimizingWhenAttributesAreIncompatible() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -120,19 +120,19 @@ public class RangeQueryOptimizerTestCase {
assertOptimized("Not optimized", "AND |s:<15;]!500 s:[;30>!500", query);
- IntItem transformedIntItem1 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem1.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem1.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem1.getWeight());
+ IntItem transformedIntItem1 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem1.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem1.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem1.getWeight(), "Weight was carried over");
- IntItem transformedIntItem2 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(1);
- assertFalse("Filter was carried over", transformedIntItem2.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem2.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem2.getWeight());
+ IntItem transformedIntItem2 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(1);
+ assertFalse(transformedIntItem2.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem2.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem2.getWeight(), "Weight was carried over");
}
@Test
- public void testDifferentCompatibleRangesPerFieldAreOptimizedSeparately() {
+ void testDifferentCompatibleRangesPerFieldAreOptimizedSeparately() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -155,21 +155,21 @@ public class RangeQueryOptimizerTestCase {
assertOptimized("Optimized", "AND s:<15;30> s:<100;150>", query);
- IntItem transformedIntItem1 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertFalse("Ranked was carried over", transformedIntItem1.isRanked());
+ IntItem transformedIntItem1 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertFalse(transformedIntItem1.isRanked(), "Ranked was carried over");
- IntItem transformedIntItem2 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(1);
- assertTrue("Ranked was carried over", transformedIntItem2.isRanked());
+ IntItem transformedIntItem2 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(1);
+ assertTrue(transformedIntItem2.isRanked(), "Ranked was carried over");
}
@Test
- public void assertOptmimizedYQLQuery() {
+ void assertOptmimizedYQLQuery() {
Query query = new Query("/?query=select%20%2A%20from%20sources%20%2A%20where%20%28range%28s%2C%20100000%2C%20100000%29%20OR%20range%28t%2C%20-20000000000L%2C%20-20000000000L%29%20OR%20range%28t%2C%2030%2C%2030%29%29%3B&type=yql");
assertOptimized("YQL usage of the IntItem API works", "OR s:100000 t:-20000000000 t:30", query);
}
@Test
- public void testTracing() {
+ void testTracing() {
Query notOptimized = new Query("/?tracelevel=2");
notOptimized.getModel().getQueryTree().setRoot(parseQuery("s:<15"));
assertOptimized("", "s:<15", notOptimized);
@@ -200,7 +200,7 @@ public class RangeQueryOptimizerTestCase {
private Query assertOptimized(String explanation, String expected, Query query) {
Chain<Searcher> chain = new Chain<>("test", new RangeQueryOptimizer());
new Execution(chain, Execution.Context.createContextStub(indexFacts)).search(query);
- assertEquals(explanation, expected, query.getModel().getQueryTree().getRoot().toString());
+ assertEquals(expected, query.getModel().getQueryTree().getRoot().toString(), explanation);
return query;
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
index ccdb612b9ba..3b9c2651bf6 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
@@ -13,9 +13,9 @@ import com.yahoo.search.grouping.GroupingQueryParser;
import com.yahoo.search.query.properties.DefaultProperties;
import com.yahoo.search.querytransform.SortingDegrader;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
public class SortingDegraderTestCase {
@Test
- public void testDegradingAscending() {
+ void testDegradingAscending() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -33,7 +33,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingDescending() {
+ void testDegradingDescending() {
Query query = new Query("?ranking.sorting=-a1%20-a2");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -42,7 +42,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultMaxHits() {
+ void testDegradingNonDefaultMaxHits() {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxHits=37");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -51,7 +51,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultMaxFilterCoverage() {
+ void testDegradingNonDefaultMaxFilterCoverage() {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxFilterCoverage=0.37");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -60,7 +60,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultIllegalMaxFilterCoverage() {
+ void testDegradingNonDefaultIllegalMaxFilterCoverage() {
try {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxFilterCoverage=37");
assertTrue(false);
@@ -75,7 +75,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testNoDegradingWhenGrouping() {
+ void testNoDegradingWhenGrouping() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2&select=all(group(a1)%20each(output(a1)))");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
@@ -83,28 +83,28 @@ public class SortingDegraderTestCase {
}
@Test
- public void testNoDegradingWhenNonFastSearchAttribute() {
+ void testNoDegradingWhenNonFastSearchAttribute() {
Query query = new Query("?ranking.sorting=%2bnonFastSearchAttribute%20-a2");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testNoDegradingWhenNonNumericalAttribute() {
+ void testNoDegradingWhenNonNumericalAttribute() {
Query query = new Query("?ranking.sorting=%2bstringAttribute%20-a2");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testNoDegradingWhenTurnedOff() {
+ void testNoDegradingWhenTurnedOff() {
Query query = new Query("?ranking.sorting=-a1%20-a2&sorting.degrading=false");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testAccessAllDegradingParametersInQuery() {
+ void testAccessAllDegradingParametersInQuery() {
Query query = new Query("?ranking.matchPhase.maxHits=555&ranking.matchPhase.attribute=foo&ranking.matchPhase.ascending=true");
execute(query);
@@ -118,7 +118,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingWithLargeMaxHits() {
+ void testDegradingWithLargeMaxHits() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2");
query.properties().set(DefaultProperties.MAX_HITS, 13 * 1000);
query.properties().set(DefaultProperties.MAX_OFFSET, 8 * 1000);
@@ -129,7 +129,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingWithoutPaginationSupport() {
+ void testDegradingWithoutPaginationSupport() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2&hits=7&offset=1");
query.properties().set(DefaultProperties.MAX_HITS, 13 * 1000);
query.properties().set(DefaultProperties.MAX_OFFSET, 8 * 1000);
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
index 7db29568d5b..c038b3c67c9 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -25,8 +25,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test adding hits to a hit group during rendering.
@@ -98,7 +98,7 @@ public class AsyncGroupPopulationTestCase {
}
@Test
- public final void test() throws InterruptedException, ExecutionException,
+ final void test() throws InterruptedException, ExecutionException,
IOException {
String rawExpected = "{"
+ " \"root\": {"
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
index 7ddc087feb7..9486eeb92de 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
@@ -56,13 +56,12 @@ import com.yahoo.tensor.serialization.TypedBinaryFormat;
import com.yahoo.text.Utf8;
import com.yahoo.yolean.Exceptions;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -78,9 +77,9 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Functional testing of {@link JsonRenderer}.
@@ -92,14 +91,11 @@ public class JsonRendererTestCase {
private static final ObjectMapper jsonMapper = new ObjectMapper();
- @Rule
- public Timeout globalTimeout = Timeout.seconds(300);
-
private static ThreadPoolExecutor executor;
private static JsonRenderer blueprint;
private JsonRenderer renderer;
- @BeforeClass
+ @BeforeAll
public static void createExecutorAndBlueprint() {
ThreadFactory threadFactory = ThreadFactoryFactory.getThreadFactory("test-rendering");
executor = new ThreadPoolExecutor(4, 4, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), threadFactory);
@@ -107,14 +103,14 @@ public class JsonRendererTestCase {
blueprint = new JsonRenderer(executor);
}
- @Before
+ @BeforeEach
public void createClone() {
// Use the shared renderer as a prototype object, as specified in the API contract
renderer = (JsonRenderer) blueprint.clone();
renderer.init();
}
- @After
+ @AfterEach
public void deconstructClone() {
if (renderer != null) {
renderer.deconstruct();
@@ -122,7 +118,7 @@ public class JsonRendererTestCase {
}
}
- @AfterClass
+ @AfterAll
public static void deconstructBlueprintAndExecutor() throws InterruptedException {
blueprint.deconstruct();
blueprint = null;
@@ -134,7 +130,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDocumentId() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDocumentId() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -163,30 +160,31 @@ public class JsonRendererTestCase {
}
@Test
- public void testTensorShortForm() throws ExecutionException, InterruptedException, IOException {
+ @Timeout(300)
+ void testTensorShortForm() throws ExecutionException, InterruptedException, IOException {
String expected = "{" +
"\"root\":{" +
- "\"id\":\"toplevel\"," +
- "\"relevance\":1.0," +
- "\"fields\":{" +
- "\"totalCount\":1" +
- "}," +
- "\"children\":[{" +
- "\"id\":\"tensors\"," +
- "\"relevance\":1.0," +
- "\"fields\":{" +
- "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
- "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
- "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
- "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}," +
- "\"summaryfeatures\":{" +
- "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
- "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
- "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
- "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}" +
- "}" +
- "}" +
- "}]" +
+ "\"id\":\"toplevel\"," +
+ "\"relevance\":1.0," +
+ "\"fields\":{" +
+ "\"totalCount\":1" +
+ "}," +
+ "\"children\":[{" +
+ "\"id\":\"tensors\"," +
+ "\"relevance\":1.0," +
+ "\"fields\":{" +
+ "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
+ "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
+ "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
+ "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}," +
+ "\"summaryfeatures\":{" +
+ "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
+ "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
+ "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
+ "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}" +
+ "}" +
+ "}" +
+ "}]" +
"}}\n";
Slime slime = new Slime();
@@ -222,12 +220,13 @@ public class JsonRendererTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'presentation.format.tensors' to 'unknown': Value must be 'long' or 'short', not 'unknown'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testDataTypes() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDataTypes() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -298,7 +297,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracing() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracing() throws IOException, InterruptedException, ExecutionException {
// which clearly shows a trace child is created once too often...
String expected = "{"
+ " \"root\": {"
@@ -353,7 +353,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfSlime() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfSlime() throws IOException, InterruptedException, ExecutionException {
// which clearly shows a trace child is created once too often...
String expected = "{"
+ " \"root\": {"
@@ -406,10 +407,10 @@ public class JsonRendererTestCase {
e2.search(subQuery);
Value.ArrayValue access = new Value.ArrayValue();
Slime slime = new Slime();
- slime.setObject().setString("colour","yellow");
+ slime.setObject().setString("colour", "yellow");
access.add(new SlimeAdapter(slime.get()));
slime = new Slime();
- slime.setObject().setString("colour","green");
+ slime.setObject().setString("colour", "green");
access.add(new SlimeAdapter(slime.get()));
subQuery.trace(access, 1);
q.trace("marker", 1);
@@ -418,7 +419,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testEmptyTracing() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testEmptyTracing() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -444,7 +446,8 @@ public class JsonRendererTestCase {
@SuppressWarnings({"unchecked"})
@Test
- public void testTracingWithEmptySubtree() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingWithEmptySubtree() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -495,17 +498,18 @@ public class JsonRendererTestCase {
}
@Test
- public void trace_is_not_included_if_tracelevel_0() throws IOException, ExecutionException, InterruptedException {
+ @Timeout(300)
+ void trace_is_not_included_if_tracelevel_0() throws IOException, ExecutionException, InterruptedException {
String expected =
"{" +
- " \"root\": {" +
- " \"id\": \"toplevel\"," +
- " \"relevance\": 1.0," +
- " \"fields\": {" +
- " \"totalCount\": 0" +
- " }" +
- " }" +
- "}";
+ " \"root\": {" +
+ " \"id\": \"toplevel\"," +
+ " \"relevance\": 1.0," +
+ " \"fields\": {" +
+ " \"totalCount\": 0" +
+ " }" +
+ " }" +
+ "}";
Query q = new Query("/?query=a&tracelevel=0");
Execution execution = new Execution(Execution.Context.createContextStub());
Result r = new Result(q);
@@ -516,7 +520,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNodesWithBothChildrenAndData() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNodesWithBothChildrenAndData() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -561,7 +566,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNodesWithBothChildrenAndDataAndEmptySubnode() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNodesWithBothChildrenAndDataAndEmptySubnode() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -602,7 +608,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNestedNodesWithDataAndSubnodes() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNestedNodesWithDataAndSubnodes() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -650,7 +657,8 @@ public class JsonRendererTestCase {
}
@Test
- public void test() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void test() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -716,7 +724,7 @@ public class JsonRendererTestCase {
Query q = new Query("/?query=a&tracelevel=5");
Execution execution = new Execution(Execution.Context.createContextStub());
Result r = new Result(q);
- r.setCoverage(new Coverage(500, 500,1,1));
+ r.setCoverage(new Coverage(500, 500, 1, 1));
FastHit h = new FastHit("http://localhost/", .95);
h.setField("$a", "Hello, world.");
@@ -737,7 +745,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testCoverage() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testCoverage() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"coverage\": {"
@@ -771,7 +780,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testMoreTypes() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testMoreTypes() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -795,8 +805,8 @@ public class JsonRendererTestCase {
+ "}";
Result r = newEmptyResult();
Hit h = new Hit("moredatatypestuff");
- h.setField("byte", (byte)8);
- h.setField("short", (short)16);
+ h.setField("byte", (byte) 8);
+ h.setField("short", (short) 16);
h.setField("bigInteger", new BigInteger("340282366920938463463374607431768211455"));
h.setField("bigDecimal", new BigDecimal("340282366920938463463374607431768211456.5"));
h.setField("nanNumber", NanNumber.NaN);
@@ -807,7 +817,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testNullField() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testNullField() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -836,7 +847,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testHitWithSource() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testHitWithSource() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -863,7 +875,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testErrorWithStackTrace() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testErrorWithStackTrace() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"errors\": ["
@@ -896,13 +909,15 @@ public class JsonRendererTestCase {
}
@Test
- public void testContentHeader() {
+ @Timeout(300)
+ void testContentHeader() {
assertEquals("utf-8", renderer.getEncoding());
assertEquals("application/json", renderer.getMimeType());
}
@Test
- public void testGrouping() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testGrouping() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -988,7 +1003,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testGroupingWithBucket() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testGroupingWithBucket() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1051,7 +1067,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testJsonObjects() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testJsonObjects() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1097,7 +1114,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testFieldValueInHit() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testFieldValueInHit() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1132,7 +1150,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testHiddenFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testHiddenFields() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1157,7 +1176,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDebugRendering() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDebugRendering() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1188,7 +1208,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTimingRendering() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testTimingRendering() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -1208,7 +1229,7 @@ public class JsonRendererTestCase {
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(
- new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -1223,7 +1244,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testJsonCallback() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testJsonCallback() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1244,7 +1266,7 @@ public class JsonRendererTestCase {
+ "}";
String jsonCallback = "some_function_name";
- Result r = newEmptyResult(new String[] {"query=a", "jsoncallback="+jsonCallback} );
+ Result r = newEmptyResult(new String[]{"query=a", "jsoncallback=" + jsonCallback});
Hit h = new Hit("jsonCallbackTest");
h.setField("documentid", new DocumentId("id:unittest:smoke::whee"));
r.hits().add(h);
@@ -1261,7 +1283,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testMapInField() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testMapInField() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1288,18 +1311,18 @@ public class JsonRendererTestCase {
Hit h = new Hit("MapInField");
Value.ArrayValue atop = new Value.ArrayValue();
atop.add(new Value.ObjectValue()
- .put("key", new Value.StringValue("foo"))
- .put("value", new Value.StringValue("string foo")))
- .add(new Value.ObjectValue()
- .put("key", new Value.StringValue("bar"))
- .put("value", new Value.ArrayValue()
- .add(new Value.StringValue("array bar elem 1"))
- .add(new Value.StringValue("array bar elem 2"))))
- .add(new Value.ObjectValue()
- .put("key", new Value.StringValue("baz"))
- .put("value", new Value.ObjectValue()
- .put("f1", new Value.StringValue("object baz field 1"))
- .put("f2", new Value.StringValue("object baz field 2"))));
+ .put("key", new Value.StringValue("foo"))
+ .put("value", new Value.StringValue("string foo")))
+ .add(new Value.ObjectValue()
+ .put("key", new Value.StringValue("bar"))
+ .put("value", new Value.ArrayValue()
+ .add(new Value.StringValue("array bar elem 1"))
+ .add(new Value.StringValue("array bar elem 2"))))
+ .add(new Value.ObjectValue()
+ .put("key", new Value.StringValue("baz"))
+ .put("value", new Value.ObjectValue()
+ .put("f1", new Value.StringValue("object baz field 1"))
+ .put("f2", new Value.StringValue("object baz field 2"))));
h.setField("structured", atop);
r.hits().add(h);
r.setTotalHitCount(1L);
@@ -1314,21 +1337,22 @@ public class JsonRendererTestCase {
}
@Test
- public void testMapDeepInFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testMapDeepInFields() throws IOException, InterruptedException, ExecutionException {
Result r = new Result(new Query("/?renderer.json.jsonMaps=true"));
var expected = dataFromSimplified(
"{root: { id:'toplevel', relevance:1.0, fields: { totalCount: 1 }," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', { mykey1: 'myvalue1', mykey2: 'myvalue2' } ]," +
- " f2: { i1: 'v2', i2: { mykey3: 'myvalue3' }, i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
- " f5: { '10001': 'myvalue6', '10002': 'myvalue7' }," +
- " f6: { i4: 'v6', i5: { '-17': 'myvalue8', '-42': 'myvalue9' } }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', { mykey1: 'myvalue1', mykey2: 'myvalue2' } ]," +
+ " f2: { i1: 'v2', i2: { mykey3: 'myvalue3' }, i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
+ " f5: { '10001': 'myvalue6', '10002': 'myvalue7' }," +
+ " f6: { i4: 'v6', i5: { '-17': 'myvalue8', '-42': 'myvalue9' } }" +
+ " }" +
+ " } ]" +
+ "}}");
Hit h = new Hit("myHitName");
h.setField("f1", dataFromSimplified("[ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]"));
h.setField("f2", dataFromSimplified("{ i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }"));
@@ -1349,17 +1373,17 @@ public class JsonRendererTestCase {
r = new Result(new Query("/?renderer.json.jsonMaps=false"));
expected = dataFromSimplified(
"{root:{id:'toplevel',relevance:1.0,fields:{totalCount:1}," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]," +
- " f2: { i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
- " f5: [ { key: 10001, value: 'myvalue6' }, { key: 10002, value: 'myvalue7' } ]," +
- " f6: { i4: 'v6', i5: [ { key: -17, value: 'myvalue8' }, { key: -42, value: 'myvalue9' } ] }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]," +
+ " f2: { i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
+ " f5: [ { key: 10001, value: 'myvalue6' }, { key: 10002, value: 'myvalue7' } ]," +
+ " f6: { i4: 'v6', i5: [ { key: -17, value: 'myvalue8' }, { key: -42, value: 'myvalue9' } ] }" +
+ " }" +
+ " } ]" +
+ "}}");
r.hits().add(h);
r.setTotalHitCount(1L);
summary = render(r);
@@ -1367,19 +1391,20 @@ public class JsonRendererTestCase {
}
@Test
- public void testWsetInFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testWsetInFields() throws IOException, InterruptedException, ExecutionException {
Result r = new Result(new Query("/?renderer.json.jsonWsets=true"));
var expected = dataFromSimplified(
"{root: { id:'toplevel', relevance:1.0, fields: { totalCount: 1 }," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', { mykey1: 10, mykey2: 20 } ]," +
- " f2: { i1: 'v2', i2: { mykey3: 30 }, i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 40, mykey5: 50 }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', { mykey1: 10, mykey2: 20 } ]," +
+ " f2: { i1: 'v2', i2: { mykey3: 30 }, i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 40, mykey5: 50 }" +
+ " }" +
+ " } ]" +
+ "}}");
Hit h = new Hit("myHitName");
h.setField("f1", dataFromSimplified("[ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]"));
h.setField("f2", dataFromSimplified("{ i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }"));
@@ -1393,15 +1418,15 @@ public class JsonRendererTestCase {
r = new Result(new Query("/?renderer.json.jsonWsets=false"));
expected = dataFromSimplified(
"{root:{id:'toplevel',relevance:1.0,fields:{totalCount:1}," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]," +
- " f2: { i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: [ { item: 'mykey4', weight: 40 }, { item: 'mykey5', weight: 50 } ]" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]," +
+ " f2: { i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: [ { item: 'mykey4', weight: 40 }, { item: 'mykey5', weight: 50 } ]" +
+ " }" +
+ " } ]" +
+ "}}");
r.hits().add(h);
r.setTotalHitCount(1L);
summary = render(r);
@@ -1409,7 +1434,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testThatTheJsonValidatorCanCatchErrors() {
+ @Timeout(300)
+ void testThatTheJsonValidatorCanCatchErrors() {
String json = "{"
+ " \"root\": {"
+ " \"invalidvalue\": 1adsf,"
@@ -1422,7 +1448,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDynamicSummary() throws Exception {
+ @Timeout(300)
+ void testDynamicSummary() throws Exception {
String content = "\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E";
Result result = createResult("one", content, true);
@@ -1430,24 +1457,24 @@ public class JsonRendererTestCase {
String expected =
"{ " +
- " \"root\":{ " +
- " \"id\":\"toplevel\"," +
- " \"relevance\":1.0," +
- " \"fields\":{ " +
- " \"totalCount\":0" +
- " }," +
- " \"children\":[ " +
- " { " +
- " \"id\":\"http://abc.html/\"," +
- " \"relevance\":1.0," +
- " \"fields\":{ " +
- " \"sddocname\":\"one\"," +
- " \"dynteaser\":\"Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />\"" +
- " }" +
- " }" +
- " ]" +
- " }" +
- "}";
+ " \"root\":{ " +
+ " \"id\":\"toplevel\"," +
+ " \"relevance\":1.0," +
+ " \"fields\":{ " +
+ " \"totalCount\":0" +
+ " }," +
+ " \"children\":[ " +
+ " { " +
+ " \"id\":\"http://abc.html/\"," +
+ " \"relevance\":1.0," +
+ " \"fields\":{ " +
+ " \"sddocname\":\"one\"," +
+ " \"dynteaser\":\"Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />\"" +
+ " }" +
+ " }" +
+ " ]" +
+ " }" +
+ "}";
assertEqualJson(expected, summary);
}
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
index 2166000cf7a..c473c11005d 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
@@ -14,16 +14,16 @@ import com.yahoo.search.statistics.ElapsedTimeTestCase.CreativeTimeSource;
import com.yahoo.search.statistics.ElapsedTimeTestCase.UselessSearcher;
import com.yahoo.search.statistics.TimeTracker;
import com.yahoo.text.Utf8;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Check the legacy sync default renderer doesn't spontaneously combust.
@@ -34,28 +34,28 @@ public class SyncDefaultRendererTestCase {
SyncDefaultRenderer d;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
d = new SyncDefaultRenderer();
d.init();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
}
@Test
- public final void testGetEncoding() {
+ final void testGetEncoding() {
assertEquals("utf-8", d.getEncoding());
}
@Test
- public final void testGetMimeType() {
+ final void testGetMimeType() {
assertEquals("text/xml", d.getMimeType());
}
@Test
- public void testRenderWriterResult() throws InterruptedException, ExecutionException {
+ void testRenderWriterResult() throws InterruptedException, ExecutionException {
Query q = new Query("/?query=a&tracelevel=5");
q.getPresentation().setTiming(true);
Result r = new Result(q);
@@ -65,7 +65,7 @@ public class SyncDefaultRendererTestCase {
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(
- new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
index a8b38130333..50234e4022c 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
@@ -24,13 +24,13 @@ import com.yahoo.search.statistics.ElapsedTimeTestCase;
import com.yahoo.search.statistics.ElapsedTimeTestCase.CreativeTimeSource;
import com.yahoo.search.statistics.TimeTracker;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.CompletableFuture;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test the XML renderer
@@ -41,21 +41,21 @@ import static org.junit.Assert.assertTrue;
public class XMLRendererTestCase {
@Test
- public void testGetEncoding() {
+ void testGetEncoding() {
XmlRenderer renderer = new XmlRenderer();
renderer.init();
assertEquals("utf-8", renderer.getEncoding());
}
@Test
- public void testGetMimeType() {
+ void testGetMimeType() {
XmlRenderer renderer = new XmlRenderer();
renderer.init();
assertEquals("text/xml", renderer.getMimeType());
}
@Test
- public void testXmlRendering() throws Exception {
+ void testXmlRendering() throws Exception {
Query q = new Query("/?query=a");
Result result = new Result(q);
@@ -82,31 +82,31 @@ public class XMLRendererTestCase {
String expected =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\" coverage-docs=\"500\" coverage-nodes=\"1\" coverage-full=\"false\" coverage=\"0\" results-full=\"0\" results=\"1\">\n" +
- " <error code=\"18\">Internal server error.</error>\n" +
- " <errordetails>\n" +
- " <error error=\"Internal server error.\" code=\"18\">message</error>\n" +
- " </errordetails>\n" +
- " <group relevancy=\"1.0\">\n" +
- " <hit type=\"summary\" relevancy=\"0.9\">\n" +
- " <field name=\"relevancy\">0.9</field>\n" +
- " <field name=\"c\">d</field>\n" +
- " </hit>\n" +
- " </group>\n" +
- " <hit type=\"grouphit\" relevancy=\"1.0\">\n" +
- " <id>type grouphit</id>\n" +
- " </hit>\n" +
- " <hit type=\"summary\" relevancy=\"0.95\">\n" +
- " <field name=\"relevancy\">0.95</field>\n" +
- " <field name=\"b\">foo</field>\n" +
- " </hit>\n" +
- "</result>\n";
+ "<result total-hit-count=\"0\" coverage-docs=\"500\" coverage-nodes=\"1\" coverage-full=\"false\" coverage=\"0\" results-full=\"0\" results=\"1\">\n" +
+ " <error code=\"18\">Internal server error.</error>\n" +
+ " <errordetails>\n" +
+ " <error error=\"Internal server error.\" code=\"18\">message</error>\n" +
+ " </errordetails>\n" +
+ " <group relevancy=\"1.0\">\n" +
+ " <hit type=\"summary\" relevancy=\"0.9\">\n" +
+ " <field name=\"relevancy\">0.9</field>\n" +
+ " <field name=\"c\">d</field>\n" +
+ " </hit>\n" +
+ " </group>\n" +
+ " <hit type=\"grouphit\" relevancy=\"1.0\">\n" +
+ " <id>type grouphit</id>\n" +
+ " </hit>\n" +
+ " <hit type=\"summary\" relevancy=\"0.95\">\n" +
+ " <field name=\"relevancy\">0.95</field>\n" +
+ " <field name=\"b\">foo</field>\n" +
+ " </hit>\n" +
+ "</result>\n";
assertEquals(expected, summary);
}
@Test
- public void testXmlRenderingOfDynamicSummary() throws Exception {
+ void testXmlRenderingOfDynamicSummary() throws Exception {
String content = "\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E";
Result result = createResult("one", content, true);
@@ -114,18 +114,18 @@ public class XMLRendererTestCase {
String expected =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\">\n" +
- " <hit relevancy=\"1.0\">\n" +
- " <field name=\"relevancy\">1.0</field>\n" +
- " <field name=\"sddocname\">one</field>\n" +
- " <field name=\"dynteaser\">Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep /></field>\n" +
- " </hit>\n" +
- "</result>\n";
+ "<result total-hit-count=\"0\">\n" +
+ " <hit relevancy=\"1.0\">\n" +
+ " <field name=\"relevancy\">1.0</field>\n" +
+ " <field name=\"sddocname\">one</field>\n" +
+ " <field name=\"dynteaser\">Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep /></field>\n" +
+ " </hit>\n" +
+ "</result>\n";
assertEquals(expected, summary);
}
@Test
- public void testXmlRenderingWithTimeTracking() throws Exception {
+ void testXmlRenderingWithTimeTracking() throws Exception {
Query q = new Query("/?query=a&tracelevel=5");
q.getPresentation().setTiming(true);
@@ -133,9 +133,9 @@ public class XMLRendererTestCase {
result.setCoverage(new Coverage(500, 1));
TimeTracker t = new TimeTracker(new Chain<Searcher>(new NoopSearcher("first"),
- new NoopSearcher("second"),
- new NoopSearcher("third")));
- ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new NoopSearcher("second"),
+ new NoopSearcher("third")));
+ ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -148,7 +148,7 @@ public class XMLRendererTestCase {
String summary = render(result);
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<result total-hit-count=\"0\"",
- summary.substring(0, 67));
+ summary.substring(0, 67));
assertTrue(summary.contains("querytime="));
assertTrue(summary.contains("summaryfetchtime="));
assertTrue(summary.contains("searchtime="));
diff --git a/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java b/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
index 5c9af0c756e..42095e263dd 100644
--- a/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
@@ -1,13 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.Iterator;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* @author Steinar Knutsen
@@ -17,13 +16,13 @@ public class DefaultErrorHitTestCase {
private static final String SOURCE = "nalle";
DefaultErrorHit de;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
de = new DefaultErrorHit(SOURCE, ErrorMessage.createUnspecifiedError("DefaultErrorHitTestCase"));
}
@Test
- public void testSetSourceTakeTwo() {
+ void testSetSourceTakeTwo() {
assertEquals(SOURCE, de.getSource());
de.setSource(null);
assertNull(de.getSource());
@@ -36,19 +35,19 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("Error: Source 'nalle': 5: Unspecified error: DefaultErrorHitTestCase", de.toString());
}
@Test
- public void testSetMainError() {
+ void testSetMainError() {
ErrorMessage e = ErrorMessage.createBackendCommunicationError("abc");
assertNull(e.getSource());
de.addError(e);
assertEquals(SOURCE, e.getSource());
boolean caught = false;
try {
- new DefaultErrorHit(SOURCE, (ErrorMessage)null);
+ new DefaultErrorHit(SOURCE, (ErrorMessage) null);
} catch (NullPointerException ex) {
caught = true;
}
@@ -64,7 +63,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testAddError() {
+ void testAddError() {
ErrorMessage e = ErrorMessage.createBackendCommunicationError("ljkhlkjh");
assertNull(e.getSource());
de.addError(e);
@@ -79,7 +78,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testAddErrors() {
+ void testAddErrors() {
DefaultErrorHit other = new DefaultErrorHit("abc", ErrorMessage.createBadRequest("sdasd"));
de.addErrors(other);
int i = 0;
@@ -98,7 +97,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testHasOnlyErrorCode() {
+ void testHasOnlyErrorCode() {
assertTrue(de.hasOnlyErrorCode(com.yahoo.container.protect.Error.UNSPECIFIED.code));
assertFalse(de.hasOnlyErrorCode(com.yahoo.container.protect.Error.BACKEND_COMMUNICATION_ERROR.code));
diff --git a/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java b/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
index f7b9817437f..5d423eceb98 100644
--- a/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author bratseth
@@ -21,7 +21,7 @@ public class FeatureDataTestCase {
private static final double delta = 0.00000001;
@Test
- public void testFeatureData() {
+ void testFeatureData() {
Cursor features = new Slime().setObject();
features.setDouble("scalar1", 1.5);
features.setDouble("scalar2", 2.5);
@@ -32,11 +32,11 @@ public class FeatureDataTestCase {
FeatureData featureData = new FeatureData(new SlimeAdapter(features));
assertEquals("scalar1,scalar2,tensor1,tensor2",
- featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
+ featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
assertNull(featureData.getDouble("nosuch1"));
assertEquals(1.5, featureData.getDouble("scalar1"), delta);
assertEquals(2.5, featureData.getDouble("scalar2"), delta);
- assertEquals("Cached lookup", 2.5, featureData.getDouble("scalar2"), delta);
+ assertEquals(2.5, featureData.getDouble("scalar2"), delta, "Cached lookup");
assertNull(featureData.getDouble("nosuch2"));
assertNull(featureData.getDouble("nosuch2"));
@@ -45,17 +45,17 @@ public class FeatureDataTestCase {
assertEquals(Tensor.from(2.5), featureData.getTensor("scalar2"));
assertEquals(tensor1, featureData.getTensor("tensor1"));
assertEquals(tensor2, featureData.getTensor("tensor2"));
- assertEquals("Cached lookup", tensor2, featureData.getTensor("tensor2"));
+ assertEquals(tensor2, featureData.getTensor("tensor2"), "Cached lookup");
assertNull(featureData.getTensor("nosuch2"));
assertNull(featureData.getTensor("nosuch2"));
String expectedJson =
"{" +
- "\"scalar1\":1.5," +
- "\"scalar2\":2.5," +
- "\"tensor1\":{\"type\":\"tensor(x[3])\",\"cells\":[{\"address\":{\"x\":\"0\"},\"value\":1.5},{\"address\":{\"x\":\"1\"},\"value\":2.0},{\"address\":{\"x\":\"2\"},\"value\":2.5}]}," +
- "\"tensor2\":{\"type\":\"tensor()\",\"cells\":[{\"address\":{},\"value\":0.5}]}" +
- "}";
+ "\"scalar1\":1.5," +
+ "\"scalar2\":2.5," +
+ "\"tensor1\":{\"type\":\"tensor(x[3])\",\"cells\":[{\"address\":{\"x\":\"0\"},\"value\":1.5},{\"address\":{\"x\":\"1\"},\"value\":2.0},{\"address\":{\"x\":\"2\"},\"value\":2.5}]}," +
+ "\"tensor2\":{\"type\":\"tensor()\",\"cells\":[{\"address\":{},\"value\":0.5}]}" +
+ "}";
assertEquals(expectedJson, featureData.toJson());
}
diff --git a/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java b/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java
index c6e5c87efb2..0790b6754fe 100644
--- a/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java
@@ -1,9 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Integrity test for representation of undefined numeric field values.
@@ -14,27 +15,27 @@ public class NanNumberTestCase {
@Test
- public final void testIntValue() {
+ final void testIntValue() {
assertEquals(0, NanNumber.NaN.intValue());
}
@Test
- public final void testLongValue() {
+ final void testLongValue() {
assertEquals(0L, NanNumber.NaN.longValue());
}
@Test
- public final void testFloatValue() {
+ final void testFloatValue() {
assertTrue(Float.isNaN(NanNumber.NaN.floatValue()));
}
@Test
- public final void testDoubleValue() {
+ final void testDoubleValue() {
assertTrue(Double.isNaN(NanNumber.NaN.doubleValue()));
}
@Test
- public final void testToString() {
+ final void testToString() {
assertEquals("", NanNumber.NaN.toString());
}
diff --git a/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java b/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
index 96039beafa5..a112cb41a64 100644
--- a/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.search.result;
import com.yahoo.data.access.simple.Value;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Arne Juul
@@ -13,7 +13,7 @@ import org.junit.Test;
public class PositionsDataTestCase {
@Test
- public void testRenderingOfSinglePosition() {
+ void testRenderingOfSinglePosition() {
Value.ObjectValue pos = createPosition(-122057174, 37374821, "N37.374821;W122.057174");
PositionsData pd = new PositionsData(pos.inspect());
@@ -23,7 +23,7 @@ public class PositionsDataTestCase {
}
@Test
- public void testRenderingOfMultiplePositions() {
+ void testRenderingOfMultiplePositions() {
Value.ArrayValue arr = new Value.ArrayValue();
arr.add(createPosition(-122057174, 37374821, "N37.374821;W122.057174"));
arr.add(createPosition(3, -7, "S0.000007;E0.000003"));
@@ -31,9 +31,9 @@ public class PositionsDataTestCase {
PositionsData pd = new PositionsData(arr.inspect());
assertXml("<position x=\"-122057174\" y=\"37374821\" latlong=\"N37.374821;W122.057174\" />" +
- "<position x=\"3\" y=\"-7\" latlong=\"S0.000007;E0.000003\" />", pd);
+ "<position x=\"3\" y=\"-7\" latlong=\"S0.000007;E0.000003\" />", pd);
assertJson("[{\"x\":-122057174,\"y\":37374821,\"latlong\":\"N37.374821;W122.057174\"}," +
- "{\"x\":3,\"y\":-7,\"latlong\":\"S0.000007;E0.000003\"}]", pd);
+ "{\"x\":3,\"y\":-7,\"latlong\":\"S0.000007;E0.000003\"}]", pd);
}
private Value.ObjectValue createPosition(long x, long y, String latlong) {
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
index d95a8068570..c0b0a90b682 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.search.result.test;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.result.Coverage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Steinar Knutsen
@@ -15,14 +15,14 @@ import static org.junit.Assert.assertNull;
public class CoverageTestCase {
@Test
- public void testZeroCoverage() {
+ void testZeroCoverage() {
Coverage c = new Coverage(0L, 0, 0, 0);
assertEquals(0, c.getResultPercentage());
assertEquals(0, c.getResultSets());
}
@Test
- public void testActiveCoverage() {
+ void testActiveCoverage() {
Coverage c = new Coverage(6, 5);
assertEquals(5, c.getActive());
assertEquals(6, c.getDocs());
@@ -34,7 +34,7 @@ public class CoverageTestCase {
}
@Test
- public void testDefaultCoverage() {
+ void testDefaultCoverage() {
boolean create = true;
Result r1 = new Result(new Query());
@@ -46,18 +46,18 @@ public class CoverageTestCase {
}
@Test
- public void testDefaultSearchScenario() {
+ void testDefaultSearchScenario() {
boolean create = true;
Result federationSearcherResult = new Result(new Query());
Result singleSourceResult = new Result(new Query());
federationSearcherResult.mergeWith(singleSourceResult);
- assertNull(federationSearcherResult.getCoverage( !create));
+ assertNull(federationSearcherResult.getCoverage(!create));
assertEquals(0, federationSearcherResult.getCoverage(create).getResultSets());
}
@Test
- public void testRequestingCoverageSearchScenario() {
+ void testRequestingCoverageSearchScenario() {
boolean create = true;
Result federationSearcherResult = new Result(new Query());
@@ -68,7 +68,7 @@ public class CoverageTestCase {
}
@Test
- public void testCoverageConversion() {
+ void testCoverageConversion() {
Coverage c = new Coverage(6, 10);
c.setDegradedReason(7);
com.yahoo.container.logging.Coverage lc = c.toLoggingCoverage();
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
index 1147cd67460..21a10bf8325 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
@@ -7,12 +7,9 @@ import java.util.NoSuchElementException;
import com.yahoo.search.result.DeepHitIterator;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Ensure that the {@link DeepHitIterator} works as intended.
@@ -22,7 +19,7 @@ import static org.junit.Assert.fail;
public class DeepHitIteratorTestCase {
@Test
- public void testEmpty() {
+ void testEmpty() {
HitGroup hits = new HitGroup();
Iterator<Hit> it = hits.deepIterator();
assertFalse(it.hasNext());
@@ -35,7 +32,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testRemove() {
+ void testRemove() {
HitGroup hits = new HitGroup();
hits.add(new Hit("foo"));
hits.add(new Hit("bar"));
@@ -62,7 +59,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testShallow() {
+ void testShallow() {
HitGroup hits = new HitGroup();
hits.add(new Hit("foo"));
hits.add(new Hit("bar"));
@@ -79,7 +76,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testDeep() {
+ void testDeep() {
HitGroup grandParent = new HitGroup();
grandParent.add(new Hit("a"));
HitGroup parent = new HitGroup();
@@ -114,7 +111,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testFirstHitIsGroup() {
+ void testFirstHitIsGroup() {
HitGroup root = new HitGroup();
HitGroup group = new HitGroup();
group.add(new Hit("foo"));
@@ -130,7 +127,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testSecondHitIsGroup() {
+ void testSecondHitIsGroup() {
HitGroup root = new HitGroup();
root.add(new Hit("foo"));
HitGroup group = new HitGroup();
@@ -146,7 +143,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testOrder() {
+ void testOrder() {
HitGroup root = new HitGroup();
MyHitGroup group = new MyHitGroup();
group.add(new Hit("foo"));
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
index ea5c11cb055..8c833ca76f3 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
@@ -3,13 +3,11 @@ package com.yahoo.search.result.test;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -17,16 +15,16 @@ import static org.junit.Assert.assertTrue;
public class FillingTestCase {
@Test
- public void testFillingAPIConsistency() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistency() {
+ HitGroup group = new HitGroup();
group.add(new Hit("hit:1"));
group.add(new Hit("hit:2"));
assertTrue(group.isFilled("summary"));
}
@Test
- public void testFillingAPIConsistencyTwoPhase() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistencyTwoPhase() {
+ HitGroup group = new HitGroup();
group.add(createNonFilled("hit:1"));
group.add(createNonFilled("hit:2"));
assertFalse(group.isFilled("summary"));
@@ -36,8 +34,8 @@ public class FillingTestCase {
}
@Test
- public void testFillingAPIConsistencyThreePhase() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistencyThreePhase() {
+ HitGroup group = new HitGroup();
group.add(createNonFilled("hit:1"));
group.add(createNonFilled("hit:2"));
assertFalse(group.isFilled("summary"));
@@ -54,7 +52,7 @@ public class FillingTestCase {
}
@Test
- public void testPartiallyFilledWith2Hits() {
+ void testPartiallyFilledWith2Hits() {
Hit hit1 = new Hit("id1");
Hit hit2 = new Hit("id2");
@@ -69,7 +67,7 @@ public class FillingTestCase {
}
@Test
- public void testPartiallyFilledDiverse() {
+ void testPartiallyFilledDiverse() {
Hit hit1 = new Hit("id1");
Hit hit2 = new Hit("id2");
Hit hit3 = new Hit("id3");
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
index 8196cf4ac74..cc4e6193103 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
@@ -7,17 +7,13 @@ import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,21 +21,21 @@ import static org.junit.Assert.assertTrue;
public class HitGroupTestCase {
@Test
- public void testErrorsConsistencyUsingErrorOperations() {
+ void testErrorsConsistencyUsingErrorOperations() {
HitGroup hits = new HitGroup();
Query query = new Query();
query.errors().add(ErrorMessage.createIllegalQuery("test1"));
query.errors().add(ErrorMessage.createTimeout("test2"));
hits.setQuery(query);
-
+
hits.addError(ErrorMessage.createForbidden("test3"));
hits.addError(ErrorMessage.createUnspecifiedError("test4"));
-
+
assertEquals(4, hits.getErrorHit().errors().size());
assertEquals(0, query.errors().size());
assertEquals(Optional.of(hits.getErrorHit()), errorHitIn(hits.asList()));
-
+
DefaultErrorHit removedErrors = hits.removeErrorHit();
assertNotNull(removedErrors);
assertEquals(4, removedErrors.errors().size());
@@ -50,7 +46,7 @@ public class HitGroupTestCase {
}
@Test
- public void testErrorsConsistencyUsingHitOperations() {
+ void testErrorsConsistencyUsingHitOperations() {
HitGroup hits = new HitGroup();
Query query = new Query();
@@ -66,7 +62,7 @@ public class HitGroupTestCase {
assertEquals(0, query.errors().size());
assertEquals(Optional.of(hits.getErrorHit()), errorHitIn(hits.asList()));
- DefaultErrorHit removedErrors = (DefaultErrorHit)hits.remove(errors.getId());
+ DefaultErrorHit removedErrors = (DefaultErrorHit) hits.remove(errors.getId());
assertNotNull(removedErrors);
assertEquals(4, removedErrors.errors().size());
assertNull(hits.get(removedErrors.getId().toString()));
@@ -76,39 +72,39 @@ public class HitGroupTestCase {
}
@Test
- public void testRecursiveGet() {
+ void testRecursiveGet() {
// Level 1
- HitGroup g1=new HitGroup();
+ HitGroup g1 = new HitGroup();
g1.add(new Hit("1"));
// Level 2
- HitGroup g1_1=new HitGroup();
+ HitGroup g1_1 = new HitGroup();
g1_1.add(new Hit("1.1"));
g1.add(g1_1);
- HitGroup g1_2=new HitGroup();
+ HitGroup g1_2 = new HitGroup();
g1_2.add(new Hit("1.2"));
g1.add(g1_2);
// Level 3
- HitGroup g1_1_1=new HitGroup();
+ HitGroup g1_1_1 = new HitGroup();
g1_1_1.add(new Hit("1.1.1"));
g1_1.add(g1_1_1);
- HitGroup g1_1_2=new HitGroup();
+ HitGroup g1_1_2 = new HitGroup();
g1_1_2.add(new Hit("1.1.2"));
g1_1.add(g1_1_2);
- HitGroup g1_2_1=new HitGroup();
+ HitGroup g1_2_1 = new HitGroup();
g1_2_1.add(new Hit("1.2.1"));
g1_2.add(g1_2_1);
- HitGroup g1_2_2=new HitGroup();
+ HitGroup g1_2_2 = new HitGroup();
g1_2_2.add(new Hit("1.2.2"));
g1_2.add(g1_2_2);
// Level 4
- HitGroup g1_1_1_1=new HitGroup();
+ HitGroup g1_1_1_1 = new HitGroup();
g1_1_1_1.add(new Hit("1.1.1.1"));
g1_1_1.add(g1_1_1_1);
@@ -121,49 +117,49 @@ public class HitGroupTestCase {
assertNotNull(g1.get("1.2.2"));
assertNotNull(g1.get("1.1.1.1"));
- assertNotNull(g1.get("1",-1));
- assertNotNull(g1.get("1.1",-1));
- assertNotNull(g1.get("1.2",-1));
- assertNotNull(g1.get("1.1.1",-1));
- assertNotNull(g1.get("1.1.2",-1));
- assertNotNull(g1.get("1.2.1",-1));
- assertNotNull(g1.get("1.2.2",-1));
- assertNotNull(g1.get("1.1.1.1",-1));
-
- assertNotNull(g1.get("1",0));
- assertNull(g1.get("1.1",0));
- assertNull(g1.get("1.2",0));
- assertNull(g1.get("1.1.1",0));
- assertNull(g1.get("1.1.2",0));
- assertNull(g1.get("1.2.1",0));
- assertNull(g1.get("1.2.2",0));
- assertNull(g1.get("1.1.1.1",0));
-
- assertNotNull(g1.get("1",1));
- assertNotNull(g1.get("1.1",1));
- assertNotNull(g1.get("1.2",1));
- assertNull(g1.get("1.1.1",1));
- assertNull(g1.get("1.1.2",1));
- assertNull(g1.get("1.2.1",1));
- assertNull(g1.get("1.2.2",1));
- assertNull(g1.get("1.1.1.1",1));
-
- assertNotNull(g1.get("1",2));
- assertNotNull(g1.get("1.1",2));
- assertNotNull(g1.get("1.2",2));
- assertNotNull(g1.get("1.1.1",2));
- assertNotNull(g1.get("1.1.2",2));
- assertNotNull(g1.get("1.2.1",2));
- assertNotNull(g1.get("1.2.2",2));
- assertNull(g1.get("1.1.1.1",2));
-
- assertNotNull(g1.get("1.1.1.1",3));
-
- assertNull(g1.get("3",2));
+ assertNotNull(g1.get("1", -1));
+ assertNotNull(g1.get("1.1", -1));
+ assertNotNull(g1.get("1.2", -1));
+ assertNotNull(g1.get("1.1.1", -1));
+ assertNotNull(g1.get("1.1.2", -1));
+ assertNotNull(g1.get("1.2.1", -1));
+ assertNotNull(g1.get("1.2.2", -1));
+ assertNotNull(g1.get("1.1.1.1", -1));
+
+ assertNotNull(g1.get("1", 0));
+ assertNull(g1.get("1.1", 0));
+ assertNull(g1.get("1.2", 0));
+ assertNull(g1.get("1.1.1", 0));
+ assertNull(g1.get("1.1.2", 0));
+ assertNull(g1.get("1.2.1", 0));
+ assertNull(g1.get("1.2.2", 0));
+ assertNull(g1.get("1.1.1.1", 0));
+
+ assertNotNull(g1.get("1", 1));
+ assertNotNull(g1.get("1.1", 1));
+ assertNotNull(g1.get("1.2", 1));
+ assertNull(g1.get("1.1.1", 1));
+ assertNull(g1.get("1.1.2", 1));
+ assertNull(g1.get("1.2.1", 1));
+ assertNull(g1.get("1.2.2", 1));
+ assertNull(g1.get("1.1.1.1", 1));
+
+ assertNotNull(g1.get("1", 2));
+ assertNotNull(g1.get("1.1", 2));
+ assertNotNull(g1.get("1.2", 2));
+ assertNotNull(g1.get("1.1.1", 2));
+ assertNotNull(g1.get("1.1.2", 2));
+ assertNotNull(g1.get("1.2.1", 2));
+ assertNotNull(g1.get("1.2.2", 2));
+ assertNull(g1.get("1.1.1.1", 2));
+
+ assertNotNull(g1.get("1.1.1.1", 3));
+
+ assertNull(g1.get("3", 2));
}
@Test
- public void testThatHitGroupIsUnFillable() {
+ void testThatHitGroupIsUnFillable() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
@@ -185,7 +181,7 @@ public class HitGroupTestCase {
}
@Test
- public void testThatHitGroupIsFillable() {
+ void testThatHitGroupIsFillable() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
@@ -209,7 +205,7 @@ public class HitGroupTestCase {
}
@Test
- public void testThatHitGroupIsFillableAfterFillableChangeunderTheHood() {
+ void testThatHitGroupIsFillableAfterFillableChangeunderTheHood() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
diff --git a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
index d2cd2c4bb33..40d6f19c275 100644
--- a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
+++ b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
@@ -2,9 +2,9 @@
package com.yahoo.search.schema;
import com.yahoo.tensor.TensorType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -12,38 +12,38 @@ import static org.junit.Assert.assertEquals;
public class SchemaInfoTest {
@Test
- public void testSchemaInfoConfiguration() {
+ void testSchemaInfoConfiguration() {
assertEquals(SchemaInfoTester.createSchemaInfoFromConfig(), SchemaInfoTester.createSchemaInfo());
}
@Test
- public void testInputResolution() {
+ void testInputResolution() {
var tester = new SchemaInfoTester();
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "", "", "commonProfile", "query(myTensor1)");
+ "", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "commonProfile", "query(myTensor1)");
+ "ab", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "a", "", "commonProfile", "query(myTensor1)");
+ "a", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "b", "", "commonProfile", "query(myTensor1)");
+ "b", "", "commonProfile", "query(myTensor1)");
tester.assertInputConflict(TensorType.fromSpec("tensor(a{},b{})"),
- "", "", "inconsistent", "query(myTensor1)");
+ "", "", "inconsistent", "query(myTensor1)");
tester.assertInputConflict(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "inconsistent", "query(myTensor1)");
+ "ab", "", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "a", "inconsistent", "query(myTensor1)");
+ "ab", "a", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(x[10])"),
- "ab", "b", "inconsistent", "query(myTensor1)");
+ "ab", "b", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "a", "", "inconsistent", "query(myTensor1)");
+ "a", "", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(x[10])"),
- "b", "", "inconsistent", "query(myTensor1)");
+ "b", "", "inconsistent", "query(myTensor1)");
tester.assertInput(null,
- "a", "", "bOnly", "query(myTensor1)");
+ "a", "", "bOnly", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "bOnly", "query(myTensor1)");
+ "ab", "", "bOnly", "query(myTensor1)");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
index 45bf5af5258..4e7dc27e73c 100644
--- a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
+++ b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
@@ -15,7 +15,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
index f0be6a25f92..298bcc82d99 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
@@ -17,7 +17,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -28,16 +28,16 @@ public class AsyncExecutionOfOneChainTestCase {
/** Tests having a result with some slow source data which should pass directly to rendering */
@Test
- public void testParallelExecutionOfOneChain() {
+ void testParallelExecutionOfOneChain() {
ExecutorService executor = Executors.newFixedThreadPool(16);
// Setup
- Chain<Searcher> mainChain=new Chain<>(new ParallelExecutor(executor),new ResultProcessor(),new RegularProvider());
+ Chain<Searcher> mainChain = new Chain<>(new ParallelExecutor(executor), new ResultProcessor(), new RegularProvider());
// Execute
- Result result=new Execution(mainChain, Execution.Context.createContextStub()).search(new Query());
+ Result result = new Execution(mainChain, Execution.Context.createContextStub()).search(new Query());
// Verify
- assertEquals("Received 2 hits from 3 threads",3*2,result.hits().size());
+ assertEquals(3 * 2, result.hits().size(), "Received 2 hits from 3 threads");
assertEquals(1.0, result.hits().get("thread-0:hit-0").getRelevance().getScore(), delta);
assertEquals(1.0, result.hits().get("thread-1:hit-0").getRelevance().getScore(), delta);
assertEquals(1.0, result.hits().get("thread-2:hit-0").getRelevance().getScore(), delta);
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
index 8f23c7eef83..0e4d1350a03 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
@@ -7,17 +7,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for aynchrounous execution
@@ -56,10 +53,10 @@ public class AsyncExecutionTestCase {
// This should take ~50+ ms
@Test
- public void testAsync() {
+ void testAsync() {
List<Searcher> searchList = new ArrayList<>();
- searchList.add(new WaitingSearcher("one",60000));
- searchList.add(new WaitingSearcher("two",0));
+ searchList.add(new WaitingSearcher("one", 60000));
+ searchList.add(new WaitingSearcher("two", 0));
Chain<Searcher> searchChain = new Chain<>(new ComponentId("chain"), searchList);
AsyncExecution asyncExecution = new AsyncExecution(searchChain, Execution.Context.createContextStub());
@@ -70,23 +67,23 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testWaitForAll() {
+ void testWaitForAll() {
Chain<Searcher> slowChain = new Chain<>(
new ComponentId("slow"),
- Arrays.asList(new Searcher[]{new WaitingSearcher("slow",30000)}
+ Arrays.asList(new Searcher[]{new WaitingSearcher("slow", 30000)}
)
);
Chain<Searcher> fastChain = new Chain<>(
new ComponentId("fast"),
Arrays.asList(new Searcher[]{new SimpleSearcher()})
- );
+ );
FutureResult slowFuture = new AsyncExecution(slowChain, Execution.Context.createContextStub()).search(new Query("?hits=0"));
FutureResult fastFuture = new AsyncExecution(fastChain, Execution.Context.createContextStub()).search(new Query("?hits=0"));
fastFuture.get();
- FutureResult [] reslist = new FutureResult[]{slowFuture,fastFuture};
- List<Result> results = AsyncExecution.waitForAll(Arrays.asList(reslist),0);
+ FutureResult [] reslist = new FutureResult[]{slowFuture, fastFuture};
+ List<Result> results = AsyncExecution.waitForAll(Arrays.asList(reslist), 0);
//assertTrue(slowFuture.isCancelled());
assertTrue(fastFuture.isDone() && !fastFuture.isCancelled());
@@ -96,27 +93,27 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testSync() {
- Query query=new Query("?query=test");
- Searcher searcher=new ResultProducingSearcher();
- Result result=new Execution(searcher, Execution.Context.createContextStub()).search(query);
+ void testSync() {
+ Query query = new Query("?query=test");
+ Searcher searcher = new ResultProducingSearcher();
+ Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
- assertEquals(1,result.hits().size());
- assertEquals("hello",result.hits().get(0).getField("test"));
+ assertEquals(1, result.hits().size());
+ assertEquals("hello", result.hits().get(0).getField("test"));
}
@Test
- public void testSyncThroughSync() {
- Query query=new Query("?query=test");
- Searcher searcher=new ResultProducingSearcher();
- Result result=new Execution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
+ void testSyncThroughSync() {
+ Query query = new Query("?query=test");
+ Searcher searcher = new ResultProducingSearcher();
+ Result result = new Execution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
- assertEquals(1,result.hits().size());
- assertEquals("hello",result.hits().get(0).getField("test"));
+ assertEquals(1, result.hits().size());
+ assertEquals("hello", result.hits().get(0).getField("test"));
}
@Test
- public void testAsyncThroughSync() {
+ void testAsyncThroughSync() {
Query query = new Query("?query=test");
Searcher searcher = new ResultProducingSearcher();
FutureResult futureResult = new AsyncExecution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
@@ -144,7 +141,7 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testAsyncExecutionTimeout() {
+ void testAsyncExecutionTimeout() {
Chain<Searcher> chain = new Chain<>(new Searcher() {
@Override
public Result search(Query query, Execution execution) {
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java b/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
index 341e55df777..e25a946c18b 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
@@ -5,16 +5,16 @@ import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests async execution of search chains.
@@ -26,12 +26,12 @@ public class VespaAsyncSearcherTest {
private ExecutorService executor;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
executor = Executors.newFixedThreadPool(16);
}
- @After
+ @AfterEach
public void tearDown() {
assertEquals(0, executor.shutdownNow().size());
}
@@ -69,7 +69,7 @@ public class VespaAsyncSearcherTest {
}
@Test
- public void testAsyncExecution() {
+ void testAsyncExecution() {
Chain<Searcher> chain = new Chain<>(new FirstSearcher(), new SecondSearcher());
Execution execution = new Execution(chain, Execution.Context.createContextStub());
Query query = new Query();
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
index 553a9233bf1..614d481cf77 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.util.Arrays;
import com.yahoo.component.chain.dependencies.After;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.component.chain.dependencies.Dependencies;
import com.yahoo.component.chain.dependencies.Provides;
@@ -17,11 +19,9 @@ import com.yahoo.search.handler.SearchHandler;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* @author Tony Vaagenes
@@ -34,14 +34,14 @@ public class DependencyConfigTestCase {
public static final String root = "src/test/java/com/yahoo/search/searchchain/config/test/dependencyConfig";
- @BeforeClass
+ @BeforeAll
public static void createComponentsConfig() throws IOException {
SearchChainConfigurerTestCase.
createComponentsConfig(root + "/chains.cfg", root + "/handlers.cfg", root + "/components.cfg");
setUp();
}
- @AfterClass
+ @AfterAll
public static void removeComponentsConfig() {
new File(root + "/components.cfg").delete();
tearDown();
@@ -69,7 +69,7 @@ public class DependencyConfigTestCase {
}
@Test
- public void test() {
+ void test() {
Dependencies dependencies = registry.getSearcherRegistry().getComponent(Searcher1.class.getName()).getDependencies();
assertTrue(dependencies.provides().containsAll(Arrays.asList("P", "P1", "P2", Searcher1.class.getSimpleName())));
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
index 781370d9e25..e851d221116 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
@@ -14,9 +14,9 @@ import com.yahoo.search.searchchain.ExecutionFactory;
import com.yahoo.search.searchchain.SearchChain;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.SearcherRegistry;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -36,13 +36,7 @@ import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -65,12 +59,12 @@ public class SearchChainConfigurerTestCase {
}
}
- @BeforeClass
+ @BeforeAll
public static void createDefaultComponentsConfigs() throws IOException {
createComponentsConfig(testDir + "chains.cfg", testDir + "handlers.cfg", testDir + "components.cfg");
}
- @AfterClass
+ @AfterAll
public static void removeDefaultComponentsConfigs() {
new File(testDir + "components.cfg").delete();
}
@@ -81,7 +75,7 @@ public class SearchChainConfigurerTestCase {
}
@Test
- public synchronized void testConfiguration() {
+ synchronized void testConfiguration() {
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper("dir:" + testDir);
SearchChain simple = getSearchChainRegistryFrom(configurer).getComponent("simple");
@@ -130,7 +124,7 @@ public class SearchChainConfigurerTestCase {
public static final class DeclaredTestSearcher extends TestSearcher {}
@Test
- public void testConfigurableSearcher() {
+ void testConfigurableSearcher() {
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper("dir:" + testDir);
SearchChain configurable = getSearchChainRegistryFrom(configurer).getComponent("configurable");
@@ -138,9 +132,9 @@ public class SearchChainConfigurerTestCase {
Searcher s = configurable.searchers().get(0);
assertTrue(s instanceof ConfigurableSearcher);
- ConfigurableSearcher searcher = (ConfigurableSearcher)s;
- assertEquals("Value from int.cfg file", 7, searcher.intConfig.intVal());
- assertEquals("Value from string.cfg file", "com.yahoo.search.searchchain.config.test", searcher.stringConfig.stringVal());
+ ConfigurableSearcher searcher = (ConfigurableSearcher) s;
+ assertEquals(7, searcher.intConfig.intVal(), "Value from int.cfg file");
+ assertEquals("com.yahoo.search.searchchain.config.test", searcher.stringConfig.stringVal(), "Value from string.cfg file");
configurer.shutdown();
}
@@ -149,7 +143,7 @@ public class SearchChainConfigurerTestCase {
* that does not contain any bootstrap configs.
*/
@Test
- public void testSearcherConfigUpdate() throws IOException {
+ void testSearcherConfigUpdate() throws IOException {
File cfgDir = getCfgDir();
copyFile(testDir + "handlers.cfg", cfgDir + "/handlers.cfg");
copyFile(testDir + "qr-search.cfg", cfgDir + "/qr-search.cfg");
@@ -167,11 +161,11 @@ public class SearchChainConfigurerTestCase {
SearcherRegistry searchers = getSearchChainRegistryFrom(configurer).getSearcherRegistry();
assertEquals(3, searchers.getComponentCount());
- IntSearcher intSearcher = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
assertEquals(16, intSearcher.intConfig.intVal());
- StringSearcher stringSearcher = (StringSearcher)searchers.getComponent(StringSearcher.class.getName());
+ StringSearcher stringSearcher = (StringSearcher) searchers.getComponent(StringSearcher.class.getName());
DeclaredTestSearcher noConfigSearcher =
- (DeclaredTestSearcher)searchers.getComponent(DeclaredTestSearcher.class.getName());
+ (DeclaredTestSearcher) searchers.getComponent(DeclaredTestSearcher.class.getName());
// Update int config for IntSearcher,
printFile(new File(cfgDir + "/int.cfg"), "intVal 17\n");
@@ -183,7 +177,7 @@ public class SearchChainConfigurerTestCase {
assertEquals(3, searchers.getComponentCount());
// Searcher with updated config is re-instantiated.
- IntSearcher intSearcher2 = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher2 = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
assertNotSame(intSearcher, intSearcher2);
assertEquals(17, intSearcher2.intConfig.intVal());
@@ -203,7 +197,7 @@ public class SearchChainConfigurerTestCase {
* and that a searcher that has been removed from the configuration is not in the new registry.
*/
@Test
- public void testChainsConfigUpdate() throws IOException {
+ void testChainsConfigUpdate() throws IOException {
File cfgDir = getCfgDir();
copyFile(testDir + "handlers.cfg", cfgDir + "/handlers.cfg");
copyFile(testDir + "qr-search.cfg", cfgDir + "/qr-search.cfg");
@@ -225,7 +219,7 @@ public class SearchChainConfigurerTestCase {
assertNull(searchers.getComponent(ConfigurableSearcher.class.getName()));
assertNull(searchers.getComponent(DeclaredTestSearcher.class.getName()));
- IntSearcher intSearcher = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
// Update chains config
copyFile(testDir + "chainsConfigUpdate_2.cfg", cfgDir + "/chains.cfg");
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
index 129437a5429..bc535e4e214 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
@@ -17,14 +17,9 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests basic search chain execution functionality
@@ -34,31 +29,31 @@ import static org.junit.Assert.assertTrue;
public class ExecutionTestCase {
@Test
- public void testLinearExecutions() {
+ void testLinearExecutions() {
// Make a chain
- List<Searcher> searchers1=new ArrayList<>();
+ List<Searcher> searchers1 = new ArrayList<>();
searchers1.add(new TestSearcher("searcher1"));
searchers1.add(new TestSearcher("searcher2"));
searchers1.add(new TestSearcher("searcher3"));
searchers1.add(new TestSearcher("searcher4"));
- Chain<Searcher> chain1=new Chain<>(new ComponentId("chain1"), searchers1);
+ Chain<Searcher> chain1 = new Chain<>(new ComponentId("chain1"), searchers1);
// Make another chain containing two of the same searcher instances and two new
- List<Searcher> searchers2=new ArrayList<>(searchers1);
- searchers2.set(1,new TestSearcher("searcher5"));
- searchers2.set(3,new TestSearcher("searcher6"));
- Chain<Searcher> chain2=new Chain<>(new ComponentId("chain2"), searchers2);
+ List<Searcher> searchers2 = new ArrayList<>(searchers1);
+ searchers2.set(1, new TestSearcher("searcher5"));
+ searchers2.set(3, new TestSearcher("searcher6"));
+ Chain<Searcher> chain2 = new Chain<>(new ComponentId("chain2"), searchers2);
// Execute both
- Query query=new Query("test");
- Result result1=new Execution(chain1, Execution.Context.createContextStub()).search(query);
- Result result2=new Execution(chain2, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("test");
+ Result result1 = new Execution(chain1, Execution.Context.createContextStub()).search(query);
+ Result result2 = new Execution(chain2, Execution.Context.createContextStub()).search(query);
// Verify results
- assertEquals(4,result1.getConcreteHitCount());
+ assertEquals(4, result1.getConcreteHitCount());
assertNotNull(result1.hits().get("searcher1-1"));
assertNotNull(result1.hits().get("searcher2-1"));
assertNotNull(result1.hits().get("searcher3-1"));
assertNotNull(result1.hits().get("searcher4-1"));
- assertEquals(4,result2.getConcreteHitCount());
+ assertEquals(4, result2.getConcreteHitCount());
assertNotNull(result2.hits().get("searcher1-2"));
assertNotNull(result2.hits().get("searcher5-1"));
assertNotNull(result2.hits().get("searcher3-2"));
@@ -66,20 +61,20 @@ public class ExecutionTestCase {
}
@Test
- public void testNestedExecution() {
+ void testNestedExecution() {
// Make a chain
- List<Searcher> searchers1=new ArrayList<>();
+ List<Searcher> searchers1 = new ArrayList<>();
searchers1.add(new FillableTestSearcher("searcher1"));
searchers1.add(new WorkflowSearcher());
searchers1.add(new TestSearcher("searcher2"));
searchers1.add(new FillingSearcher());
searchers1.add(new FillableTestSearcherAtTheEnd("searcher3"));
- Chain<Searcher> chain1=new Chain<>(new ComponentId("chain1"), searchers1);
+ Chain<Searcher> chain1 = new Chain<>(new ComponentId("chain1"), searchers1);
// Execute it
- Query query=new Query("test");
- Result result1=new Execution(chain1, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("test");
+ Result result1 = new Execution(chain1, Execution.Context.createContextStub()).search(query);
// Verify results
- assertEquals(7,result1.getConcreteHitCount());
+ assertEquals(7, result1.getConcreteHitCount());
assertNotNull(result1.hits().get("searcher1-1"));
assertNotNull(result1.hits().get("searcher2-1"));
assertNotNull(result1.hits().get("searcher3-1"));
@@ -90,7 +85,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCacheSingleLengthSearchChain() {
+ void testContextCacheSingleLengthSearchChain() {
IndexFacts[] contextsBefore = new IndexFacts[1];
IndexFacts[] contextsAfter = new IndexFacts[1];
List<Searcher> l = new ArrayList<>(1);
@@ -103,7 +98,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCache() {
+ void testContextCache() {
IndexFacts[] contextsBefore = new IndexFacts[5];
IndexFacts[] contextsAfter = new IndexFacts[5];
List<Searcher> l = new ArrayList<>(5);
@@ -129,7 +124,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCacheMoreSearchers() {
+ void testContextCacheMoreSearchers() {
IndexFacts[] contextsBefore = new IndexFacts[7];
IndexFacts[] contextsAfter = new IndexFacts[7];
List<Searcher> l = new ArrayList<>(7);
@@ -161,7 +156,7 @@ public class ExecutionTestCase {
}
@Test
- public void testBasicFill() {
+ void testBasicFill() {
Chain<Searcher> chain = new Chain<Searcher>(new FillableResultSearcher());
Execution execution = new Execution(chain, Execution.Context.createContextStub());
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
index 15517270cb9..c78c0d75477 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
@@ -14,16 +14,15 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests using the async capabilities of the Processing parent framework of searchers.
@@ -33,16 +32,16 @@ import static org.junit.Assert.assertTrue;
public class FutureDataTestCase {
@Test
- public void testAsyncFederation() throws InterruptedException, ExecutionException {
+ void testAsyncFederation() throws InterruptedException, ExecutionException {
// Setup environment
AsyncProviderSearcher asyncProviderSearcher = new AsyncProviderSearcher();
Searcher syncProviderSearcher = new SyncProviderSearcher();
Chain<Searcher> asyncSource = new Chain<>(new ComponentId("async"), asyncProviderSearcher);
Chain<Searcher> syncSource = new Chain<>(new ComponentId("sync"), syncProviderSearcher);
- SearchChainResolver searchChainResolver=
+ SearchChainResolver searchChainResolver =
new SearchChainResolver.Builder().addSearchChain(new ComponentId("sync"), new FederationOptions().setUseByDefault(true)).
- addSearchChain(new ComponentId("async"), new FederationOptions().setUseByDefault(true)).
- build();
+ addSearchChain(new ComponentId("async"), new FederationOptions().setUseByDefault(true)).
+ build();
Chain<Searcher> main = new Chain<>(new FederationSearcher(new ComponentId("federator"), searchChainResolver));
SearchChainRegistry searchChainRegistry = new SearchChainRegistry();
searchChainRegistry.register(main);
@@ -54,32 +53,32 @@ public class FutureDataTestCase {
Result result = new Execution(main, Execution.Context.createContextStub(searchChainRegistry)).search(query);
assertNotNull(result);
- HitGroup syncGroup = (HitGroup)result.hits().get("source:sync");
+ HitGroup syncGroup = (HitGroup) result.hits().get("source:sync");
assertNotNull(syncGroup);
- HitGroup asyncGroup = (HitGroup)result.hits().get("source:async");
+ HitGroup asyncGroup = (HitGroup) result.hits().get("source:async");
assertNotNull(asyncGroup);
- assertEquals("Got all sync data", 3, syncGroup.size());
+ assertEquals(3, syncGroup.size(), "Got all sync data");
assertEquals("sync:0", syncGroup.get(0).getId().toString());
assertEquals("sync:1", syncGroup.get(1).getId().toString());
assertEquals("sync:2", syncGroup.get(2).getId().toString());
- assertTrue(asyncGroup.incoming()==asyncProviderSearcher.incomingData);
- assertEquals("Got no async data yet", 0, asyncGroup.size());
+ assertEquals(asyncGroup.incoming(), asyncProviderSearcher.incomingData);
+ assertEquals(0, asyncGroup.size(), "Got no async data yet");
asyncProviderSearcher.simulateOneHitIOComplete(new Hit("async:0"));
- assertEquals("Got no async data yet, as we haven't completed the incoming buffer and there is no data listener", 0, asyncGroup.size());
+ assertEquals(0, asyncGroup.size(), "Got no async data yet, as we haven't completed the incoming buffer and there is no data listener");
asyncProviderSearcher.simulateOneHitIOComplete(new Hit("async:1"));
asyncProviderSearcher.simulateAllHitsIOComplete();
- assertEquals("Got no async data yet, as we haven't pulled it", 0, asyncGroup.size());
+ assertEquals(0, asyncGroup.size(), "Got no async data yet, as we haven't pulled it");
asyncGroup.completeFuture().get();
- assertEquals("Completed, so we have the data", 2, asyncGroup.size());
+ assertEquals(2, asyncGroup.size(), "Completed, so we have the data");
assertEquals("async:0", asyncGroup.get(0).getId().toString());
assertEquals("async:1", asyncGroup.get(1).getId().toString());
}
@Test
- public void testFutureData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFutureData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
AsyncProviderSearcher futureDataSource = new AsyncProviderSearcher();
Chain<Searcher> chain = new Chain<>(Collections.<Searcher>singletonList(futureDataSource));
@@ -89,16 +88,14 @@ public class FutureDataTestCase {
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
// Verify the result prior to completion of delayed data
- assertEquals("The result has been returned, but no hits are available yet",
- 0, result.hits().getConcreteSize());
+ assertEquals(0, result.hits().getConcreteSize(), "The result has been returned, but no hits are available yet");
// pretend we're the IO layer and complete delayed data - this is typically done in a callback from jDisc
futureDataSource.simulateOneHitIOComplete(new Hit("hit:0"));
futureDataSource.simulateOneHitIOComplete(new Hit("hit:1"));
futureDataSource.simulateAllHitsIOComplete();
- assertEquals("Async arriving hits are still not visible because we haven't asked for them",
- 0, result.hits().getConcreteSize());
+ assertEquals(0, result.hits().getConcreteSize(), "Async arriving hits are still not visible because we haven't asked for them");
// Results with future hit groups will be passed to rendering directly and start rendering immediately.
// For this test we block and wait for the data instead:
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
index d7fd73a81e6..ef35b5beabe 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.search.searchchain.test;
import static com.yahoo.search.searchchain.test.SimpleSearchChain.searchChain;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
@@ -19,28 +19,27 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests basic search chain functionality - creation, inheritance and ordering
*
* @author bratseth
*/
-@SuppressWarnings("deprecation")
public class SearchChainTestCase {
@Test
- public void testEmptySearchChain() {
+ void testEmptySearchChain() {
SearchChain empty = new SearchChain(new ComponentId("empty"));
assertEquals("empty", empty.getId().getName());
}
@Test
- public void testSearchChainCreation() {
- assertEquals("test",searchChain.getId().stringValue());
- assertEquals("test",searchChain.getId().getName());
+ void testSearchChainCreation() {
+ assertEquals("test", searchChain.getId().stringValue());
+ assertEquals("test", searchChain.getId().getName());
assertEquals(Version.emptyVersion, searchChain.getId().getVersion());
- assertEquals(new Version(),searchChain.getId().getVersion());
+ assertEquals(new Version(), searchChain.getId().getVersion());
assertEqualMembers(Arrays.asList("one", "two"), searcherNames(searchChain.searchers()));
}
@@ -60,34 +59,34 @@ public class SearchChainTestCase {
}
@Test
- public void testSearchChainToStringEmpty() {
+ void testSearchChainToStringEmpty() {
assertEquals("chain 'test' []", new Chain<>(new ComponentId("test"), createSearchers(0)).toString());
}
@Test
- public void testSearchChainToStringVeryShort() {
- assertEquals("chain 'test' [s1]", new Chain<>(new ComponentId("test"),createSearchers(1)).toString());
+ void testSearchChainToStringVeryShort() {
+ assertEquals("chain 'test' [s1]", new Chain<>(new ComponentId("test"), createSearchers(1)).toString());
}
@Test
- public void testSearchChainToStringShort() {
- assertEquals("chain 'test' [s1 -> s2 -> s3]", new Chain<>(new ComponentId("test"),createSearchers(3)).toString());
+ void testSearchChainToStringShort() {
+ assertEquals("chain 'test' [s1 -> s2 -> s3]", new Chain<>(new ComponentId("test"), createSearchers(3)).toString());
}
@Test
- public void testSearchChainToStringLong() {
- assertEquals("chain 'test' [s1 -> s2 -> ... -> s4]", new Chain<>(new ComponentId("test"),createSearchers(4)).toString());
+ void testSearchChainToStringLong() {
+ assertEquals("chain 'test' [s1 -> s2 -> ... -> s4]", new Chain<>(new ComponentId("test"), createSearchers(4)).toString());
}
@Test
- public void testSearchChainToStringVeryLong() {
- assertEquals("chain 'test' [s1 -> s2 -> ... -> s10]", new Chain<>(new ComponentId("test"),createSearchers(10)).toString());
+ void testSearchChainToStringVeryLong() {
+ assertEquals("chain 'test' [s1 -> s2 -> ... -> s10]", new Chain<>(new ComponentId("test"), createSearchers(10)).toString());
}
private List<Searcher> createSearchers(int count) {
List<Searcher> searchers=new ArrayList<>(count);
for (int i=0; i<count; i++)
- searchers.add(new TestSearcher("s" + String.valueOf(i+1)));
+ searchers.add(new TestSearcher("s" + (i+1)));
return searchers;
}
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
index 04b1fd85872..f2c8551126b 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
@@ -19,8 +19,8 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Tests tracing scenarios where traces from multiple executions over the same query are involved.
@@ -30,27 +30,27 @@ import static org.junit.Assert.assertFalse;
public class TraceTestCase {
@Test
- public void testTracingOnCorrectAPIUseNonParallel() {
- assertTracing(true,false);
+ void testTracingOnCorrectAPIUseNonParallel() {
+ assertTracing(true, false);
}
@Test
- public void testTracingOnIncorrectAPIUseNonParallel() {
- assertTracing(false,false);
+ void testTracingOnIncorrectAPIUseNonParallel() {
+ assertTracing(false, false);
}
@Test
- public void testTracingOnCorrectAPIUseParallel() {
+ void testTracingOnCorrectAPIUseParallel() {
assertTracing(true, true);
}
@Test
- public void testTracingOnIncorrectAPIUseParallel() {
- assertTracing(false,true);
+ void testTracingOnIncorrectAPIUseParallel() {
+ assertTracing(false, true);
}
@Test
- public void testTraceWithQuery() {
+ void testTraceWithQuery() {
testQueryInTrace(true, "trace.query=true");
testQueryInTrace(false, "trace.query=false");
testQueryInTrace(true, "");
@@ -71,13 +71,13 @@ public class TraceTestCase {
assertEquals(" During tracer1: 0", trace.next());
}
- @Test
- public void testTraceInvocationsUnfillableHits() {
+ @Test
+ void testTraceInvocationsUnfillableHits() {
final int traceLevel = 5;
Query query = new Query("?trace.level=" + traceLevel);
- Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
- new Tracer("tracer2"),
- new Backend("backend1", false));
+ Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
+ new Tracer("tracer2"),
+ new Backend("backend1", false));
Execution execution = new Execution(forkingChain, Execution.Context.createContextStub());
Result result = execution.search(query);
execution.fill(result, "mySummary");
@@ -104,12 +104,12 @@ public class TraceTestCase {
}
@Test
- public void testTraceInvocationsFillableHits() {
+ void testTraceInvocationsFillableHits() {
final int traceLevel = 5;
Query query = new Query("?tracelevel=" + traceLevel);
Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
- new Tracer("tracer2"),
- new Backend("backend1", true));
+ new Tracer("tracer2"),
+ new Backend("backend1", true));
Execution execution = new Execution(forkingChain, Execution.Context.createContextStub());
Result result = execution.search(query);
execution.fill(result, "mySummary");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
index 587b40dfd03..1cf8159e19e 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
@@ -1,7 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers;
-import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.prelude.IndexFacts;
import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
@@ -13,16 +12,16 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.yql.YqlParser;
-import com.yahoo.vespa.config.search.AttributesConfig.Attribute;
import com.yahoo.vespa.config.search.AttributesConfig;
-import org.junit.Test;
+import com.yahoo.vespa.config.search.AttributesConfig.Attribute;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author alexeyche
@@ -33,35 +32,25 @@ public class ValidateFuzzySearcherTestCase {
List<String> attributes;
public ValidateFuzzySearcherTestCase() {
- int i = 0;
attributes = new ArrayList<>();
- StringBuilder attributeConfig = new StringBuilder();
+ AttributesConfig.Builder configBuilder = new AttributesConfig.Builder();
+ List<AttributesConfig.Attribute.Builder> attributesList = new ArrayList<>();
for (Attribute.Datatype.Enum attr: Attribute.Datatype.Enum.values()) {
for (Attribute.Collectiontype.Enum ctype: Attribute.Collectiontype.Enum.values()) {
+ AttributesConfig.Attribute.Builder attributesBuilder = new AttributesConfig.Attribute.Builder();
String attributeName = attr.name().toLowerCase() + "_" + ctype.name().toLowerCase();
+ attributesBuilder.name(attributeName);
+ attributesBuilder.datatype(attr);
+ attributesBuilder.collectiontype(ctype);
+ attributesList.add(attributesBuilder);
- attributeConfig.append("attribute[" + i + "].name ");
- attributeConfig.append(attributeName);
- attributeConfig.append("\n");
-
- attributeConfig.append("attribute[" + i + "].datatype ");
- attributeConfig.append(attr.name());
- attributeConfig.append("\n");
-
- attributeConfig.append("attribute[" + i + "].collectiontype ");
- attributeConfig.append(ctype.name());
- attributeConfig.append("\n");
-
- i += 1;
attributes.add(attributeName);
}
}
+ configBuilder.attribute(attributesList);
+ AttributesConfig config = configBuilder.build();
- searcher = new ValidateFuzzySearcher(ConfigGetter.getConfig(
- AttributesConfig.class,
- "raw: " +
- "attribute[" + attributes.size() + "]\n" +
- attributeConfig));
+ searcher = new ValidateFuzzySearcher(config);
}
private String makeQuery(String attribute, String query, int maxEditDistance, int prefixLength) {
@@ -76,10 +65,10 @@ public class ValidateFuzzySearcherTestCase {
@Test
- public void testQueriesToAllAttributes() {
+ void testQueriesToAllAttributes() {
final Set<String> validAttributes = Set.of("string_single", "string_array", "string_weightedset");
- for (String attribute: attributes) {
+ for (String attribute : attributes) {
String q = makeQuery(attribute, "fuzzy");
Result r = doSearch(searcher, q);
if (validAttributes.contains(attribute)) {
@@ -91,28 +80,28 @@ public class ValidateFuzzySearcherTestCase {
}
@Test
- public void testInvalidEmptyStringQuery() {
+ void testInvalidEmptyStringQuery() {
String q = makeQuery("string_single", "");
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(,2,0) string_single: fuzzy query must be non-empty", r);
}
@Test
- public void testInvalidQueryWrongMaxEditDistance() {
+ void testInvalidQueryWrongMaxEditDistance() {
String q = makeQuery("string_single", "fuzzy", -1, 0);
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,-1,0) string_single:fuzzy has invalid maxEditDistance -1: Must be >= 0", r);
}
@Test
- public void testInvalidQueryWrongPrefixLength() {
+ void testInvalidQueryWrongPrefixLength() {
String q = makeQuery("string_single", "fuzzy", 2, -1);
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,2,-1) string_single:fuzzy has invalid prefixLength -1: Must be >= 0", r);
}
@Test
- public void testInvalidQueryWrongAttributeName() {
+ void testInvalidQueryWrongAttributeName() {
String q = makeQuery("wrong_name", "fuzzy");
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,2,0) wrong_name:fuzzy field is not a string attribute", r);
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
index 9a760bfb0cb..b8be0b3dd43 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
@@ -2,30 +2,24 @@
package com.yahoo.search.searchers;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.config.subscription.FileSource;
-import com.yahoo.config.subscription.RawSource;
import com.yahoo.prelude.IndexFacts;
import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
+import com.yahoo.search.Result;
+import com.yahoo.search.query.QueryTree;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
-import com.yahoo.search.query.QueryTree;
-import com.yahoo.search.Result;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.yql.YqlParser;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.vespa.config.search.AttributesConfig;
+import org.junit.jupiter.api.Test;
-import com.yahoo.vespa.config.search.RankProfilesConfig;
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author arnej
@@ -34,6 +28,7 @@ public class ValidateNearestNeighborTestCase {
ValidateNearestNeighborSearcher searcher;
+ @SuppressWarnings("deprecation")
public ValidateNearestNeighborTestCase() {
searcher = new ValidateNearestNeighborSearcher(
ConfigGetter.getConfig(AttributesConfig.class,
@@ -108,7 +103,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryDoubleVectors() {
+ void testValidQueryDoubleVectors() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -116,7 +111,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryFloatVectors() {
+ void testValidQueryFloatVectors() {
String q = makeQuery("fvector", "qvector");
Tensor t = makeTensor(tt_dense_fvector_3);
Result r = doSearch(searcher, q, t);
@@ -124,7 +119,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryDoubleVectorAgainstFloatVector() {
+ void testValidQueryDoubleVectorAgainstFloatVector() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_fvector_3);
Result r = doSearch(searcher, q, t);
@@ -132,7 +127,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryFloatVectorAgainstDoubleVector() {
+ void testValidQueryFloatVectorAgainstDoubleVector() {
String q = makeQuery("fvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -157,7 +152,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMissingTargetNumHits() {
+ void testMissingTargetNumHits() {
String q = "select * from sources * where nearestNeighbor(dvector,qvector)";
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -165,7 +160,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMissingQueryTensor() {
+ void testMissingQueryTensor() {
String q = makeQuery("dvector", "foo");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -173,7 +168,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testWrongTensorType() {
+ void testWrongTensorType() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_2, 2);
Result r = doSearch(searcher, q, t);
@@ -181,7 +176,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testNotAttribute() {
+ void testNotAttribute() {
String q = makeQuery("foo", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -189,7 +184,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testWrongAttributeType() {
+ void testWrongAttributeType() {
String q = makeQuery("simple", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -197,7 +192,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testSeveralAttributesWithSameName() {
+ void testSeveralAttributesWithSameName() {
String q = makeQuery("threetypes", "qvector");
Tensor t1 = makeTensor(tt_dense_fvector_3);
Result r1 = doSearch(searcher, q, t1);
@@ -211,7 +206,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testSparseTensor() {
+ void testSparseTensor() {
String q = makeQuery("sparse", "qvector");
Tensor t = makeTensor(tt_sparse_vector_x);
Result r = doSearch(searcher, q, t);
@@ -219,7 +214,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMatrix() {
+ void testMatrix() {
String q = makeQuery("matrix", "qvector");
Tensor t = makeMatrix(tt_dense_matrix_xy);
Result r = doSearch(searcher, q, t);
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
index b0fd77897fc..dc99185f4b8 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
@@ -8,15 +8,12 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.CacheControlSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.search.searchers.CacheControlSearcher.CACHE_CONTROL_HEADER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit test cases for CacheControlSearcher.
@@ -54,17 +51,17 @@ public class CacheControlSearcherTestCase {
* @param cacheheaders - The "Cache-Control" headers from the response ListMap
*/
private void assertCacheHeaders(String[] values, List<String> cacheheaders) {
- assertNotNull("No headers to test for (was null)", values);
- assertTrue("No headers to test for (no elements in array)", values.length > 0);
- assertNotNull("No cache headers set in response", cacheheaders);
+ assertNotNull(values, "No headers to test for (was null)");
+ assertTrue(values.length > 0, "No headers to test for (no elements in array)");
+ assertNotNull(cacheheaders, "No cache headers set in response");
assertEquals(values.length, cacheheaders.size());
for (String header : values) {
- assertTrue("Cache header does not contain header '" + header + "'", cacheheaders.contains(header));
+ assertTrue(cacheheaders.contains(header), "Cache header does not contain header '" + header + "'");
}
}
@Test
- public void testNoHeader() {
+ void testNoHeader() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo");
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
@@ -72,7 +69,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testInvalidAgeParams() {
+ void testInvalidAgeParams() {
Chain<Searcher> chain = getSearchChain();
try {
@@ -97,7 +94,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testMaxAge() {
+ void testMaxAge() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=120");
@@ -106,7 +103,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testNoCache() {
+ void testNoCache() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=120&noCache");
@@ -119,7 +116,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testStateWhileRevalidate() {
+ void testStateWhileRevalidate() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.staleage=3600");
@@ -128,7 +125,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testStaleAndMaxAge() {
+ void testStaleAndMaxAge() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=60&cachecontrol.staleage=3600");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
index 48dc0975efe..5323149ae1d 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -12,8 +12,7 @@ import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.Container;
@@ -35,7 +34,7 @@ import com.yahoo.search.searchers.ConnectionControlSearcher;
public class ConnectionControlSearcherTestCase {
@Test
- public final void test() throws URISyntaxException {
+ final void test() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=1");
long connectedAtMillis = 0L;
long nowMillis = 2L * 1000L;
@@ -44,7 +43,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testForcedClose() throws URISyntaxException {
+ final void testForcedClose() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=0");
long connectedAtMillis = 0L;
long nowMillis = 0L;
@@ -53,7 +52,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testNormalCloseWithoutJdisc() {
+ final void testNormalCloseWithoutJdisc() {
long nowMillis = 2L;
Query query = new Query("/?connectioncontrol.maxlifetime=1");
Execution e = new Execution(new Chain<Searcher>(ConnectionControlSearcher.createTestInstance(() -> nowMillis)),
@@ -63,7 +62,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testNoMaxLifetime() throws URISyntaxException {
+ final void testNoMaxLifetime() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/");
long connectedAtMillis = 0L;
long nowMillis = 0L;
@@ -72,7 +71,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testYoungEnoughConnection() throws URISyntaxException {
+ final void testYoungEnoughConnection() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=1");
long connectedAtMillis = 0L;
long nowMillis = 500L;
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
index 91784c82800..2cd65f65209 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
@@ -1,16 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers.test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.prelude.IndexFacts;
@@ -30,44 +29,44 @@ public class InputCheckingSearcherTestCase {
Execution execution;
- @Before
+ @BeforeEach
public void setUp() {
execution = new Execution(new Chain<Searcher>(new InputCheckingSearcher(MetricReceiver.nullImplementation)),
Execution.Context.createContextStub());
}
- @After
+ @AfterEach
public void tearDown() {
execution = null;
}
@Test
- public void testCommonCase() {
+ void testCommonCase() {
Result r = execution.search(new Query("/search/?query=three+blind+mice"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButAsciiOnly() {
+ void candidateButAsciiOnly() {
Result r = execution.search(new Query("/search/?query=a+a+a+a+a+a"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButValid() throws UnsupportedEncodingException {
+ void candidateButValid() throws UnsupportedEncodingException {
Result r = execution.search(new Query("/search/?query=" + URLEncoder.encode("å å å å å å", "UTF-8")));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButValidAndOutsideFirst256() throws UnsupportedEncodingException {
+ void candidateButValidAndOutsideFirst256() throws UnsupportedEncodingException {
Result r = execution.search(new Query("/search/?query=" + URLEncoder.encode("œ œ œ œ œ œ", "UTF-8")));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testDoubleEncoded() throws UnsupportedEncodingException {
+ void testDoubleEncoded() throws UnsupportedEncodingException {
String rawQuery = "å å å å å å";
byte[] encodedOnce = Utf8.toBytes(rawQuery);
char[] secondEncodingBuffer = new char[encodedOnce.length];
@@ -80,37 +79,37 @@ public class InputCheckingSearcherTestCase {
}
@Test
- public void testRepeatedConsecutiveTermsInPhrase() {
+ void testRepeatedConsecutiveTermsInPhrase() {
Result r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.0.c%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("More than 5 occurrences of term '0' in a row detected in phrase : \"a b 0 0 0 0 0 0 c\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
r = execution.search(new Query("/search/?query=a.b.0.0.0.1.0.0.0.c"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testThatMaxRepeatedConsecutiveTermsInPhraseIs5() {
+ void testThatMaxRepeatedConsecutiveTermsInPhraseIs5() {
Result r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.0.c%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("More than 5 occurrences of term '0' in a row detected in phrase : \"a b 0 0 0 0 0 0 c\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.1.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testThatMaxRepeatedTermsInPhraseIs10() {
+ void testThatMaxRepeatedTermsInPhraseIs10() {
Result r = execution.search(new Query("/search/?query=%220.a.1.a.2.a.3.a.4.a.5.a.6.a.7.a.9.a%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%220.a.1.a.2.a.3.a.4.a.5.a.6.a.7.a.8.a.9.a.10.a%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("Phrase contains more than 10 occurrences of term 'a' in phrase : \"0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 10 a\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
index d5fb1c0cfe3..64fb4354003 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.QueryValidator;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -18,7 +18,7 @@ import static org.junit.Assert.fail;
public class QueryValidatorTestCase {
@Test
- public void testValidation() {
+ void testValidation() {
SearchDefinition sd = new SearchDefinition("test");
sd.addCommand("mytensor1", "type tensor(x[100]");
sd.addCommand("mytensor2", "type tensor<float>(x[100]");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
index 4ee57112960..102f9bda5dc 100755
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
@@ -14,15 +14,13 @@ import com.yahoo.search.config.RateLimitingConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.RateLimitingSearcher;
import com.yahoo.yolean.chain.After;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import com.yahoo.test.ManualClock;
import java.time.Duration;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for RateLimitingSearcher
@@ -32,7 +30,7 @@ import static org.junit.Assert.assertFalse;
public class RateLimitingSearcherTestCase {
@Test
- public void testRateLimiting() {
+ void testRateLimiting() {
RateLimitingConfig.Builder rateLimitingConfig = new RateLimitingConfig.Builder();
rateLimitingConfig.maxAvailableCapacity(4);
rateLimitingConfig.capacityIncrement(2);
@@ -46,36 +44,36 @@ public class RateLimitingSearcherTestCase {
MetricReceiver.MockReceiver metric = new MetricReceiver.MockReceiver();
Chain<Searcher> chain = new Chain<>("test", new RateLimitingSearcher(new RateLimitingConfig(rateLimitingConfig),
- new ClusterInfoConfig(clusterInfoConfig),
- metric, clock),
- new CostSettingSearcher());
- assertEquals("'rate' request are available initially", 2, tryRequests(chain, "id1"));
- assertTrue("However, don't reject if we dryRun", executeWasAllowed(chain, "id1", true));
+ new ClusterInfoConfig(clusterInfoConfig),
+ metric, clock),
+ new CostSettingSearcher());
+ assertEquals(2, tryRequests(chain, "id1"), "'rate' request are available initially");
+ assertTrue(executeWasAllowed(chain, "id1", true), "However, don't reject if we dryRun");
clock.advance(Duration.ofMillis(1500)); // causes 2 new requests to become available
- assertEquals("'rate' new requests became available", 2, tryRequests(chain, "id1"));
+ assertEquals(2, tryRequests(chain, "id1"), "'rate' new requests became available");
- assertEquals("Another id", 2, tryRequests(chain, "id2"));
+ assertEquals(2, tryRequests(chain, "id2"), "Another id");
clock.advance(Duration.ofMillis(1000000));
- assertEquals("'maxAvailableCapacity' request became available", 4, tryRequests(chain, "id2"));
+ assertEquals(4, tryRequests(chain, "id2"), "'maxAvailableCapacity' request became available");
- assertFalse("If quota is set to 0, all requests are rejected, even initially", executeWasAllowed(chain, "id3", 0));
+ assertFalse(executeWasAllowed(chain, "id3", 0), "If quota is set to 0, all requests are rejected, even initially");
clock.advance(Duration.ofMillis(1000000));
- assertTrue("A single query which costs more than capacity is allowed as cost is calculated after allowing it",
- executeWasAllowed(chain, "id1", 8, 8, false));
- assertFalse("capacity is -4: disallowing", executeWasAllowed(chain, "id1"));
+ assertTrue(executeWasAllowed(chain, "id1", 8, 8, false),
+ "A single query which costs more than capacity is allowed as cost is calculated after allowing it");
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is -4: disallowing");
clock.advance(Duration.ofMillis(1000));
- assertFalse("capacity is -2: disallowing", executeWasAllowed(chain, "id1"));
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is -2: disallowing");
clock.advance(Duration.ofMillis(1000));
- assertFalse("capacity is 0: disallowing", executeWasAllowed(chain, "id1"));
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is 0: disallowing");
clock.advance(Duration.ofMillis(1000));
assertTrue(executeWasAllowed(chain, "id1"));
// check metrics
- Map<Point,UntypedMetric> map = metric.getSnapshot().getMapForMetric("requestsOverQuota");
- assertEquals(requestsToTry-2 + 1 + requestsToTry-2 + 3, map.get(metric.point("id", "id1")).getCount());
- assertEquals(requestsToTry-2 + requestsToTry-4, map.get(metric.point("id", "id2")).getCount());
+ Map<Point, UntypedMetric> map = metric.getSnapshot().getMapForMetric("requestsOverQuota");
+ assertEquals(requestsToTry - 2 + 1 + requestsToTry - 2 + 3, map.get(metric.point("id", "id1")).getCount());
+ assertEquals(requestsToTry - 2 + requestsToTry - 4, map.get(metric.point("id", "id2")).getCount());
}
private int requestsToTry = 50;
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
index 01e360858c1..a040575c4b4 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
@@ -3,19 +3,18 @@ package com.yahoo.search.searchers.test;
import com.yahoo.component.chain.Chain;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.config.subscription.RawSource;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.ValidateMatchPhaseSearcher;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.vespa.config.search.AttributesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author baldersheim
@@ -24,6 +23,7 @@ public class ValidateMatchPhaseSearcherTestCase {
private final ValidateMatchPhaseSearcher searcher;
+ @SuppressWarnings("deprecation")
public ValidateMatchPhaseSearcherTestCase() {
searcher = new ValidateMatchPhaseSearcher(
ConfigGetter.getConfig(AttributesConfig.class,
@@ -61,7 +61,7 @@ public class ValidateMatchPhaseSearcherTestCase {
}
@Test
- public void testMatchPhaseAttribute() {
+ void testMatchPhaseAttribute() {
assertEquals("", search(""));
assertEquals("", match("ok"));
assertEquals(getErrorMatch("not_numeric"), match("not_numeric"));
@@ -71,7 +71,7 @@ public class ValidateMatchPhaseSearcherTestCase {
}
@Test
- public void testDiversityAttribute() {
+ void testDiversityAttribute() {
assertEquals("", search(""));
assertEquals("", diversify("ok"));
assertEquals("", diversify("not_numeric"));
diff --git a/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java b/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
index c7983a55e8b..4d6b2e4cbe3 100644
--- a/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
@@ -10,11 +10,9 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.statistics.TimeTracker.Activity;
import com.yahoo.search.statistics.TimeTracker.SearcherTimer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Check sanity of TimeTracker and ElapsedTime.
@@ -145,9 +143,9 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasic() {
+ void testBasic() {
TimeTracker t = new TimeTracker(null);
- t.injectTimeSource(new CreativeTimeSource(new long[] {1L, 2L, 3L, 4L}));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L}));
Query q = new Query();
Result r = new Result(q);
t.sampleSearch(0, false);
@@ -164,9 +162,9 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testMultiSearchAndPing() {
+ void testMultiSearchAndPing() {
TimeTracker t = new TimeTracker(null);
- t.injectTimeSource(new CreativeTimeSource(new long[] {1L, 4L, 16L, 32L, 64L, 128L, 256L}));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 4L, 16L, 32L, 64L, 128L, 256L}));
Query q = new Query();
Result r = new Result(q);
t.sampleSearch(0, false);
@@ -189,7 +187,7 @@ public class ElapsedTimeTestCase {
// multiple adds is supposed to be safe
assertEquals(255L, t.totalTime());
TimeTracker tx = new TimeTracker(null);
- tx.injectTimeSource(new CreativeTimeSource(new long[] {1L, 2L, 3L, 4L}));
+ tx.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L}));
Query qx = new Query();
Result rx = new Result(qx);
tx.sampleSearch(0, false);
@@ -203,12 +201,12 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdown() {
+ void testBasicBreakdown() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
- 4L, 5L, 6L, 7L }));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
+ 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -223,7 +221,7 @@ public class ElapsedTimeTestCase {
// This test is to make sure the other tests correctly simulate the call
// order into the TimeTracker
@Test
- public void testBasicBreakdownFullyWiredIn() {
+ void testBasicBreakdownFullyWiredIn() {
Chain<? extends Searcher> chain = new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third"));
@@ -250,7 +248,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownWithFillFullyWiredIn() {
+ void testBasicBreakdownWithFillFullyWiredIn() {
Chain<? extends Searcher> chain = new Chain<>(
new UselessSearcher("first"), new UselessSearcher("second"),
new AlmostUselessSearcher("third"));
@@ -279,7 +277,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownFullyWiredInFirstSearcherNotFirstInChain() {
+ void testBasicBreakdownFullyWiredInFirstSearcherNotFirstInChain() {
Chain<? extends Searcher> chain = new Chain<>(
new TestingSearcher(),
new UselessSearcher("first"), new UselessSearcher("second"),
@@ -289,7 +287,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownWithFillFullyWiredInFirstSearcherNotFirstInChain() {
+ void testBasicBreakdownWithFillFullyWiredInFirstSearcherNotFirstInChain() {
Chain<? extends Searcher> chain = new Chain<>(
new SecondTestingSearcher(),
new UselessSearcher("first"), new UselessSearcher("second"),
@@ -299,7 +297,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testTimingWithShortChain() {
+ void testTimingWithShortChain() {
Chain<? extends Searcher> chain = new Chain<>(
new ShortChainTestingSearcher(),
new NoForwardSearcher());
@@ -308,12 +306,12 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownReturnInsideSearchChain() {
+ void testBasicBreakdownReturnInsideSearchChain() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
- 4L, 5L, 6L }));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
+ 4L, 5L, 6L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -325,16 +323,16 @@ public class ElapsedTimeTestCase {
assertEquals(Long.valueOf(1L), searchers[1].getInvoking(Activity.SEARCH));
assertEquals(Long.valueOf(1L), searchers[2].getInvoking(Activity.SEARCH));
assertNull(searchers[2].getReturning(Activity.SEARCH));
- assertEquals(Long.valueOf(1L) ,searchers[1].getReturning(Activity.SEARCH));
- assertEquals(Long.valueOf(1L) ,searchers[0].getReturning(Activity.SEARCH));
+ assertEquals(Long.valueOf(1L), searchers[1].getReturning(Activity.SEARCH));
+ assertEquals(Long.valueOf(1L), searchers[0].getReturning(Activity.SEARCH));
}
@Test
- public void testBasicBreakdownWithFill() {
+ void testBasicBreakdownWithFill() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
4L, 5L, 6L, 7L, 7L, 8L, 9L, 10L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
@@ -400,7 +398,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testMixedActivity() {
+ void testMixedActivity() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
@@ -424,7 +422,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testReportGeneration() {
+ void testReportGeneration() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
diff --git a/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
index 7cd7e20b76f..f8a77445a40 100644
--- a/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
@@ -45,8 +45,8 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.Exceptions;
import org.json.JSONObject;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -59,14 +59,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -74,10 +67,10 @@ import static org.junit.Assert.fail;
public class QueryTestCase {
@Test
- public void testIt() throws Exception {
+ void testIt() throws Exception {
JSONObject newroot = new JSONObject("{\"key\": 3}");
var hit = new FastHit();
- hit.setField("data", (JsonProducer)s -> s.append(newroot));
+ hit.setField("data", (JsonProducer) s -> s.append(newroot));
var field = hit.getField("data");
if (field instanceof JsonProducer) {
System.out.println((((JsonProducer) field).toJson()));
@@ -85,7 +78,7 @@ public class QueryTestCase {
}
@Test
- public void testSimpleFunctionality() {
+ void testSimpleFunctionality() {
Query q = new Query(QueryTestCase.httpEncode("/sdfsd.html?query=this is a simple query&aParameter"));
assertEquals("this is a simple query", q.getModel().getQueryString());
assertNotNull(q.getModel().getQueryTree());
@@ -105,23 +98,23 @@ public class QueryTestCase {
}
// TODO: YQL work in progress (jon)
- @Ignore
+ @Disabled
@Test
- public void testSimpleProgram() {
+ void testSimpleProgram() {
Query q = new Query(httpEncode("?program=select * from * where myfield contains(word)"));
assertEquals("", q.getModel().getQueryTree().toString());
}
// TODO: YQL work in progress (jon)
- @Ignore
+ @Disabled
@Test
- public void testSimpleProgramParameterAlias() {
+ void testSimpleProgramParameterAlias() {
Query q = new Query(httpEncode("/sdfsd.html?yql=select * from source where myfield contains(word)"));
assertEquals("", q.getModel().getQueryTree().toString());
}
@Test
- public void testClone() {
+ void testClone() {
Query q = new Query(httpEncode("/sdfsd.html?query=this+is+a+simple+query&aParameter"));
q.getPresentation().setHighlight(new Highlight());
Query p = q.clone();
@@ -157,10 +150,10 @@ public class QueryTestCase {
}
@Test
- public void testCloneWithConnectivity() {
+ void testCloneWithConnectivity() {
List<String> l = List.of("a", "b", "c", "a");
printIt(l.stream().filter(i -> isA(i)).collect(Collectors.toList()));
- printIt(l.stream().filter(i -> ! isA(i)).collect(Collectors.toList()));
+ printIt(l.stream().filter(i -> !isA(i)).collect(Collectors.toList()));
Query q = new Query();
WordItem a = new WordItem("a");
@@ -200,18 +193,18 @@ public class QueryTestCase {
Query qClone = q.clone();
assertEquals(q, qClone);
- RankItem rankClone = (RankItem)qClone.getModel().getQueryTree().getRoot();
- AndItem and1Clone = (AndItem)rankClone.getItem(0);
- AndItem and2Clone = (AndItem)rankClone.getItem(1);
- OrItem orClone = (OrItem)and1Clone.getItem(2);
+ RankItem rankClone = (RankItem) qClone.getModel().getQueryTree().getRoot();
+ AndItem and1Clone = (AndItem) rankClone.getItem(0);
+ AndItem and2Clone = (AndItem) rankClone.getItem(1);
+ OrItem orClone = (OrItem) and1Clone.getItem(2);
- WordItem aClone = (WordItem)and1Clone.getItem(0);
- WordItem bClone = (WordItem)and1Clone.getItem(1);
- WordItem cClone = (WordItem)orClone.getItem(0);
- WordItem dClone = (WordItem)orClone.getItem(1);
- WordItem eClone = (WordItem)and1Clone.getItem(3);
- WordItem fClone = (WordItem)and2Clone.getItem(0);
- WordItem gClone = (WordItem)and2Clone.getItem(1);
+ WordItem aClone = (WordItem) and1Clone.getItem(0);
+ WordItem bClone = (WordItem) and1Clone.getItem(1);
+ WordItem cClone = (WordItem) orClone.getItem(0);
+ WordItem dClone = (WordItem) orClone.getItem(1);
+ WordItem eClone = (WordItem) and1Clone.getItem(3);
+ WordItem fClone = (WordItem) and2Clone.getItem(0);
+ WordItem gClone = (WordItem) and2Clone.getItem(1);
assertTrue(rankClone != rank);
assertTrue(and1Clone != and1);
@@ -226,12 +219,12 @@ public class QueryTestCase {
assertTrue(fClone != f);
assertTrue(gClone != g);
- assertTrue(aClone.getConnectedItem() == bClone);
- assertTrue(bClone.getConnectedItem() == cClone);
- assertTrue(cClone.getConnectedItem() == dClone);
- assertTrue(dClone.getConnectedItem() == eClone);
- assertTrue(eClone.getConnectedItem() == fClone);
- assertTrue(fClone.getConnectedItem() == gClone);
+ assertEquals(aClone.getConnectedItem(), bClone);
+ assertEquals(bClone.getConnectedItem(), cClone);
+ assertEquals(cClone.getConnectedItem(), dClone);
+ assertEquals(dClone.getConnectedItem(), eClone);
+ assertEquals(eClone.getConnectedItem(), fClone);
+ assertEquals(fClone.getConnectedItem(), gClone);
double delta = 0.0000001;
assertEquals(0.1, aClone.getConnectivity(), delta);
@@ -243,7 +236,7 @@ public class QueryTestCase {
}
@Test
- public void test_that_cloning_preserves_timeout() {
+ void test_that_cloning_preserves_timeout() {
Query original = new Query();
original.setTimeout(9876L);
@@ -252,7 +245,7 @@ public class QueryTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
// yes, this test depends on numbers which have exact IEEE representations
Query q = new Query(httpEncode("/search?timeout=500"));
assertEquals(500000L, q.getTimeout());
@@ -283,20 +276,20 @@ public class QueryTestCase {
assertEquals(42000, q.getTimeout());
assertEquals(0, q.errors().size());
- q=new Query();
+ q = new Query();
q.setTimeout(53L);
assertEquals(53L, q.properties().get("timeout"));
assertEquals(53L, q.getTimeout());
// This is the unfortunate consequence of this legacy:
- q=new Query();
+ q = new Query();
q.properties().set("timeout", 53L);
assertEquals(53L * 1000, q.properties().get("timeout"));
assertEquals(53L * 1000, q.getTimeout());
}
@Test
- public void testUnparseableTimeout() {
+ void testUnparseableTimeout() {
try {
new Query(httpEncode("/search?timeout=nalle"));
fail("Above statement should throw");
@@ -307,7 +300,7 @@ public class QueryTestCase {
}
@Test
- public void testCloneTimeout() {
+ void testCloneTimeout() {
Query q = new Query(httpEncode("/search?timeout=300ms"));
assertEquals(300, q.getTimeout());
Query clonedQ = q.clone();
@@ -315,7 +308,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution1() {
+ void testQueryProfileSubstitution1() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("myField", "Profile: %{queryProfile}", null);
Query q = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -323,7 +316,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSourceAccess() {
+ void testQueryProfileSourceAccess() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("myField", "Profile: %{queryProfile}", null);
Query query = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -333,7 +326,7 @@ public class QueryTestCase {
}
@Test
- public void testBooleanParameter() {
+ void testBooleanParameter() {
QueryProfile profile = new QueryProfile("myProfile");
Query query = new Query("/?query=something&ranking.softtimeout.enable=false", profile.compile(null));
assertFalse(query.properties().getBoolean("ranking.softtimeout.enable"));
@@ -341,7 +334,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution2() {
+ void testQueryProfileSubstitution2() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("model.language", "en-US", null);
profile.set("myField", "Language: %{lang}", null);
@@ -350,7 +343,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution3() {
+ void testQueryProfileSubstitution3() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("model.locale", "en-US", null);
profile.set("myField", "Language: %{lang}, locale: %{locale}", null);
@@ -359,7 +352,7 @@ public class QueryTestCase {
}
@Test
- public void testTimeoutInRequestOverridesQueryProfile() {
+ void testTimeoutInRequestOverridesQueryProfile() {
QueryProfile profile = new QueryProfile("test");
profile.set("timeout", 318, null);
Query q = new Query(QueryTestCase.httpEncode("/search?timeout=500"), profile.compile(null));
@@ -367,7 +360,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileClearAndSet() {
+ void testQueryProfileClearAndSet() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("b", "b-value", null);
Query q = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -375,7 +368,7 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value");
q.properties().set("b", null, null);
- assertContains(q.properties().listProperties("b"), (Object)null);
+ assertContains(q.properties().listProperties("b"), (Object) null);
q.properties().set("b", "b-value", null);
assertEquals("b-value", q.properties().get("b"));
@@ -383,7 +376,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileClearValue() {
+ void testQueryProfileClearValue() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("a", "a-value", null);
profile.set("b", "b-value", null);
@@ -397,10 +390,10 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value", "b.c-value", "b.d-value");
q.properties().set("a", null, null);
- assertEquals(null, q.properties().get("a"));
+ assertNull(q.properties().get("a"));
q.properties().set("b", null, null);
- assertEquals(null, q.properties().get("b"));
+ assertNull(q.properties().get("b"));
assertEquals("b.c-value", q.properties().get("b.c"));
assertEquals("b.d-value", q.properties().get("b.d"));
assertContains(q.properties().listProperties("b"), null, "b.c-value", "b.d-value");
@@ -413,67 +406,67 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value", "b.c-value", "b.d-value", "b.e-value", "b.f-value");
q.properties().clearAll("b");
- assertEquals(null, q.properties().get("b"));
- assertEquals(null, q.properties().get("b.c"));
- assertEquals(null, q.properties().get("b.d"));
- assertEquals(null, q.properties().get("b.e"));
- assertEquals(null, q.properties().get("b.f"));
- assertContains(q.properties().listProperties("b"), (Object)null);
+ assertNull(q.properties().get("b"));
+ assertNull(q.properties().get("b.c"));
+ assertNull(q.properties().get("b.d"));
+ assertNull(q.properties().get("b.e"));
+ assertNull(q.properties().get("b.f"));
+ assertContains(q.properties().listProperties("b"), (Object) null);
}
@Test
- public void testNotEqual() {
+ void testNotEqual() {
Query q = new Query("/?query=something+test&nocache");
Query p = new Query("/?query=something+test");
- assertEquals(q,p);
- assertEquals(q.hashCode(),p.hashCode());
+ assertEquals(q, p);
+ assertEquals(q.hashCode(), p.hashCode());
Query r = new Query("?query=something+test&hits=5");
- assertNotSame(q,r);
- assertNotSame(q.hashCode(),r.hashCode());
+ assertNotSame(q, r);
+ assertNotSame(q.hashCode(), r.hashCode());
}
@Test
- public void testEqual() {
- assertEquals(new Query("?query=12").hashCode(),new Query("?query=12").hashCode());
- assertEquals(new Query("?query=12"),new Query("?query=12"));
+ void testEqual() {
+ assertEquals(new Query("?query=12").hashCode(), new Query("?query=12").hashCode());
+ assertEquals(new Query("?query=12"), new Query("?query=12"));
}
@Test
- public void testUtf8Decoding() {
+ void testUtf8Decoding() {
Query q = new Query("/?query=beyonc%C3%A9");
assertEquals("WEAKAND(100) beyonc\u00e9", q.getModel().getQueryTree().toString());
}
@Test
- public void testQueryProfileInSubstitution() {
+ void testQueryProfileInSubstitution() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.setOverridable("u", false, DimensionValues.empty);
- testProfile.set("d","e", null);
- testProfile.set("u","11", null);
+ testProfile.set("d", "e", null);
+ testProfile.set("u", "11", null);
testProfile.set("foo.bar", "wiz", null);
Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"),
- testProfile.compile(null));
+ testProfile.compile(null));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
}
@Test
- public void testDefaultIndex() {
+ void testDefaultIndex() {
Query q = new Query("?query=hi%20hello%20keyword:kanoo%20" +
- "default:munkz%20%22phrases+too%22&default-index=def");
+ "default:munkz%20%22phrases+too%22&default-index=def");
assertEquals("WEAKAND(100) def:hi def:hello keyword:kanoo default:munkz def:\"phrases too\"",
- q.getModel().getQueryTree().toString());
+ q.getModel().getQueryTree().toString());
}
@Test
- public void testHashCode() {
+ void testHashCode() {
Query p = new Query("?query=foo&type=any");
Query q = new Query("?query=foo&type=all");
assertTrue(p.hashCode() != q.hashCode());
}
@Test
- public void testSimpleQueryParsing() {
+ void testSimpleQueryParsing() {
Query q = new Query("/search?query=foobar&offset=10&hits=20");
assertEquals("WEAKAND(100) foobar", q.getModel().getQueryTree().toString());
assertEquals(10, q.getOffset());
@@ -482,15 +475,15 @@ public class QueryTestCase {
/** "input.*" is an alias for "ranking.feature.*", but just "input" is not */
@Test
- public void testPrefixAlias() {
+ void testPrefixAlias() {
Query q = new Query("/search?query=foobar&input=foo",
- new QueryProfile("test").compile(null));
+ new QueryProfile("test").compile(null));
assertEquals("foo", q.properties().get("input"));
}
/** Test that GET parameter names are case in-sensitive */
@Test
- public void testGETParametersCase() {
+ void testGETParametersCase() {
Query q = new Query("?QUERY=testing&hits=10&oFfSeT=10");
assertEquals("testing", q.getModel().getQueryString());
assertEquals(10, q.getHits());
@@ -499,19 +492,19 @@ public class QueryTestCase {
/** Test that we get the last value if a parameter is assigned multiple times */
@Test
- public void testRepeatedParameter() {
+ void testRepeatedParameter() {
Query q = new Query("?query=test&hits=5&hits=10");
assertEquals(10, q.getHits());
}
@Test
- public void testNoCache() {
+ void testNoCache() {
Query q = new Query("search?query=foobar&nocache");
assertTrue(q.getNoCache());
}
@Test
- public void testSessionCache() {
+ void testSessionCache() {
Query q = new Query("search?query=foobar&groupingSessionCache");
assertTrue(q.getGroupingSessionCache());
q = new Query("search?query=foobar");
@@ -531,7 +524,7 @@ public class QueryTestCase {
}
@Test
- public void testSetting() {
+ void testSetting() {
Query q = new Query();
q.properties().set("test", "test");
assertEquals(q.properties().get("test"), "test");
@@ -544,21 +537,21 @@ public class QueryTestCase {
}
@Test
- public void testAlias() {
+ void testAlias() {
Query q = new Query("search?query=testing&language=en");
assertEquals(q.getModel().getLanguage(), q.properties().get("model.language"));
}
@Test
- public void testTracing() {
+ void testTracing() {
Query q = new Query("?query=foo&type=all&traceLevel=2");
assertEquals(2, q.getTrace().getLevel());
q.trace(true, 1, "trace1");
- q.trace(false,2, "trace2");
+ q.trace(false, 2, "trace2");
q.trace(true, 3, "Ignored");
q.trace(true, 2, "trace3-1", ", ", "trace3-2");
- q.trace(false,1, "trace4-1", ", ", "trace4-2");
- q.trace(false,3, "Ignored-1", "Ignored-2");
+ q.trace(false, 1, "trace4-1", ", ", "trace4-2");
+ q.trace(false, 3, "Ignored-1", "Ignored-2");
Set<String> traces = new HashSet<>();
for (String trace : q.getContext(true).getTrace().traceNode().descendants(String.class))
traces.add(trace);
@@ -569,10 +562,10 @@ public class QueryTestCase {
}
@Test
- public void testNullTracing() {
+ void testNullTracing() {
Query q = new Query("?query=foo&traceLevel=2");
assertEquals(2, q.getTrace().getLevel());
- q.trace(false,2, "trace2 ", null);
+ q.trace(false, 2, "trace2 ", null);
Set<String> traces = new HashSet<>();
for (String trace : q.getContext(true).getTrace().traceNode().descendants(String.class))
traces.add(trace);
@@ -580,20 +573,20 @@ public class QueryTestCase {
}
@Test
- public void testExplain() {
+ void testExplain() {
Query q = new Query("?query=foo&explainLevel=2");
assertEquals(2, q.getTrace().getExplainLevel());
assertEquals(0, q.getTrace().getLevel());
}
@Test
- public void testQueryPropertyResolveTracing() {
+ void testQueryPropertyResolveTracing() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.setOverridable("u", false, DimensionValues.empty);
- testProfile.set("d","e", null);
- testProfile.set("u","11", null);
+ testProfile.set("d", "e", null);
+ testProfile.set("u", "11", null);
testProfile.set("foo.bar", "wiz", null);
- Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"),testProfile.compile(null));
+ Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"), testProfile.compile(null));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
assertTrue(contains("query: a:>5 (from request)", traceLines));
@@ -605,7 +598,7 @@ public class QueryTestCase {
}
@Test
- public void testNonleafInRequestDoesNotOverrideProfile() {
+ void testNonleafInRequestDoesNotOverrideProfile() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.set("a.b", "foo", null);
testProfile.freeze();
@@ -622,7 +615,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyResolveTracing2() {
+ void testQueryPropertyResolveTracing2() {
QueryProfile defaultProfile = new QueryProfile("default");
defaultProfile.freeze();
Query q = new Query(QueryTestCase.httpEncode("?query=dvd&a.b=foo&tracelevel=9"), defaultProfile.compile(null));
@@ -633,7 +626,7 @@ public class QueryTestCase {
}
@Test
- public void testNativeProperties() {
+ void testNativeProperties() {
Set<String> nativeProperties = Query.nativeProperties.stream().map(CompoundName::toString).collect(Collectors.toSet());
// Sample the content
assertTrue(nativeProperties.contains("hits"));
@@ -642,16 +635,16 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyListingAndTrace() {
+ void testQueryPropertyListingAndTrace() {
QueryProfile defaultProfile = new QueryProfile("default");
defaultProfile.setDimensions(new String[]{"x"});
- defaultProfile.set("a.b","a.b-x1-value", new String[] {"x1"}, null);
+ defaultProfile.set("a.b", "a.b-x1-value", new String[]{"x1"}, null);
defaultProfile.set("a.b", "a.b-x2-value", new String[]{"x2"}, null);
defaultProfile.freeze();
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b-x1-value", propertyList.get("a.b"));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
@@ -660,14 +653,14 @@ public class QueryTestCase {
{
Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a");
+ Map<String, Object> propertyList = q.properties().listProperties("a");
assertEquals(1, propertyList.size());
assertEquals("a.b-x1-value", propertyList.get("b"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b-x2-value", propertyList.get("a.b"));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
@@ -676,45 +669,45 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyListingThreeLevel() {
+ void testQueryPropertyListingThreeLevel() {
QueryProfile defaultProfile = new QueryProfile("default");
- defaultProfile.setDimensions(new String[] {"x"});
+ defaultProfile.setDimensions(new String[]{"x"});
defaultProfile.set("a.b.c", "a.b.c-x1-value", new String[]{"x1"}, null);
defaultProfile.set("a.b.c", "a.b.c-x2-value", new String[]{"x2"}, null);
defaultProfile.freeze();
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b.c-x1-value", propertyList.get("a.b.c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a");
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties("a");
assertEquals(1, propertyList.size());
assertEquals("a.b.c-x1-value", propertyList.get("b.c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a.b");
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties("a.b");
assertEquals(1, propertyList.size());
assertEquals("a.b.c-x1-value", propertyList.get("c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b.c-x2-value", propertyList.get("a.b.c"));
}
}
@Test
- public void testQueryPropertyReplacement() {
+ void testQueryPropertyReplacement() {
QueryProfile defaultProfile = new QueryProfile("default");
- defaultProfile.set("model.queryString","myquery", null);
- defaultProfile.set("queryUrl","http://provider:80?query=%{model.queryString}", null);
+ defaultProfile.set("model.queryString", "myquery", null);
+ defaultProfile.set("queryUrl", "http://provider:80?query=%{model.queryString}", null);
defaultProfile.freeze();
Query q1 = new Query(QueryTestCase.httpEncode(""), defaultProfile.compile(null));
@@ -725,17 +718,17 @@ public class QueryTestCase {
assertEquals("foo", q2.getModel().getQueryString());
assertEquals("http://provider:80?query=foo", q2.properties().get("queryUrl"));
- Query q3 = new Query(QueryTestCase.httpEncode("?query=foo"),defaultProfile.compile(null));
- assertEquals("foo",q3.getModel().getQueryString());
- assertEquals("http://provider:80?query=foo",q3.properties().get("queryUrl"));
+ Query q3 = new Query(QueryTestCase.httpEncode("?query=foo"), defaultProfile.compile(null));
+ assertEquals("foo", q3.getModel().getQueryString());
+ assertEquals("http://provider:80?query=foo", q3.properties().get("queryUrl"));
- Query q4 = new Query(QueryTestCase.httpEncode("?query=foo"),defaultProfile.compile(null));
+ Query q4 = new Query(QueryTestCase.httpEncode("?query=foo"), defaultProfile.compile(null));
q4.getModel().setQueryString("bar");
- assertEquals("http://provider:80?query=bar",q4.properties().get("queryUrl"));
+ assertEquals("http://provider:80?query=bar", q4.properties().get("queryUrl"));
}
@Test
- public void testNoQueryString() {
+ void testNoQueryString() {
Query q = new Query(httpEncode("?tracelevel=1"));
Chain<Searcher> chain = new Chain<>(new RandomSearcher());
new Execution(chain, Execution.Context.createContextStub()).search(q);
@@ -743,7 +736,7 @@ public class QueryTestCase {
}
@Test
- public void testSetCollapseField() {
+ void testSetCollapseField() {
Query q = new Query(httpEncode("?collapsefield=foo&presentation.format=tiled"));
assertEquals("foo", q.properties().get("collapsefield"));
assertEquals("tiled", q.properties().get("presentation.format"));
@@ -751,44 +744,44 @@ public class QueryTestCase {
}
@Test
- public void testSetNullProperty() {
+ void testSetNullProperty() {
QueryProfile profile = new QueryProfile("test");
- profile.set("property","initialValue", null);
+ profile.set("property", "initialValue", null);
Query query = new Query(httpEncode("?query=test"), profile.compile(null));
- assertEquals("initialValue",query.properties().get("property"));
+ assertEquals("initialValue", query.properties().get("property"));
query.properties().set("property", null);
assertNull(query.properties().get("property"));
}
@Test
- public void testSetNullPropertyNoQueryProfile() {
+ void testSetNullPropertyNoQueryProfile() {
Query query = new Query();
query.properties().set("a", null);
assertNull(query.properties().get("a"));
}
@Test
- public void testMissingParameter() {
+ void testMissingParameter() {
Query q = new Query("?query=foo&hits=");
assertEquals(0, q.errors().size());
}
@Test
- public void testModelProperties() {
+ void testModelProperties() {
{
Query query = new Query();
query.properties().set("model.searchPath", "foo");
- assertEquals("Set dynamic get dynamic works","foo", query.properties().get("model.searchPath"));
- assertEquals("Set dynamic get static works","foo", query.getModel().getSearchPath());
+ assertEquals("foo", query.properties().get("model.searchPath"), "Set dynamic get dynamic works");
+ assertEquals("foo", query.getModel().getSearchPath(), "Set dynamic get static works");
Map<String, Object> properties = query.properties().listProperties();
- assertEquals("Listing built-in properties works", "foo", properties.get("model.searchPath"));
+ assertEquals("foo", properties.get("model.searchPath"), "Listing built-in properties works");
}
{
Query query = new Query();
query.getModel().setSearchPath("foo");
- assertEquals("Set static get dynamic works","foo", query.properties().get("model.searchPath"));
- assertEquals("Set static get static works","foo", query.getModel().getSearchPath());
+ assertEquals("foo", query.properties().get("model.searchPath"), "Set static get dynamic works");
+ assertEquals("foo", query.getModel().getSearchPath(), "Set static get static works");
}
{
@@ -801,7 +794,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsUniquePerQuery() {
+ void testThatSessionIdIsUniquePerQuery() {
Query q = new Query();
assertNull(q.getSessionId());
assertNull(q.getSessionId());
@@ -816,8 +809,9 @@ public class QueryTestCase {
assertNotEquals(q.getSessionId(), q2.getSessionId("node-0"));
assertNotEquals(q.getSessionId().toString(), q2.getSessionId("node-0").toString());
}
+
@Test
- public void testThatCloneGetANewSessionId() {
+ void testThatCloneGetANewSessionId() {
Query q = new Query();
q.getSessionId("node-0");
Query clonedQ = q.clone();
@@ -826,7 +820,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsUniquePerRankProfilePerQuery() {
+ void testThatSessionIdIsUniquePerRankProfilePerQuery() {
Query q = new Query();
SessionId s1 = q.getSessionId("node-0");
q.getRanking().setProfile("my-profile");
@@ -835,7 +829,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsNotSharedIfCreatedAfterClone() {
+ void testThatSessionIdIsNotSharedIfCreatedAfterClone() {
Query q = new Query();
Query q2 = q.clone();
assertNull(q.getSessionId());
@@ -849,7 +843,7 @@ public class QueryTestCase {
}
@Test
- public void testPositiveTerms() {
+ void testPositiveTerms() {
Query q = new Query(httpEncode("/?query=-a \"b c\" d e"));
Item i = q.getModel().getQueryTree().getRoot();
List<IndexedItem> l = QueryTree.getPositiveTerms(i);
@@ -857,18 +851,18 @@ public class QueryTestCase {
}
@Test
- public void testHeuristicLanguageDetectionTextExtraction() {
+ void testHeuristicLanguageDetectionTextExtraction() {
assertDetectionText("b ", "a:b", "text:a", "text:default");
assertDetectionText("b ", "b", "text:default");
- assertDetectionText("b ", "b","text:b", "text:default");
- assertDetectionText("a b ", "a:b","text:b", "text:default");
- assertDetectionText("foo bar fuz ", "foo a:bar --() fuz","text:a", "text:default");
- assertDetectionText(" 彭 博士 觀 風向 彭 博士 觀 風向 彭 博士 觀 風向 ","headline:\"彭 博士 觀 風向\" content:\"彭 博士 觀 風向\" description:\"彭 博士 觀 風向\" sddocname:contentindexing!0 embargo:<1484665288753!0 expires:>1484665288753!0",
- "text:headline", "text:content", "text:description", "text:default", "nontext:tags", "nontext:sddocname", "nontext:embargo", "nontext:expires");
+ assertDetectionText("b ", "b", "text:b", "text:default");
+ assertDetectionText("a b ", "a:b", "text:b", "text:default");
+ assertDetectionText("foo bar fuz ", "foo a:bar --() fuz", "text:a", "text:default");
+ assertDetectionText(" 彭 博士 觀 風向 彭 博士 觀 風向 彭 博士 觀 風向 ", "headline:\"彭 博士 觀 風向\" content:\"彭 博士 觀 風向\" description:\"彭 博士 觀 風向\" sddocname:contentindexing!0 embargo:<1484665288753!0 expires:>1484665288753!0",
+ "text:headline", "text:content", "text:description", "text:default", "nontext:tags", "nontext:sddocname", "nontext:embargo", "nontext:expires");
}
@Test
- public void testCompositeChildVerification() {
+ void testCompositeChildVerification() {
CompositeItem root = new AndItem();
try {
root.addItem(null);
@@ -908,7 +902,7 @@ public class QueryTestCase {
}
@Test
- public void queryLanguageAlternatives() {
+ void queryLanguageAlternatives() {
// Given:
// Person = {
// Name: 'Joe',
@@ -967,13 +961,13 @@ public class QueryTestCase {
}
@Test
- public void testImplicitPhraseIsDefault() {
+ void testImplicitPhraseIsDefault() {
Query query = new Query(httpEncode("?query=it's fine"));
assertEquals("WEAKAND(100) (SAND it s) fine", query.getModel().getQueryTree().toString());
}
@Test
- public void testImplicitPhrase() {
+ void testImplicitPhrase() {
Query query = new Query(httpEncode("?query=myfield:it's myfield:a.b myfield:c&type=all"));
SearchDefinition test = new SearchDefinition("test");
@@ -988,7 +982,7 @@ public class QueryTestCase {
}
@Test
- public void testImplicitAnd() {
+ void testImplicitAnd() {
Query query = new Query(httpEncode("?query=myfield:it's myfield:a.b myfield:c"));
SearchDefinition test = new SearchDefinition("test");
@@ -1001,18 +995,18 @@ public class QueryTestCase {
assertEquals("WEAKAND(100) (SAND myfield:it myfield:s) (AND myfield:a myfield:b) myfield:c", query.getModel().getQueryTree().toString());
// 'it' and 's' should have connectivity 1
- WeakAndItem root = (WeakAndItem)query.getModel().getQueryTree().getRoot();
- AndSegmentItem sand = (AndSegmentItem)root.getItem(0);
- WordItem it = (WordItem)sand.getItem(0);
+ WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
+ AndSegmentItem sand = (AndSegmentItem) root.getItem(0);
+ WordItem it = (WordItem) sand.getItem(0);
assertEquals("it", it.getWord());
- WordItem s = (WordItem)sand.getItem(1);
+ WordItem s = (WordItem) sand.getItem(1);
assertEquals("s", s.getWord());
assertEquals(s, it.getConnectedItem());
assertEquals(1.0, it.getConnectivity(), 0.00000001);
}
@Test
- public void testImplicitAndConnectivity() {
+ void testImplicitAndConnectivity() {
SearchDefinition test = new SearchDefinition("test");
Index myField = new Index("myfield");
myField.addCommand("phrase-segmenting false");
@@ -1024,7 +1018,7 @@ public class QueryTestCase {
query.getModel().setExecution(new Execution(Execution.Context.createContextStub(new IndexFacts(indexModel))));
assertEquals("WEAKAND(100) (AND myfield:b myfield:c myfield:d)", query.getModel().getQueryTree().toString());
WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
- AndItem and = (AndItem)root.getItem(0);
+ AndItem and = (AndItem) root.getItem(0);
WordItem b = (WordItem) and.getItem(0);
WordItem c = (WordItem) and.getItem(1);
WordItem d = (WordItem) and.getItem(2);
@@ -1040,7 +1034,7 @@ public class QueryTestCase {
assertEquals("WEAKAND(100) myfield:a (AND myfield:b myfield:c myfield:d) myfield:e", query.getModel().getQueryTree().toString());
WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
WordItem a = (WordItem) root.getItem(0);
- AndItem and = (AndItem)root.getItem(1);
+ AndItem and = (AndItem) root.getItem(1);
WordItem b = (WordItem) and.getItem(0);
WordItem c = (WordItem) and.getItem(1);
WordItem d = (WordItem) and.getItem(2);
@@ -1056,7 +1050,7 @@ public class QueryTestCase {
}
@Test
- public void testImplicitAndInPhrase() {
+ void testImplicitAndInPhrase() {
Query query = new Query(httpEncode("?query=myfield:\"it's fine\""));
SearchDefinition test = new SearchDefinition("test");
@@ -1071,7 +1065,7 @@ public class QueryTestCase {
}
@Test
- public void testOldStyleSelect() {
+ void testOldStyleSelect() {
// The same as testOldStyleSelectAndNativeQueryProfileType but not inheriting native
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("mytype");
@@ -1081,15 +1075,15 @@ public class QueryTestCase {
registry.getTypeRegistry().register(type);
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(httpEncode("?query=sddocname:sentence&select=all(group(context_id) max(10) each(each(output(summary()))))"),
- cRegistry.findQueryProfile("default"));
+ cRegistry.findQueryProfile("default"));
GroupingQueryParser parser = new GroupingQueryParser();
parser.search(query, new Execution(parser, Execution.Context.createContextStub()));
assertEquals("[all(group(context_id) max(10) each(each(output(summary())))), all(group(context_id) max(10) each(each(output(summary()))))]",
- query.getSelect().getGrouping().toString());
+ query.getSelect().getGrouping().toString());
}
@Test
- public void testOldStyleSelectAndNativeQueryProfileType() {
+ void testOldStyleSelectAndNativeQueryProfileType() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("mytype");
type.inherited().add(registry.getType("native"));
@@ -1099,11 +1093,11 @@ public class QueryTestCase {
registry.getTypeRegistry().register(type);
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(httpEncode("?query=sddocname:sentence&select=all(group(context_id) max(10) each(each(output(summary()))))"),
- cRegistry.findQueryProfile("default"));
+ cRegistry.findQueryProfile("default"));
GroupingQueryParser parser = new GroupingQueryParser();
parser.search(query, new Execution(parser, Execution.Context.createContextStub()));
assertEquals("[all(group(context_id) max(10) each(each(output(summary())))), all(group(context_id) max(10) each(each(output(summary()))))]",
- query.getSelect().getGrouping().toString());
+ query.getSelect().getGrouping().toString());
}
/**
@@ -1111,7 +1105,7 @@ public class QueryTestCase {
* This is special because presentation.format is a native query profile.
*/
@Test
- public void testSettingNativeQueryProfileValueInQueryProfile() {
+ void testSettingNativeQueryProfileValueInQueryProfile() {
{
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("default");
@@ -1140,7 +1134,7 @@ public class QueryTestCase {
type.inherited().add(registry.getType("native"));
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding)", "tensor(x[5])"),
- registry.getTypeRegistry());
+ registry.getTypeRegistry());
QueryProfile profile = new QueryProfile("default");
profile.setType(type);
registry.register(profile);
@@ -1169,13 +1163,12 @@ public class QueryTestCase {
private void assertContains(Map<String, Object> properties, Object ... expectedValues) {
if (expectedValues == null) {
assertEquals(1, properties.size());
- assertTrue("Contains value null", properties.containsValue(null));
+ assertTrue(properties.containsValue(null), "Contains value null");
}
else {
- assertEquals(properties + " contains values " + Arrays.toString(expectedValues),
- expectedValues.length, properties.size());
+ assertEquals(expectedValues.length, properties.size(), properties + " contains values " + Arrays.toString(expectedValues));
for (Object expectedValue : expectedValues)
- assertTrue("Contains value " + expectedValue, properties.containsValue(expectedValue));
+ assertTrue(properties.containsValue(expectedValue), "Contains value " + expectedValue);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java b/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
index cc47ec813df..a1f3a3a5a1c 100644
--- a/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -12,14 +12,14 @@ import static org.junit.Assert.assertEquals;
public class RequestParameterPreservationTestCase {
@Test
- public void testPreservation() {
- Query query=new Query("?query=test...&offset=15&hits=10");
- query.setWindow(25,13);
- assertEquals(25,query.getOffset());
- assertEquals(13,query.getHits());
+ void testPreservation() {
+ Query query = new Query("?query=test...&offset=15&hits=10");
+ query.setWindow(25, 13);
+ assertEquals(25, query.getOffset());
+ assertEquals(13, query.getHits());
assertEquals("15", query.getHttpRequest().getProperty("offset"));
assertEquals("10", query.getHttpRequest().getProperty("hits"));
- assertEquals("test...",query.getHttpRequest().getProperty("query"));
+ assertEquals("test...", query.getHttpRequest().getProperty("query"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
index 8a6a48afd9f..3d4f52472a8 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
-
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.fastsearch.FastHit;
import com.yahoo.search.Query;
@@ -31,7 +29,7 @@ public class FieldFilterTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
Query query = new Query("?query=test");
@@ -58,7 +56,7 @@ public class FieldFilterTestCase {
return h;
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
searchChain = null;
context = null;
@@ -66,7 +64,7 @@ public class FieldFilterTestCase {
}
@Test
- public final void testBasic() {
+ final void testBasic() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD_B);
Result result = execution.search(query);
execution.fill(result);
@@ -77,7 +75,7 @@ public class FieldFilterTestCase {
}
@Test
- public final void testNoFiltering() {
+ final void testNoFiltering() {
final Query query = new Query("?query=test");
Result result = execution.search(query);
execution.fill(result);
diff --git a/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
index 890f847ebfe..1e6e29bb700 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
@@ -5,6 +5,7 @@ import com.google.common.base.Charsets;
import com.yahoo.component.chain.Chain;
import com.yahoo.language.Language;
import com.yahoo.language.simple.SimpleLinguistics;
+import com.yahoo.processing.IllegalInputException;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
@@ -17,18 +18,17 @@ import com.yahoo.search.query.Sorting.UcaSorter;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Smoke test for first generation YQL+ integration.
@@ -39,14 +39,14 @@ public class MinimalQueryInserterTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
searchChain = new Chain<>(new MinimalQueryInserter());
context = Execution.Context.createContextStub();
execution = new Execution(searchChain, context);
}
- @After
+ @AfterEach
public void tearDown() {
searchChain = null;
context = null;
@@ -54,7 +54,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void requireThatGroupingStepsAreAttachedToQuery() {
+ void requireThatGroupingStepsAreAttachedToQuery() {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
@@ -68,24 +68,24 @@ public class MinimalQueryInserterTestCase {
assertEquals("foo", query.getPresentation().getSummaryFields().toArray(new String[1])[0]);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))");
+ "| all(group(a) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[]all(group(a) each(output(count())))]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count()))) " +
- "| all(group(b) each(output(count())))");
+ "| all(group(a) each(output(count()))) " +
+ "| all(group(b) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[]all(group(a) each(output(count())))," +
- " []all(group(b) each(output(count())))]", query);
+ " []all(group(b) each(output(count())))]", query);
}
@Test
- public void requireThatGroupingContinuationsAreAttachedToQuery() {
+ void requireThatGroupingContinuationsAreAttachedToQuery() {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
@@ -96,36 +96,36 @@ public class MinimalQueryInserterTestCase {
assertGrouping("[]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(a) each(output(count())))");
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(a) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(a) each(output(count()))) " +
- "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
- "all(group(b) each(output(count())))");
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(a) each(output(count()))) " +
+ "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
+ "all(group(b) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))," +
- " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]", query);
+ " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]", query);
}
- @Test
- @Ignore
// TODO: YQL work in progress (jon)
- public void testTmp() {
+ @Test
+ @Disabled
+ void testTmp() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
//execution.search(query);
assertEquals("AND title:madonna easilyRecognizedString", query.getModel().getQueryTree().toString());
}
@Test
- public void testSearch() {
+ void testSearch() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -133,25 +133,25 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testExplicitLanguageIsHonoredWithVerbatimQuery() {
+ void testExplicitLanguageIsHonoredWithVerbatimQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?language=ja" + "&yql=select%20ignoredField%20from%20ignoredsource%20where%20title%20contains%20%22" + encode(japaneseWord) + "%22");
execution.search(query);
assertEquals(Language.JAPANESE, query.getModel().getParsingLanguage());
- assertEquals("title:"+ japaneseWord, query.getModel().getQueryTree().toString());
+ assertEquals("title:" + japaneseWord, query.getModel().getQueryTree().toString());
}
@Test
- public void testUserLanguageIsDetectedWithVerbatimQuery() {
+ void testUserLanguageIsDetectedWithVerbatimQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?yql=select%20ignoredField%20from%20ignoredsource%20where%20title%20contains%20%22" + encode(japaneseWord) + "%22");
execution.search(query);
assertEquals(Language.JAPANESE, query.getModel().getParsingLanguage());
- assertEquals("title:"+ japaneseWord, query.getModel().getQueryTree().toString());
+ assertEquals("title:" + japaneseWord, query.getModel().getQueryTree().toString());
}
@Test
- public void testUserLanguageIsDetectedWithUserInput() {
+ void testUserLanguageIsDetectedWithUserInput() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?userString=" + encode(japaneseWord) + "&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userInput(@userString)");
execution.search(query);
@@ -160,7 +160,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testUserLanguageIsDetectedWithUserQuery() {
+ void testUserLanguageIsDetectedWithUserQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?query=" + encode(japaneseWord) + "&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
@@ -169,14 +169,14 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testUserQueryFailsWithoutArgument() {
+ void testUserQueryFailsWithoutArgument() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
}
@Test
- public void testSearchFromAllSourcesWithUserSource() {
+ void testSearchFromAllSourcesWithUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&sources=abc&yql=select%20ignoredfield%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -184,7 +184,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromAllSourcesWithoutUserSource() {
+ void testSearchFromAllSourcesWithoutUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -192,7 +192,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromSomeSourcesWithoutUserSource() {
+ void testSearchFromSomeSourcesWithoutUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -202,7 +202,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromSomeSourcesWithUserSource() {
+ void testSearchFromSomeSourcesWithUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&sources=abc&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -213,7 +213,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public final void testSearchFromSomeSourcesWithOverlappingUserSource() {
+ final void testSearchFromSomeSourcesWithOverlappingUserSource() {
final Query query = new Query("search/?query=easilyRecognizedString&sources=abc,sourceA&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -224,17 +224,17 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testLimitAndOffset() {
+ void testLimitAndOffset() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2031offset%207");
execution.search(query);
assertEquals(7, query.getOffset());
assertEquals(24, query.getHits());
assertEquals("select * from sources * where title contains \"madonna\" limit 31 offset 7",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testMaxOffset() {
+ void testMaxOffset() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2040031offset%2040000");
Result r = execution.search(query);
assertEquals(1, r.hits().getErrorHit().errors().size());
@@ -244,7 +244,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testMaxLimit() {
+ void testMaxLimit() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2040000offset%207");
Result r = execution.search(query);
assertEquals(1, r.hits().getErrorHit().errors().size());
@@ -254,7 +254,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20timeout%2051");
execution.search(query);
assertEquals(51L, query.getTimeout());
@@ -262,12 +262,12 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testTimeoutWithGrouping() {
+ void testTimeoutWithGrouping() {
var select = "select x, y, z from sources * "
+ "where (x > 0 AND y contains \"foo\" AND z contains \"bar\") "
+ "order by x limit 20 offset 10 timeout 30 "
+ "| all(group(y) max(3) each(output(count())))";
- Query query = new Query("search/?yql="+ URLEncoder.encode(select, Charsets.UTF_8));
+ Query query = new Query("search/?yql=" + URLEncoder.encode(select, Charsets.UTF_8));
execution.search(query);
assertEquals(10, query.getHits());
@@ -279,7 +279,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testOrdering() {
+ void testOrdering() {
{
String yql = "select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20order%20by%20something%2C%20shoesize%20desc%20limit%20300%20timeout%203";
Query query = new Query("search/?yql=" + yql);
@@ -333,24 +333,54 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testStringRepresentation() {
+ void testStringRepresentation() {
String yql = "select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20order%20by%20something%2C%20shoesize%20desc%20limit%20300%20timeout%203";
Query query = new Query("search/?yql=" + yql);
execution.search(query);
assertEquals("select ignoredfield from ignoredsource where title contains \"madonna\" order by something, shoesize desc limit 300 timeout 3",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
Query query = new Query("?yql=select%20%2A%20from%20sources%20%2A%20where%20%5B%7B%22defaultIndex%22%3A%20%22default%22%2C%22grammar%22%3A%20%22web%22%2C%22stem%22%3A%20true%2C%22allowEmpty%22%3A%20true%7D%5DuserInput%28%40animal%29%3B&animal=m%26m%27s&tracelevel=3");
execution.search(query);
assertEquals("select * from sources * where (default contains \"m\" AND default contains ({origin: {original: \"m\\'s\", offset: 0, length: 3}, andSegmenting: true}phrase(\"m\", \"s\")))",
- query.yqlRepresentation());
+ query.yqlRepresentation());
+ }
+
+ @Test
+ void globalMaxGroupsIsCarriedOver() {
+ URIBuilder builder = new URIBuilder();
+ builder.setPath("search/");
+ builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
+ "| all(group(a) each(output(count())))");
+ Query query = new Query(builder.toString());
+ query.properties().set("grouping.globalMaxGroups", -1);
+ execution.search(query);
+ assertEquals(1, query.getSelect().getGrouping().size());
+ assertEquals(-1L, query.getSelect().getGrouping().get(0).globalMaxGroups().getAsLong());
+ }
+
+ @Test
+ void globalMaxGroupsCannotBeSetInRequest() {
+ try {
+ URIBuilder builder = new URIBuilder();
+ builder.setPath("search/");
+ builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
+ "| all(group(a) each(output(count())))");
+ builder.setParameter("grouping.globalMaxGroups", "-1");
+ Query query = new Query(builder.toString());
+ execution.search(query);
+ fail();
+ }
+ catch (IllegalInputException e) {
+ assertEquals("grouping.globalMaxGroups must be specified in a query profile.", e.getCause().getMessage());
+ }
}
@Test
- public void verifyThatWarmupIsSane() {
+ void verifyThatWarmupIsSane() {
assertTrue(MinimalQueryInserter.warmup());
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
index 44f784e96f3..8037ea097ab 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.search.yql;
import com.yahoo.prelude.query.WeightedSetItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class ParameterListParserTestCase {
@Test
- public void testMapParsing() {
+ void testMapParsing() {
assertParsed("{}", Map.of());
assertParsed("{a:12}", Map.of("a", 12));
assertParsed("{'a':12}", Map.of("a", 12));
@@ -27,7 +27,7 @@ public class ParameterListParserTestCase {
}
@Test
- public void testArrayParsing() {
+ void testArrayParsing() {
assertParsed("[]", Map.of());
assertParsed("[[0,12]]", Map.of(0L, 12));
assertParsed("[[0,12],[1,13]]", Map.of(0L, 12, 1L, 13));
@@ -39,9 +39,9 @@ public class ParameterListParserTestCase {
WeightedSetItem item = new WeightedSetItem("test");
ParameterListParser.addItemsFromString(string, item);
for (var entry : expected.entrySet()) {
- assertEquals("Key '" + entry.getKey() + "'", entry.getValue(), item.getTokenWeight(entry.getKey()));
+ assertEquals(entry.getValue(), item.getTokenWeight(entry.getKey()), "Key '" + entry.getKey() + "'");
}
- assertEquals("Token count is correct", expected.size(), item.getNumTokens());
+ assertEquals(expected.size(), item.getNumTokens(), "Token count is correct");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
index 30254aa5738..3f04f36f64e 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.searchchain.Execution;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests YQL expressions where a list of terms are supplied by indirection
@@ -21,33 +21,33 @@ import static org.junit.Assert.assertNull;
public class TermListTestCase {
@Test
- public void testTermListInWeightedSet() {
+ void testTermListInWeightedSet() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, '2':1, 3:1}");
builder.setParameter("yql", "select * from sources * where weightedSet(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where weightedSet(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testTermListInWand() {
+ void testTermListInWand() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, 2:1, '3':1}");
builder.setParameter("yql", "select * from sources * where wand(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where wand(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testTermListInDotProduct() {
+ void testTermListInDotProduct() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, '2':1, '3':1}");
builder.setParameter("yql", "select * from sources * where dotProduct(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where dotProduct(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
private Query searchAndAssertNoErrors(URIBuilder builder) {
@@ -57,9 +57,9 @@ public class TermListTestCase {
var execution = new Execution(searchChain, context);
Result r = execution.search(query);
var exception = exceptionOf(r);
- assertNull(exception == null ? "No error":
- exception.getMessage() + "\n" + Arrays.toString(exception.getStackTrace()),
- r.hits().getError());
+ assertNull(r.hits().getError(),
+ exception == null ? "No error":
+ exception.getMessage() + "\n" + Arrays.toString(exception.getStackTrace()));
return query;
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
index 5e97b59646f..8fe451dd095 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
@@ -1,14 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import com.yahoo.search.query.QueryTree;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
@@ -30,14 +29,14 @@ public class UserInputTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
searchChain = new Chain<>(new MinimalQueryInserter());
context = Execution.Context.createContextStub();
execution = new Execution(searchChain, context);
}
- @After
+ @AfterEach
public void tearDown() {
searchChain = null;
context = null;
@@ -45,7 +44,7 @@ public class UserInputTestCase {
}
@Test
- public void testSimpleUserInput() {
+ void testSimpleUserInput() {
{
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where userInput(\"nalle\")");
@@ -70,7 +69,7 @@ public class UserInputTestCase {
}
@Test
- public void testRawUserInput() {
+ void testRawUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"raw\"}userInput(\"nal le\")");
Query query = searchAndAssertNoErrors(builder);
@@ -78,7 +77,7 @@ public class UserInputTestCase {
}
@Test
- public void testSegmentedUserInput() {
+ void testSegmentedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {grammar: \"segment\"}userInput(\"nal le\")");
@@ -87,7 +86,7 @@ public class UserInputTestCase {
}
@Test
- public void testSegmentedNoiseUserInput() {
+ void testSegmentedNoiseUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {grammar: \"segment\"}userInput(\"^^^^^^^^\")");
@@ -96,45 +95,45 @@ public class UserInputTestCase {
}
@Test
- public void testAnyParsedUserInput() {
+ void testAnyParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"any\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where (default contains \"foo\" OR default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testAllParsedUserInput() {
+ void testAllParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"all\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where (default contains \"foo\" AND default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testWeakAndParsedUserInput() {
+ void testWeakAndParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"weakAnd\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where weakAnd(default contains \"foo\", default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testIllegalGrammar() {
+ void testIllegalGrammar() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"nonesuch\"}userInput('foo bar')");
Query query = new Query(builder.toString());
Result r = execution.search(query);
assertNotNull(r.hits().getError());
assertEquals("Could not create query from YQL: No query type 'nonesuch'",
- r.hits().getError().getDetailedMessage());
+ r.hits().getError().getDetailedMessage());
}
@Test
- public void testCustomDefaultIndexUserInput() {
+ void testCustomDefaultIndexUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {defaultIndex: \"glompf\"}userInput(\"nalle\")");
@@ -143,7 +142,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputStemming() {
+ void testAnnotatedUserInputStemming() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {stem: false}userInput(\"nalle\")");
@@ -154,18 +153,18 @@ public class UserInputTestCase {
}
@Test
- public void testNegativeNumberComparison() {
+ void testNegativeNumberComparison() {
URIBuilder builder = searchUri();
builder.setParameter("myinput", "-5");
builder.setParameter("yql",
- "select * from ecitem where rank(({defaultIndex:\"myfield\"}(userInput(@myinput))))");
+ "select * from ecitem where rank(({defaultIndex:\"myfield\"}(userInput(@myinput))))");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from ecitem where rank(weakAnd(myfield = (-5)))", query.yqlRepresentation());
assertEquals("RANK (WEAKAND(100) myfield:-5)", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAnnotatedUserInputUnrankedTerms() {
+ void testAnnotatedUserInputUnrankedTerms() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {ranked: false}userInput(\"nalle\")");
@@ -176,7 +175,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputFiltersTerms() {
+ void testAnnotatedUserInputFiltersTerms() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {filter: true}userInput(\"nalle\")");
@@ -187,7 +186,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputCaseNormalization() {
+ void testAnnotatedUserInputCaseNormalization() {
URIBuilder builder = searchUri();
builder.setParameter(
"yql",
@@ -199,7 +198,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputAccentRemoval() {
+ void testAnnotatedUserInputAccentRemoval() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {accentDrop: false}userInput(\"nalle\")");
@@ -210,7 +209,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputPositionData() {
+ void testAnnotatedUserInputPositionData() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {usePositionData: false}userInput(\"nalle\")");
@@ -221,7 +220,7 @@ public class UserInputTestCase {
}
@Test
- public void testQueryPropertiesAsStringArguments() {
+ void testQueryPropertiesAsStringArguments() {
URIBuilder builder = searchUri();
builder.setParameter("nalle", "bamse");
builder.setParameter("meta", "syntactic");
@@ -232,7 +231,7 @@ public class UserInputTestCase {
}
@Test
- public void testReferenceInComparison() {
+ void testReferenceInComparison() {
URIBuilder builder = searchUri();
builder.setParameter("varref", "1980");
builder.setParameter("yql", "select * from sources * where year > @varref");
@@ -241,22 +240,22 @@ public class UserInputTestCase {
}
@Test
- public void testReferenceInContinuation() {
+ void testReferenceInContinuation() {
URIBuilder builder = searchUri();
builder.setParameter("continuation", "BCBCBCBEBG");
builder.setParameter("yql",
- "select * from sources * where myfield contains 'token'" +
- "| {'continuations':[@continuation, 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))");
+ "select * from sources * where myfield contains 'token'" +
+ "| {'continuations':[@continuation, 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where myfield contains \"token\" | { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))", query.yqlRepresentation());
}
@Test
- public void testReferenceInEquiv() {
+ void testReferenceInEquiv() {
URIBuilder builder = searchUri();
builder.setParameter("term", "A");
builder.setParameter("yql",
- "select foo from bar where fieldName contains equiv(@term,'B')");
+ "select foo from bar where fieldName contains equiv(@term,'B')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select foo from bar where fieldName contains equiv(\"A\", \"B\")", query.yqlRepresentation());
}
@@ -264,7 +263,7 @@ public class UserInputTestCase {
private Query searchAndAssertNoErrors(URIBuilder builder) {
Query query = new Query(builder.toString());
Result r = execution.search(query);
- assertNull(stackTraceIfAny(r), r.hits().getError());
+ assertNull(r.hits().getError(), stackTraceIfAny(r));
return query;
}
@@ -281,14 +280,14 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyUserInput() {
+ void testEmptyUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where userInput(\"\")");
assertQueryFails(builder);
}
@Test
- public void testEmptyUserInputFromQueryProperty() {
+ void testEmptyUserInputFromQueryProperty() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where userInput(@foo)");
@@ -296,7 +295,7 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyQueryProperty() {
+ void testEmptyQueryProperty() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where bar contains \"a\" and nonEmpty(foo contains @foo)");
@@ -304,7 +303,7 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyQueryPropertyInsideExpression() {
+ void testEmptyQueryPropertyInsideExpression() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql",
@@ -313,7 +312,7 @@ public class UserInputTestCase {
}
@Test
- public void testCompositeWithoutArguments() {
+ void testCompositeWithoutArguments() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where bar contains \"a\" and foo contains phrase()");
searchAndAssertNoErrors(builder);
@@ -323,7 +322,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnoyingPlacementOfNonEmpty() {
+ void testAnnoyingPlacementOfNonEmpty() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where bar contains \"a\" and foo contains nonEmpty(phrase(\"a\", \"b\"))");
@@ -336,7 +335,7 @@ public class UserInputTestCase {
}
@Test
- public void testAllowEmptyUserInput() {
+ void testAllowEmptyUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where [{allowEmpty: true}]userInput(@foo)");
@@ -344,7 +343,7 @@ public class UserInputTestCase {
}
@Test
- public void testAllowEmptyNullFromQueryParsing() {
+ void testAllowEmptyNullFromQueryParsing() {
URIBuilder builder = searchUri();
builder.setParameter("foo", ",,,,,,,,");
builder.setParameter("yql", "select * from sources * where [{allowEmpty: true}]userInput(@foo)");
@@ -352,11 +351,20 @@ public class UserInputTestCase {
}
@Test
- public void testDisallowEmptyNullFromQueryParsing() {
+ void testDisallowEmptyNullFromQueryParsing() {
URIBuilder builder = searchUri();
builder.setParameter("foo", ",,,,,,,,");
builder.setParameter("yql", "select * from sources * where userInput(@foo)");
assertQueryFails(builder);
}
+ @Test
+ void testUserInputWithEmptyRangeStart() {
+ URIBuilder builder = searchUri();
+ builder.setParameter("wql", "[;boom]");
+ builder.setParameter("yql", "select * from sources * where ([{\"defaultIndex\": \"text_field\",\"grammar\": \"any\"}]userInput(@wql))");
+ Query query = searchAndAssertNoErrors(builder);
+ assertEquals("select * from sources * where text_field contains \"boom\"", query.yqlRepresentation());
+ }
+
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
index 553c3a3e583..9e5cde76c82 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
-
import com.yahoo.prelude.query.SameElementItem;
import com.yahoo.search.Query;
import com.yahoo.search.grouping.Continuation;
@@ -12,10 +10,9 @@ import com.yahoo.search.grouping.request.AttributeFunction;
import com.yahoo.search.grouping.request.CountAggregator;
import com.yahoo.search.grouping.request.EachOperation;
import com.yahoo.search.grouping.request.GroupingOperation;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.AndSegmentItem;
import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.MarkerWordItem;
@@ -28,73 +25,75 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import java.util.Arrays;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class VespaSerializerTestCase {
private static final String SELECT = "select ignoredfield from sourceA where ";
private YqlParser parser;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
parser = null;
}
@Test
- public void requireThatGroupingRequestsAreSerialized() {
+ void requireThatGroupingRequestsAreSerialized() {
Query query = new Query();
query.getModel().getQueryTree().setRoot(new WordItem("foo"));
assertEquals("default contains ({implicitTransforms: false}\"foo\")",
- VespaSerializer.serialize(query));
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("a"))
- .addChild(new EachOperation().addOutput(new CountAggregator())));
+ .addChild(new EachOperation().addOutput(new CountAggregator())));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| all(group(attribute(a)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| all(group(attribute(a)) each(output(count())))",
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("b"))
- .addChild(new EachOperation().addOutput(new CountAggregator())));
+ .addChild(new EachOperation().addOutput(new CountAggregator())));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| all(group(attribute(a)) each(output(count()))) " +
- "| all(group(attribute(b)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| all(group(attribute(a)) each(output(count()))) " +
+ "| all(group(attribute(b)) each(output(count())))",
+ VespaSerializer.serialize(query));
}
@Test
- public void requireThatGroupingContinuationsAreSerialized() {
+ void requireThatGroupingContinuationsAreSerialized() {
Query query = new Query();
query.getModel().getQueryTree().setRoot(new WordItem("foo"));
assertEquals("default contains ({implicitTransforms: false}\"foo\")",
- VespaSerializer.serialize(query));
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("a"))
- .addChild(new EachOperation().addOutput(new CountAggregator())),
- Continuation.fromString("BCBCBCBEBG"),
- Continuation.fromString("BCBKCBACBKCCK"));
+ .addChild(new EachOperation().addOutput(new CountAggregator())),
+ Continuation.fromString("BCBCBCBEBG"),
+ Continuation.fromString("BCBKCBACBKCCK"));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(attribute(a)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(attribute(a)) each(output(count())))",
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("b"))
- .addChild(new EachOperation().addOutput(new CountAggregator())),
- Continuation.fromString("BCBBBBBDBF"),
- Continuation.fromString("BCBJBPCBJCCJ"));
+ .addChild(new EachOperation().addOutput(new CountAggregator())),
+ Continuation.fromString("BCBBBBBDBF"),
+ Continuation.fromString("BCBJBPCBJCCJ"));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(attribute(a)) each(output(count()))) " +
- "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
- "all(group(attribute(b)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(attribute(a)) each(output(count()))) " +
+ "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
+ "all(group(attribute(b)) each(output(count())))",
+ VespaSerializer.serialize(query));
}
@Test
- public void testAnd() {
+ void testAnd() {
parseAndConfirm("(description contains \"a\" AND title contains \"that\")");
}
@@ -109,17 +108,17 @@ public class VespaSerializerTestCase {
}
@Test
- public void testAndNot() {
+ void testAndNot() {
parseAndConfirm("(description contains \"a\") AND !(title contains \"that\")");
}
@Test
- public void testEquiv() {
+ void testEquiv() {
parseAndConfirm("title contains equiv(\"a\", \"b\")");
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
parseAndConfirm("geoLocation(workplace, 63.418417, 10.433033, \"0.5 deg\")");
parseAndConfirm("geoLocation(headquarters, 37.41638, -122.024683, \"180.0 deg\")");
parseAndConfirm("geoLocation(home, -17.0, 42.0, \"0.0 deg\")");
@@ -127,13 +126,13 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNear() {
+ void testNear() {
parseAndConfirm("title contains near(\"a\", \"b\")");
parseAndConfirm("title contains ({distance: 50}near(\"a\", \"b\"))");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
parseAndConfirm("{label: \"foo\", targetNumHits: 1000}nearestNeighbor(semantic_embedding, my_property)");
parseAndConfirm("{targetNumHits: 42}nearestNeighbor(semantic_embedding, my_property)");
parseAndConfirm("{targetNumHits: 1, hnsw.exploreAdditionalHits: 76}nearestNeighbor(semantic_embedding, my_property)");
@@ -143,26 +142,26 @@ public class VespaSerializerTestCase {
}
@Test
- public void testTrueAndFalse() {
+ void testTrueAndFalse() {
parseAndConfirm("true");
parseAndConfirm("false");
}
@Test
- public void testNumbers() {
+ void testNumbers() {
parseAndConfirm("title = 500");
parseAndConfirm("title > 500");
parseAndConfirm("title < 500");
}
@Test
- public void testBoolean() {
+ void testBoolean() {
parseAndConfirm("flag = true");
parseAndConfirm("flag = false");
}
@Test
- public void testAnnotatedNumbers() {
+ void testAnnotatedNumbers() {
parseAndConfirm("title = ({filter: true}500)");
parseAndConfirm("title > ({filter: true}500)");
parseAndConfirm("title < ({filter: true}(-500))");
@@ -171,32 +170,32 @@ public class VespaSerializerTestCase {
}
@Test
- public void testRange() {
+ void testRange() {
parseAndConfirm("range(title, 1, 500)");
}
@Test
- public void testAnnotatedRange() {
+ void testAnnotatedRange() {
parseAndConfirm("{filter: true}range(title, 1, 500)");
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
parseAndConfirm("title contains onear(\"a\", \"b\")");
}
@Test
- public void testOr() {
+ void testOr() {
parseAndConfirm("(description contains \"a\" OR title contains \"that\")");
}
@Test
- public void testDotProduct() {
+ void testDotProduct() {
parseAndConfirm("dotProduct(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testPredicate() {
+ void testPredicate() {
parseAndConfirm("predicate(boolean,{\"gender\":\"male\"},{\"age\":25L})");
parseAndConfirm("predicate(boolean,{\"gender\":\"male\",\"hobby\":\"music\",\"hobby\":\"hiking\"}," +
"{\"age\":25L})",
@@ -204,37 +203,37 @@ public class VespaSerializerTestCase {
parseAndConfirm("predicate(boolean,{\"0x3\":{\"gender\":\"male\"},\"0x1\":{\"hobby\":\"music\"},\"0x1\":{\"hobby\":\"hiking\"}},{\"0x80ffffffffffffff\":{\"age\":23L}})",
"predicate(boolean,{\"0x3\":{\"gender\":\"male\"},\"0x1\":{\"hobby\":[\"music\",\"hiking\"]}},{\"0x80ffffffffffffff\":{\"age\":23L}})");
parseAndConfirm("predicate(boolean,0,0)");
- parseAndConfirm("predicate(boolean,0,0)","predicate(boolean,null,void)");
- parseAndConfirm("predicate(boolean,0,0)","predicate(boolean,{},{})");
+ parseAndConfirm("predicate(boolean,0,0)", "predicate(boolean,null,void)");
+ parseAndConfirm("predicate(boolean,0,0)", "predicate(boolean,{},{})");
}
@Test
- public void testPhrase() {
+ void testPhrase() {
parseAndConfirm("description contains phrase(\"a\", \"b\")");
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
parseAndConfirm("description contains ({id: 1}phrase(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedNear() {
+ void testAnnotatedNear() {
parseAndConfirm("description contains ({distance: 37}near(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedOnear() {
+ void testAnnotatedOnear() {
parseAndConfirm("description contains ({distance: 37}onear(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedEquiv() {
+ void testAnnotatedEquiv() {
parseAndConfirm("description contains ({id: 1}equiv(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedPhraseSegment() {
+ void testAnnotatedPhraseSegment() {
PhraseSegmentItem phraseSegment = new PhraseSegmentItem("abc", true, false);
phraseSegment.addItem(new WordItem("a", "indexNamePlaceholder"));
phraseSegment.addItem(new WordItem("b", "indexNamePlaceholder"));
@@ -246,7 +245,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testSameElement() {
+ void testSameElement() {
SameElementItem sameElement = new SameElementItem("ss");
sameElement.addItem(new WordItem("a", "f1"));
sameElement.addItem(new WordItem("b", "f2"));
@@ -254,8 +253,9 @@ public class VespaSerializerTestCase {
assertEquals("ss contains sameElement(f1 contains ({implicitTransforms: false}\"a\"), f2 contains ({implicitTransforms: false}\"b\"))", VespaSerializer.serialize(sameElement));
}
+
@Test
- public void testAnnotatedAndSegment() {
+ void testAnnotatedAndSegment() {
AndSegmentItem andSegment = new AndSegmentItem("abc", true, false);
andSegment.addItem(new WordItem("a", "indexNamePlaceholder"));
andSegment.addItem(new WordItem("b", "indexNamePlaceholder"));
@@ -270,42 +270,42 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPhraseWithAnnotations() {
+ void testPhraseWithAnnotations() {
parseAndConfirm("description contains phrase(({id: 15}\"a\"), \"b\")");
}
@Test
- public void testPhraseSegmentInPhrase() {
+ void testPhraseSegmentInPhrase() {
parseAndConfirm("description contains phrase(\"a\", \"b\", ({origin: {original: \"c d\", offset: 0, length: 3}}phrase(\"c\", \"d\")))");
}
@Test
- public void testRank() {
+ void testRank() {
parseAndConfirm("rank(a contains \"A\", b contains \"B\")");
}
@Test
- public void testWand() {
+ void testWand() {
parseAndConfirm("wand(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testWeakAnd() {
+ void testWeakAnd() {
parseAndConfirm("weakAnd(a contains \"A\", b contains \"B\")");
}
@Test
- public void testAnnotatedWeakAnd() {
+ void testAnnotatedWeakAnd() {
parseAndConfirm("({" + YqlParser.TARGET_NUM_HITS + ": 10}weakAnd(a contains \"A\", b contains \"B\"))");
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
parseAndConfirm("weightedSet(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testAnnotatedWord() {
+ void testAnnotatedWord() {
parseAndConfirm("description contains ({andSegmenting: true}\"a\")");
parseAndConfirm("description contains ({weight: 37}\"a\")");
parseAndConfirm("description contains ({id: 37}\"a\")");
@@ -317,29 +317,29 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPrefix() {
+ void testPrefix() {
parseAndConfirm("description contains ({prefix: true}\"a\")");
}
@Test
- public void testSuffix() {
+ void testSuffix() {
parseAndConfirm("description contains ({suffix: true}\"a\")");
}
@Test
- public void testSubstring() {
+ void testSubstring() {
parseAndConfirm("description contains ({substring: true}\"a\")");
}
@Test
- public void testExoticItemTypes() {
+ void testExoticItemTypes() {
Item item = MarkerWordItem.createEndOfHost();
String q = VespaSerializer.serialize(item);
assertEquals("default contains ({implicitTransforms: false}\"$\")", q);
}
@Test
- public void testEmptyIndex() {
+ void testEmptyIndex() {
Item item = new WordItem("nalle", true);
String q = VespaSerializer.serialize(item);
assertEquals("default contains \"nalle\"", q);
@@ -347,7 +347,7 @@ public class VespaSerializerTestCase {
@Test
- public void testLongAndNot() {
+ void testLongAndNot() {
NotItem item = new NotItem();
item.addItem(new WordItem("a"));
item.addItem(new WordItem("b"));
@@ -358,7 +358,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPhraseAsOperatorArgument() {
+ void testPhraseAsOperatorArgument() {
// flattening phrases is a feature, not a bug
parseAndConfirm("description contains phrase(\"a\", \"b\", \"c\")",
"description contains phrase(\"a\", phrase(\"b\", \"c\"))");
@@ -372,7 +372,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeInt() {
+ void testNumberTypeInt() {
parseAndConfirm("title = 500");
parseAndConfirm("title > 500");
parseAndConfirm("title < (-500)");
@@ -382,7 +382,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeLong() {
+ void testNumberTypeLong() {
parseAndConfirm("title = 549755813888L");
parseAndConfirm("title > 549755813888L");
parseAndConfirm("title < (-549755813888L)");
@@ -392,7 +392,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeFloat() {
+ void testNumberTypeFloat() {
parseAndConfirm("title = 500.0"); // silly
parseAndConfirm("title > 500.0");
parseAndConfirm("title < (-500.0)");
@@ -402,19 +402,19 @@ public class VespaSerializerTestCase {
}
@Test
- public void testAnnotatedLong() {
+ void testAnnotatedLong() {
parseAndConfirm("title >= ({id: 2014}(-549755813888L))");
}
@Test
- public void testHitLimit() {
+ void testHitLimit() {
parseAndConfirm("title <= ({hitLimit: 89}(-500))");
parseAndConfirm("title <= ({hitLimit: 89}(-500))");
parseAndConfirm("{hitLimit: 89}range(title, 1, 500)");
}
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
parseAndConfirm("range(title, 0.0, 500.0)");
parseAndConfirm("({bounds: \"open\"}range(title, 0.0, 500.0))");
parseAndConfirm("({bounds: \"leftOpen\"}range(title, 0.0, 500.0))");
@@ -423,18 +423,18 @@ public class VespaSerializerTestCase {
}
@Test
- public void testRegExp() {
+ void testRegExp() {
parseAndConfirm("foo matches \"a b\"");
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
parseAndConfirm("foo contains" + " ({origin: {original: \" trees \", offset: 1, length: 5}}"
+ "alternatives({\"trees\": 1.0, \"tree\": 0.7}))");
}
@Test
- public void testWordAlternativesInPhrase() {
+ void testWordAlternativesInPhrase() {
parseAndConfirm("foo contains phrase(\"forest\","
+ " ({origin: {original: \" trees \", offset: 1, length: 5}}"
+ "alternatives({\"trees\": 1.0, \"tree\": 0.7}))"
@@ -442,12 +442,12 @@ public class VespaSerializerTestCase {
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
parseAndConfirm("foo contains fuzzy(\"a\")");
}
@Test
- public void testFuzzyAnnotations() {
+ void testFuzzyAnnotations() {
parseAndConfirm("foo contains ({maxEditDistance:3,prefixLength:5}fuzzy(\"a\"))");
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
index ee933a86578..cf3c7911d0e 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
@@ -12,10 +10,9 @@ import java.util.Map;
import com.yahoo.search.schema.DocumentSummary;
import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
@@ -41,7 +38,7 @@ public class YqlFieldAndSourceTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
Query query = new Query("?query=test");
@@ -80,7 +77,7 @@ public class YqlFieldAndSourceTestCase {
return new SchemaInfo(List.of(schema.build()), Map.of());
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
searchChain = null;
context = null;
@@ -88,7 +85,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testTrivial() {
+ final void testTrivial() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD1);
Result result = execution.search(query);
execution.fill(result);
@@ -98,7 +95,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testWithOnlyAttribute() {
+ final void testWithOnlyAttribute() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD2);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
@@ -109,7 +106,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testWithOnlyDiskfieldCorrectClassRequested() {
+ final void testWithOnlyDiskfieldCorrectClassRequested() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD3);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
@@ -120,7 +117,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testTrivialCaseWithOnlyDiskfieldWrongClassRequested() {
+ final void testTrivialCaseWithOnlyDiskfieldWrongClassRequested() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD1);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
diff --git a/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
index 299a7ff9d30..935b1aa62f9 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
@@ -44,19 +44,15 @@ import com.yahoo.search.query.Sorting.UcaSorter;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Specification for the conversion of YQL+ expressions to Vespa search queries.
@@ -68,286 +64,288 @@ public class YqlParserTestCase {
private final YqlParser parser = new YqlParser(new ParserEnvironment());
- @Test(timeout = 120_000)
- public void failsGracefullyOnMissingQuoteEscapingAndSubsequentUnicodeCharacter() {
+ @Test
+ @Timeout(120_000)
+ void failsGracefullyOnMissingQuoteEscapingAndSubsequentUnicodeCharacter() {
assertParseFail("select * from bar where rank(ids contains 'http://en.wikipedia.org/wiki/Hors_d'œuvre') limit 10",
new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: query:L1:79 token recognition error at: 'œ'"));
}
@Test
- public void testParserDefaults() {
+ void testParserDefaults() {
assertTrue(parser.isQueryParser());
assertNull(parser.getDocTypes());
}
-
+
@Test
- public void testLanguageDetection() {
+ void testLanguageDetection() {
// SimpleDetector used here can detect japanese and will set that as language at the root of the user input
QueryTree tree = parse("select * from sources * where userInput(\"\u30ab\u30bf\u30ab\u30ca\")");
assertEquals(Language.JAPANESE, tree.getRoot().getLanguage());
}
@Test
- public void testGroupingStep() {
+ void testGroupingStep() {
assertParse("select foo from bar where baz contains 'cox'",
- "baz:cox");
+ "baz:cox");
assertEquals("[]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))",
- "baz:cox");
+ "| all(group(a) each(output(count())))",
+ "baz:cox");
assertEquals("[[]all(group(a) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count()))) " +
- "| all(group(b) each(output(count())))",
- "baz:cox");
+ "| all(group(a) each(output(count()))) " +
+ "| all(group(b) each(output(count())))",
+ "baz:cox");
assertEquals("[[]all(group(a) each(output(count())))," +
- " []all(group(b) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ " []all(group(b) each(output(count())))]",
+ toString(parser.getGroupingSteps()));
}
@Test
- public void testGroupingContinuation() {
+ void testGroupingContinuation() {
assertParse("select foo from bar where baz contains 'cox' " +
- "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count())))",
- "baz:cox");
+ "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count())))",
+ "baz:cox");
assertEquals("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count()))) " +
- "| { 'continuations': ['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }all(group(b) each(output(count())))",
- "baz:cox");
+ "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count()))) " +
+ "| { 'continuations': ['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }all(group(b) each(output(count())))",
+ "baz:cox");
assertEquals("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))," +
- " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]",
+ toString(parser.getGroupingSteps()));
}
@Test
- public void testHitLimit() {
+ void testHitLimit() {
assertParse("select artist_name, track_name, track_uri from sources * where (myField contains ({prefix:true}\"m\") and ({hitLimit: 5000, descending: true}range(static_score,0,Infinity))) limit 30 offset 0",
- "AND myField:m* static_score:[0;;-5000]");
+ "AND myField:m* static_score:[0;;-5000]");
}
@Test
- public void test() {
+ void test() {
assertParse("select foo from bar where title contains \"madonna\"",
- "title:madonna");
+ "title:madonna");
}
@Test
- public void testKeywordAsFieldName() {
+ void testKeywordAsFieldName() {
assertParse("select * from sources * where cast contains sameElement(id contains '16')",
- "cast:{id:16}");
+ "cast:{id:16}");
}
@Test
- public void testComplexExpression() {
+ void testComplexExpression() {
String queryTreeYql = "rank((((filter contains ({origin: {original: \"filter:VideoAdsCappingTestCPM\", \"offset\": 7, length: 22}, normalizeCase: false, id: 1}\"videoadscappingtestcpm\") AND hasRankRestriction contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 2}\"0\") AND ((objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 3}\"install_app\") AND availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 4}\"cpiparams\")) OR (availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 5}\"appinstallinfo\") AND availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 6}\"appmetroplexinfo\")) OR (dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 7}\"default\")) AND !(objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 8}\"install_app\"))) AND advt_age = ({\"id\": 9}2147483647) AND advt_gender contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 10}\"all\") AND advt_all_segments = ({\"id\": 11}2147483647) AND advt_keywords contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 12}\"all\") AND advMobilePlatform = ({\"id\": 13}2147483647) AND advMobileDeviceType = ({\"id\": 14}2147483647) AND advMobileCon = ({\"id\": 15}2147483647) AND advMobileOSVersions = ({\"id\": 16}2147483647) AND advCarrier = ({\"id\": 17}2147483647) AND ({\"id\": 18}weightedSet(advt_supply, {\"all\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) AND (advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 19, \"weight\": 1}\"adv_tuesday\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 20, \"weight\": 1}\"adv_tuesday_17\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 21, \"weight\": 1}\"adv_tuesday_17_forty_five\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 22}\"all\")) AND isAppReengagementAd = ({\"id\": 23}0) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 24}\"default\") AND serveWithPromotionOnly = ({\"id\": 26}0) AND budgetAdvertiserThrottleRateFilter = ({\"id\": 27}0) AND budgetResellerThrottleRateFilter = ({\"id\": 28}0) AND (isMystiqueRequired = ({\"id\": 29}0) OR (isMystiqueRequired = ({\"id\": 30}1) AND useBcFactorFilter = ({\"id\": 31}1))) AND (((budgetCampaignThrottleRateBits = ({\"id\": 32}55) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 33}\"default\"))) AND !(useBcFactorFilter = ({\"id\": 34}1)) OR ((useBcFactorFilter = ({\"id\": 35}1) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 36}\"default\") AND (bcFactorTiers = ({\"id\": 38}127) OR bcFactorTiers = ({\"id\": 39}0)) AND ((firstPriceEnforced = ({\"id\": 40}0) AND (secondPriceEnforced = ({\"id\": 41}1) OR isPrivateDeal = ({\"id\": 42}0) OR (dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 43}\"default\")) AND !(bcActiveTier = ({\"id\": 44}0)))) OR mystiqueCampaignThrottleRateBits = ({\"id\": 45}18)))) AND !(isOutOfDailyBudget = ({\"id\": 37}1))) AND testCreative = ({\"id\": 46}0) AND advt_geo = ({\"id\": 47}2147483647) AND ((adType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 48}\"strm_video\") AND isPortraitVideo = ({\"id\": 49}0)) OR adType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 50}\"stream_ad\")) AND ((isCPM = ({\"id\": 51}0) AND isOCPC = ({\"id\": 52}0) AND isECPC = ({\"id\": 53}0) AND ((priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 54}\"cpcv\") AND bid >= ({\"id\": 55}0.005)) OR (priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 56}\"cpv\") AND bid >= ({\"id\": 57}0.01)) OR (priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 58}\"cpc\") AND bid >= ({\"id\": 59}0.05)) OR (objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 60}\"promote_content\") AND bid >= ({\"id\": 61}0.01)) OR hasFloorPriceUsd = ({\"id\": 62}1))) OR isECPC = ({\"id\": 63}1) OR (isCPM = ({\"id\": 64}1) AND isOCPM = ({\"id\": 65}0) AND (({\"id\": 66}range(bid, 0.25, Infinity)) OR hasFloorPriceUsd = ({\"id\": 67}1)))) AND start_date <= ({\"id\": 68}1572976776299L) AND end_date >= ({\"id\": 69}1572976776299L))) AND !(isHoldoutAd = ({\"id\": 25}1))) AND !((disclaimerExtensionsTypes contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 70}\"pharma\") OR ({\"id\": 71}weightedSet(exclusion_advt_supply, {\"extsite223\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) OR isPersonalized = ({\"id\": 72}1) OR blocked_section_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 73}\"223\") OR blocked_publisher_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 74}\"223\") OR blocked_site_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 75}\"223\"))), {\"id\": 76, \"label\": \"ad_ocpc_max_cpc\"}dotProduct(ocpc_max_cpc, {\"0\": 1}), {\"id\": 77, \"label\": \"ad_ocpc_min_cpc\"}dotProduct(ocpc_min_cpc, {\"0\": 1}), {\"id\": 78, \"label\": \"ad_ocpc_max_alpha\"}dotProduct(ocpc_max_alpha, {\"0\": 1}), {\"id\": 79, \"label\": \"ad_ocpc_min_alpha\"}dotProduct(ocpc_min_alpha, {\"0\": 1}), {\"id\": 80, \"label\": \"ad_ocpc_alpha_0\"}dotProduct(ocpc_alpha_0, {\"0\": 1}), {\"id\": 81, \"label\": \"ad_ocpc_alpha_1\"}dotProduct(ocpc_alpha_1, {\"0\": 1}), (bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 82, \"weight\": 1}\"adv_tuesday\") OR bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 83, \"weight\": 1}\"adv_tuesday_17\") OR bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 84, \"weight\": 1}\"adv_tuesday_17_forty_five\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 85, \"weight\": 1}\"adv_tuesday\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 86, \"weight\": 1}\"adv_tuesday_17\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 87, \"weight\": 1}\"adv_tuesday_17_forty_five\")), bidAdjustmentForCpi = ({\"id\": 88, \"weight\": 1}223), {\"id\": 89, \"label\": \"boostingForBackfill\"}dotProduct(boostingForBackfill, {\"priority\": 1000})) limit 0 timeout 3980 | all(group(adTypeForGrouping) each(group(advertiser_id) max(11) output(count() as(groupingCounter)) each(max(1) each(output(summary())))))";
QueryTree parsed = assertParse("select * from sources * where " + queryTreeYql + ";",
- "RANK (+(+(AND filter:VideoAdsCappingTestCPM hasRankRestriction:0 (OR (AND objective:install_app availableExtendedFields:cpiparams) (AND availableExtendedFields:appinstallinfo availableExtendedFields:appmetroplexinfo) (+dummyField:default -objective:install_app)) advt_age:2147483647 advt_gender:all advt_all_segments:2147483647 advt_keywords:all advMobilePlatform:2147483647 advMobileDeviceType:2147483647 advMobileCon:2147483647 advMobileOSVersions:2147483647 advCarrier:2147483647 WEIGHTEDSET advt_supply{[1]:\"site223\",[1]:\"pub223\",[1]:\"all\",[1]:\"sec223\"} (OR advt_day_parting:adv_tuesday!1 advt_day_parting:adv_tuesday_17!1 advt_day_parting:adv_tuesday_17_forty_five!1 advt_day_parting:all) isAppReengagementAd:0 dummyField:default serveWithPromotionOnly:0 budgetAdvertiserThrottleRateFilter:0 budgetResellerThrottleRateFilter:0 (OR isMystiqueRequired:0 (AND isMystiqueRequired:1 useBcFactorFilter:1)) (OR (+(AND budgetCampaignThrottleRateBits:55 dummyField:default) -useBcFactorFilter:1) (+(AND useBcFactorFilter:1 dummyField:default (OR bcFactorTiers:127 bcFactorTiers:0) (OR (AND firstPriceEnforced:0 (OR secondPriceEnforced:1 isPrivateDeal:0 (+dummyField:default -bcActiveTier:0))) mystiqueCampaignThrottleRateBits:18)) -isOutOfDailyBudget:1)) testCreative:0 advt_geo:2147483647 (OR (AND adType:strm_video isPortraitVideo:0) adType:stream_ad) (OR (AND isCPM:0 isOCPC:0 isECPC:0 (OR (AND priceType:cpcv bid:[0.005;]) (AND priceType:cpv bid:[0.01;]) (AND priceType:cpc bid:[0.05;]) (AND objective:promote_content bid:[0.01;]) hasFloorPriceUsd:1)) isECPC:1 (AND isCPM:1 isOCPM:0 (OR bid:[0.25;] hasFloorPriceUsd:1))) start_date:[;1572976776299] end_date:[1572976776299;]) -isHoldoutAd:1) -(OR disclaimerExtensionsTypes:pharma WEIGHTEDSET exclusion_advt_supply{[1]:\"extsite223\",[1]:\"site223\",[1]:\"pub223\",[1]:\"sec223\"} isPersonalized:1 blocked_section_ids:223 blocked_publisher_ids:223 blocked_site_ids:223)) DOTPRODUCT ocpc_max_cpc{[1]:\"0\"} DOTPRODUCT ocpc_min_cpc{[1]:\"0\"} DOTPRODUCT ocpc_max_alpha{[1]:\"0\"} DOTPRODUCT ocpc_min_alpha{[1]:\"0\"} DOTPRODUCT ocpc_alpha_0{[1]:\"0\"} DOTPRODUCT ocpc_alpha_1{[1]:\"0\"} (OR bidAdjustmentDayParting:adv_tuesday!1 bidAdjustmentDayParting:adv_tuesday_17!1 bidAdjustmentDayParting:adv_tuesday_17_forty_five!1 bidAdjustmentDayPartingForCostCap:adv_tuesday!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17_forty_five!1) bidAdjustmentForCpi:223!1 DOTPRODUCT boostingForBackfill{[1000]:\"priority\"}");
+ "RANK (+(+(AND filter:VideoAdsCappingTestCPM hasRankRestriction:0 (OR (AND objective:install_app availableExtendedFields:cpiparams) (AND availableExtendedFields:appinstallinfo availableExtendedFields:appmetroplexinfo) (+dummyField:default -objective:install_app)) advt_age:2147483647 advt_gender:all advt_all_segments:2147483647 advt_keywords:all advMobilePlatform:2147483647 advMobileDeviceType:2147483647 advMobileCon:2147483647 advMobileOSVersions:2147483647 advCarrier:2147483647 WEIGHTEDSET advt_supply{[1]:\"site223\",[1]:\"pub223\",[1]:\"all\",[1]:\"sec223\"} (OR advt_day_parting:adv_tuesday!1 advt_day_parting:adv_tuesday_17!1 advt_day_parting:adv_tuesday_17_forty_five!1 advt_day_parting:all) isAppReengagementAd:0 dummyField:default serveWithPromotionOnly:0 budgetAdvertiserThrottleRateFilter:0 budgetResellerThrottleRateFilter:0 (OR isMystiqueRequired:0 (AND isMystiqueRequired:1 useBcFactorFilter:1)) (OR (+(AND budgetCampaignThrottleRateBits:55 dummyField:default) -useBcFactorFilter:1) (+(AND useBcFactorFilter:1 dummyField:default (OR bcFactorTiers:127 bcFactorTiers:0) (OR (AND firstPriceEnforced:0 (OR secondPriceEnforced:1 isPrivateDeal:0 (+dummyField:default -bcActiveTier:0))) mystiqueCampaignThrottleRateBits:18)) -isOutOfDailyBudget:1)) testCreative:0 advt_geo:2147483647 (OR (AND adType:strm_video isPortraitVideo:0) adType:stream_ad) (OR (AND isCPM:0 isOCPC:0 isECPC:0 (OR (AND priceType:cpcv bid:[0.005;]) (AND priceType:cpv bid:[0.01;]) (AND priceType:cpc bid:[0.05;]) (AND objective:promote_content bid:[0.01;]) hasFloorPriceUsd:1)) isECPC:1 (AND isCPM:1 isOCPM:0 (OR bid:[0.25;] hasFloorPriceUsd:1))) start_date:[;1572976776299] end_date:[1572976776299;]) -isHoldoutAd:1) -(OR disclaimerExtensionsTypes:pharma WEIGHTEDSET exclusion_advt_supply{[1]:\"extsite223\",[1]:\"site223\",[1]:\"pub223\",[1]:\"sec223\"} isPersonalized:1 blocked_section_ids:223 blocked_publisher_ids:223 blocked_site_ids:223)) DOTPRODUCT ocpc_max_cpc{[1]:\"0\"} DOTPRODUCT ocpc_min_cpc{[1]:\"0\"} DOTPRODUCT ocpc_max_alpha{[1]:\"0\"} DOTPRODUCT ocpc_min_alpha{[1]:\"0\"} DOTPRODUCT ocpc_alpha_0{[1]:\"0\"} DOTPRODUCT ocpc_alpha_1{[1]:\"0\"} (OR bidAdjustmentDayParting:adv_tuesday!1 bidAdjustmentDayParting:adv_tuesday_17!1 bidAdjustmentDayParting:adv_tuesday_17_forty_five!1 bidAdjustmentDayPartingForCostCap:adv_tuesday!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17_forty_five!1) bidAdjustmentForCpi:223!1 DOTPRODUCT boostingForBackfill{[1000]:\"priority\"}");
String serializedQueryTreeYql = VespaSerializer.serialize(parsed);
// Note: All the details here are not verified
assertEquals("rank((((filter contains ({normalizeCase: false, id: 1}\"VideoAdsCappingTestCPM\") AND hasRankRestriction contains ({normalizeCase: false, implicitTransforms: false, id: 2}\"0\") AND ((objective contains ({normalizeCase: false, implicitTransforms: false, id: 3}\"install_app\") AND availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 4}\"cpiparams\")) OR (availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 5}\"appinstallinfo\") AND availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 6}\"appmetroplexinfo\")) OR (dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 7}\"default\")) AND !(objective contains ({normalizeCase: false, implicitTransforms: false, id: 8}\"install_app\"))) AND advt_age = ({id: 9}2147483647) AND advt_gender contains ({normalizeCase: false, implicitTransforms: false, id: 10}\"all\") AND advt_all_segments = ({id: 11}2147483647) AND advt_keywords contains ({normalizeCase: false, implicitTransforms: false, id: 12}\"all\") AND advMobilePlatform = ({id: 13}2147483647) AND advMobileDeviceType = ({id: 14}2147483647) AND advMobileCon = ({id: 15}2147483647) AND advMobileOSVersions = ({id: 16}2147483647) AND advCarrier = ({id: 17}2147483647) AND ({id: 18}weightedSet(advt_supply, {\"all\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) AND (advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 19, weight: 1}\"adv_tuesday\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 20, weight: 1}\"adv_tuesday_17\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 21, weight: 1}\"adv_tuesday_17_forty_five\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 22}\"all\")) AND isAppReengagementAd = ({id: 23}0) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 24}\"default\") AND serveWithPromotionOnly = ({id: 26}0) AND budgetAdvertiserThrottleRateFilter = ({id: 27}0) AND budgetResellerThrottleRateFilter = ({id: 28}0) AND (isMystiqueRequired = ({id: 29}0) OR (isMystiqueRequired = ({id: 30}1) AND useBcFactorFilter = ({id: 31}1))) AND (((budgetCampaignThrottleRateBits = ({id: 32}55) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 33}\"default\"))) AND !(useBcFactorFilter = ({id: 34}1)) OR ((useBcFactorFilter = ({id: 35}1) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 36}\"default\") AND (bcFactorTiers = ({id: 38}127) OR bcFactorTiers = ({id: 39}0)) AND ((firstPriceEnforced = ({id: 40}0) AND (secondPriceEnforced = ({id: 41}1) OR isPrivateDeal = ({id: 42}0) OR (dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 43}\"default\")) AND !(bcActiveTier = ({id: 44}0)))) OR mystiqueCampaignThrottleRateBits = ({id: 45}18)))) AND !(isOutOfDailyBudget = ({id: 37}1))) AND testCreative = ({id: 46}0) AND advt_geo = ({id: 47}2147483647) AND ((adType contains ({normalizeCase: false, implicitTransforms: false, id: 48}\"strm_video\") AND isPortraitVideo = ({id: 49}0)) OR adType contains ({normalizeCase: false, implicitTransforms: false, id: 50}\"stream_ad\")) AND ((isCPM = ({id: 51}0) AND isOCPC = ({id: 52}0) AND isECPC = ({id: 53}0) AND ((priceType contains ({normalizeCase: false, implicitTransforms: false, id: 54}\"cpcv\") AND bid >= ({id: 55}0.005)) OR (priceType contains ({normalizeCase: false, implicitTransforms: false, id: 56}\"cpv\") AND bid >= ({id: 57}0.01)) OR (priceType contains ({normalizeCase: false, implicitTransforms: false, id: 58}\"cpc\") AND bid >= ({id: 59}0.05)) OR (objective contains ({normalizeCase: false, implicitTransforms: false, id: 60}\"promote_content\") AND bid >= ({id: 61}0.01)) OR hasFloorPriceUsd = ({id: 62}1))) OR isECPC = ({id: 63}1) OR (isCPM = ({id: 64}1) AND isOCPM = ({id: 65}0) AND ({id: 66}range(bid, 0.25, Infinity) OR hasFloorPriceUsd = ({id: 67}1)))) AND start_date <= ({id: 68}1572976776299L) AND end_date >= ({id: 69}1572976776299L))) AND !(isHoldoutAd = ({id: 25}1))) AND !((disclaimerExtensionsTypes contains ({normalizeCase: false, implicitTransforms: false, id: 70}\"pharma\") OR ({id: 71}weightedSet(exclusion_advt_supply, {\"extsite223\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) OR isPersonalized = ({id: 72}1) OR blocked_section_ids contains ({normalizeCase: false, implicitTransforms: false, id: 73}\"223\") OR blocked_publisher_ids contains ({normalizeCase: false, implicitTransforms: false, id: 74}\"223\") OR blocked_site_ids contains ({normalizeCase: false, implicitTransforms: false, id: 75}\"223\"))), ({id: 76, label: \"ad_ocpc_max_cpc\"}dotProduct(ocpc_max_cpc, {\"0\": 1})), ({id: 77, label: \"ad_ocpc_min_cpc\"}dotProduct(ocpc_min_cpc, {\"0\": 1})), ({id: 78, label: \"ad_ocpc_max_alpha\"}dotProduct(ocpc_max_alpha, {\"0\": 1})), ({id: 79, label: \"ad_ocpc_min_alpha\"}dotProduct(ocpc_min_alpha, {\"0\": 1})), ({id: 80, label: \"ad_ocpc_alpha_0\"}dotProduct(ocpc_alpha_0, {\"0\": 1})), ({id: 81, label: \"ad_ocpc_alpha_1\"}dotProduct(ocpc_alpha_1, {\"0\": 1})), (bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 82, weight: 1}\"adv_tuesday\") OR bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 83, weight: 1}\"adv_tuesday_17\") OR bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 84, weight: 1}\"adv_tuesday_17_forty_five\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 85, weight: 1}\"adv_tuesday\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 86, weight: 1}\"adv_tuesday_17\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 87, weight: 1}\"adv_tuesday_17_forty_five\")), bidAdjustmentForCpi = ({id: 88, weight: 1}223), ({id: 89, label: \"boostingForBackfill\"}dotProduct(boostingForBackfill, {\"priority\": 1000})))",
- serializedQueryTreeYql);
+ serializedQueryTreeYql);
}
@Test
- public void testDottedFieldNames() {
+ void testDottedFieldNames() {
assertParse("select foo from bar where my.nested.title contains \"madonna\"",
"my.nested.title:madonna");
}
+
@Test
- public void testDottedNestedFieldNames() {
+ void testDottedNestedFieldNames() {
assertParse("select foo from bar where my.title contains \"madonna\"",
"my.title:madonna");
}
@Test
- public void testOr() {
+ void testOr() {
assertParse("select foo from bar where title contains \"madonna\" or title contains \"saint\"",
- "OR title:madonna title:saint");
+ "OR title:madonna title:saint");
assertParse("select foo from bar where title contains \"madonna\" or title contains \"saint\" or title " +
- "contains \"angel\"",
- "OR title:madonna title:saint title:angel");
+ "contains \"angel\"",
+ "OR title:madonna title:saint title:angel");
}
@Test
- public void testAnd() {
+ void testAnd() {
assertParse("select foo from bar where title contains \"madonna\" and title contains \"saint\"",
- "AND title:madonna title:saint");
+ "AND title:madonna title:saint");
assertParse("select foo from bar where title contains \"madonna\" and title contains \"saint\" and title " +
- "contains \"angel\"",
- "AND title:madonna title:saint title:angel");
+ "contains \"angel\"",
+ "AND title:madonna title:saint title:angel");
}
@Test
- public void testAndNot() {
+ void testAndNot() {
assertParse("select foo from bar where title contains \"madonna\" and !(title contains \"saint\")",
- "+title:madonna -title:saint");
+ "+title:madonna -title:saint");
}
@Test
- public void testSingleNot() {
+ void testSingleNot() {
assertParse("select foo from bar where !(title contains \"saint\")",
- "-title:saint");
+ "-title:saint");
}
@Test
- public void testMultipleNot() {
+ void testMultipleNot() {
assertParse("select foo from bar where !(title contains \"saint\") AND !(title contains \"etienne\")",
- "-title:saint -title:etienne");
+ "-title:saint -title:etienne");
}
@Test
- public void testLessThan() {
+ void testLessThan() {
assertParse("select foo from bar where price < 500", "price:<500");
assertParse("select foo from bar where 500 < price", "price:>500");
}
@Test
- public void testGreaterThan() {
+ void testGreaterThan() {
assertParse("select foo from bar where price > 500", "price:>500");
assertParse("select foo from bar where 500 > price", "price:<500");
}
@Test
- public void testLessThanOrEqual() {
+ void testLessThanOrEqual() {
assertParse("select foo from bar where price <= 500", "price:[;500]");
assertParse("select foo from bar where 500 <= price", "price:[500;]");
}
@Test
- public void testGreaterThanOrEqual() {
+ void testGreaterThanOrEqual() {
assertParse("select foo from bar where price >= 500", "price:[500;]");
assertParse("select foo from bar where 500 >= price", "price:[;500]");
}
@Test
- public void testEquality() {
+ void testEquality() {
assertParse("select foo from bar where price = 500", "price:500");
assertParse("select foo from bar where 500 = price", "price:500");
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
assertParse("select foo from bar where price < -500", "price:<-500");
assertParse("select foo from bar where -500 < price", "price:>-500");
}
@Test
- public void testNegativeGreaterThan() {
+ void testNegativeGreaterThan() {
assertParse("select foo from bar where price > -500", "price:>-500");
assertParse("select foo from bar where -500 > price", "price:<-500");
}
@Test
- public void testNegativeLessThanOrEqual() {
+ void testNegativeLessThanOrEqual() {
assertParse("select foo from bar where price <= -500", "price:[;-500]");
assertParse("select foo from bar where -500 <= price", "price:[-500;]");
}
@Test
- public void testNegativeGreaterThanOrEqual() {
+ void testNegativeGreaterThanOrEqual() {
assertParse("select foo from bar where price >= -500", "price:[-500;]");
assertParse("select foo from bar where -500 >= price", "price:[;-500]");
}
@Test
- public void testNegativeEquality() {
+ void testNegativeEquality() {
assertParse("select foo from bar where price = -500", "price:-500");
assertParse("select foo from bar where -500 = price", "price:-500");
}
@Test
- public void testAnnotatedLessThan() {
+ void testAnnotatedLessThan() {
assertParse("select foo from bar where price < ({filter: true}(-500))", "|price:<-500");
assertParse("select foo from bar where ({filter: true}500) < price", "|price:>500");
}
@Test
- public void testAnnotatedGreaterThan() {
+ void testAnnotatedGreaterThan() {
assertParse("select foo from bar where price > ({filter: true}500)", "|price:>500");
assertParse("select foo from bar where ({filter: true}(-500)) > price", "|price:<-500");
}
@Test
- public void testAnnotatedLessThanOrEqual() {
+ void testAnnotatedLessThanOrEqual() {
assertParse("select foo from bar where price <= ({filter: true}(-500))", "|price:[;-500]");
assertParse("select foo from bar where ({filter: true}500) <= price", "|price:[500;]");
}
@Test
- public void testAnnotatedGreaterThanOrEqual() {
+ void testAnnotatedGreaterThanOrEqual() {
assertParse("select foo from bar where price >= ({filter: true}500)", "|price:[500;]");
assertParse("select foo from bar where ({filter: true}(-500)) >= price", "|price:[;-500]");
}
@Test
- public void testAnnotatedEquality() {
+ void testAnnotatedEquality() {
assertParse("select foo from bar where price = ({filter: true}(-500))", "|price:-500");
assertParse("select foo from bar where ({filter: true}500) = price", "|price:500");
}
@Test
- public void testBoolean() {
+ void testBoolean() {
assertParse("select foo from bar where flag = true;", "flag:true");
QueryTree query = assertParse("select foo from bar where flag = false;", "flag:false");
assertEquals(BoolItem.class, query.getRoot().getClass());
- BoolItem item = (BoolItem)query.getRoot();
+ BoolItem item = (BoolItem) query.getRoot();
assertEquals("flag", item.getIndexName());
assertEquals(false, item.value());
}
@Test
- public void testTermAnnotations() {
+ void testTermAnnotations() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "({label: \"merkelapp\"}\"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "({label: \"merkelapp\"}\"colors\")").getLabel());
assertEquals("another",
- getRootWord("select foo from bar where baz contains " +
- "({annotations: {cox: \"another\"}}\"colors\")").getAnnotation("cox"));
+ getRootWord("select foo from bar where baz contains " +
+ "({annotations: {cox: \"another\"}}\"colors\")").getAnnotation("cox"));
assertEquals(23.0, getRootWord("select foo from bar where baz contains " +
- "({significance: 23.0}\"colors\")").getSignificance(), 1E-6);
+ "({significance: 23.0}\"colors\")").getSignificance(), 1E-6);
assertEquals(23, getRootWord("select foo from bar where baz contains " +
- "({id: 23}\"colors\")").getUniqueID());
+ "({id: 23}\"colors\")").getUniqueID());
assertEquals(150, getRootWord("select foo from bar where baz contains " +
- "({weight: 150}\"colors\")").getWeight());
+ "({weight: 150}\"colors\")").getWeight());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "({usePositionData: false}\"colors\")").usePositionData());
+ "({usePositionData: false}\"colors\")").usePositionData());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "({filter: true}\"colors\")").isFilter());
+ "({filter: true}\"colors\")").isFilter());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "({ranked: false}\"colors\")").isRanked());
+ "({ranked: false}\"colors\")").isRanked());
Substring origin = getRootWord("select foo from bar where baz contains " +
- "({origin: {original: \"abc\", offset: 1, length: 2}}" +
- "\"colors\")").getOrigin();
+ "({origin: {original: \"abc\", offset: 1, length: 2}}" +
+ "\"colors\")").getOrigin();
assertEquals("abc", origin.string);
assertEquals(1, origin.start);
assertEquals(3, origin.end);
}
@Test
- public void testAnnotationsCanBeInBrackets() {
+ void testAnnotationsCanBeInBrackets() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "([ {label: \"merkelapp\"} ]\"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "([ {label: \"merkelapp\"} ]\"colors\")").getLabel());
}
@Test
- public void testValuesCanBeQuoted() {
+ void testValuesCanBeQuoted() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "( {label: \"merkelapp\"} \"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "( {label: \"merkelapp\"} \"colors\")").getLabel());
}
@Test
- public void testSameElement() {
+ void testSameElement() {
assertParse("select foo from bar where baz contains sameElement(f1 contains \"a\", f2 contains \"b\")",
"baz:{f1:a f2:b}");
assertParse("select foo from bar where baz contains sameElement(f1 contains \"a\", f2 = 10)",
@@ -361,27 +359,27 @@ public class YqlParserTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
assertParse("select foo from bar where baz contains phrase(\"a\", \"b\")",
- "baz:\"a b\"");
+ "baz:\"a b\"");
}
@Test
- public void testNestedPhrase() {
+ void testNestedPhrase() {
assertParse("select foo from bar where baz contains phrase(\"a\", \"b\", phrase(\"c\", \"d\"))",
- "baz:\"a b c d\"");
+ "baz:\"a b c d\"");
}
@Test
- public void testNestedPhraseSegment() {
+ void testNestedPhraseSegment() {
assertParse("select foo from bar where baz contains " +
- "phrase(\"a\", \"b\", [ {origin: {original: \"c d\", offset: 0, length: 3}} ]" +
- "phrase(\"c\", \"d\"));",
- "baz:\"a b 'c d'\"");
+ "phrase(\"a\", \"b\", [ {origin: {original: \"c d\", offset: 0, length: 3}} ]" +
+ "phrase(\"c\", \"d\"));",
+ "baz:\"a b 'c d'\"");
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
QueryTree x = parse("select foo from bar where baz contains fuzzy(\"a b\")");
Item root = x.getRoot();
assertSame(FuzzyItem.class, root.getClass());
@@ -392,7 +390,7 @@ public class YqlParserTestCase {
}
@Test
- public void testFuzzyAnnotations() {
+ void testFuzzyAnnotations() {
QueryTree x = parse(
"select foo from bar where baz contains ({maxEditDistance: 3, prefixLength: 10}fuzzy(\"a b\"))"
);
@@ -405,17 +403,17 @@ public class YqlParserTestCase {
}
@Test
- public void testStemming() {
+ void testStemming() {
assertTrue(getRootWord("select foo from bar where baz contains " +
- "([ {stem: false} ]\"colors\")").isStemmed());
+ "([ {stem: false} ]\"colors\")").isStemmed());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "([ {stem: true} ]\"colors\")").isStemmed());
+ "([ {stem: true} ]\"colors\")").isStemmed());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isStemmed());
+ "\"colors\"").isStemmed());
}
@Test
- public void testRaw() {
+ void testRaw() {
// Default: Not raw, for comparison
Item root = parse("select foo from bar where baz contains (\"yoni jo dima\")").getRoot();
assertEquals("baz:'yoni jo dima'", root.toString());
@@ -426,7 +424,7 @@ public class YqlParserTestCase {
assertEquals("baz:yoni jo dima", root.toString());
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
root = parse("select foo from bar where {grammar:\"all\"}userInput(\"yoni jo dima\")").getRoot();
assertTrue(root instanceof AndItem);
@@ -436,232 +434,232 @@ public class YqlParserTestCase {
root = parse("select foo from bar where {grammar:\"raw\"}userInput(\"yoni jo dima\")").getRoot();
assertTrue(root instanceof WordItem);
assertTrue(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
}
@Test
- public void testAccentDropping() {
+ void testAccentDropping() {
assertFalse(getRootWord("select foo from bar where baz contains " +
- "( {accentDrop: false} \"colors\")").isNormalizable());
+ "( {accentDrop: false} \"colors\")").isNormalizable());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "( {accentDrop: true} \"colors\")").isNormalizable());
+ "( {accentDrop: true} \"colors\")").isNormalizable());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isNormalizable());
+ "\"colors\"").isNormalizable());
}
@Test
- public void testCaseNormalization() {
+ void testCaseNormalization() {
assertTrue(getRootWord("select foo from bar where baz contains " +
- "( {normalizeCase: false} \"colors\")").isLowercased());
+ "( {normalizeCase: false} \"colors\")").isLowercased());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "( {normalizeCase: true} \"colors\")").isLowercased());
+ "( {normalizeCase: true} \"colors\")").isLowercased());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isLowercased());
+ "\"colors\"").isLowercased());
}
@Test
- public void testSegmentingRule() {
+ void testSegmentingRule() {
assertEquals(SegmentingRule.PHRASE,
- getRootWord("select foo from bar where baz contains " +
- "( {andSegmenting: false} \"colors\")").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "( {andSegmenting: false} \"colors\")").getSegmentingRule());
assertEquals(SegmentingRule.BOOLEAN_AND,
- getRootWord("select foo from bar where baz contains " +
- "( {andSegmenting: true} \"colors\")").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "( {andSegmenting: true} \"colors\")").getSegmentingRule());
assertEquals(SegmentingRule.LANGUAGE_DEFAULT,
- getRootWord("select foo from bar where baz contains " +
- "\"colors\"").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "\"colors\"").getSegmentingRule());
}
@Test
- public void testNfkc() {
+ void testNfkc() {
assertEquals("a\u030a",
- getRootWord("select foo from bar where baz contains " +
- "( {nfkc: false} \"a\\u030a\")").getWord());
+ getRootWord("select foo from bar where baz contains " +
+ "( {nfkc: false} \"a\\u030a\")").getWord());
assertEquals("\u00e5",
- getRootWord("select foo from bar where baz contains " +
- "( {nfkc: true} \"a\\u030a\")").getWord());
- assertEquals("No NKFC by default",
- "a\u030a",
- getRootWord("select foo from bar where baz contains " +
- "(\"a\\u030a\")").getWord());
+ getRootWord("select foo from bar where baz contains " +
+ "( {nfkc: true} \"a\\u030a\")").getWord());
+ assertEquals("a\u030a",
+ getRootWord("select foo from bar where baz contains " +
+ "(\"a\\u030a\")").getWord(),
+ "No NKFC by default");
}
@Test
- public void testImplicitTransforms() {
+ void testImplicitTransforms() {
assertFalse(getRootWord("select foo from bar where baz contains ({implicitTransforms: " +
- "false} \"cox\")").isFromQuery());
+ "false} \"cox\")").isFromQuery());
assertTrue(getRootWord("select foo from bar where baz contains ({implicitTransforms: " +
- "true} \"cox\")").isFromQuery());
+ "true} \"cox\")").isFromQuery());
assertTrue(getRootWord("select foo from bar where baz contains \"cox\"").isFromQuery());
}
@Test
- public void testConnectivity() {
+ void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
- "title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
- "and title contains ({id: 2}\"saint\") " +
- "and title contains ({id: 3}\"angel\")");
+ "title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
+ "and title contains ({id: 2}\"saint\") " +
+ "and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel",
- parsed.toString());
- AndItem root = (AndItem)parsed.getRoot();
- WordItem first = (WordItem)root.getItem(0);
- WordItem second = (WordItem)root.getItem(1);
- WordItem third = (WordItem)root.getItem(2);
- assertTrue(first.getConnectedItem() == third);
+ parsed.toString());
+ AndItem root = (AndItem) parsed.getRoot();
+ WordItem first = (WordItem) root.getItem(0);
+ WordItem second = (WordItem) root.getItem(1);
+ WordItem third = (WordItem) root.getItem(2);
+ assertEquals(first.getConnectedItem(), third);
assertEquals(first.getConnectivity(), 7.0d, 1E-6);
assertNull(second.getConnectedItem());
assertParseFail("select foo from bar where " +
- "title contains ({id: 1, connectivity: {id: 4, weight: 7.0}}\"madonna\") " +
- "and title contains ({id: 2}\"saint\") " +
- "and title contains ({id: 3}\"angel\")",
- new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
- "which does not exist in the query."));
+ "title contains ({id: 1, connectivity: {id: 4, weight: 7.0}}\"madonna\") " +
+ "and title contains ({id: 2}\"saint\") " +
+ "and title contains ({id: 3}\"angel\")",
+ new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
+ "which does not exist in the query."));
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
QueryTree parsed =
parse("select foo from bar where baz contains ({label: \"hello world\"}phrase(\"a\", \"b\"))");
assertEquals("baz:\"a b\"", parsed.toString());
- PhraseItem phrase = (PhraseItem)parsed.getRoot();
+ PhraseItem phrase = (PhraseItem) parsed.getRoot();
assertEquals("hello world", phrase.getLabel());
}
@Test
- public void testRange() {
+ void testRange() {
QueryTree parsed = parse("select foo from bar where range(baz,1,8)");
assertEquals("baz:[1;8]", parsed.toString());
}
@Test
- public void testRangeWithEndInfinity() {
+ void testRangeWithEndInfinity() {
QueryTree parsed = parse("select foo from bar where range(baz,1,Infinity)");
assertEquals("baz:[1;]", parsed.toString());
}
@Test
- public void testRangeWithStartInfinity() {
+ void testRangeWithStartInfinity() {
QueryTree parsed = parse("select foo from bar where range(baz,-Infinity,8)");
assertEquals("baz:[;8]", parsed.toString());
}
@Test
- public void testNegativeRange() {
+ void testNegativeRange() {
QueryTree parsed = parse("select foo from bar where range(baz,-8,-1)");
assertEquals("baz:[-8;-1]", parsed.toString());
}
@Test
- public void testRangeIllegalArguments() {
+ void testRangeIllegalArguments() {
assertParseFail("select foo from bar where range(baz,cox,8)",
- new IllegalArgumentException("Expected a numerical argument (or 'Infinity') to range but got 'cox'"));
+ new IllegalArgumentException("Expected a numerical argument (or 'Infinity') to range but got 'cox'"));
}
@Test
- public void testNear() {
+ void testNear() {
assertParse("select foo from bar where description contains near(\"a\", \"b\")",
- "NEAR(2) description:a description:b");
+ "NEAR(2) description:a description:b");
assertParse("select foo from bar where description contains ({distance: 100} near(\"a\", \"b\"))",
- "NEAR(100) description:a description:b");
+ "NEAR(100) description:a description:b");
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
assertParse("select foo from bar where description contains onear(\"a\", \"b\");",
- "ONEAR(2) description:a description:b");
+ "ONEAR(2) description:a description:b");
assertParse("select foo from bar where description contains ({distance: 100} onear(\"a\", \"b\"))",
- "ONEAR(100) description:a description:b");
+ "ONEAR(100) description:a description:b");
}
@Test
- public void testWand() {
+ void testWand() {
assertParse("select foo from bar where wand(description, {\"a\":1, \"b\":2});",
"WAND(10,0.0,1.0) description{[1]:\"a\",[2]:\"b\"}");
assertParse("select foo from bar where {scoreThreshold : 13.3, targetHits: 7, " +
- "thresholdBoostFactor: 2.3} wand(description, {\"a\":1, \"b\":2})",
- "WAND(7,13.3,2.3) description{[1]:\"a\",[2]:\"b\"}");
+ "thresholdBoostFactor: 2.3} wand(description, {\"a\":1, \"b\":2})",
+ "WAND(7,13.3,2.3) description{[1]:\"a\",[2]:\"b\"}");
}
@Test
- public void testQuotedAnnotations() {
+ void testQuotedAnnotations() {
assertParse("select foo from bar where {\"scoreThreshold\": 13.3, \"targetHits\": 7, " +
- "'thresholdBoostFactor': 2.3} wand(description, {\"a\":1})",
- "WAND(7,13.3,2.3) description{[1]:\"a\"}");
+ "'thresholdBoostFactor': 2.3} wand(description, {\"a\":1})",
+ "WAND(7,13.3,2.3) description{[1]:\"a\"}");
}
@Test
- public void testNumericWand() {
+ void testNumericWand() {
String numWand = "WAND(10,0.0,1.0) description{[1]:\"11\",[2]:\"37\"}";
assertParse("select foo from bar where wand(description, [[11,1], [37,2]])", numWand);
assertParse("select foo from bar where wand(description, [[11L,1], [37L,2]])", numWand);
assertParseFail("select foo from bar where wand(description, 12);",
- new IllegalArgumentException("Expected ARRAY or MAP, got LITERAL."));
+ new IllegalArgumentException("Expected ARRAY or MAP, got LITERAL."));
}
- @Test
//This test is order dependent. Fix it!
- public void testWeightedSet() {
+ @Test
+ void testWeightedSet() {
assertParse("select foo from bar where weightedSet(description, {\"a\":1, \"b\":2})",
- "WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
+ "WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
assertParseFail("select foo from bar where weightedSet(description, {\"a\":g, \"b\":2})",
- new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: " +
- "query:L1:56 no viable alternative at input 'weightedSet(description, {\"a\":g'"));
+ new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: " +
+ "query:L1:56 no viable alternative at input 'weightedSet(description, {\"a\":g'"));
assertParseFail("select foo from bar where weightedSet(description);",
- new IllegalArgumentException("Expected 2 arguments, got 1."));
+ new IllegalArgumentException("Expected 2 arguments, got 1."));
}
//This test is order dependent. Fix it!
@Test
- public void testDotProduct() {
+ void testDotProduct() {
assertParse("select foo from bar where dotProduct(description, {\"a\":1, \"b\":2})",
- "DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
+ "DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
assertParse("select foo from bar where dotProduct(description, {\"a\":2})",
- "DOTPRODUCT description{[2]:\"a\"}");
+ "DOTPRODUCT description{[2]:\"a\"}");
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
assertParse("select foo from bar where geoLocation(workplace, 63.418417, 10.433033, \"0.5 deg\")",
- "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
+ "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
assertParse("select foo from bar where geoLocation(headquarters, \"37.416383\", \"-122.024683\", \"100 miles\")",
- "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
+ "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
assertParse("select foo from bar where geoLocation(home, \"E10.433033\", \"N63.418417\", \"5km\")",
- "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
+ "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
assertParseFail("select foo from bar where geoLocation(qux, 1, 2)",
- new IllegalArgumentException("Expected 4 arguments, got 3."));
+ new IllegalArgumentException("Expected 4 arguments, got 3."));
assertParseFail("select foo from bar where geoLocation(qux, 2.0, \"N5.0\", \"0.5 deg\");",
- new IllegalArgumentException(
- "Invalid geoLocation coordinates 'Latitude: 2.0 degrees' and 'Latitude: 5.0 degrees'"));
+ new IllegalArgumentException(
+ "Invalid geoLocation coordinates 'Latitude: 2.0 degrees' and 'Latitude: 5.0 degrees'"));
assertParse("select foo from bar where geoLocation(workplace, -12, -34, \"-77 d\")",
- "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
+ "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
assertParse("select foo from bar where nearestNeighbor(semantic_embedding, my_vector);",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
assertParse("select foo from bar where {targetHits: 37} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=37}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=37}");
assertParse("select foo from bar where {approximate: false, hnsw.exploreAdditionalHits: 8, targetHits: 3} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=8,distanceThreshold=Infinity,approximate=false,targetHits=3}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=8,distanceThreshold=Infinity,approximate=false,targetHits=3}");
assertParse("select foo from bar where {targetHits: 7, distanceThreshold: 100100.25} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=100100.25,approximate=true,targetHits=7}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=100100.25,approximate=true,targetHits=7}");
}
@Test
- public void testTrueAndFalse() {
+ void testTrueAndFalse() {
assertParse("select foo from bar where true", "TRUE");
assertParse("select foo from bar where false", "FALSE");
assertParse("select foo from bar where ((title contains \"foo\") AND true) AND !((title contains \"bar\") or false)",
- "+(AND title:foo TRUE) -(OR title:bar FALSE)");
+ "+(AND title:foo TRUE) -(OR title:bar FALSE)");
}
@Test
- public void testPredicate() {
+ void testPredicate() {
assertParse("select foo from bar where predicate(predicate_field, " +
"{\"gender\":\"male\", \"hobby\":[\"music\", \"hiking\"]}, {\"age\":23L})",
"PREDICATE_QUERY_ITEM gender=male, hobby=music, hobby=hiking, age:23");
@@ -673,113 +671,113 @@ public class YqlParserTestCase {
}
@Test
- public void testPredicateWithSubQueries() {
+ void testPredicateWithSubQueries() {
assertParse("select foo from bar where predicate(predicate_field, " +
"{\"0x03\":{\"gender\":\"male\"},\"0x01\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"0x80ffffffffffffff\":{\"age\":23L}})",
"PREDICATE_QUERY_ITEM gender=male[0x3], hobby=music[0x1], hobby=hiking[0x1], age:23[0x80ffffffffffffff]");
assertParseFail("select foo from bar where predicate(foo, null, {\"0x80000000000000000\":{\"age\":23}})",
new NumberFormatException("Too long subquery string: 0x80000000000000000"));
assertParse("select foo from bar where predicate(predicate_field, " +
- "{\"[0,1]\":{\"gender\":\"male\"},\"[0]\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"[62, 63]\":{\"age\":23L}})",
+ "{\"[0,1]\":{\"gender\":\"male\"},\"[0]\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"[62, 63]\":{\"age\":23L}})",
"PREDICATE_QUERY_ITEM gender=male[0x3], hobby=music[0x1], hobby=hiking[0x1], age:23[0xc000000000000000]");
}
@Test
- public void testRank() {
+ void testRank() {
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\")",
- "RANK a:A b:B");
+ "RANK a:A b:B");
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\", c " +
- "contains \"C\")",
- "RANK a:A b:B c:C");
+ "contains \"C\")",
+ "RANK a:A b:B c:C");
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\" or c " +
- "contains \"C\")",
- "RANK a:A (OR b:B c:C)");
+ "contains \"C\")",
+ "RANK a:A (OR b:B c:C)");
}
@Test
@SuppressWarnings("deprecation")
- public void testWeakAnd() {
+ void testWeakAnd() {
assertParse("select foo from bar where weakAnd(a contains \"A\", b contains \"B\")",
- "WEAKAND(100) a:A b:B");
+ "WEAKAND(100) a:A b:B");
assertParse("select foo from bar where {targetHits: 37}weakAnd(a contains \"A\", " +
- "b contains \"B\")",
- "WEAKAND(37) a:A b:B");
+ "b contains \"B\")",
+ "WEAKAND(37) a:A b:B");
QueryTree tree = parse("select foo from bar where weakAnd(a " +
- "contains \"A\", b contains \"B\")");
+ "contains \"A\", b contains \"B\")");
assertEquals("WEAKAND(100) a:A b:B", tree.toString());
assertEquals(WeakAndItem.class, tree.getRoot().getClass());
}
@Test
- public void testEquiv() {
+ void testEquiv() {
assertParse("select foo from bar where fieldName contains equiv(\"A\",\"B\")",
- "EQUIV fieldName:A fieldName:B");
+ "EQUIV fieldName:A fieldName:B");
assertParse("select foo from bar where fieldName contains " +
- "equiv(\"ny\",phrase(\"new\",\"york\"));",
- "EQUIV fieldName:ny fieldName:\"new york\"");
+ "equiv(\"ny\",phrase(\"new\",\"york\"));",
+ "EQUIV fieldName:ny fieldName:\"new york\"");
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\")",
- new IllegalArgumentException("Expected 2 or more arguments, got 1."));
+ new IllegalArgumentException("Expected 2 or more arguments, got 1."));
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\", nalle(void))",
- new IllegalArgumentException("Expected function 'phrase', got 'nalle'."));
+ new IllegalArgumentException("Expected function 'phrase', got 'nalle'."));
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\", 42)",
- new ClassCastException("Cannot cast java.lang.Integer to java.lang.String"));
+ new ClassCastException("Cannot cast java.lang.Integer to java.lang.String"));
}
@Test
- public void testAffixItems() {
+ void testAffixItems() {
assertRootClass("select foo from bar where baz contains ({suffix: true}\"colors\")",
- SuffixItem.class);
+ SuffixItem.class);
assertRootClass("select foo from bar where baz contains ({prefix: true}\"colors\")",
- PrefixItem.class);
+ PrefixItem.class);
assertRootClass("select foo from bar where baz contains ({substring: true}\"colors\")",
- SubstringItem.class);
+ SubstringItem.class);
assertParseFail("select foo from bar where description contains ({suffix: true, " +
- "prefix: true}\"colors\")",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ "prefix: true}\"colors\")",
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
assertParseFail("select foo from bar where description contains ({suffix: true, " +
- "substring: true}\"colors\")",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ "substring: true}\"colors\")",
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
}
@Test
- public void testLongNumberInSimpleExpression() {
+ void testLongNumberInSimpleExpression() {
assertParse("select foo from bar where price = 8589934592L", "price:8589934592");
assertParse("select foo from bar where price = 8589934592", "price:8589934592");
}
@Test
- public void testNegativeLongNumberInSimpleExpression() {
+ void testNegativeLongNumberInSimpleExpression() {
assertParse("select foo from bar where price = -8589934592L", "price:-8589934592");
}
@Test
- public void testSources() {
+ void testSources() {
assertSources("select foo from sourceA where price <= 500", List.of("sourceA"));
}
@Test
- public void testQueryWithSemicolon() {
+ void testQueryWithSemicolon() {
assertParse("select foo from bar where price = 1", "price:1");
}
@Test
- public void testSourcesWithDash() {
+ void testSourcesWithDash() {
assertSources("select foo from source-a where price <= 500", List.of("source-a"));
}
@Test
- public void testWildCardSources() {
+ void testWildCardSources() {
assertSources("select foo from sources * where price <= 500", List.of());
}
@Test
- public void testMultiSources() {
+ void testMultiSources() {
assertSources("select foo from sources sourceA, sourceB where price <= 500", List.of("sourceA", "sourceB"));
}
@Test
- public void testFields() {
+ void testFields() {
assertSummaryFields("select fieldA from bar where price <= 500", List.of("fieldA"));
assertSummaryFields("select fieldA, fieldB from bar where price <= 500", List.of("fieldA", "fieldB"));
assertSummaryFields("select fieldA, fieldB, fieldC from bar where price <= 500", List.of("fieldA", "fieldB", "fieldC"));
@@ -787,37 +785,37 @@ public class YqlParserTestCase {
}
@Test
- public void testFieldsRoot() {
+ void testFieldsRoot() {
assertParse("select * from bar where price <= 500", "price:[;500]");
}
@Test
- public void testOffset() {
+ void testOffset() {
assertParse("select foo from bar where title contains \"madonna\" offset 37", "title:madonna");
assertEquals(Integer.valueOf(37), parser.getOffset());
}
@Test
- public void testLimit() {
+ void testLimit() {
assertParse("select foo from bar where title contains \"madonna\" limit 29", "title:madonna");
assertEquals(Integer.valueOf(29), parser.getHits());
}
@Test
- public void testOffsetAndLimit() {
+ void testOffsetAndLimit() {
assertParse("select foo from bar where title contains \"madonna\" limit 31 offset 29",
- "title:madonna");
+ "title:madonna");
assertEquals(Integer.valueOf(29), parser.getOffset());
assertEquals(Integer.valueOf(2), parser.getHits());
assertParse("select * from bar where title contains \"madonna\" limit 41 offset 37",
- "title:madonna");
+ "title:madonna");
assertEquals(Integer.valueOf(37), parser.getOffset());
assertEquals(Integer.valueOf(4), parser.getHits());
}
@Test
- public void testTimeout() {
+ void testTimeout() {
assertParse("select * from bar where title contains \"madonna\" timeout 7", "title:madonna");
assertEquals(Integer.valueOf(7), parser.getTimeout());
@@ -826,10 +824,10 @@ public class YqlParserTestCase {
}
@Test
- public void testOrdering() {
+ void testOrdering() {
assertParse("select foo from bar where title contains \"madonna\" order by something asc, " +
- "shoesize desc limit 600 timeout 3",
- "title:madonna");
+ "shoesize desc limit 600 timeout 3",
+ "title:madonna");
assertEquals(2, parser.getSorting().fieldOrders().size());
assertEquals("something", parser.getSorting().fieldOrders().get(0).getFieldName());
assertEquals(Order.ASCENDING, parser.getSorting().fieldOrders().get(0).getSortOrder());
@@ -837,14 +835,14 @@ public class YqlParserTestCase {
assertEquals(Order.DESCENDING, parser.getSorting().fieldOrders().get(1).getSortOrder());
assertParse("select foo from bar where title contains \"madonna\" order by other limit 600 " +
- "timeout 3",
- "title:madonna");
+ "timeout 3",
+ "title:madonna");
assertEquals("other", parser.getSorting().fieldOrders().get(0).getFieldName());
assertEquals(Order.ASCENDING, parser.getSorting().fieldOrders().get(0).getSortOrder());
}
@Test
- public void testAnnotatedOrdering() {
+ void testAnnotatedOrdering() {
assertParse(
"select foo from bar where title contains \"madonna\""
+ " order by {function: \"uca\", locale: \"en_US\", strength: \"IDENTICAL\"}other desc"
@@ -860,7 +858,7 @@ public class YqlParserTestCase {
}
@Test
- public void testMultipleAnnotatedOrdering() {
+ void testMultipleAnnotatedOrdering() {
assertParse(
"select foo from bar where title contains \"madonna\""
+ " order by {\"function\": \"uca\", \"locale\": \"en_US\", \"strength\": \"IDENTICAL\"}other desc,"
@@ -886,40 +884,40 @@ public class YqlParserTestCase {
}
@Test
- public void testSegmenting() {
+ void testSegmenting() {
assertParse("select * from bar where title contains 'foo.bar'", "title:'foo bar'");
assertParse("select * from bar where title contains 'foo&123'", "title:'foo 123'");
}
@Test
- public void testNegativeHitLimit() {
+ void testNegativeHitLimit() {
assertParse("select * from sources * where {hitLimit: -38}range(foo, 0, 1)", "foo:[0;1;-38]");
}
@Test
- public void testRangeSearchHitPopulationOrdering() {
+ void testRangeSearchHitPopulationOrdering() {
assertParse("select * from sources * where {hitLimit: 38, ascending: true}range(foo, 0, 1)",
- "foo:[0;1;38]");
+ "foo:[0;1;38]");
assertParse("select * from sources * where {hitLimit: 38, ascending: false}range(foo, 0, 1)",
- "foo:[0;1;-38]");
+ "foo:[0;1;-38]");
assertParse("select * from sources * where {hitLimit: 38, descending: true}range(foo, 0, 1)",
- "foo:[0;1;-38]");
+ "foo:[0;1;-38]");
assertParse("select * from sources * where {hitLimit: 38, descending: false}range(foo, 0, 1)",
- "foo:[0;1;38]");
+ "foo:[0;1;38]");
boolean gotExceptionFromParse = false;
try {
parse("select * from sources * where {hitLimit: 38, ascending: true, descending: false}range(foo, 0, 1)");
} catch (IllegalArgumentException e) {
- assertTrue("Expected information about abuse of settings.",
- e.getMessage().contains("both ascending and descending ordering set"));
+ assertTrue(e.getMessage().contains("both ascending and descending ordering set"),
+ "Expected information about abuse of settings.");
gotExceptionFromParse = true;
}
assertTrue(gotExceptionFromParse);
}
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
assertParse("select * from sources * where range(title, 0.0, 500.0)",
"title:[0.0;500.0]");
assertParse(
@@ -934,7 +932,7 @@ public class YqlParserTestCase {
}
@Test
- public void testInheritedAnnotations() {
+ void testInheritedAnnotations() {
{
QueryTree x = parse("select * from sources * where ({ranked: false}(foo contains \"a\" and bar contains \"b\")) or foor contains ({ranked: false}\"c\")");
List<IndexedItem> terms = QueryTree.getPositiveTerms(x);
@@ -954,12 +952,12 @@ public class YqlParserTestCase {
}
@Test
- public void testMoreInheritedAnnotations() {
+ void testMoreInheritedAnnotations() {
String yqlQuery = "select * from sources * where " +
- "({ranked: false}(foo contains \"a\" " +
- "and ({ranked: true}(bar contains \"b\" " +
- "or ({ranked: false}(foo contains \"c\" " +
- "and foo contains ({ranked: true}\"d\")))))))";
+ "({ranked: false}(foo contains \"a\" " +
+ "and ({ranked: true}(bar contains \"b\" " +
+ "or ({ranked: false}(foo contains \"c\" " +
+ "and foo contains ({ranked: true}\"d\")))))))";
QueryTree x = parse(yqlQuery);
List<IndexedItem> terms = QueryTree.getPositiveTerms(x);
assertEquals(4, terms.size());
@@ -980,11 +978,11 @@ public class YqlParserTestCase {
}
@Test
- public void testFieldAliases() {
+ void testFieldAliases() {
IndexInfoConfig modelConfig = new IndexInfoConfig(new IndexInfoConfig.Builder().indexinfo(new Indexinfo.Builder()
.name("music").command(new Command.Builder().indexname("title").command("index"))
.alias(new Alias.Builder().alias("song").indexname("title"))));
- IndexModel model = new IndexModel(modelConfig, (QrSearchersConfig)null);
+ IndexModel model = new IndexModel(modelConfig, (QrSearchersConfig) null);
IndexFacts indexFacts = new IndexFacts(model);
ParserEnvironment parserEnvironment = new ParserEnvironment().setIndexFacts(indexFacts);
@@ -999,7 +997,7 @@ public class YqlParserTestCase {
}
@Test
- public void testRegexp() {
+ void testRegexp() {
QueryTree x = parse("select * from sources * where foo matches \"a b\"");
Item root = x.getRoot();
assertSame(RegExpItem.class, root.getClass());
@@ -1007,7 +1005,7 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
QueryTree x = parse("select * from sources * where foo contains alternatives({trees: 1.0, \"tree\": 0.7})");
Item root = x.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
@@ -1016,10 +1014,10 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternativesWithOrigin() {
+ void testWordAlternativesWithOrigin() {
QueryTree q = parse("select * from sources * where foo contains" +
- " ({origin: {original: \" trees \", offset: 1, length: 5}}" +
- "alternatives({trees: 1.0, tree: 0.7}))");
+ " ({origin: {original: \" trees \", offset: 1, length: 5}}" +
+ "alternatives({trees: 1.0, tree: 0.7}))");
Item root = q.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
WordAlternativesItem alternatives = (WordAlternativesItem) root;
@@ -1032,9 +1030,9 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternativesInPhrase() {
+ void testWordAlternativesInPhrase() {
QueryTree q = parse("select * from sources * where" +
- " foo contains phrase(\"forest\", alternatives({trees: 1.0, tree: 0.7}))");
+ " foo contains phrase(\"forest\", alternatives({trees: 1.0, tree: 0.7}))");
Item root = q.getRoot();
assertSame(PhraseItem.class, root.getClass());
PhraseItem phrase = (PhraseItem) root;
@@ -1046,7 +1044,7 @@ public class YqlParserTestCase {
/** Verifies that we can search for a backslash */
@Test
- public void testBackslash() {
+ void testBackslash() {
{
String queryString = "select * from testtype where title contains \"\\\\\""; // Java escaping * YQL escaping
@@ -1063,7 +1061,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingDefaultAnchors() {
+ void testUrlHostSearchingDefaultAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:google.com&type=all"), false, true, true);
@@ -1074,7 +1072,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingNoAnchors() {
+ void testUrlHostSearchingNoAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:google.com*&type=all"), false, false, true);
@@ -1085,7 +1083,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingBothAnchors() {
+ void testUrlHostSearchingBothAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:%5Egoogle.com&type=all"), true, true, true); // %5E = ^
@@ -1096,7 +1094,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUriNonHostDoesNotCreateAnchors() {
+ void testUriNonHostDoesNotCreateAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield", new Query("?query=urlfield:google.com&type=all"), false, false, false);
@@ -1107,13 +1105,13 @@ public class YqlParserTestCase {
}
@Test
- public void testReservedWordInSource() {
+ void testReservedWordInSource() {
parse("select * from sources like where text contains \"test\"");
// success: parsed without exception
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
parse("select * from sources * where (default contains ({stem: false}\"m\") AND default contains ({origin: {original: \"m\'s\", offset: 0, length: 3}, andSegmenting: true}phrase(\"m\", \"s\"))) timeout 472");
}
@@ -1198,11 +1196,11 @@ public class YqlParserTestCase {
assertEquals(2, alternatives.getAlternatives().size());
for (WordAlternativesItem.Alternative alternative : alternatives.getAlternatives()) {
if (tree.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenTree);
+ assertFalse(seenTree, "Duplicate term introduced");
seenTree = true;
assertEquals(.7d, alternative.exactness, 1e-15d);
} else if (forest.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenForest);
+ assertFalse(seenForest, "Duplicate term introduced");
seenForest = true;
assertEquals(1.0d, alternative.exactness, 1e-15d);
} else {
diff --git a/container-search/src/test/java/com/yahoo/select/SelectTestCase.java b/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
index 6ebcc3a1aae..887a1a3a033 100644
--- a/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
+++ b/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
@@ -33,18 +33,12 @@ import com.yahoo.search.query.SelectParser;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.yql.VespaGroupingStep;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests Query.Select
@@ -61,7 +55,7 @@ public class SelectTestCase {
//------------------------------------------------------------------- "where" tests
@Test
- public void test_contains() {
+ void test_contains() {
ObjectNode json = jsonMapper.createObjectNode();
ArrayNode arrayNode = jsonMapper.createArrayNode();
arrayNode.add("default").add("foo");
@@ -70,22 +64,21 @@ public class SelectTestCase {
}
@Test
- public void test() {
+ void test() {
assertParse("{'contains' : ['title', 'madonna']}",
"title:madonna");
}
@Test
- public void testDottedFieldNames() {
+ void testDottedFieldNames() {
assertParse("{ 'contains' : ['my.nested.title', 'madonna']}",
"my.nested.title:madonna");
}
-
@Test
- public void testOr() throws Exception {
+ void testOr() throws Exception {
ObjectNode json_two_or = jsonMapper.createObjectNode();
ObjectNode json_three_or = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
@@ -107,7 +100,7 @@ public class SelectTestCase {
}
@Test
- public void testAnd() throws Exception{
+ void testAnd() throws Exception {
ObjectNode json_two_and = jsonMapper.createObjectNode();
ObjectNode json_three_and = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
@@ -129,7 +122,7 @@ public class SelectTestCase {
}
@Test
- public void testAndNot() {
+ void testAndNot() {
ObjectNode json_and_not = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
ArrayNode contains2 = jsonMapper.createArrayNode().add("title").add("saint");
@@ -146,7 +139,7 @@ public class SelectTestCase {
}
@Test
- public void testLessThan() {
+ void testLessThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<", 500);
@@ -160,7 +153,7 @@ public class SelectTestCase {
}
@Test
- public void testGreaterThan() {
+ void testGreaterThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">", 500);
@@ -174,7 +167,7 @@ public class SelectTestCase {
}
@Test
- public void testLessThanOrEqual() {
+ void testLessThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<=", 500);
@@ -188,7 +181,7 @@ public class SelectTestCase {
}
@Test
- public void testGreaterThanOrEqual() {
+ void testGreaterThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">=", 500);
@@ -202,7 +195,7 @@ public class SelectTestCase {
}
@Test
- public void testEquality() {
+ void testEquality() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("=", 500);
@@ -216,7 +209,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<", -500);
@@ -230,7 +223,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeGreaterThan() {
+ void testNegativeGreaterThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">", -500);
@@ -244,7 +237,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeLessThanOrEqual() {
+ void testNegativeLessThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<=", -500);
@@ -258,7 +251,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeGreaterThanOrEqual() {
+ void testNegativeGreaterThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">=", -500);
@@ -272,7 +265,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeEquality() {
+ void testNegativeEquality() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("=", -500);
@@ -286,38 +279,38 @@ public class SelectTestCase {
}
@Test
- public void testAnnotatedLessThan() {
+ void testAnnotatedLessThan() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"<\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:<-500");
}
@Test
- public void testAnnotatedGreaterThan() {
+ void testAnnotatedGreaterThan() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\">\" : 500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:>500");
}
@Test
- public void testAnnotatedLessThanOrEqual() {
+ void testAnnotatedLessThanOrEqual() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"<=\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:[;-500]");
}
@Test
- public void testAnnotatedGreaterThanOrEqual() {
+ void testAnnotatedGreaterThanOrEqual() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\">=\" : 500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:[500;]");
}
@Test
- public void testAnnotatedEquality() {
+ void testAnnotatedEquality() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"=\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:-500");
}
@Test
- public void testTermAnnotations() {
+ void testTermAnnotations() {
assertEquals("merkelapp",
getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"label\" : \"merkelapp\"} } }").getLabel());
assertEquals("another",
@@ -334,7 +327,7 @@ public class SelectTestCase {
}
@Test
- public void testSameElement() {
+ void testSameElement() {
assertParse("{ \"contains\": [ \"baz\", {\"sameElement\" : [ { \"contains\" : [\"f1\", \"a\"] }, { \"contains\" : [\"f2\", \"b\"] } ]} ] }",
"baz:{f1:a f2:b}");
@@ -346,53 +339,53 @@ public class SelectTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
assertParse("{ \"contains\": [ \"baz\", {\"phrase\" : [ \"a\", \"b\"] } ] }",
"baz:\"a b\"");
}
@Test
- public void testNestedPhrase() {
+ void testNestedPhrase() {
assertParse("{ \"contains\": [ \"baz\", {\"phrase\" : [ \"a\", \"b\", {\"phrase\" : [ \"c\", \"d\"] }] } ] }",
"baz:\"a b c d\"");
}
@Test
- public void testStemming() {
+ void testStemming() {
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"stem\" : false} } }").isStemmed());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"stem\" : true} } }").isStemmed());
assertFalse(getRootWord("{ \"contains\": [\"baz\", \"colors\"] }").isStemmed());
}
@Test
- public void testRaw() {
+ void testRaw() {
Item root = parseWhere("{ \"contains\":[ \"baz\", \"yoni jo dima\" ] }").getRoot();
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
root = parseWhere("{ \"contains\": { \"children\" : [\"baz\", \"yoni jo dima\"], \"attributes\" : {\"grammar\" : \"raw\"} } }").getRoot();
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
}
@Test
- public void testAccentDropping() {
+ void testAccentDropping() {
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"accentDrop\" : false} } }").isNormalizable());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"accentDrop\" : true} } }").isNormalizable());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"] } }").isNormalizable());
}
@Test
- public void testCaseNormalization() {
+ void testCaseNormalization() {
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"normalizeCase\" : false} } }").isLowercased());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"normalizeCase\" : true} } }").isLowercased());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"] } }").isLowercased());
}
@Test
- public void testSegmentingRule() {
+ void testSegmentingRule() {
assertEquals(SegmentingRule.PHRASE,
getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"andSegmenting\" : false} } }").getSegmentingRule());
assertEquals(SegmentingRule.BOOLEAN_AND,
@@ -402,30 +395,30 @@ public class SelectTestCase {
}
@Test
- public void testNfkc() {
+ void testNfkc() {
assertEquals("a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"], \"attributes\" : {\"nfkc\" : false} } }").getWord());
assertEquals("\u00e5", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"], \"attributes\" : {\"nfkc\" : true} } }").getWord());
- assertEquals("No NKFC by default", "a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"] } } ").getWord());
+ assertEquals("a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"] } } ").getWord(), "No NKFC by default");
}
@Test
- public void testImplicitTransforms() {
+ void testImplicitTransforms() {
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"], \"attributes\" : {\"implicitTransforms\" : false} } }").isFromQuery());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"], \"attributes\" : {\"implicitTransforms\" : true} } }").isFromQuery());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"] } }").isFromQuery());
}
@Test
- public void testConnectivity() {
+ void testConnectivity() {
QueryTree parsed = parseWhere("{ \"and\": [ {\"contains\" : { \"children\" : [\"title\", \"madonna\"], \"attributes\" : {\"id\": 1, \"connectivity\": {\"id\": 3, \"weight\": 7.0}} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"saint\"], \"attributes\" : {\"id\": 2} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"angel\"], \"attributes\" : {\"id\": 3} } } ] }");
assertEquals("AND title:madonna title:saint title:angel", parsed.toString());
- AndItem root = (AndItem)parsed.getRoot();
- WordItem first = (WordItem)root.getItem(0);
- WordItem second = (WordItem)root.getItem(1);
- WordItem third = (WordItem)root.getItem(2);
+ AndItem root = (AndItem) parsed.getRoot();
+ WordItem first = (WordItem) root.getItem(0);
+ WordItem second = (WordItem) root.getItem(1);
+ WordItem third = (WordItem) root.getItem(2);
assertEquals(third, first.getConnectedItem());
assertEquals(first.getConnectivity(), 7.0d, 1E-6);
assertNull(second.getConnectedItem());
@@ -434,37 +427,37 @@ public class SelectTestCase {
"{ \"contains\" : { \"children\" : [\"title\", \"saint\"], \"attributes\" : {\"id\": 2} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"angel\"], \"attributes\" : {\"id\": 3} } } ] }",
new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
- "which does not exist in the query."));
+ "which does not exist in the query."));
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
QueryTree parsed = parseWhere("{ \"contains\": [\"baz\", { \"phrase\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"label\": \"hello world\" } } }] }");
assertEquals("baz:\"a b\"", parsed.toString());
- PhraseItem phrase = (PhraseItem)parsed.getRoot();
+ PhraseItem phrase = (PhraseItem) parsed.getRoot();
assertEquals("hello world", phrase.getLabel());
}
@Test
- public void testRange() {
+ void testRange() {
QueryTree parsed = parseWhere("{ \"range\": [\"baz\", { \">=\": 1, \"<=\": 8 }] }");
assertEquals("baz:[1;8]", parsed.toString());
}
@Test
- public void testNegativeRange() {
+ void testNegativeRange() {
QueryTree parsed = parseWhere("{ \"range\": [\"baz\", { \">=\": -8, \"<=\": -1 }] }");
assertEquals("baz:[-8;-1]", parsed.toString());
}
@Test
- public void testRangeIllegalArguments() {
+ void testRangeIllegalArguments() {
assertParseFail("{ \"range\": [\"baz\", { \">=\": \"cox\", \"<=\": -1 }] }",
new IllegalArgumentException("Expected a numeric argument to range, but got the string 'cox'"));
}
@Test
- public void testNear() {
+ void testNear() {
assertParse("{ \"contains\": [\"description\", { \"near\": [\"a\", \"b\"] }] }",
"NEAR(2) description:a description:b");
assertParse("{ \"contains\": [\"description\", { \"near\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"distance\": 100 } } } ] }",
@@ -472,7 +465,7 @@ public class SelectTestCase {
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
assertParse("{ \"contains\": [\"description\", { \"onear\": [\"a\", \"b\"] }] }",
"ONEAR(2) description:a description:b");
assertParse("{ \"contains\": [\"description\", { \"onear\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"distance\": 100 } } } ] }",
@@ -480,7 +473,7 @@ public class SelectTestCase {
}
@Test
- public void testWand() {
+ void testWand() {
assertParse("{ \"wand\": [\"description\", { \"a\": 1, \"b\": 2 }] }",
"WAND(10,0.0,1.0) description{[1]:\"a\",[2]:\"b\"}");
assertParse("{ \"wand\": { \"children\": [\"description\", { \"a\": 1, \"b\": 2 }], \"attributes\": { \"scoreThreshold\": 13.3, \"targetHits\": 7, \"thresholdBoostFactor\": 2.3 } } }",
@@ -488,7 +481,7 @@ public class SelectTestCase {
}
@Test
- public void testNumericWand() {
+ void testNumericWand() {
String numWand = "WAND(10,0.0,1.0) description{[1]:\"11\",[2]:\"37\"}";
assertParse("{ \"wand\" : [\"description\", [[11,1], [37,2]] ]}", numWand);
assertParseFail("{ \"wand\" : [\"description\", 12] }",
@@ -496,7 +489,7 @@ public class SelectTestCase {
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
assertParse("{ \"weightedSet\" : [\"description\", {\"a\":1, \"b\":2} ]}",
"WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
assertParseFail("{ \"weightedSet\" : [\"description\", {\"a\":\"g\", \"b\":2} ]}",
@@ -506,7 +499,7 @@ public class SelectTestCase {
}
@Test
- public void testDotProduct() {
+ void testDotProduct() {
assertParse("{ \"dotProduct\" : [\"description\", {\"a\":1, \"b\":2} ]}",
"DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
assertParse("{ \"dotProduct\" : [\"description\", {\"a\":2} ]}",
@@ -514,7 +507,7 @@ public class SelectTestCase {
}
@Test
- public void testPredicate() {
+ void testPredicate() {
assertParse("{ \"predicate\" : [\"predicate_field\", {\"gender\":\"male\", \"hobby\":[\"music\", \"hiking\"]}, {\"age\":23} ]}",
"PREDICATE_QUERY_ITEM gender=male, hobby=music, hobby=hiking, age:23");
assertParse("{ \"predicate\" : [\"predicate_field\", 0, \"void\" ]}",
@@ -522,7 +515,7 @@ public class SelectTestCase {
}
@Test
- public void testRank() {
+ void testRank() {
assertParse("{ \"rank\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ] }",
"RANK a:A b:B");
assertParse("{ \"rank\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] }, { \"contains\": [\"c\", \"C\"] } ] }",
@@ -532,19 +525,19 @@ public class SelectTestCase {
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
assertParse("{ \"geoLocation\": [ \"workplace\", 63.418417, 10.433033, \"0.5 deg\" ] }",
- "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
+ "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
assertParse("{ \"geoLocation\": [ \"headquarters\", \"37.416383\", \"-122.024683\", \"100 miles\" ] }",
- "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
+ "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
assertParse("{ \"geoLocation\": [ \"home\", \"E10.433033\", \"N63.418417\", \"5km\" ] }",
- "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
+ "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
assertParse("{ \"geoLocation\": [ \"workplace\", -12.0, -34.0, \"-77 deg\" ] }",
- "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
+ "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
assertParse("{ \"nearestNeighbor\": [ \"f1field\", \"q2prop\" ] }",
"NEAREST_NEIGHBOR {field=f1field,queryTensorName=q2prop,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
@@ -554,7 +547,7 @@ public class SelectTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testWeakAnd() {
+ void testWeakAnd() {
assertParse("{ \"weakAnd\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ] }",
"WEAKAND(100) a:A b:B");
assertParse("{ \"weakAnd\": { \"children\" : [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ], \"attributes\" : {\"targetHits\": 37} }}",
@@ -566,7 +559,7 @@ public class SelectTestCase {
}
@Test
- public void testEquiv() {
+ void testEquiv() {
assertParse("{ \"contains\" : [\"fieldName\", {\"equiv\" : [\"A\",\"B\"]}]}",
"EQUIV fieldName:A fieldName:B");
@@ -582,42 +575,42 @@ public class SelectTestCase {
}
@Test
- public void testAffixItems() {
+ void testAffixItems() {
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true} } }",
- SuffixItem.class);
+ SuffixItem.class);
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"prefix\": true} } }",
- PrefixItem.class);
+ PrefixItem.class);
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"substring\": true} } }",
- SubstringItem.class);
+ SubstringItem.class);
assertParseFail("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true, \"prefix\" : true} } }",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
assertParseFail("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true, \"substring\" : true} } }",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
}
@Test
- public void testLongNumberInSimpleExpression() {
+ void testLongNumberInSimpleExpression() {
assertParse("{ \"range\" : [ \"price\", { \"=\" : 8589934592 }]}",
"price:8589934592");
}
@Test
- public void testNegativeLongNumberInSimpleExpression() {
+ void testNegativeLongNumberInSimpleExpression() {
assertParse("{ \"range\" : [ \"price\", { \"=\" : -8589934592 }]}",
"price:-8589934592");
}
@Test
- public void testNegativeHitLimit() {
+ void testNegativeHitLimit() {
assertParse(
"{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": -38 } } }",
"foo:[0;1;-38]");
}
@Test
- public void testRangeSearchHitPopulationOrdering() {
+ void testRangeSearchHitPopulationOrdering() {
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"ascending\": true} } }", "foo:[0;1;38]");
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"ascending\": false} } }", "foo:[0;1;-38]");
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"descending\": true} } }", "foo:[0;1;-38]");
@@ -627,8 +620,8 @@ public class SelectTestCase {
try {
parseWhere("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38, \"ascending\": true, \"descending\": false} } }");
} catch (IllegalArgumentException e) {
- assertTrue("Expected information about abuse of settings.",
- e.getCause().getMessage().contains("both ascending and descending ordering set"));
+ assertTrue(e.getCause().getMessage().contains("both ascending and descending ordering set"),
+ "Expected information about abuse of settings.");
gotExceptionFromParse = true;
}
assertTrue(gotExceptionFromParse);
@@ -636,9 +629,9 @@ public class SelectTestCase {
// NB: Uses operator-keys to set bounds, not annotations
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
assertParse("{ \"range\" : { \"children\":[ \"title\", { \">=\" : 0.0, \"<=\" : 500.0 }] } }" +
- "select * from sources * where range(title, 0.0, 500.0)",
+ "select * from sources * where range(title, 0.0, 500.0)",
"title:[0.0;500.0]");
assertParse(
"{ \"range\" : { \"children\":[ \"title\", { \">\" : 0.0, \"<\" : 500.0 }] } }",
@@ -652,13 +645,13 @@ public class SelectTestCase {
}
@Test
- public void testEquals() {
- assertParse("{\"equals\": [\"public\",true]}","public:true");
- assertParse("{\"equals\": [\"public\",5]}","public:5");
+ void testEquals() {
+ assertParse("{\"equals\": [\"public\",true]}", "public:true");
+ assertParse("{\"equals\": [\"public\",5]}", "public:5");
}
@Test
- public void testRegexp() {
+ void testRegexp() {
QueryTree x = parseWhere("{ \"matches\" : [\"foo\", \"a b\"]}");
Item root = x.getRoot();
assertSame(RegExpItem.class, root.getClass());
@@ -666,7 +659,7 @@ public class SelectTestCase {
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
QueryTree x = parseWhere("{\"contains\" : [\"foo\", {\"alternatives\" : [{\"trees\": 1.0, \"tree\": 0.7}]}]}");
Item root = x.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
@@ -675,7 +668,7 @@ public class SelectTestCase {
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
QueryTree x = parseWhere("{ \"contains\": [\"description\", { \"fuzzy\": [\"a b\"] }] }");
Item root = x.getRoot();
assertSame(FuzzyItem.class, root.getClass());
@@ -686,14 +679,14 @@ public class SelectTestCase {
//------------------------------------------------------------------- grouping tests
@Test
- public void testGrouping(){
+ void testGrouping() {
String grouping = "[ { \"all\" : { \"group\" : \"time.year(a)\", \"each\" : { \"output\" : \"count()\" } } } ]";
String expected = "[[]all(group(time.year(a)) each(output(count())))]";
assertGrouping(expected, parseGrouping(grouping));
}
@Test
- public void testMultipleGroupings() {
+ void testMultipleGroupings() {
String grouping = "[ { \"all\" : { \"group\" : \"a\", \"each\" : { \"output\" : \"count()\"}}}, { \"all\" : { \"group\" : \"b\", \"each\" : { \"output\" : \"count()\"}}} ]";
String expected = "[[]all(group(a) each(output(count()))), []all(group(b) each(output(count())))]";
@@ -701,14 +694,14 @@ public class SelectTestCase {
}
@Test
- public void testGroupingWithPredefinedBuckets() {
+ void testGroupingWithPredefinedBuckets() {
String grouping = "[ { \"all\" : { \"group\" : { \"predefined\" : [ \"foo\", { \"bucket\": [1,2]}, { \"bucket\": [3,4]} ] } } } ]";
String expected = "[[]all(group(predefined(foo, bucket[1, 2>, bucket[3, 4>)))]";
assertGrouping(expected, parseGrouping(grouping));
}
@Test
- public void testMultipleOutputs() {
+ void testMultipleOutputs() {
String grouping = "[ { \"all\" : { \"group\" : \"b\", \"each\" : {\"output\": [ \"count()\", \"avg(foo)\" ] } } } ]";
String expected = "[[]all(group(b) each(output(count(), avg(foo))))]";
assertGrouping(expected, parseGrouping(grouping));
@@ -717,7 +710,7 @@ public class SelectTestCase {
//------------------------------------------------------------------- Other tests
@Test
- public void testOverridingOtherQueryTree() {
+ void testOverridingOtherQueryTree() {
Query query = new Query("?query=default:query");
assertEquals("WEAKAND(100) default:query", query.getModel().getQueryTree().toString());
assertEquals(Query.Type.WEAKAND, query.getModel().getType());
@@ -728,7 +721,7 @@ public class SelectTestCase {
}
@Test
- public void testOverridingWhereQueryTree() {
+ void testOverridingWhereQueryTree() {
Query query = new Query("?query=default:query");
query.getSelect().setWhereString("{\"contains\" : [\"default\", \"select\"] }");
assertEquals("default:select", query.getModel().getQueryTree().toString());
@@ -741,7 +734,7 @@ public class SelectTestCase {
}
@Test
- public void testProgrammaticAssignment() {
+ void testProgrammaticAssignment() {
Query query = new Query();
query.getSelect().setGroupingString("[ { \"all\" : { \"group\" : \"time.year(a)\", \"each\" : { \"output\" : \"count()\" } } } ]");
assertEquals(1, query.getSelect().getGrouping().size());
@@ -754,7 +747,7 @@ public class SelectTestCase {
}
@Test
- public void testConstructionAndClone() {
+ void testConstructionAndClone() {
Query query = new Query();
query.getSelect().setWhereString("{\"contains\" : [\"default\", \"select\"] }");
query.getSelect().setGroupingString("[ { \"all\" : { \"group\" : \"time.dayofmonth(a)\", \"each\" : { \"output\" : \"count()\" } } } ]");
@@ -776,7 +769,7 @@ public class SelectTestCase {
}
@Test
- public void testCloneWithGroupingExpressionString() {
+ void testCloneWithGroupingExpressionString() {
Query query = new Query();
query.getSelect().setGroupingExpressionString("all(group(foo) each(output(count())))");
@@ -785,12 +778,12 @@ public class SelectTestCase {
}
@Test
- public void testProgrammaticBuilding() {
+ void testProgrammaticBuilding() {
String expected =
"all(group(myfield) max(10000) each(" +
- "output(min(foo), max(bar)) " +
- "all(group(foo) max(10000) output(count()))" +
- "))";
+ "output(min(foo), max(bar)) " +
+ "all(group(foo) max(10000) output(count()))" +
+ "))";
Query query = new Query();
GroupingRequest grouping = GroupingRequest.newInstance(query);
AllOperation root = new AllOperation();
@@ -871,11 +864,11 @@ public class SelectTestCase {
assertEquals(2, alternatives.getAlternatives().size());
for (WordAlternativesItem.Alternative alternative : alternatives.getAlternatives()) {
if (tree.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenTree);
+ assertFalse(seenTree, "Duplicate term introduced");
seenTree = true;
assertEquals(.7d, alternative.exactness, 1e-15d);
} else if (forest.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenForest);
+ assertFalse(seenForest, "Duplicate term introduced");
seenForest = true;
assertEquals(1.0d, alternative.exactness, 1e-15d);
} else {
diff --git a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
index f439db390ee..fcb77851f0f 100644
--- a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
@@ -11,12 +11,9 @@ import com.yahoo.text.interpretation.AnnotationClass;
import com.yahoo.text.interpretation.Annotations;
import com.yahoo.text.interpretation.Interpretation;
import com.yahoo.text.interpretation.Span;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -24,12 +21,12 @@ import static org.junit.Assert.assertTrue;
public class AnnotationTestCase {
@Test
- public void testSimpleAnnotations() {
- Interpretation i= new Interpretation("new york hotel");
- i.annotate("sentence").put("isValid",true);
- i.annotate(0,3,"token");
- i.annotate(0,8,"place_name").put("^taxonomy:place_category","city");
- i.annotate(0,8,"place_name").put("woeid","12345678");
+ void testSimpleAnnotations() {
+ Interpretation i = new Interpretation("new york hotel");
+ i.annotate("sentence").put("isValid", true);
+ i.annotate(0, 3, "token");
+ i.annotate(0, 8, "place_name").put("^taxonomy:place_category", "city");
+ i.annotate(0, 8, "place_name").put("woeid", "12345678");
//i.getInterpretationAnnotation().put("domain","jaffa");
i.setProbability(0.5);
@@ -37,32 +34,32 @@ public class AnnotationTestCase {
}
@Test
- public void testAnnotationAPI() {
+ void testAnnotationAPI() {
Interpretation a = new Interpretation("new york hotel");
- a.annotate(0,3,"token");
- a.annotate(0,8,"state").put("name","New York");
- a.annotate(0,8,"state").put("country","US");
- a.annotate(0,8,"state").put("coast","east");
- a.annotate(9,14,"business");
- a.annotate(4,8,"token");
- a.annotate(9,14,"token");
+ a.annotate(0, 3, "token");
+ a.annotate(0, 8, "state").put("name", "New York");
+ a.annotate(0, 8, "state").put("country", "US");
+ a.annotate(0, 8, "state").put("coast", "east");
+ a.annotate(9, 14, "business");
+ a.annotate(4, 8, "token");
+ a.annotate(9, 14, "token");
- for(Span span : a.getTokens()) {
+ for (Span span : a.getTokens()) {
assertTrue(span.hasClass(new AnnotationClass("token")));
}
- Set<AnnotationClass> annotationClasses = a.getClasses(0,3);
+ Set<AnnotationClass> annotationClasses = a.getClasses(0, 3);
Set<AnnotationClass> testClass = new HashSet<>(Arrays.asList(
new AnnotationClass("token"), new AnnotationClass("state")));
- assertEquals(testClass,annotationClasses);
+ assertEquals(testClass, annotationClasses);
- assertNull(a.get("state","country"));
- assertEquals("US", a.get(0,8,"state","country"));
+ assertNull(a.get("state", "country"));
+ assertEquals("US", a.get(0, 8, "state", "country"));
assertEquals("new york", a.root().getSubSpans().get(0).getText());
assertEquals("hotel", a.root().getSubSpans().get(1).getText());
- assertEquals(2,a.root().getSubSpans().size());
+ assertEquals(2, a.root().getSubSpans().size());
//Test scoring
@@ -77,37 +74,37 @@ public class AnnotationTestCase {
//This is bad about the API, getTokens may not necessairily return what a user thinks a token is
//But it should still be tested
- a.annotate(0,1,"n");
- Set<String> testSet = new HashSet<>(Arrays.asList("n","york","hotel"));
- for(Span span:a.getTokens()) {
+ a.annotate(0, 1, "n");
+ Set<String> testSet = new HashSet<>(Arrays.asList("n", "york", "hotel"));
+ for (Span span :a.getTokens()) {
assertTrue(testSet.remove(span.getText()));
}
- assertEquals(0,testSet.size());
+ assertEquals(0, testSet.size());
}
//The following testcase is a test with the api on a use_case, no cornercases here
@Test
- public void testUsability() {
+ void testUsability() {
Interpretation interpretation = new Interpretation("new york crab pizza");
- interpretation.annotate(0,8,"place_name").put("^taxonomy:place_category","city");
- interpretation.annotate(0,8,"place_name").put("woe_id",2459115);
- interpretation.annotate(9,13,"food");
- interpretation.annotate(14,19,"food");
+ interpretation.annotate(0, 8, "place_name").put("^taxonomy:place_category", "city");
+ interpretation.annotate(0, 8, "place_name").put("woe_id", 2459115);
+ interpretation.annotate(9, 13, "food");
+ interpretation.annotate(14, 19, "food");
//Here we want to write code that finds out if the interpretation
//matches pizza and toppings.
List<Span> pizzaSpans = interpretation.getTermSpans("pizza");
- if(pizzaSpans.size() > 0) {
+ if (pizzaSpans.size() > 0) {
//We know that we have pizza, now we want to get some topping
//In a perfect world, pizza topping would have its own annotation class
//but for now, we'll just accept terms that have been tokenized with food
List<String> toppings = new ArrayList<>();
- for(Annotations annotations :interpretation.getAll("food")) {
- if(!annotations.getSubString().equalsIgnoreCase("pizza")) {
+ for (Annotations annotations :interpretation.getAll("food")) {
+ if (!annotations.getSubString().equalsIgnoreCase("pizza")) {
toppings.add(annotations.getSubString());
}
}
@@ -116,13 +113,13 @@ public class AnnotationTestCase {
//that all spans that has the annotation "place_name" has a "woe_id".
int woe_id = 0;
- for(Annotations annotations :interpretation.getAll("place_name")) {
+ for (Annotations annotations :interpretation.getAll("place_name")) {
//This will return either 0 or throw a bad exception
//if a number is not found
woe_id = annotations.getInteger("woe_id");
}
- assertEquals(Arrays.asList("crab"),toppings);
- assertEquals(2459115,woe_id);
+ assertEquals(Arrays.asList("crab"), toppings);
+ assertEquals(2459115, woe_id);
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
index 5523fe3c893..97dc2674256 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Carlin
@@ -31,9 +31,9 @@ public class ListMergerTestCase {
}
@Test
- public void testMergeLists() {
+ void testMergeLists() {
int entryCount = 6;
- int padding = (int)Math.log10(entryCount) + 1;
+ int padding = (int) Math.log10(entryCount) + 1;
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
@@ -42,17 +42,17 @@ public class ListMergerTestCase {
List<String> newList = ListMerger.mergeIntoArrayList(list1, list2);
verifyList(newList, entryCount, padding);
- newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount/2);
- verifyList(newList, entryCount/2, padding);
+ newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount / 2);
+ verifyList(newList, entryCount / 2, padding);
- ListMerger.mergeLinkedLists(list1, list2, entryCount/2);
- verifyList(list1, entryCount/2, padding);
+ ListMerger.mergeLinkedLists(list1, list2, entryCount / 2);
+ verifyList(list1, entryCount / 2, padding);
}
@Test
- public void testMergeListsReversed() {
+ void testMergeListsReversed() {
int entryCount = 6;
- int padding = (int)Math.log10(entryCount) + 1;
+ int padding = (int) Math.log10(entryCount) + 1;
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
@@ -61,11 +61,11 @@ public class ListMergerTestCase {
List<String> newList = ListMerger.mergeIntoArrayList(list1, list2);
verifyList(newList, entryCount, padding);
- newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount/2);
- verifyList(newList, entryCount/2, padding);
+ newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount / 2);
+ verifyList(newList, entryCount / 2, padding);
- ListMerger.mergeLinkedLists(list1, list2, entryCount/2);
- verifyList(list1, entryCount/2, padding);
+ ListMerger.mergeLinkedLists(list1, list2, entryCount / 2);
+ verifyList(list1, entryCount / 2, padding);
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
index c407945ee15..8e2380f72c2 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
@@ -9,11 +9,9 @@ import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.vdslib.VisitorStatistics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Carlin
@@ -36,12 +34,12 @@ public class MetricsSearcherTestCase {
assertEquals("news:0", result.hits().get(0).getId().toString());
} else {
assertNotNull(result.hits().getError());
- assertTrue("Expected '" + message + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message));
- assertTrue("Expected '" + detailedMessage + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage));
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message),
+ "Expected '" + message + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'");
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage),
+ "Expected '" + detailedMessage + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'");
}
if (metricParam == null) {
@@ -77,21 +75,21 @@ public class MetricsSearcherTestCase {
}
@Test
- public void testBasics() {
+ void testBasics() {
// Start counting at -1 since count is reset upon the first query by MetricsSearcher.search
expStatsLt1.count--;
- String[] loadTypes = { LOADTYPE1, LOADTYPE2};
+ String[] loadTypes = {LOADTYPE1, LOADTYPE2};
for (String loadType : loadTypes) {
- verifySearch("streaming.loadtype="+loadType, null, null);
- verifySearch("metricsearcher.id="+loadType, null, null);
+ verifySearch("streaming.loadtype=" + loadType, null, null);
+ verifySearch("metricsearcher.id=" + loadType, null, null);
verifySearch(null, null, null);
- verifySearch("streaming.loadtype="+loadType, "Backend communication error", "Detailed error message");
+ verifySearch("streaming.loadtype=" + loadType, "Backend communication error", "Detailed error message");
}
}
@Test
- public void searcherDoesNotTryToDereferenceNullQueryContext() {
+ void searcherDoesNotTryToDereferenceNullQueryContext() {
backend.setImplicitlyCreateContext(false);
// This will crash with an NPE if the searcher does not cope with null
// query contexts.
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
index 3cf2a38982a..0ecf1db01e5 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
@@ -23,7 +23,7 @@ import com.yahoo.vespa.streamingvisitors.tracing.MockUtils;
import com.yahoo.vespa.streamingvisitors.tracing.MonotonicNanoClock;
import com.yahoo.vespa.streamingvisitors.tracing.SamplingStrategy;
import com.yahoo.vespa.streamingvisitors.tracing.TraceExporter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
@@ -31,11 +31,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -185,12 +181,12 @@ public class VdsStreamingSearcherTestCase {
for (Query query : generateTestQueries(queryString)) {
Result result = executeQuery(searcher, query);
assertNotNull(result.hits().getError());
- assertTrue("Expected '" + message + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message));
- assertTrue("Expected '" + detailedMessage + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage));
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message),
+ "Expected '" + message + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'");
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage),
+ "Expected '" + detailedMessage + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'");
}
}
@@ -217,17 +213,17 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void testBasics() {
+ void testBasics() {
MockVisitorFactory factory = new MockVisitorFactory();
VdsStreamingSearcher searcher = new VdsStreamingSearcher(factory);
var schema = new Schema.Builder("test");
schema.add(new com.yahoo.search.schema.DocumentSummary.Builder("default").build());
searcher.init("container.0",
- new SummaryParameters("default"),
- new ClusterParams("clusterName"),
- new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")).build(),
- new SchemaInfo(List.of(schema.build()), Map.of()));
+ new SummaryParameters("default"),
+ new ClusterParams("clusterName"),
+ new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")).build(),
+ new SchemaInfo(List.of(schema.build()), Map.of()));
// Magic query values are used to trigger specific behaviors from mock visitor.
checkError(searcher, "/?query=noselection",
@@ -256,7 +252,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void testVerifyDocId() {
+ void testVerifyDocId() {
Query generalQuery = new Query("/?streaming.selection=true&query=test");
Query user1Query = new Query("/?streaming.userid=1&query=test");
Query group1Query = new Query("/?streaming.groupname=group1&query=test");
@@ -321,7 +317,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_level_set_if_sampling_strategy_returns_true() {
+ void trace_level_set_if_sampling_strategy_returns_true() {
var f = TraceFixture.withSampledTrace(true);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception"));
@@ -330,7 +326,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_level_not_set_if_sampling_strategy_returns_false() {
+ void trace_level_not_set_if_sampling_strategy_returns_false() {
var f = TraceFixture.withSampledTrace(false);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception"));
@@ -339,7 +335,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_is_exported_if_timed_out_beyond_threshold() {
+ void trace_is_exported_if_timed_out_beyond_threshold() {
// Default mock timeout threshold is 2x timeout
var f = TraceFixture.withTracingAndClockSampledAt(1000, 3001);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception&timeout=1.0"));
@@ -348,7 +344,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_is_not_exported_if_timed_out_less_than_threshold() {
+ void trace_is_not_exported_if_timed_out_less_than_threshold() {
// Default mock timeout threshold is 2x timeout
var f = TraceFixture.withTracingAndClockSampledAt(1000, 2999);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception&timeout=1.0"));
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
index 19fa8c50424..0e3ecf1c8cc 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
@@ -19,13 +19,13 @@ import com.yahoo.text.Utf8String;
import com.yahoo.vdslib.DocumentSummary;
import com.yahoo.vdslib.SearchResult;
import com.yahoo.vespa.objects.BufferSerializer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:ulf@yahoo-inc.com">Ulf Carlin</a>
@@ -280,13 +280,13 @@ public class VdsVisitorTestCase {
}
@Test
- public void testGetQueryFlags() {
+ void testGetQueryFlags() {
assertEquals(0x00028000, VdsVisitor.getQueryFlags(new Query("/?query=test")));
assertEquals(0x00028080, VdsVisitor.getQueryFlags(new Query("/?query=test&hitcountestimate=true")));
assertEquals(0x00068000, VdsVisitor.getQueryFlags(new Query("/?query=test&rankfeatures=true")));
assertEquals(0x00068080, VdsVisitor.getQueryFlags(new Query("/?query=test&hitcountestimate=true&rankfeatures=true")));
- Query query= new Query("/?query=test");
+ Query query = new Query("/?query=test");
assertEquals(0x00028000, VdsVisitor.getQueryFlags(query));
query.setNoCache(true);
assertEquals(0x00038000, VdsVisitor.getQueryFlags(query));
@@ -295,7 +295,7 @@ public class VdsVisitorTestCase {
}
@Test
- public void testBasics() throws Exception {
+ void testBasics() throws Exception {
Route route = Route.parse("storageClusterRouteSpec");
String searchCluster = "searchClusterConfigId";
MockVisitorSessionFactory factory = new MockVisitorSessionFactory();
@@ -318,7 +318,7 @@ public class VdsVisitorTestCase {
}
@Test
- public void testFailures() throws Exception {
+ void testFailures() throws Exception {
Route route = Route.parse("storageClusterRouteSpec");
String searchCluster = "searchClusterConfigId";
MockVisitorSessionFactory factory = new MockVisitorSessionFactory();
@@ -346,11 +346,11 @@ public class VdsVisitorTestCase {
VdsVisitor visitor = new VdsVisitor(buildQuery(qa), searchCluster, route, "mytype", factory, 0);
try {
visitor.doSearch();
- assertTrue("Visitor did not fail", false);
+ assertTrue(false, "Visitor did not fail");
} catch (TimeoutException te) {
- assertTrue("Got TimeoutException unexpectedly", factory.timeoutQuery);
+ assertTrue(factory.timeoutQuery, "Got TimeoutException unexpectedly");
} catch (IllegalArgumentException iae) {
- assertTrue("Got IllegalArgumentException unexpectedly", factory.failQuery);
+ assertTrue(factory.failQuery, "Got IllegalArgumentException unexpectedly");
}
}
@@ -363,7 +363,7 @@ public class VdsVisitorTestCase {
visitor.onMessage(createDSM("id:ns:type::2"), ackToken);
try {
visitor.onMessage(createM(), ackToken);
- assertTrue("Unsupported message did not cause exception", false);
+ assertTrue(false, "Unsupported message did not cause exception");
} catch (UnsupportedOperationException uoe) {
assertTrue(uoe.getMessage().contains("VdsVisitor can only accept query result, search result, and documentsummary messages"));
}
@@ -389,10 +389,10 @@ public class VdsVisitorTestCase {
assertEquals("id:ns:type::0", hit.getDocId());
assertEquals(0.3, hit.getRank(), 0.01);
} else {
- assertTrue("Got too many hits", false);
+ assertTrue(false, "Got too many hits");
}
DocumentSummary.Summary summary = visitor.getSummaryMap().get(hit.getDocId());
- assertNotNull("Did not find summary for " + hit.getDocId(), summary);
+ assertNotNull(summary, "Did not find summary for " + hit.getDocId());
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
index cd951e83699..349bedafcce 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
@@ -1,22 +1,22 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class MaxSamplesPerPeriodTest {
@Test
- public void first_sample_in_period_returns_true() {
+ void first_sample_in_period_returns_true() {
var clock = MockUtils.mockedClockReturning(1000L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L);
assertTrue(sampler.shouldSample());
}
@Test
- public void samples_exceeding_period_count_return_false() {
+ void samples_exceeding_period_count_return_false() {
var clock = MockUtils.mockedClockReturning(1000L, 1100L, 1200L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 2L);
assertTrue(sampler.shouldSample());
@@ -25,7 +25,7 @@ public class MaxSamplesPerPeriodTest {
}
@Test
- public void sample_in_new_period_returns_true() {
+ void sample_in_new_period_returns_true() {
var clock = MockUtils.mockedClockReturning(1000L, 1900L, 2000L, 2900L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L);
assertTrue(sampler.shouldSample());
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
index 1ce05df5f26..f5576d5d512 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ProbabilisticSampleRateTest {
@@ -15,7 +15,7 @@ public class ProbabilisticSampleRateTest {
}
@Test
- public void samples_are_rate_limited_per_second() {
+ void samples_are_rate_limited_per_second() {
var clock = MockUtils.mockedClockReturning(ms2ns(10_000), ms2ns(10_500), ms2ns(10_500), ms2ns(10_501));
var rng = MockUtils.mockedRandomReturning(0.1, 0.51, 0.49, 0.01);
var sampler = new ProbabilisticSampleRate(clock, () -> rng, 1.0);
@@ -30,7 +30,7 @@ public class ProbabilisticSampleRateTest {
}
@Test
- public void zero_desired_sample_rate_returns_false() {
+ void zero_desired_sample_rate_returns_false() {
var clock = MockUtils.mockedClockReturning(ms2ns(10_000));
var rng = MockUtils.mockedRandomReturning(0.99999999); // [0, 1)
var sampler = new ProbabilisticSampleRate(clock, () -> rng, 0.0);
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java
index 36b6ed35213..f143efbf786 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -12,7 +12,7 @@ import static org.mockito.Mockito.when;
public class SamplingTraceExporterTest {
@Test
- public void sampling_decision_is_deferred_to_provided_sampler() {
+ void sampling_decision_is_deferred_to_provided_sampler() {
var exporter = mock(TraceExporter.class);
var sampler = mock(SamplingStrategy.class);
when(sampler.shouldSample()).thenReturn(true, false);
diff --git a/controller-api/pom.xml b/controller-api/pom.xml
index f7057c93561..c7ac5d3518a 100644
--- a/controller-api/pom.xml
+++ b/controller-api/pom.xml
@@ -85,17 +85,21 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>configdefinitions</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZmsClientMock.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZmsClientMock.java
index 53e2592e0a6..4e5f2ab64cb 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZmsClientMock.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZmsClientMock.java
@@ -274,6 +274,16 @@ public class ZmsClientMock implements ZmsClient {
}
@Override
+ public void deleteSubdomain(AthenzDomain parent, String name) {
+ athenz.domains.remove(new AthenzDomain(parent.getName() + "." + name));
+ }
+
+ @Override
+ public void deletePolicy(AthenzDomain domain, String athenzPolicy) {
+ athenz.getOrCreateDomain(domain).policies.remove(athenzPolicy);
+ }
+
+ @Override
public void close() {}
private static AthenzDomain getTenantDomain(AthenzResourceName resource) {
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZtsClientMock.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZtsClientMock.java
index 7322c8e15f8..4d019f2ce59 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZtsClientMock.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/athenz/ZtsClientMock.java
@@ -75,7 +75,7 @@ public class ZtsClientMock implements ZtsClient {
}
@Override
- public AthenzAccessToken getAccessToken(AthenzDomain domain) {
+ public AthenzAccessToken getAccessToken(AthenzDomain domain, List<AthenzIdentity> proxyPrincipals) {
throw new UnsupportedOperationException();
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/NoopRoleService.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/NoopRoleService.java
index 541eb3dbe90..1ef1bc5106c 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/NoopRoleService.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/NoopRoleService.java
@@ -35,4 +35,9 @@ public class NoopRoleService implements RoleService {
@Override
public void maintainRoles(List<TenantName> tenants) { }
+
+ @Override
+ public void cleanupRoles(List<TenantName> tenants) {
+
+ }
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/RoleService.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/RoleService.java
index bc661077537..0a35893a7c4 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/RoleService.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/aws/RoleService.java
@@ -27,4 +27,6 @@ public interface RoleService {
* Maintain roles for the tenants in the system. Create missing roles, update trust.
*/
void maintainRoles(List<TenantName> tenants);
+
+ void cleanupRoles(List<TenantName> deletedTenants);
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateDetails.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateDetails.java
index bf1c9333e84..3f5514dce8c 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateDetails.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateDetails.java
@@ -2,223 +2,30 @@
package com.yahoo.vespa.hosted.controller.api.integration.certificates;
import java.util.List;
-import java.util.Objects;
-import java.util.StringJoiner;
/**
- * This class is used when requesting additional metadata about an application's endpoint certificate from the provider.
+ * This record is used when requesting additional metadata about an application's endpoint certificate from the provider.
*
* @author andreer
*/
-public class EndpointCertificateDetails {
-
- private final String request_id;
- private final String requestor;
- private final String status;
- private final String ticket_id;
- private final String athenz_domain;
- private final List<EndpointCertificateRequestMetadata.DnsNameStatus> dnsnames;
- private final String duration_sec;
- private final String expiry;
- private final String private_key_kgname;
- private final String private_key_keyname;
- private final String private_key_version;
- private final String cert_key_kgname;
- private final String cert_key_keyname;
- private final String cert_key_version;
- private final String create_time;
- private final boolean expiry_protection;
- private final String public_key_algo;
- private final String issuer;
- private final String serial;
-
- public EndpointCertificateDetails(String request_id,
- String requestor,
- String status,
- String ticket_id,
- String athenz_domain,
- List<EndpointCertificateRequestMetadata.DnsNameStatus> dnsnames,
- String duration_sec,
- String expiry,
- String private_key_kgname,
- String private_key_keyname,
- String private_key_version,
- String cert_key_kgname,
- String cert_key_keyname,
- String cert_key_version,
- String create_time,
- boolean expiry_protection,
- String public_key_algo,
- String issuer,
- String serial) {
- this.request_id = request_id;
- this.requestor = requestor;
- this.status = status;
- this.ticket_id = ticket_id;
- this.athenz_domain = athenz_domain;
- this.dnsnames = dnsnames;
- this.duration_sec = duration_sec;
- this.expiry = expiry;
- this.private_key_kgname = private_key_kgname;
- this.private_key_keyname = private_key_keyname;
- this.private_key_version = private_key_version;
- this.cert_key_kgname = cert_key_kgname;
- this.cert_key_keyname = cert_key_keyname;
- this.cert_key_version = cert_key_version;
- this.create_time = create_time;
- this.expiry_protection = expiry_protection;
- this.public_key_algo = public_key_algo;
- this.issuer = issuer;
- this.serial = serial;
- }
-
- public String request_id() {
- return request_id;
- }
-
- public String requestor() {
- return requestor;
- }
-
- public String status() {
- return status;
- }
-
- public String ticket_id() {
- return ticket_id;
- }
-
- public String athenz_domain() {
- return athenz_domain;
- }
-
- public List<EndpointCertificateRequestMetadata.DnsNameStatus> dnsnames() {
- return dnsnames;
- }
-
- public String duration_sec() {
- return duration_sec;
- }
-
- public String expiry() {
- return expiry;
- }
-
- public String private_key_kgname() {
- return private_key_kgname;
- }
-
- public String private_key_keyname() {
- return private_key_keyname;
- }
-
- public String private_key_version() {
- return private_key_version;
- }
-
- public String cert_key_kgname() {
- return cert_key_kgname;
- }
-
- public String cert_key_keyname() {
- return cert_key_keyname;
- }
-
- public String cert_key_version() {
- return cert_key_version;
- }
-
- public String create_time() {
- return create_time;
- }
-
- public boolean expiry_protection() {
- return expiry_protection;
- }
-
- public String public_key_algo() {
- return public_key_algo;
- }
-
- public String issuer() {
- return issuer;
- }
-
- public String serial() {
- return serial;
- }
-
- @Override
- public String toString() {
- return new StringJoiner(", ", EndpointCertificateDetails.class.getSimpleName() + "[", "]")
- .add("request_id='" + request_id + "'")
- .add("requestor='" + requestor + "'")
- .add("status='" + status + "'")
- .add("ticket_id='" + ticket_id + "'")
- .add("athenz_domain='" + athenz_domain + "'")
- .add("dnsnames=" + dnsnames)
- .add("duration_sec='" + duration_sec + "'")
- .add("expiry='" + expiry + "'")
- .add("private_key_kgname='" + private_key_kgname + "'")
- .add("private_key_keyname='" + private_key_keyname + "'")
- .add("private_key_version='" + private_key_version + "'")
- .add("cert_key_kgname='" + cert_key_kgname + "'")
- .add("cert_key_keyname='" + cert_key_keyname + "'")
- .add("cert_key_version='" + cert_key_version + "'")
- .add("create_time='" + create_time + "'")
- .add("expiry_protection=" + expiry_protection)
- .add("public_key_algo='" + public_key_algo + "'")
- .add("issuer='" + issuer + "'")
- .add("serial='" + serial + "'")
- .toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- EndpointCertificateDetails that = (EndpointCertificateDetails) o;
- return expiry_protection == that.expiry_protection
- && request_id.equals(that.request_id)
- && requestor.equals(that.requestor)
- && status.equals(that.status)
- && ticket_id.equals(that.ticket_id)
- && athenz_domain.equals(that.athenz_domain)
- && dnsnames.equals(that.dnsnames)
- && duration_sec.equals(that.duration_sec)
- && expiry.equals(that.expiry)
- && private_key_kgname.equals(that.private_key_kgname)
- && private_key_keyname.equals(that.private_key_keyname)
- && private_key_version.equals(that.private_key_version)
- && cert_key_kgname.equals(that.cert_key_kgname)
- && cert_key_keyname.equals(that.cert_key_keyname)
- && cert_key_version.equals(that.cert_key_version)
- && create_time.equals(that.create_time)
- && public_key_algo.equals(that.public_key_algo)
- && issuer.equals(that.issuer)
- && serial.equals(that.serial);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(request_id,
- requestor,
- status,
- ticket_id,
- athenz_domain,
- dnsnames,
- duration_sec,
- expiry,
- private_key_kgname,
- private_key_keyname,
- private_key_version,
- cert_key_kgname,
- cert_key_keyname,
- cert_key_version,
- create_time,
- expiry_protection,
- public_key_algo,
- issuer,
- serial);
- }
-}
+public record EndpointCertificateDetails(
+ String request_id,
+ String requestor,
+ String status,
+ String ticket_id,
+ String athenz_domain,
+ List<EndpointCertificateRequestMetadata.DnsNameStatus> dnsnames,
+ String duration_sec,
+ String expiry,
+ String private_key_kgname,
+ String private_key_keyname,
+ String private_key_version,
+ String cert_key_kgname,
+ String cert_key_keyname,
+ String cert_key_version,
+ String create_time,
+ boolean expiry_protection,
+ String public_key_algo,
+ String issuer,
+ String serial
+) { } \ No newline at end of file
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateValidatorImpl.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateValidatorImpl.java
index 9bfd8f9d34e..ecea1ce6913 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateValidatorImpl.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/certificates/EndpointCertificateValidatorImpl.java
@@ -59,7 +59,7 @@ public class EndpointCertificateValidatorImpl implements EndpointCertificateVali
X509Certificate endEntityCertificate = x509CertificateList.get(0);
Set<String> subjectAlternativeNames = X509CertificateUtils.getSubjectAlternativeNames(endEntityCertificate).stream()
- .filter(san -> san.getType().equals(SubjectAlternativeName.Type.DNS_NAME))
+ .filter(san -> san.getType().equals(SubjectAlternativeName.Type.DNS))
.map(SubjectAlternativeName::getValue).collect(Collectors.toSet());
if (!subjectAlternativeNames.containsAll(requiredNamesForZone))
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/Node.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/Node.java
index a381bcd5bed..3355f765f42 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/Node.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/Node.java
@@ -41,6 +41,7 @@ public class Node {
private final Version wantedVersion;
private final Version currentOsVersion;
private final Version wantedOsVersion;
+ private final boolean deferOsUpgrade;
private final DockerImage currentDockerImage;
private final DockerImage wantedDockerImage;
private final ServiceState serviceState;
@@ -76,7 +77,7 @@ public class Node {
private Node(String id, HostName hostname, Optional<HostName> parentHostname, State state, NodeType type,
NodeResources resources, Optional<ApplicationId> owner, Version currentVersion, Version wantedVersion,
- Version currentOsVersion, Version wantedOsVersion, Optional<Instant> currentFirmwareCheck,
+ Version currentOsVersion, Version wantedOsVersion, boolean deferOsUpgrade, Optional<Instant> currentFirmwareCheck,
Optional<Instant> wantedFirmwareCheck, ServiceState serviceState, Optional<Instant> suspendedSince,
long restartGeneration, long wantedRestartGeneration, long rebootGeneration,
long wantedRebootGeneration, int cost, int failCount, Optional<String> flavor, String clusterId,
@@ -97,6 +98,7 @@ public class Node {
this.wantedVersion = Objects.requireNonNull(wantedVersion, "wantedVersion must be non-null");
this.currentOsVersion = Objects.requireNonNull(currentOsVersion, "currentOsVersion must be non-null");
this.wantedOsVersion = Objects.requireNonNull(wantedOsVersion, "wantedOsVersion must be non-null");
+ this.deferOsUpgrade = deferOsUpgrade;
this.currentFirmwareCheck = Objects.requireNonNull(currentFirmwareCheck, "currentFirmwareCheck must be non-null");
this.wantedFirmwareCheck = Objects.requireNonNull(wantedFirmwareCheck, "wantedFirmwareCheck must be non-null");
this.serviceState = Objects.requireNonNull(serviceState, "serviceState must be non-null");
@@ -184,6 +186,11 @@ public class Node {
return wantedOsVersion;
}
+ /** Returns whether the node is currently deferring any OS upgrade */
+ public boolean deferOsUpgrade() {
+ return deferOsUpgrade;
+ }
+
/** The container image of this is currently running */
public DockerImage currentDockerImage() {
return currentDockerImage;
@@ -455,6 +462,7 @@ public class Node {
private Version wantedVersion = Version.emptyVersion;
private Version currentOsVersion = Version.emptyVersion;
private Version wantedOsVersion = Version.emptyVersion;
+ private boolean deferOsUpgrade = false;
private DockerImage currentDockerImage = DockerImage.EMPTY;
private DockerImage wantedDockerImage = DockerImage.EMPTY;
private Optional<Instant> currentFirmwareCheck = Optional.empty();
@@ -502,6 +510,7 @@ public class Node {
this.wantedVersion = node.wantedVersion;
this.currentOsVersion = node.currentOsVersion;
this.wantedOsVersion = node.wantedOsVersion;
+ this.deferOsUpgrade = node.deferOsUpgrade;
this.currentDockerImage = node.currentDockerImage;
this.wantedDockerImage = node.wantedDockerImage;
this.serviceState = node.serviceState;
@@ -599,6 +608,11 @@ public class Node {
return this;
}
+ public Builder deferOsUpgrade(boolean deferOsUpgrade) {
+ this.deferOsUpgrade = deferOsUpgrade;
+ return this;
+ }
+
public Builder currentDockerImage(DockerImage currentDockerImage) {
this.currentDockerImage = currentDockerImage;
return this;
@@ -761,7 +775,7 @@ public class Node {
public Node build() {
return new Node(id, hostname, parentHostname, state, type, resources, owner, currentVersion, wantedVersion,
- currentOsVersion, wantedOsVersion, currentFirmwareCheck, wantedFirmwareCheck, serviceState,
+ currentOsVersion, wantedOsVersion, deferOsUpgrade, currentFirmwareCheck, wantedFirmwareCheck, serviceState,
suspendedSince, restartGeneration, wantedRestartGeneration, rebootGeneration,
wantedRebootGeneration, cost, failCount, flavor, clusterId, clusterType, group, index, retired,
wantToRetire, wantToDeprovision, wantToRebuild, down, reservedTo, exclusiveTo, wantedDockerImage,
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/NodeRepoStats.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/NodeRepoStats.java
index 68ebc5e86aa..5ddf5aaff28 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/NodeRepoStats.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/NodeRepoStats.java
@@ -8,16 +8,23 @@ import java.util.List;
*/
public class NodeRepoStats {
+ private final double totalCost;
+ private final double totalAllocatedCost;
private final Load load;
private final Load activeLoad;
private final List<ApplicationStats> applicationStats;
- public NodeRepoStats(Load load, Load activeLoad, List<ApplicationStats> applicationStats) {
+ public NodeRepoStats(double totalCost, double totalAllocatedCost,
+ Load load, Load activeLoad, List<ApplicationStats> applicationStats) {
+ this.totalCost = totalCost;
+ this.totalAllocatedCost = totalAllocatedCost;
this.load = load;
this.activeLoad = activeLoad;
this.applicationStats = List.copyOf(applicationStats);
}
+ public double totalCost() { return totalCost; }
+ public double totalAllocatedCost() { return totalAllocatedCost; }
public Load load() { return load; }
public Load activeLoad() { return activeLoad; }
public List<ApplicationStats> applicationStats() { return applicationStats; }
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobType.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobType.java
index 079383dd808..b6905a97b5f 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobType.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobType.java
@@ -1,18 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.deployment;
-import com.yahoo.config.provision.Cloud;
import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
-import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.config.provision.zone.ZoneList;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
-import java.util.Comparator;
import java.util.List;
-import java.util.stream.Collectors;
import java.util.stream.Stream;
import static ai.vespa.validation.Validation.require;
@@ -22,7 +18,6 @@ import static com.yahoo.config.provision.Environment.prod;
import static com.yahoo.config.provision.Environment.staging;
import static com.yahoo.config.provision.Environment.test;
import static java.util.Comparator.naturalOrder;
-import static java.util.stream.Collectors.toUnmodifiableList;
/**
* Specification for a deployment and/or test job to run: what zone, and whether it is a production test.
@@ -31,6 +26,8 @@ import static java.util.stream.Collectors.toUnmodifiableList;
*/
public final class JobType implements Comparable<JobType> {
+ private static final RegionName unknown = RegionName.from("unknown");
+
private final String jobName;
private final ZoneId zone;
private final boolean isProductionTest;
@@ -53,8 +50,11 @@ public final class JobType implements Comparable<JobType> {
/** Returns a test job in the given environment, preferring the given cloud, is possible; using the system cloud otherwise. */
private static JobType testIn(Environment environment, ZoneRegistry zones, CloudName cloud) {
+ if (cloud == null)
+ return deploymentTo(ZoneId.from(environment, unknown));
+
ZoneList candidates = zones.zones().controllerUpgraded().in(environment);
- if (cloud == null || candidates.in(cloud).zones().isEmpty())
+ if (candidates.in(cloud).zones().isEmpty())
cloud = zones.systemZone().getCloudName();
return candidates.in(cloud).zones().stream().findFirst()
@@ -152,7 +152,8 @@ public final class JobType implements Comparable<JobType> {
public static List<JobType> allIn(ZoneRegistry zones) {
return zones.zones().reachable().zones().stream()
.flatMap(zone -> zone.getEnvironment().isProduction() ? Stream.of(deploymentTo(zone.getId()), productionTestOf(zone.getId()))
- : Stream.of(deploymentTo(zone.getId())))
+ : zone.getEnvironment().isTest() ? Stream.of(deploymentTo(ZoneId.from(zone.getEnvironment(), unknown)))
+ : Stream.of(deploymentTo(zone.getId())))
.distinct()
.sorted(naturalOrder())
.toList();
@@ -160,7 +161,7 @@ public final class JobType implements Comparable<JobType> {
/** A serialized form of this: {@code &lt;environment&gt;.&lt;region&gt;[.test]}; the inverse of {@link #ofSerialized(String)} */
public String serialized() {
- return zone.environment().value() + "." + zone.region().value() + (isProductionTest ? ".test" : "");
+ return zone().value() + (isProductionTest ? ".test" : "");
}
public String jobName() {
@@ -169,6 +170,10 @@ public final class JobType implements Comparable<JobType> {
/** Returns the zone for this job. */
public ZoneId zone() {
+ // sigh ... but the alternative is worse.
+ if (zone.region() == unknown)
+ throw new IllegalStateException("this job type was not initiated with a proper zone, programming error");
+
return zone;
}
@@ -203,7 +208,7 @@ public final class JobType implements Comparable<JobType> {
@Override
public int compareTo(JobType other) {
int result;
- if (0 != (result = environment().compareTo(other.environment()))) return -result;
+ if (0 != (result = environment().compareTo(other.environment())) || environment().isTest()) return -result;
if (0 != (result = zone.region().compareTo(other.zone.region()))) return result;
return Boolean.compare(isProductionTest, other.isProductionTest);
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/TestReport.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/TestReport.java
index 92063e1afee..60cb4248035 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/TestReport.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/TestReport.java
@@ -5,6 +5,7 @@ package com.yahoo.vespa.hosted.controller.api.integration.deployment;
* @author mortent
*/
public class TestReport {
+
private final String report;
private TestReport(String report) {
@@ -18,4 +19,5 @@ public class TestReport {
public static TestReport fromJson(String report) {
return new TestReport(report);
}
+
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepoStatsData.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepoStatsData.java
index 36677143f7a..75ac919f776 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepoStatsData.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepoStatsData.java
@@ -16,6 +16,12 @@ import java.util.stream.Collectors;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeRepoStatsData {
+ @JsonProperty("totalCost")
+ public Double totalCost;
+
+ @JsonProperty("totalAllocatedCost")
+ public Double totalAllocatedCost;
+
@JsonProperty("load")
public LoadData load;
@@ -26,7 +32,8 @@ public class NodeRepoStatsData {
public List<ApplicationStatsData> applications;
public NodeRepoStats toNodeRepoStats() {
- return new NodeRepoStats(load.toLoad(), activeLoad.toLoad(),
+ return new NodeRepoStats(totalCost, totalAllocatedCost,
+ load.toLoad(), activeLoad.toLoad(),
applications.stream().map(stats -> stats.toApplicationStats()).collect(Collectors.toList()));
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepositoryNode.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepositoryNode.java
index 8964e1b5127..d8a804ecd2c 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepositoryNode.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeRepositoryNode.java
@@ -63,6 +63,8 @@ public class NodeRepositoryNode {
private String currentOsVersion;
@JsonProperty("wantedOsVersion")
private String wantedOsVersion;
+ @JsonProperty("deferOsUpgrade")
+ private Boolean deferOsUpgrade;
@JsonProperty("currentFirmwareCheck")
private Long currentFirmwareCheck;
@JsonProperty("wantedFirmwareCheck")
@@ -250,6 +252,14 @@ public class NodeRepositoryNode {
this.wantedVespaVersion = wantedVespaVersion;
}
+ public Boolean getDeferOsUpgrade() {
+ return deferOsUpgrade;
+ }
+
+ public void setDeferOsUpgrade(Boolean deferOsUpgrade) {
+ this.deferOsUpgrade = deferOsUpgrade;
+ }
+
public Integer getFailCount() {
return failCount;
}
@@ -441,12 +451,13 @@ public class NodeRepositoryNode {
// --- end
+
@Override
public String toString() {
return "NodeRepositoryNode{" +
"url='" + url + '\'' +
", id='" + id + '\'' +
- ", state=" + state +
+ ", state='" + state + '\'' +
", hostname='" + hostname + '\'' +
", ipAddresses=" + ipAddresses +
", additionalIpAddresses=" + additionalIpAddresses +
@@ -464,11 +475,12 @@ public class NodeRepositoryNode {
", wantedVespaVersion='" + wantedVespaVersion + '\'' +
", currentOsVersion='" + currentOsVersion + '\'' +
", wantedOsVersion='" + wantedOsVersion + '\'' +
+ ", deferOsUpgrade=" + deferOsUpgrade +
", currentFirmwareCheck=" + currentFirmwareCheck +
", wantedFirmwareCheck=" + wantedFirmwareCheck +
", failCount=" + failCount +
- ", environment=" + environment +
- ", type=" + type +
+ ", environment='" + environment + '\'' +
+ ", type='" + type + '\'' +
", wantedDockerImage='" + wantedDockerImage + '\'' +
", currentDockerImage='" + currentDockerImage + '\'' +
", parentHostname='" + parentHostname + '\'' +
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/user/UserSessionManager.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/user/UserSessionManager.java
new file mode 100644
index 00000000000..eae62c66b35
--- /dev/null
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/user/UserSessionManager.java
@@ -0,0 +1,13 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.controller.api.integration.user;
+
+import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
+
+/**
+ * @author freva
+ */
+public interface UserSessionManager {
+
+ /** Returns whether the existing session for the given SecurityContext should be expired */
+ boolean shouldExpireSessionFor(SecurityContext context);
+}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
index 781be9a6c13..e0f867b97be 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
@@ -48,6 +48,10 @@ public class VespaChangeRequest extends ChangeRequest {
return new VespaChangeRequest(getId(), source, getImpactedSwitches(), getImpactedHosts(), getApproval(), getImpact(), status, hostActionPlan, zoneId);
}
+ public VespaChangeRequest withImpact(Impact impact) {
+ return new VespaChangeRequest(getId(), getChangeRequestSource(), getImpactedSwitches(), getImpactedHosts(), getApproval(), impact, status, hostActionPlan, zoneId);
+ }
+
public VespaChangeRequest withApproval(Approval approval) {
return new VespaChangeRequest(getId(), getChangeRequestSource(), getImpactedSwitches(), getImpactedHosts(), approval, getImpact(), status, hostActionPlan, zoneId);
}
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/role/PathGroup.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/role/PathGroup.java
index a3c1a0315ec..51da1d42926 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/role/PathGroup.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/role/PathGroup.java
@@ -126,6 +126,7 @@ enum PathGroup {
"/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/service/{*}",
"/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/access/support",
"/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/global-rotation/{*}",
+ "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/scaling",
"/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/nodes",
"/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/clusters",
"/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/logs",
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/tenant/CloudTenant.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/tenant/CloudTenant.java
index 54924b9c456..44f9c0ea3b8 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/tenant/CloudTenant.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/tenant/CloudTenant.java
@@ -25,17 +25,19 @@ public class CloudTenant extends Tenant {
private final TenantInfo info;
private final List<TenantSecretStore> tenantSecretStores;
private final ArchiveAccess archiveAccess;
+ private final Optional<Instant> invalidateUserSessionsBefore;
/** Public for the serialization layer — do not use! */
public CloudTenant(TenantName name, Instant createdAt, LastLoginInfo lastLoginInfo, Optional<Principal> creator,
BiMap<PublicKey, Principal> developerKeys, TenantInfo info,
- List<TenantSecretStore> tenantSecretStores, ArchiveAccess archiveAccess) {
+ List<TenantSecretStore> tenantSecretStores, ArchiveAccess archiveAccess, Optional<Instant> invalidateUserSessionsBefore) {
super(name, createdAt, lastLoginInfo, Optional.empty());
this.creator = creator;
this.developerKeys = developerKeys;
this.info = Objects.requireNonNull(info);
this.tenantSecretStores = tenantSecretStores;
this.archiveAccess = Objects.requireNonNull(archiveAccess);
+ this.invalidateUserSessionsBefore = invalidateUserSessionsBefore;
}
/** Creates a tenant with the given name, provided it passes validation. */
@@ -44,7 +46,7 @@ public class CloudTenant extends Tenant {
createdAt,
LastLoginInfo.EMPTY,
Optional.ofNullable(creator),
- ImmutableBiMap.of(), TenantInfo.empty(), List.of(), new ArchiveAccess());
+ ImmutableBiMap.of(), TenantInfo.empty(), List.of(), new ArchiveAccess(), Optional.empty());
}
/** The user that created the tenant */
@@ -75,6 +77,11 @@ public class CloudTenant extends Tenant {
return archiveAccess;
}
+ /** Returns instant before which all user sessions that have access to this tenant must be refreshed */
+ public Optional<Instant> invalidateUserSessionsBefore() {
+ return invalidateUserSessionsBefore;
+ }
+
@Override
public Type type() {
return Type.cloud;
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
index 0dcb800ca04..902d260c86d 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
@@ -2,129 +2,168 @@
package com.yahoo.vespa.hosted.controller.api.identifiers;
import com.yahoo.config.provision.zone.ZoneId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author smorgrav
*/
public class IdentifierTest {
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_not_empty() {
- new TenantId("");
+ @Test
+ void existing_tenant_id_not_empty() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_must_check_pattern() {
- new TenantId("`");
+ @Test
+ void existing_tenant_id_must_check_pattern() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("`");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void default_not_allowed_for_tenants() {
- new TenantId("default");
+ @Test
+ void default_not_allowed_for_tenants() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("default");
+ });
}
@Test
- public void existing_tenant_id_must_accept_valid_id() {
+ void existing_tenant_id_must_accept_valid_id() {
new TenantId("msbe");
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_cannot_be_uppercase() {
- new TenantId("MixedCaseTenant");
+ @Test
+ void existing_tenant_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("MixedCaseTenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_cannot_contain_dots() {
- new TenantId("tenant.with.dots");
+ @Test
+ void existing_tenant_id_cannot_contain_dots() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("tenant.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_underscore() {
- TenantId.validate("underscore_tenant");
+ @Test
+ void new_tenant_id_cannot_contain_underscore() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("underscore_tenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_dot() {
- TenantId.validate("tenant.with.dots");
+ @Test
+ void new_tenant_id_cannot_contain_dot() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("tenant.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_uppercase() {
- TenantId.validate("UppercaseTenant");
+ @Test
+ void new_tenant_id_cannot_contain_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("UppercaseTenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_start_with_dash() {
- TenantId.validate("-tenant");
+ @Test
+ void new_tenant_id_cannot_start_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("-tenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_end_with_dash() {
- TenantId.validate("tenant-");
+ @Test
+ void new_tenant_id_cannot_end_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("tenant-");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_application_id_cannot_be_uppercase() {
- new ApplicationId("MixedCaseApplication");
+ @Test
+ void existing_application_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("MixedCaseApplication");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_application_id_cannot_contain_dots() {
- new ApplicationId("application.with.dots");
+ @Test
+ void existing_application_id_cannot_contain_dots() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("application.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_underscore() {
- ApplicationId.validate("underscore_application");
+ @Test
+ void new_application_id_cannot_contain_underscore() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("underscore_application");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_dot() {
- ApplicationId.validate("application.with.dots");
+ @Test
+ void new_application_id_cannot_contain_dot() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("application.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_uppercase() {
- ApplicationId.validate("UppercaseApplication");
+ @Test
+ void new_application_id_cannot_contain_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("UppercaseApplication");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_start_with_dash() {
- ApplicationId.validate("-application");
+ @Test
+ void new_application_id_cannot_start_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("-application");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_end_with_dash() {
- ApplicationId.validate("application-");
+ @Test
+ void new_application_id_cannot_end_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("application-");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void instance_id_cannot_be_uppercase() {
- new InstanceId("MixedCaseInstance");
+ @Test
+ void instance_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new InstanceId("MixedCaseInstance");
+ });
}
@Test
- public void dns_names_has_no_underscore() {
+ void dns_names_has_no_underscore() {
assertEquals("a-b-c", new ApplicationId("a_b_c").toDns());
}
- @Test(expected = IllegalArgumentException.class)
- public void identifiers_cannot_be_named_api() {
- new ApplicationId("api");
+ @Test
+ void identifiers_cannot_be_named_api() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("api");
+ });
}
@Test
- public void application_instance_id_dotted_string_is_subindentifers_concatinated_with_dots() {
+ void application_instance_id_dotted_string_is_subindentifers_concatinated_with_dots() {
DeploymentId id = new DeploymentId(com.yahoo.config.provision.ApplicationId.from("tenant", "application", "instance"),
- ZoneId.from("prod", "region"));
+ ZoneId.from("prod", "region"));
assertEquals("tenant.application.prod.region.instance", id.dottedString());
}
@Test
- public void revision_id_can_contain_application_version_number() {
+ void revision_id_can_contain_application_version_number() {
new RevisionId("1.0.1078-24825d1f6");
}
}
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
index bbe0c2bd458..1693f752b89 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.controller.api.integration.deployment;
import com.yahoo.config.provision.zone.ZoneId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class JobTypeTest {
@Test
- public void test() {
+ void test() {
assertEquals(JobType.test("us-east-3"), JobType.ofSerialized("prod.us-east-3.test"));
assertEquals(JobType.dev("aws-us-east-1c"), JobType.ofSerialized("dev.aws-us-east-1c"));
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
index 35d2ad1ffca..9cbba8107ef 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.controller.api.integration.dns;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.zone.ZoneId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class AliasTargetTest {
@Test
- public void packing() {
+ void packing() {
List<AliasTarget> tests = List.of(
new LatencyAliasTarget(HostName.of("foo.example.com"), "dns-zone-1", ZoneId.from("prod.us-north-1")),
new WeightedAliasTarget(HostName.of("bar.example.com"), "dns-zone-2", ZoneId.from("prod.us-north-2"), 50)
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
index 55f33d7e3e1..4cec90eb48d 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
@@ -2,14 +2,14 @@
package com.yahoo.vespa.hosted.controller.api.integration.maven;
import com.yahoo.component.Version;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class MetadataTest {
@Test
- public void testParsing() {
+ void testParsing() {
Metadata metadata = Metadata.fromXml(metadataXml);
assertEquals("com.yahoo.vespa", metadata.id().groupId());
assertEquals("tenant-base", metadata.id().artifactId());
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
index 9e128a17c13..59484fbb0ce 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
@@ -6,9 +6,10 @@ import com.yahoo.config.provision.TenantName;
import com.yahoo.vespa.hosted.controller.api.role.ApplicationRole;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.TenantRole;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author jonmv
@@ -16,7 +17,7 @@ import static org.junit.Assert.assertEquals;
public class RolesTest {
@Test
- public void testSerialization() {
+ void testSerialization() {
TenantName tenant = TenantName.from("my-tenant");
for (TenantRole role : Roles.tenantRoles(tenant))
assertEquals(role, Roles.toRole(Roles.valueOf(role)));
@@ -26,38 +27,48 @@ public class RolesTest {
assertEquals(role, Roles.toRole(Roles.valueOf(role)));
assertEquals(Role.hostedOperator(),
- Roles.toRole("hostedOperator"));
+ Roles.toRole("hostedOperator"));
assertEquals(Role.hostedSupporter(),
- Roles.toRole("hostedSupporter"));
+ Roles.toRole("hostedSupporter"));
assertEquals(Role.administrator(tenant), Roles.toRole("my-tenant.administrator"));
assertEquals(Role.developer(tenant), Roles.toRole("my-tenant.developer"));
assertEquals(Role.reader(tenant), Roles.toRole("my-tenant.reader"));
assertEquals(Role.headless(tenant, application), Roles.toRole("my-tenant.my-application.headless"));
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalTenantName() {
- Roles.valueOf(Role.developer(TenantName.from("my.tenant")));
+ @Test
+ void illegalTenantName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.valueOf(Role.developer(TenantName.from("my.tenant")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalApplicationName() {
- Roles.valueOf(Role.headless(TenantName.from("my-tenant"), ApplicationName.from("my.app")));
+ @Test
+ void illegalApplicationName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.valueOf(Role.headless(TenantName.from("my-tenant"), ApplicationName.from("my.app")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalRoleValue() {
- Roles.toRole("my-tenant.awesomePerson");
+ @Test
+ void illegalRoleValue() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("my-tenant.awesomePerson");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalCombination() {
- Roles.toRole("my-tenant.my-application.tenantOwner");
+ @Test
+ void illegalCombination() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("my-tenant.my-application.tenantOwner");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalValue() {
- Roles.toRole("everyone");
+ @Test
+ void illegalValue() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("everyone");
+ });
}
}
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java
index 1923365976e..4a8e9785c88 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.role;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author jonmv
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class PathGroupTest {
@Test
- public void uniqueMatches() {
+ void uniqueMatches() {
// Ensure that each path group contains at most one match for any given path, to avoid undefined context extraction.
Set<String> checkedAgainstSelf = new HashSet<>();
for (PathGroup group1 : PathGroup.values())
@@ -37,29 +37,29 @@ public class PathGroupTest {
// and the other doesn't end with a wildcard matcher ...
// and the longest one isn't just one wildcard longer ...
// then one is strictly longer than the other, and it's not a match.
- if (end < parts1.length && (end == 0 || ! parts2[end - 1].equals("{*}")) && ! parts1[end].equals("{*}")) continue;
- if (end < parts2.length && (end == 0 || ! parts1[end - 1].equals("{*}")) && ! parts2[end].equals("{*}")) continue;
+ if (end < parts1.length && (end == 0 || !parts2[end - 1].equals("{*}")) && !parts1[end].equals("{*}")) continue;
+ if (end < parts2.length && (end == 0 || !parts1[end - 1].equals("{*}")) && !parts2[end].equals("{*}")) continue;
int i;
for (i = 0; i < end; i++)
if ( ! parts1[i].equals(parts2[i])
- && ! (parts1[i].startsWith("{") && parts1[i].endsWith("}"))
- && ! (parts2[i].startsWith("{") && parts2[i].endsWith("}"))) break;
+ && !(parts1[i].startsWith("{") && parts1[i].endsWith("}"))
+ && !(parts2[i].startsWith("{") && parts2[i].endsWith("}"))) break;
if (i == end) fail("Paths '" + path1 + "' and '" + path2 + "' overlap.");
}
assertEquals(PathGroup.all().stream().mapToInt(group -> group.pathSpecs.size()).sum(),
- checkedAgainstSelf.size());
+ checkedAgainstSelf.size());
}
@Test
- public void contextMatches() {
+ void contextMatches() {
for (PathGroup group : PathGroup.values())
for (String spec : group.pathSpecs) {
for (PathGroup.Matcher matcher : PathGroup.Matcher.values()) {
if (group.matchers.contains(matcher)) {
- if ( ! spec.contains(matcher.pattern))
+ if (!spec.contains(matcher.pattern))
fail("Spec '" + spec + "' in '" + group.name() + "' should contain matcher '" + matcher.pattern + "'.");
if (spec.replaceFirst(Pattern.quote(matcher.pattern), "").contains(matcher.pattern))
fail("Spec '" + spec + "' in '" + group.name() + "' contains more than one instance of '" + matcher.pattern + "'.");
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
index 872f74ca1ab..9dac13482e0 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
@@ -4,14 +4,14 @@ package com.yahoo.vespa.hosted.controller.api.role;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.TenantName;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.stream.Stream;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -23,7 +23,7 @@ public class RoleTest {
private static final Enforcer publicCdEnforcer = new Enforcer(SystemName.PublicCd);
@Test
- public void operator_membership() {
+ void operator_membership() {
Role role = Role.hostedOperator();
// Operator actions
@@ -39,7 +39,7 @@ public class RoleTest {
}
@Test
- public void supporter_membership() {
+ void supporter_membership() {
Role role = Role.hostedSupporter();
// No create update or delete
@@ -64,11 +64,11 @@ public class RoleTest {
}
@Test
- public void tenant_membership() {
+ void tenant_membership() {
Role role = Role.athenzTenantAdmin(TenantName.from("t1"));
assertFalse(mainEnforcer.allows(role, Action.create, URI.create("/not/explicitly/defined")));
- assertFalse("Deny access to operator API", mainEnforcer.allows(role, Action.create, URI.create("/controller/v1/foo")));
- assertFalse("Deny access to other tenant and app", mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t2/application/a2")));
+ assertFalse(mainEnforcer.allows(role, Action.create, URI.create("/controller/v1/foo")), "Deny access to operator API");
+ assertFalse(mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t2/application/a2")), "Deny access to other tenant and app");
assertTrue(mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t1/application/a1")));
Role publicSystem = Role.athenzTenantAdmin(TenantName.from("t1"));
@@ -78,16 +78,16 @@ public class RoleTest {
}
@Test
- public void build_service_membership() {
+ void build_service_membership() {
Role role = Role.buildService(TenantName.from("t1"), ApplicationName.from("a1"));
assertFalse(publicEnforcer.allows(role, Action.create, URI.create("/not/explicitly/defined")));
assertFalse(publicEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t1/application/a1")));
assertTrue(publicEnforcer.allows(role, Action.create, URI.create("/application/v4/tenant/t1/application/a1/submit")));
- assertFalse("No global read access", publicEnforcer.allows(role, Action.read, URI.create("/controller/v1/foo")));
+ assertFalse(publicEnforcer.allows(role, Action.read, URI.create("/controller/v1/foo")), "No global read access");
}
@Test
- public void new_implications() {
+ void new_implications() {
TenantName tenant1 = TenantName.from("t1");
ApplicationName application1 = ApplicationName.from("a1");
ApplicationName application2 = ApplicationName.from("a2");
@@ -103,7 +103,7 @@ public class RoleTest {
}
@Test
- public void system_flags() {
+ void system_flags() {
URI deployUri = URI.create("/system-flags/v1/deploy");
Action action = Action.update;
assertTrue(mainEnforcer.allows(Role.systemFlagsDeployer(), action, deployUri));
@@ -121,7 +121,7 @@ public class RoleTest {
}
@Test
- public void routing() {
+ void routing() {
var tenantUrl = URI.create("/routing/v1/status/tenant/t1");
var applicationUrl = URI.create("/routing/v1/status/tenant/t1/application/a1");
var instanceUrl = URI.create("/routing/v1/status/tenant/t1/application/a1/instance/i1");
@@ -130,8 +130,8 @@ public class RoleTest {
for (var url : List.of(tenantUrl, applicationUrl, instanceUrl, deploymentUrl)) {
var allowedRole = Role.reader(TenantName.from("t1"));
var disallowedRole = Role.reader(TenantName.from("t2"));
- assertTrue(allowedRole + " can read " + url, mainEnforcer.allows(allowedRole, Action.read, url));
- assertFalse(disallowedRole + " cannot read " + url, mainEnforcer.allows(disallowedRole, Action.read, url));
+ assertTrue(mainEnforcer.allows(allowedRole, Action.read, url), allowedRole + " can read " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.read, url), disallowedRole + " cannot read " + url);
}
// Write
@@ -139,15 +139,15 @@ public class RoleTest {
var url = URI.create("/routing/v1/inactive/tenant/t1/application/a1/instance/i1/environment/prod/region/us-north-1");
var allowedRole = Role.developer(TenantName.from("t1"));
var disallowedRole = Role.developer(TenantName.from("t2"));
- assertTrue(allowedRole + " can override status at " + url, mainEnforcer.allows(allowedRole, Action.create, url));
- assertTrue(allowedRole + " can clear status at " + url, mainEnforcer.allows(allowedRole, Action.delete, url));
- assertFalse(disallowedRole + " cannot override status at " + url, mainEnforcer.allows(disallowedRole, Action.create, url));
- assertFalse(disallowedRole + " cannot clear status at " + url, mainEnforcer.allows(disallowedRole, Action.delete, url));
+ assertTrue(mainEnforcer.allows(allowedRole, Action.create, url), allowedRole + " can override status at " + url);
+ assertTrue(mainEnforcer.allows(allowedRole, Action.delete, url), allowedRole + " can clear status at " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.create, url), disallowedRole + " cannot override status at " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.delete, url), disallowedRole + " cannot clear status at " + url);
}
}
@Test
- public void payment_instrument() {
+ void payment_instrument() {
URI paymentInstrumentUri = URI.create("/billing/v1/tenant/t1/instrument/foobar");
URI tenantPaymentInstrumentUri = URI.create("/billing/v1/tenant/t1/instrument");
URI tokenUri = URI.create("/billing/v1/tenant/t1/token");
@@ -172,7 +172,7 @@ public class RoleTest {
}
@Test
- public void billing_tenant() {
+ void billing_tenant() {
URI billing = URI.create("/billing/v1/tenant/t1/billing");
Role user = Role.reader(TenantName.from("t1"));
@@ -189,7 +189,7 @@ public class RoleTest {
}
@Test
- public void billing_test() {
+ void billing_test() {
var tester = new EnforcerTester(publicEnforcer);
var accountant = Role.hostedAccountant();
@@ -302,12 +302,12 @@ public class RoleTest {
allowed.forEach(action -> {
var msg = String.format("%s should be allowed to %s on %s", role, action, resource);
- assertTrue(msg, enforcer.allows(role, action, resource));
+ assertTrue(enforcer.allows(role, action, resource), msg);
});
Action.all().stream().filter(a -> ! allowed.contains(a)).forEach(action -> {
var msg = String.format("%s should not be allowed to %s on %s", role, action, resource);
- assertFalse(msg, enforcer.allows(role, action, resource));
+ assertFalse(enforcer.allows(role, action, resource), msg);
});
return this;
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
index ce2746f92e0..c40788ecb3f 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
@@ -16,10 +16,8 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.RawFlag;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -37,9 +35,10 @@ import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -53,12 +52,8 @@ public class SystemFlagsDataArchiveTest {
private static final FlagId MY_TEST_FLAG = new FlagId("my-test-flag");
private static final FlagId FLAG_WITH_EMPTY_DATA = new FlagId("flag-with-empty-data");
- @Rule
- public final TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException expectedException = ExpectedException.none();
+ @TempDir
+ public File temporaryFolder;
private static final FlagsTarget mainControllerTarget = FlagsTarget.forController(SYSTEM);
private static final FlagsTarget cdControllerTarget = FlagsTarget.forController(SystemName.cd);
@@ -75,8 +70,8 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void can_serialize_and_deserialize_archive() throws IOException {
- File tempFile = temporaryFolder.newFile("serialized-flags-archive");
+ void can_serialize_and_deserialize_archive() throws IOException {
+ File tempFile = File.createTempFile("serialized-flags-archive", null, temporaryFolder);
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile))) {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
archive.toZip(out);
@@ -88,26 +83,27 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void retrieves_correct_flag_data_for_target() {
+ void retrieves_correct_flag_data_for_target() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
assertArchiveReturnsCorrectTestFlagDataForTarget(archive);
}
@Test
- public void supports_multi_level_flags_directory() {
+ void supports_multi_level_flags_directory() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level/"));
assertFlagDataHasValue(archive, MY_TEST_FLAG, mainControllerTarget, "default");
}
@Test
- public void duplicated_flagdata_is_detected() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("contains redundant flag data for id 'my-test-flag' already set in another directory!");
- var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level-with-duplicated-flagdata/"));
+ void duplicated_flagdata_is_detected() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level-with-duplicated-flagdata/"));
+ });
+ assertTrue(exception.getMessage().contains("contains redundant flag data for id 'my-test-flag' already set in another directory!"));
}
@Test
- public void empty_files_are_handled_as_no_flag_data_for_target() {
+ void empty_files_are_handled_as_no_flag_data_for_target() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
assertNoFlagData(archive, FLAG_WITH_EMPTY_DATA, mainControllerTarget);
assertFlagDataHasValue(archive, FLAG_WITH_EMPTY_DATA, prodUsWestCfgTarget, "main.prod.us-west-1");
@@ -116,43 +112,45 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void throws_exception_on_non_json_file() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Only JSON files are allowed in 'flags/' directory (found 'flags/my-test-flag/file-name-without-dot-json')");
- SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-invalid-file-name/"));
+ void throws_exception_on_non_json_file() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-invalid-file-name/"));
+ });
+ assertTrue(exception.getMessage().contains("Only JSON files are allowed in 'flags/' directory (found 'flags/my-test-flag/file-name-without-dot-json')"));
}
@Test
- public void throws_exception_on_unknown_file() {
- SystemFlagsDataArchive archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-file-name/"));
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Unknown flag file: flags/my-test-flag/main.prod.unknown-region.json");
- archive.validateAllFilesAreForTargets(SystemName.main, Set.of(mainControllerTarget, prodUsWestCfgTarget));
+ void throws_exception_on_unknown_file() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-file-name/"));
+ archive.validateAllFilesAreForTargets(SystemName.main, Set.of(mainControllerTarget, prodUsWestCfgTarget));
+ });
+ assertTrue(exception.getMessage().contains("Unknown flag file: flags/my-test-flag/main.prod.unknown-region.json"));
}
@Test
- public void throws_exception_on_unknown_region() {
- Path directory = Paths.get("src/test/resources/system-flags-with-unknown-file-name/");
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(
- "Environment or zone in filename 'main.prod.unknown-region.json' does not exist");
- SystemFlagsDataArchive.fromDirectoryAndSystem(directory, createZoneRegistryMock());
+ void throws_exception_on_unknown_region() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ Path directory = Paths.get("src/test/resources/system-flags-with-unknown-file-name/");
+ SystemFlagsDataArchive.fromDirectoryAndSystem(directory, createZoneRegistryMock());
+ });
+ assertTrue(exception.getMessage().contains("Environment or zone in filename 'main.prod.unknown-region.json' does not exist"));
}
@Test
- public void throws_on_unknown_field() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(
- "flags/my-test-flag/main.prod.us-west-1.json contains unknown non-comment fields: after removing any comment fields the JSON is:\n" +
+ void throws_on_unknown_field() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-field-name/"));
+ });
+ assertTrue(exception.getMessage().contains("flags/my-test-flag/main.prod.us-west-1.json contains unknown non-comment fields: after removing any comment fields the JSON is:\n" +
" {\"id\":\"my-test-flag\",\"rules\":[{\"condition\":[{\"type\":\"whitelist\",\"dimension\":\"hostname\",\"values\":[\"foo.com\"]}],\"value\":\"default\"}]}\n" +
"but deserializing this ended up with a JSON that are missing some of the fields:\n" +
" {\"id\":\"my-test-flag\",\"rules\":[{\"value\":\"default\"}]}\n" +
- "See https://git.ouroath.com/vespa/hosted-feature-flags for more info on the JSON syntax");
- SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-field-name/"));
+ "See https://git.ouroath.com/vespa/hosted-feature-flags for more info on the JSON syntax"));
}
@Test
- public void remove_comments() {
+ void remove_comments() {
assertTrue(JSON.equals("{\n" +
" \"a\": {\n" +
" \"b\": 1\n" +
@@ -184,7 +182,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_application() {
+ void normalize_json_fail_on_invalid_application() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -208,7 +206,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_node_type() {
+ void normalize_json_fail_on_invalid_node_type() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -232,7 +230,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_email() {
+ void normalize_json_fail_on_invalid_email() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -256,7 +254,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_tenant_id() {
+ void normalize_json_fail_on_invalid_tenant_id() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -280,7 +278,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void ignores_files_not_related_to_specified_system_definition() {
+ void ignores_files_not_related_to_specified_system_definition() {
ZoneRegistry registry = createZoneRegistryMock();
Path testDirectory = Paths.get("src/test/resources/system-flags-for-multiple-systems/");
var archive = SystemFlagsDataArchive.fromDirectoryAndSystem(testDirectory, registry);
diff --git a/controller-server/pom.xml b/controller-server/pom.xml
index 773d63202b6..3e889d926b1 100644
--- a/controller-server/pom.xml
+++ b/controller-server/pom.xml
@@ -169,12 +169,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>application</artifactId>
<version>${project.version}</version>
@@ -186,11 +180,25 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-standalone</artifactId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
<scope>test</scope>
</dependency>
@@ -199,6 +207,16 @@
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/Application.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/Application.java
index af8965bdeff..bdb68f655ff 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/Application.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/Application.java
@@ -33,6 +33,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* An application. Belongs to a {@link Tenant}, and may have multiple {@link Instance}s.
@@ -161,7 +162,7 @@ public class Application {
public ApplicationActivity activity() {
return ApplicationActivity.from(instances.values().stream()
.flatMap(instance -> instance.deployments().values().stream())
- .collect(Collectors.toUnmodifiableList()));
+ .toList());
}
public Map<InstanceName, List<Deployment>> productionDeployments() {
@@ -183,33 +184,44 @@ public class Application {
.min(Comparator.naturalOrder());
}
- /**
- * Returns the oldest application version this has deployed in a permanent zone (not test or staging).
- */
+ /** Returns the oldest application version this has deployed in a permanent zone (not test or staging) */
public Optional<RevisionId> oldestDeployedRevision() {
+ return productionRevisions().min(Comparator.naturalOrder());
+ }
+
+ /** Returns the latest application version this has deployed in a permanent zone (not test or staging) */
+ public Optional<RevisionId> latestDeployedRevision() {
+ return productionRevisions().max(Comparator.naturalOrder());
+ }
+
+ private Stream<RevisionId> productionRevisions() {
return productionDeployments().values().stream().flatMap(List::stream)
.map(Deployment::revision)
- .filter(RevisionId::isProduction)
- .min(Comparator.naturalOrder());
+ .filter(RevisionId::isProduction);
}
/** Returns the total quota usage for this application, excluding temporary deployments */
public QuotaUsage quotaUsage() {
return instances().values().stream()
- .map(Instance::quotaUsage).reduce(QuotaUsage::add).orElse(QuotaUsage.none);
+ .map(Instance::quotaUsage)
+ .reduce(QuotaUsage::add)
+ .orElse(QuotaUsage.none);
}
/** Returns the total quota usage for manual deployments for this application */
public QuotaUsage manualQuotaUsage() {
return instances().values().stream()
- .map(Instance::manualQuotaUsage).reduce(QuotaUsage::add).orElse(QuotaUsage.none);
+ .map(Instance::manualQuotaUsage)
+ .reduce(QuotaUsage::add)
+ .orElse(QuotaUsage.none);
}
/** Returns the total quota usage for this application, excluding one specific deployment (and temporary deployments) */
public QuotaUsage quotaUsage(ApplicationId application, ZoneId zone) {
return instances().values().stream()
.map(instance -> instance.quotaUsageExcluding(application, zone))
- .reduce(QuotaUsage::add).orElse(QuotaUsage.none);
+ .reduce(QuotaUsage::add)
+ .orElse(QuotaUsage.none);
}
/** Returns the set of deploy keys for this application. */
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/ApplicationController.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/ApplicationController.java
index e48ad7596ea..78063a383dc 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/ApplicationController.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/ApplicationController.java
@@ -237,7 +237,7 @@ public class ApplicationController {
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
- public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
+ public void setTargetMajorVersion(OptionalInt targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
@@ -340,7 +340,10 @@ public class ApplicationController {
Version oldestInstalledPlatform = oldestInstalledPlatform(id);
// Target platforms are all versions not older than the oldest installed platform, unless forcing a major version change.
- Predicate<Version> isTargetPlatform = targetMajor.isEmpty() || targetMajor.getAsInt() == oldestInstalledPlatform.getMajor()
+ // Only major version specified in deployment spec is enough to force a downgrade, while all sources may force an upgrade.
+ Predicate<Version> isTargetPlatform = targetMajor.isEmpty()
+ || targetMajor.getAsInt() == oldestInstalledPlatform.getMajor()
+ || wantedMajor.isEmpty() && targetMajor.getAsInt() <= oldestInstalledPlatform.getMajor()
? version -> ! version.isBefore(oldestInstalledPlatform)
: version -> targetMajor.getAsInt() == version.getMajor();
Set<Version> platformVersions = versionStatus.versions().stream()
@@ -446,7 +449,7 @@ public class ApplicationController {
}
/** Deploys an application package for an existing application instance. */
- public ActivateResult deploy(JobId job, boolean deploySourceVersions) {
+ public ActivateResult deploy(JobId job, boolean deploySourceVersions, Consumer<String> deployLogger) {
if (job.application().instance().isTester())
throw new IllegalArgumentException("'" + job.application() + "' is a tester application!");
@@ -479,6 +482,7 @@ public class ApplicationController {
applicationPackage = applicationPackage.withTrustedCertificate(run.testerCertificate().get());
endpointCertificateMetadata = endpointCertificates.getMetadata(instance, zone, applicationPackage.deploymentSpec());
+
containerEndpoints = controller.routing().of(deployment).prepare(application);
} // Release application lock while doing the deployment, which is a lengthy task.
@@ -487,6 +491,8 @@ public class ApplicationController {
ActivateResult result = deploy(job.application(), applicationPackage, zone, platform, containerEndpoints,
endpointCertificateMetadata, run.isDryRun());
+ endpointCertificateMetadata.ifPresent(e -> deployLogger.accept("Using CA signed certificate version %s".formatted(e.version())));
+
// Record the quota usage for this application
var quotaUsage = deploymentQuotaUsage(zone, job.application());
@@ -544,10 +550,9 @@ public class ApplicationController {
controller.jobController().deploymentStatus(application.get());
for (Notification notification : controller.notificationsDb().listNotifications(NotificationSource.from(application.get().id()), true)) {
- if ( ! notification.source().instance().map(declaredInstances::contains).orElse(true))
- controller.notificationsDb().removeNotifications(notification.source());
- if (notification.source().instance().isPresent() &&
- ! notification.source().zoneId().map(application.get().require(notification.source().instance().get()).deployments()::containsKey).orElse(false))
+ if ( notification.source().instance().isPresent()
+ && ( ! declaredInstances.contains(notification.source().instance().get())
+ || ! notification.source().zoneId().map(application.get().require(notification.source().instance().get()).deployments()::containsKey).orElse(false)))
controller.notificationsDb().removeNotifications(notification.source());
}
@@ -641,7 +646,7 @@ public class ApplicationController {
.filter(zone -> deploymentSpec.instance(instance).isEmpty()
|| ! deploymentSpec.requireInstance(instance).deploysTo(zone.environment(),
zone.region()))
- .collect(toList());
+ .toList();
if (deploymentsToRemove.isEmpty())
return application;
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/LockedTenant.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/LockedTenant.java
index 4f58e87035b..ac7c6319c1b 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/LockedTenant.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/LockedTenant.java
@@ -129,25 +129,27 @@ public abstract class LockedTenant {
private final TenantInfo info;
private final List<TenantSecretStore> tenantSecretStores;
private final ArchiveAccess archiveAccess;
+ private final Optional<Instant> invalidateUserSessionsBefore;
private Cloud(TenantName name, Instant createdAt, LastLoginInfo lastLoginInfo, Optional<Principal> creator,
BiMap<PublicKey, Principal> developerKeys, TenantInfo info,
- List<TenantSecretStore> tenantSecretStores, ArchiveAccess archiveAccess) {
+ List<TenantSecretStore> tenantSecretStores, ArchiveAccess archiveAccess, Optional<Instant> invalidateUserSessionsBefore) {
super(name, createdAt, lastLoginInfo);
this.developerKeys = ImmutableBiMap.copyOf(developerKeys);
this.creator = creator;
this.info = info;
this.tenantSecretStores = tenantSecretStores;
this.archiveAccess = archiveAccess;
+ this.invalidateUserSessionsBefore = invalidateUserSessionsBefore;
}
private Cloud(CloudTenant tenant) {
- this(tenant.name(), tenant.createdAt(), tenant.lastLoginInfo(), tenant.creator(), tenant.developerKeys(), tenant.info(), tenant.tenantSecretStores(), tenant.archiveAccess());
+ this(tenant.name(), tenant.createdAt(), tenant.lastLoginInfo(), tenant.creator(), tenant.developerKeys(), tenant.info(), tenant.tenantSecretStores(), tenant.archiveAccess(), tenant.invalidateUserSessionsBefore());
}
@Override
public CloudTenant get() {
- return new CloudTenant(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess);
+ return new CloudTenant(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withDeveloperKey(PublicKey key, Principal principal) {
@@ -155,38 +157,42 @@ public abstract class LockedTenant {
if (keys.containsKey(key))
throw new IllegalArgumentException("Key " + KeyUtils.toPem(key) + " is already owned by " + keys.get(key));
keys.put(key, principal);
- return new Cloud(name, createdAt, lastLoginInfo, creator, keys, info, tenantSecretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, keys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withoutDeveloperKey(PublicKey key) {
BiMap<PublicKey, Principal> keys = HashBiMap.create(developerKeys);
keys.remove(key);
- return new Cloud(name, createdAt, lastLoginInfo, creator, keys, info, tenantSecretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, keys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withInfo(TenantInfo newInfo) {
- return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, newInfo, tenantSecretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, newInfo, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
@Override
public LockedTenant with(LastLoginInfo lastLoginInfo) {
- return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withSecretStore(TenantSecretStore tenantSecretStore) {
ArrayList<TenantSecretStore> secretStores = new ArrayList<>(tenantSecretStores);
secretStores.add(tenantSecretStore);
- return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, secretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, secretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withoutSecretStore(TenantSecretStore tenantSecretStore) {
ArrayList<TenantSecretStore> secretStores = new ArrayList<>(tenantSecretStores);
secretStores.remove(tenantSecretStore);
- return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, secretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, secretStores, archiveAccess, invalidateUserSessionsBefore);
}
public Cloud withArchiveAccess(ArchiveAccess archiveAccess) {
- return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess);
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
+ }
+
+ public Cloud withInvalidateUserSessionsBefore(Instant invalidateUserSessionsBefore) {
+ return new Cloud(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess, Optional.of(invalidateUserSessionsBefore));
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
index 9f93033a1a2..1d7d75d9193 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
@@ -2,7 +2,6 @@
package com.yahoo.vespa.hosted.controller.deployment;
import com.google.common.collect.ImmutableMap;
-import com.yahoo.collections.Iterables;
import com.yahoo.component.Version;
import com.yahoo.component.VersionCompatibility;
import com.yahoo.config.application.api.DeploymentInstanceSpec;
@@ -231,9 +230,9 @@ public class DeploymentStatus {
firstProductionJobWithDeploymentInCloud.flatMap(this::deploymentFor),
fallbackPlatform(change, job));
if (step.completedAt(change, firstProductionJobWithDeploymentInCloud).isEmpty()) {
- JobType actualType = job.type().isSystemTest() ? systemTest(firstProductionJobWithDeploymentInCloud.map(JobId::type).orElse(null))
- : stagingTest(firstProductionJobWithDeploymentInCloud.map(JobId::type).orElse(null));
- jobs.merge(job, List.of(new Job(actualType, versions, step.readyAt(change), change)), DeploymentStatus::union);
+ CloudName cloud = firstProductionJobWithDeploymentInCloud.map(JobId::type).map(this::findCloud).orElse(zones.systemZone().getCloudName());
+ JobType typeWithZone = job.type().isSystemTest() ? JobType.systemTest(zones, cloud) : JobType.stagingTest(zones, cloud);
+ jobs.merge(job, List.of(new Job(typeWithZone, versions, step.readyAt(change), change)), DeploymentStatus::union);
}
}
});
@@ -291,19 +290,16 @@ public class DeploymentStatus {
}
private <T extends Comparable<T>> Optional<T> newestTested(InstanceName instance, Function<Run, T> runMapper) {
- Set<CloudName> clouds = jobSteps.keySet().stream()
- .filter(job -> job.type().isProduction())
- .map(job -> findCloud(job.type()))
- .collect(toSet());
+ Set<CloudName> clouds = Stream.concat(Stream.of(zones.systemZone().getCloudName()),
+ jobSteps.keySet().stream()
+ .filter(job -> job.type().isProduction())
+ .map(job -> findCloud(job.type())))
+ .collect(toSet());
List<ZoneId> testZones = new ArrayList<>();
- if (application.deploymentSpec().requireInstance(instance).concerns(test)) {
- if (clouds.isEmpty()) testZones.add(JobType.systemTest(zones, null).zone());
- else for (CloudName cloud: clouds) testZones.add(JobType.systemTest(zones, cloud).zone());
- }
- if (application.deploymentSpec().requireInstance(instance).concerns(staging)) {
- if (clouds.isEmpty()) testZones.add(JobType.stagingTest(zones, null).zone());
- else for (CloudName cloud: clouds) testZones.add(JobType.stagingTest(zones, cloud).zone());
- }
+ if (application.deploymentSpec().requireInstance(instance).concerns(test))
+ for (CloudName cloud: clouds) testZones.add(JobType.systemTest(zones, cloud).zone());
+ if (application.deploymentSpec().requireInstance(instance).concerns(staging))
+ for (CloudName cloud: clouds) testZones.add(JobType.stagingTest(zones, cloud).zone());
Map<ZoneId, Optional<T>> newestPerZone = instanceJobs().get(application.id().instance(instance))
.type(systemTest(null), stagingTest(null))
@@ -548,7 +544,9 @@ public class DeploymentStatus {
if (job.type().isProduction() && job.type().isDeployment()) {
declaredTest(job.application(), testType).ifPresent(testJob -> {
for (Job productionJob : versionsList)
- if (allJobs.successOn(testType, productionJob.versions()).asList().isEmpty())
+ if (allJobs.successOn(testType, productionJob.versions())
+ .instance(testJob.application().instance())
+ .asList().isEmpty())
testJobs.merge(testJob, List.of(new Job(testJob.type(),
productionJob.versions(),
jobSteps().get(testJob).readyAt(productionJob.change),
@@ -580,7 +578,7 @@ public class DeploymentStatus {
}
private CloudName findCloud(JobType job) {
- return zones.zones().all().get(job.zone()).map(ZoneApi::getCloudName).orElse(null);
+ return zones.zones().all().get(job.zone()).map(ZoneApi::getCloudName).orElse(zones.systemZone().getCloudName());
}
private JobId firstDeclaredOrElseImplicitTest(JobType testJob) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatusList.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatusList.java
index 22df5ca559e..4a00a272c75 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatusList.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatusList.java
@@ -3,6 +3,7 @@ package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.collections.AbstractFilteringList;
import com.yahoo.component.Version;
+import com.yahoo.vespa.hosted.controller.application.Change;
import java.time.Instant;
import java.util.Collection;
@@ -36,8 +37,10 @@ public class DeploymentStatusList extends AbstractFilteringList<DeploymentStatus
/** Returns the subset of applications which have been failing an application change since the given instant */
public DeploymentStatusList failingApplicationChangeSince(Instant threshold) {
- return matching(status -> status.instanceJobs().values().stream()
- .anyMatch(jobs -> failingApplicationChangeSince(jobs, threshold)));
+ return matching(status -> status.instanceJobs().entrySet().stream()
+ .anyMatch(jobs -> failingApplicationChangeSince(jobs.getValue(),
+ status.application().require(jobs.getKey().instance()).change(),
+ threshold)));
}
private static boolean failingUpgradeToVersionSince(JobList jobs, Version version, Instant threshold) {
@@ -47,10 +50,8 @@ public class DeploymentStatusList extends AbstractFilteringList<DeploymentStatus
.isEmpty();
}
- private static boolean failingApplicationChangeSince(JobList jobs, Instant threshold) {
- return ! jobs.failingApplicationChange()
- .firstFailing().endedNoLaterThan(threshold)
- .isEmpty();
+ private static boolean failingApplicationChangeSince(JobList jobs, Change change, Instant threshold) {
+ return change.revision().map(revision -> ! jobs.failingWithBrokenRevisionSince(revision, threshold).isEmpty()).orElse(false);
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java
index c28f94bc4d7..d83f552ab25 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java
@@ -61,6 +61,7 @@ import static java.util.stream.Collectors.toMap;
public class DeploymentTrigger {
public static final Duration maxPause = Duration.ofDays(3);
+ public static final Duration maxFailingRevisionTime = Duration.ofDays(5);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
@@ -227,10 +228,9 @@ public class DeploymentTrigger {
Instance instance = application.require(applicationId.instance());
JobId job = new JobId(instance.id(), jobType);
JobStatus jobStatus = jobs.jobStatus(new JobId(applicationId, jobType));
- Versions versions = jobStatus.lastTriggered()
- .orElseThrow(() -> new IllegalArgumentException(job + " has never been triggered"))
- .versions();
- trigger(deploymentJob(instance, versions, jobType, jobStatus, clock.instant()), reason);
+ Run last = jobStatus.lastTriggered()
+ .orElseThrow(() -> new IllegalArgumentException(job + " has never been triggered"));
+ trigger(deploymentJob(instance, last.versions(), last.id().type(), jobStatus.isNodeAllocationFailure(), clock.instant()), reason);
return job;
}
@@ -258,7 +258,12 @@ public class DeploymentTrigger {
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
jobs.forEach((jobId, versionsList) -> {
- trigger(deploymentJob(application.require(job.application().instance()), versionsList.get(0).versions(), jobId.type(), status.jobs().get(jobId).get(), clock.instant()), reason);
+ trigger(deploymentJob(application.require(job.application().instance()),
+ versionsList.get(0).versions(),
+ jobId.type(),
+ status.jobs().get(jobId).get().isNodeAllocationFailure(),
+ clock.instant()),
+ reason);
});
return List.copyOf(jobs.keySet());
}
@@ -387,7 +392,7 @@ public class DeploymentTrigger {
jobs.add(deploymentJob(status.application().require(jobId.application().instance()),
job.versions(),
job.type(),
- status.instanceJobs(jobId.application().instance()).get(jobId.type()),
+ status.instanceJobs(jobId.application().instance()).get(jobId.type()).isNodeAllocationFailure(),
job.readyAt().get()));
});
return Collections.unmodifiableList(jobs);
@@ -448,6 +453,8 @@ public class DeploymentTrigger {
private boolean acceptNewRevision(DeploymentStatus status, InstanceName instance, RevisionId revision) {
if (status.application().deploymentSpec().instance(instance).isEmpty()) return false; // Unknown instance.
+ if ( ! status.jobs().failingWithBrokenRevisionSince(revision, clock.instant().minus(maxFailingRevisionTime))
+ .isEmpty()) return false; // Don't deploy a broken revision.
boolean isChangingRevision = status.application().require(instance).change().revision().isPresent();
DeploymentInstanceSpec spec = status.application().deploymentSpec().requireInstance(instance);
Predicate<RevisionId> revisionFilter = spec.revisionTarget() == DeploymentSpec.RevisionTarget.next
@@ -472,8 +479,8 @@ public class DeploymentTrigger {
// ---------- Version and job helpers ----------
- private Job deploymentJob(Instance instance, Versions versions, JobType jobType, JobStatus jobStatus, Instant availableSince) {
- return new Job(instance, versions, jobType, availableSince, jobStatus.isNodeAllocationFailure(), instance.change().revision().isPresent());
+ private Job deploymentJob(Instance instance, Versions versions, JobType jobType, boolean isNodeAllocationFailure, Instant availableSince) {
+ return new Job(instance, versions, jobType, availableSince, isNodeAllocationFailure, instance.change().revision().isPresent());
}
// ---------- Data containers ----------
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunner.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunner.java
index 813e3454e80..ef3474e0c1e 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunner.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunner.java
@@ -174,7 +174,7 @@ public class InternalStepRunner implements StepRunner {
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).testerCertificate();
- return deploy(() -> controller.applications().deploy(id.job(), setTheStage),
+ return deploy(() -> controller.applications().deploy(id.job(), setTheStage, logger::log),
controller.jobController().run(id)
.stepInfo(setTheStage ? deployInitialReal : deployReal).get()
.startTime().get(),
@@ -224,6 +224,9 @@ public class InternalStepRunner implements StepRunner {
// Retry certain failures for up to one hour.
Optional<RunStatus> result = startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(deploymentFailed) : Optional.empty();
+ if (result.isPresent())
+ logger.log(WARNING, "Deployment failed for one hour; giving up now!");
+
switch (e.code()) {
case CERTIFICATE_NOT_READY:
logger.log("No valid CA signed certificate for app available to config server");
@@ -424,10 +427,14 @@ public class InternalStepRunner implements StepRunner {
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(testerId, zone),
Optional.of(platform));
if (services.isEmpty()) {
- logger.log("Config status not currently available -- will retry.");
- return run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(5)))
- ? Optional.of(error)
- : Optional.empty();
+ if (run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(30)))) {
+ logger.log(WARNING, "Config status not available after 30 minutes; giving up!");
+ return Optional.of(error);
+ }
+ else {
+ logger.log("Config status not currently available -- will retry.");
+ return Optional.empty();
+ }
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone,
NodeFilter.all()
@@ -649,10 +656,13 @@ public class InternalStepRunner implements StepRunner {
controller.jobController().updateTestReport(id);
return Optional.of(testFailure);
case INCONCLUSIVE:
- long sleepMinutes = Math.max(15, Math.min(120, Duration.between(deployment.get().at(), controller.clock().instant()).toMinutes() / 20));
- logger.log("Tests were inconclusive, and will run again in " + sleepMinutes + " minutes.");
controller.jobController().updateTestReport(id);
- controller.jobController().locked(id, run -> run.sleepingUntil(controller.clock().instant().plusSeconds(60 * sleepMinutes)));
+ controller.jobController().locked(id, run -> {
+ Instant nextAttemptAt = run.start();
+ while ( ! nextAttemptAt.isAfter(controller.clock().instant())) nextAttemptAt = nextAttemptAt.plusSeconds(1800);
+ logger.log("Tests were inconclusive, and will run again at " + nextAttemptAt + ".");
+ return run.sleepingUntil(nextAttemptAt);
+ });
return Optional.of(reset);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
@@ -799,6 +809,7 @@ public class InternalStepRunner implements StepRunner {
Consumer<String> updater = msg -> controller.notificationsDb().setNotification(source, Notification.Type.deployment, Notification.Level.error, msg);
switch (run.status()) {
case aborted: return; // wait and see how the next run goes.
+ case noTests:
case running:
case success:
controller.notificationsDb().removeNotification(source, Notification.Type.deployment);
@@ -815,10 +826,6 @@ public class InternalStepRunner implements StepRunner {
case testFailure:
updater.accept("one or more verification tests against the deployment failed. Please review test output in the deployment job log.");
return;
- case noTests:
- controller.notificationsDb().setNotification(source, Notification.Type.deployment, Notification.Level.warning,
- "no tests were found for this job type. Please review test output in the deployment job log.");
- return;
case error:
case endpointCertificateTimeout:
break;
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobController.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobController.java
index 5113d386b23..881107fa0f9 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobController.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobController.java
@@ -158,7 +158,7 @@ public class JobController {
/** Stores the given log entries for the given run and step. */
public void log(RunId id, Step step, List<LogEntry> entries) {
locked(id, __ -> {
- logs.append(id.application(), id.type(), step, entries);
+ logs.append(id.application(), id.type(), step, entries, true);
return __;
});
}
@@ -211,7 +211,7 @@ public class JobController {
if (log.isEmpty())
return run;
- logs.append(id.application(), id.type(), Step.copyVespaLogs, log);
+ logs.append(id.application(), id.type(), Step.copyVespaLogs, log, false);
return run.with(log.get(log.size() - 1).at());
});
}
@@ -230,7 +230,7 @@ public class JobController {
if (entries.isEmpty())
return run;
- logs.append(id.application(), id.type(), step.get(), entries);
+ logs.append(id.application(), id.type(), step.get(), entries, false);
return run.with(entries.stream().mapToLong(LogEntry::id).max().getAsLong());
});
}
@@ -408,11 +408,6 @@ public class JobController {
locked(id, run -> run.with(status, step));
}
- /** Invoked when starting the step */
- public void setStartTimestamp(RunId id, Instant timestamp, LockedStep step) {
- locked(id, run -> run.with(timestamp, step));
- }
-
/**
* Changes the status of the given run to inactive, and stores it as a historic run.
* Throws TimeoutException if some step in this job is still being run.
@@ -774,7 +769,8 @@ public class JobController {
public void locked(RunId id, UnaryOperator<Run> modifications) {
try (Mutex __ = curator.lock(id.application(), id.type())) {
active(id).ifPresent(run -> {
- curator.writeLastRun(modifications.apply(run));
+ Run modified = modifications.apply(run);
+ if (modified != null) curator.writeLastRun(modified);
});
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobList.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobList.java
index 551f841233e..3074c9ac3ba 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobList.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/JobList.java
@@ -4,7 +4,6 @@ package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.collections.AbstractFilteringList;
import com.yahoo.component.Version;
import com.yahoo.config.provision.InstanceName;
-import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
@@ -74,6 +73,14 @@ public class JobList extends AbstractFilteringList<JobStatus, JobList> {
return matching(JobList::failingApplicationChange);
}
+ /** Returns the subset of jobs which are failing because of an application change, and have been since the threshold, on the given revision. */
+ public JobList failingWithBrokenRevisionSince(RevisionId broken, Instant threshold) {
+ return failingApplicationChange().matching(job -> job.runs().values().stream()
+ .anyMatch(run -> run.versions().targetRevision().equals(broken)
+ && run.hasFailed()
+ && run.start().isBefore(threshold)));
+ }
+
/** Returns the subset of jobs which are failing with the given run status. */
public JobList withStatus(RunStatus status) {
return matching(job -> job.lastStatus().map(status::equals).orElse(false));
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
index f4c4b8bebd4..d683f1cb5c7 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
@@ -76,7 +76,7 @@ public class Versions {
targetRevision.equals(versions.targetRevision());
}
- /** Returns wheter this change could result in the given target versions. */
+ /** Returns whether this change could result in the given target versions. */
public boolean targetsMatch(Change change) {
return change.platform().map(targetPlatform::equals).orElse(true)
&& change.revision().map(targetRevision::equals).orElse(true);
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationMetaDataGarbageCollector.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationMetaDataGarbageCollector.java
index 09e0fec41d1..c8c5a1834c7 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationMetaDataGarbageCollector.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationMetaDataGarbageCollector.java
@@ -14,14 +14,17 @@ public class ApplicationMetaDataGarbageCollector extends ControllerMaintainer {
private static final Logger log = Logger.getLogger(ApplicationMetaDataGarbageCollector.class.getName());
+ private final Duration timeToLive;
+
public ApplicationMetaDataGarbageCollector(Controller controller, Duration interval) {
super(controller, interval);
+ this.timeToLive = controller.system().isCd() ? Duration.ofDays(7) : Duration.ofDays(365);
}
@Override
protected double maintain() {
try {
- controller().applications().applicationStore().pruneMeta(controller().clock().instant().minus(Duration.ofDays(365)));
+ controller().applications().applicationStore().pruneMeta(controller().clock().instant().minus(timeToLive));
return 1.0;
}
catch (Exception e) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
index aa36d204c09..a279cf46415 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
@@ -70,6 +70,7 @@ public class ChangeRequestMaintainer extends ControllerMaintainer {
var vcmr = existingChangeRequests
.getOrDefault(changeRequest.getId(), new VespaChangeRequest(changeRequest, zone))
.withSource(changeRequest.getChangeRequestSource())
+ .withImpact(changeRequest.getImpact())
.withApproval(changeRequest.getApproval());
logger.fine(() -> "Storing " + vcmr);
curator.writeChangeRequest(vcmr);
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirer.java
index b1b7e80e9a0..18ef47759f4 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirer.java
@@ -13,14 +13,13 @@ import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
-import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Expires unused tenants from Vespa Cloud.
- *
+ * <p>
* TODO: Should support sending notifications some time before the various expiry events happen.
*
* @author ogronnesby
@@ -29,7 +28,7 @@ public class CloudTrialExpirer extends ControllerMaintainer {
private static final Logger log = Logger.getLogger(CloudTrialExpirer.class.getName());
private static final Duration nonePlanAfter = Duration.ofDays(14);
- private static final Duration tombstoneAfter = Duration.ofDays(365);
+ private static final Duration tombstoneAfter = Duration.ofDays(183);
private final ListFlag<String> extendedTrialTenants;
public CloudTrialExpirer(Controller controller, Duration interval) {
@@ -39,38 +38,43 @@ public class CloudTrialExpirer extends ControllerMaintainer {
@Override
protected double maintain() {
- tombstoneNonePlanTenants();
- moveInactiveTenantsToNonePlan();
- return 1.0;
+ var a = tombstoneNonePlanTenants();
+ var b = moveInactiveTenantsToNonePlan();
+ return (a ? 0.5 : 0.0) + (b ? 0.5 : 0.0);
}
- private void moveInactiveTenantsToNonePlan() {
- var predicate = tenantReadersNotLoggedIn(nonePlanAfter)
- .and(this::tenantHasTrialPlan);
-
- forTenant("'none' plan", predicate, this::setPlanNone);
- }
+ private boolean moveInactiveTenantsToNonePlan() {
+ var idleTrialTenants = controller().tenants().asList().stream()
+ .filter(this::tenantIsCloudTenant)
+ .filter(this::tenantIsNotExemptFromExpiry)
+ .filter(this::tenantHasNoDeployments)
+ .filter(this::tenantHasTrialPlan)
+ .filter(tenantReadersNotLoggedIn(nonePlanAfter))
+ .toList();
+
+ if (! idleTrialTenants.isEmpty()) {
+ var tenants = idleTrialTenants.stream().map(Tenant::name).map(TenantName::value).collect(Collectors.joining(", "));
+ log.info("Setting tenants to 'none' plan: " + tenants);
+ }
- private void tombstoneNonePlanTenants() {
- var predicate = tenantReadersNotLoggedIn(tombstoneAfter).and(this::tenantHasNonePlan);
- forTenant("tombstoned", predicate, this::tombstoneTenants);
+ return setPlanNone(idleTrialTenants);
}
- private void forTenant(String name, Predicate<Tenant> p, Consumer<List<Tenant>> c) {
- var predicate = p.and(this::tenantIsCloudTenant)
- .and(this::tenantIsNotExemptFromExpiry)
- .and(this::tenantHasNoDeployments);
-
- var tenants = controller().tenants().asList().stream()
- .filter(predicate)
- .collect(Collectors.toList());
-
- if (! tenants.isEmpty()) {
- var tenantNames = tenants.stream().map(Tenant::name).map(TenantName::value).collect(Collectors.joining(", "));
- log.info("Setting tenants as " + name + ": " + tenantNames);
+ private boolean tombstoneNonePlanTenants() {
+ var idleOldPlanTenants = controller().tenants().asList().stream()
+ .filter(this::tenantIsCloudTenant)
+ .filter(this::tenantIsNotExemptFromExpiry)
+ .filter(this::tenantHasNoDeployments)
+ .filter(this::tenantHasNonePlan)
+ .filter(tenantReadersNotLoggedIn(tombstoneAfter))
+ .toList();
+
+ if (! idleOldPlanTenants.isEmpty()) {
+ var tenants = idleOldPlanTenants.stream().map(Tenant::name).map(TenantName::value).collect(Collectors.joining(", "));
+ log.info("Setting tenants as tombstoned: " + tenants);
}
- c.accept(tenants);
+ return tombstoneTenants(idleOldPlanTenants);
}
private boolean tenantIsCloudTenant(Tenant tenant) {
@@ -98,7 +102,7 @@ public class CloudTrialExpirer extends ControllerMaintainer {
}
private boolean tenantIsNotExemptFromExpiry(Tenant tenant) {
- return ! extendedTrialTenants.value().contains(tenant.name().value());
+ return !extendedTrialTenants.value().contains(tenant.name().value());
}
private boolean tenantHasNoDeployments(Tenant tenant) {
@@ -108,23 +112,46 @@ public class CloudTrialExpirer extends ControllerMaintainer {
.sum() == 0;
}
- private void setPlanNone(List<Tenant> tenants) {
- tenants.forEach(tenant -> {
- controller().serviceRegistry().billingController().setPlan(tenant.name(), PlanId.from("none"), false, false);
- });
+ private boolean setPlanNone(List<Tenant> tenants) {
+ var success = true;
+ for (var tenant : tenants) {
+ try {
+ controller().serviceRegistry().billingController().setPlan(tenant.name(), PlanId.from("none"), false, false);
+ } catch (RuntimeException e) {
+ log.info("Could not change plan for " + tenant.name() + ": " + e.getMessage());
+ success = false;
+ }
+ }
+ return success;
}
- private void tombstoneTenants(List<Tenant> tenants) {
- tenants.forEach(tenant -> {
- deleteApplicationsWithNoDeployments(tenant);
- controller().tenants().delete(tenant.name(), Optional.empty(), false);
- });
+ private boolean tombstoneTenants(List<Tenant> tenants) {
+ var success = true;
+ for (var tenant : tenants) {
+ success &= deleteApplicationsWithNoDeployments(tenant);
+ log.fine("Tombstoning empty tenant: " + tenant.name());
+ try {
+ controller().tenants().delete(tenant.name(), Optional.empty(), false);
+ } catch (RuntimeException e) {
+ log.info("Could not tombstone tenant " + tenant.name() + ": " + e.getMessage());
+ success = false;
+ }
+ }
+ return success;
}
- private void deleteApplicationsWithNoDeployments(Tenant tenant) {
- controller().applications().asList(tenant.name()).forEach(application -> {
- // this only removes applications with no active deployments
- controller().applications().deleteApplication(application.id(), Optional.empty());
- });
+ private boolean deleteApplicationsWithNoDeployments(Tenant tenant) {
+ // this method only removes applications with no active deployments in them
+ var success = true;
+ for (var application : controller().applications().asList(tenant.name())) {
+ try {
+ log.fine("Removing empty application: " + application.id());
+ controller().applications().deleteApplication(application.id(), Optional.empty());
+ } catch (RuntimeException e) {
+ log.info("Could not removing application " + application.id() + ": " + e.getMessage());
+ success = false;
+ }
+ }
+ return success;
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintenance.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintenance.java
index 4aeecdcd4ff..ab2e0312b15 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintenance.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintenance.java
@@ -33,6 +33,7 @@ import static java.time.temporal.ChronoUnit.SECONDS;
public class ControllerMaintenance extends AbstractComponent {
private final Upgrader upgrader;
+ private final OsUpgradeScheduler osUpgradeScheduler;
private final List<Maintainer> maintainers = new CopyOnWriteArrayList<>();
@Inject
@@ -40,7 +41,9 @@ public class ControllerMaintenance extends AbstractComponent {
public ControllerMaintenance(Controller controller, Metric metric, UserManagement userManagement, AthenzClientFactory athenzClientFactory) {
Intervals intervals = new Intervals(controller.system());
upgrader = new Upgrader(controller, intervals.defaultInterval);
+ osUpgradeScheduler = new OsUpgradeScheduler(controller, intervals.osUpgradeScheduler);
maintainers.add(upgrader);
+ maintainers.add(osUpgradeScheduler);
maintainers.addAll(osUpgraders(controller, intervals.osUpgrader));
maintainers.add(new DeploymentExpirer(controller, intervals.defaultInterval));
maintainers.add(new DeploymentUpgrader(controller, intervals.defaultInterval));
@@ -54,7 +57,6 @@ public class ControllerMaintenance extends AbstractComponent {
maintainers.add(new SystemUpgrader(controller, intervals.systemUpgrader));
maintainers.add(new JobRunner(controller, intervals.jobRunner));
maintainers.add(new OsVersionStatusUpdater(controller, intervals.osVersionStatusUpdater));
- maintainers.add(new OsUpgradeScheduler(controller, intervals.osUpgradeScheduler));
maintainers.add(new ContactInformationMaintainer(controller, intervals.contactInformationMaintainer));
maintainers.add(new NameServiceDispatcher(controller, intervals.nameServiceDispatcher));
maintainers.add(new CostReportMaintainer(controller, intervals.costReportMaintainer, controller.serviceRegistry().costReportConsumer()));
@@ -70,7 +72,7 @@ public class ControllerMaintenance extends AbstractComponent {
maintainers.add(new ArchiveAccessMaintainer(controller, metric, intervals.archiveAccessMaintainer));
maintainers.add(new TenantRoleMaintainer(controller, intervals.tenantRoleMaintainer));
maintainers.add(new ChangeRequestMaintainer(controller, intervals.changeRequestMaintainer));
- maintainers.add(new VcmrMaintainer(controller, intervals.vcmrMaintainer));
+ maintainers.add(new VcmrMaintainer(controller, intervals.vcmrMaintainer, metric));
maintainers.add(new CloudTrialExpirer(controller, intervals.defaultInterval));
maintainers.add(new RetriggerMaintainer(controller, intervals.retriggerMaintainer));
maintainers.add(new UserManagementMaintainer(controller, intervals.userManagementMaintainer, controller.serviceRegistry().roleMaintainer()));
@@ -80,6 +82,8 @@ public class ControllerMaintenance extends AbstractComponent {
public Upgrader upgrader() { return upgrader; }
+ public OsUpgradeScheduler osUpgradeScheduler() { return osUpgradeScheduler; }
+
@Override
public void deconstruct() {
maintainers.forEach(Maintainer::shutdown);
@@ -156,7 +160,7 @@ public class ControllerMaintenance extends AbstractComponent {
this.containerImageExpirer = duration(12, HOURS);
this.hostInfoUpdater = duration(12, HOURS);
this.reindexingTriggerer = duration(1, HOURS);
- this.endpointCertificateMaintainer = duration(12, HOURS);
+ this.endpointCertificateMaintainer = duration(1, HOURS);
this.trafficFractionUpdater = duration(5, MINUTES);
this.archiveUriUpdater = duration(5, MINUTES);
this.archiveAccessMaintainer = duration(10, MINUTES);
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainer.java
index f3256237284..2e2680cd34a 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainer.java
@@ -7,7 +7,6 @@ import com.yahoo.config.provision.ApplicationId;
import com.yahoo.container.jdisc.secretstore.SecretNotFoundException;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import com.yahoo.transaction.Mutex;
-import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.Instance;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateDetails;
@@ -15,6 +14,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCe
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateProvider;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateRequestMetadata;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
+import com.yahoo.vespa.hosted.controller.application.Deployment;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
@@ -23,6 +23,8 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -48,6 +50,7 @@ public class EndpointCertificateMaintainer extends ControllerMaintainer {
private final CuratorDb curator;
private final SecretStore secretStore;
private final EndpointCertificateProvider endpointCertificateProvider;
+ final Comparator<EligibleJob> oldestFirst = Comparator.comparing(e -> e.deployment.at());
@Inject
public EndpointCertificateMaintainer(Controller controller, Duration interval) {
@@ -92,11 +95,14 @@ public class EndpointCertificateMaintainer extends ControllerMaintainer {
}));
}
+ record EligibleJob(Deployment deployment, ApplicationId applicationId, JobType job) {}
/**
- * If it's been four days since the cert has been refreshed, re-trigger all prod deployment jobs.
+ * If it's been four days since the cert has been refreshed, re-trigger prod deployment jobs (one at a time).
*/
private void deployRefreshedCertificates() {
var now = clock.instant();
+ var eligibleJobs = new ArrayList<EligibleJob>();
+
curator.readAllEndpointCertificateMetadata().forEach((applicationId, endpointCertificateMetadata) ->
endpointCertificateMetadata.lastRefreshed().ifPresent(lastRefreshTime -> {
Instant refreshTime = Instant.ofEpochSecond(lastRefreshTime);
@@ -105,13 +111,19 @@ public class EndpointCertificateMaintainer extends ControllerMaintainer {
.ifPresent(instance -> instance.productionDeployments().forEach((zone, deployment) -> {
if (deployment.at().isBefore(refreshTime)) {
JobType job = JobType.deploymentTo(zone);
- deploymentTrigger.reTrigger(applicationId, job, "re-triggered by EndpointCertificateMaintainer");
- log.info("Re-triggering deployment job " + job.jobName() + " for instance " +
- applicationId.serializedForm() + " to roll out refreshed endpoint certificate");
+ eligibleJobs.add(new EligibleJob(deployment, applicationId, job));
}
}));
}
}));
+
+ eligibleJobs.stream()
+ .min(oldestFirst)
+ .ifPresent(e -> {
+ deploymentTrigger.reTrigger(e.applicationId, e.job, "re-triggered by EndpointCertificateMaintainer");
+ log.info("Re-triggering deployment job " + e.job.jobName() + " for instance " +
+ e.applicationId.serializedForm() + " to roll out refreshed endpoint certificate");
+ });
}
private OptionalInt latestVersionInSecretStore(EndpointCertificateMetadata originalCertificateMetadata) {
@@ -156,8 +168,8 @@ public class EndpointCertificateMaintainer extends ControllerMaintainer {
List<EndpointCertificateRequestMetadata> endpointCertificateMetadata = endpointCertificateProvider.listCertificates();
Map<ApplicationId, EndpointCertificateMetadata> storedEndpointCertificateMetadata = curator.readAllEndpointCertificateMetadata();
- List<String> leafRequestIds = storedEndpointCertificateMetadata.values().stream().flatMap(m -> m.leafRequestId().stream()).collect(Collectors.toList());
- List<String> rootRequestIds = storedEndpointCertificateMetadata.values().stream().map(EndpointCertificateMetadata::rootRequestId).collect(Collectors.toList());
+ List<String> leafRequestIds = storedEndpointCertificateMetadata.values().stream().flatMap(m -> m.leafRequestId().stream()).toList();
+ List<String> rootRequestIds = storedEndpointCertificateMetadata.values().stream().map(EndpointCertificateMetadata::rootRequestId).toList();
for (var providerCertificateMetadata : endpointCertificateMetadata) {
if (!rootRequestIds.contains(providerCertificateMetadata.requestId()) && !leafRequestIds.contains(providerCertificateMetadata.requestId())) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/InfrastructureUpgrader.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/InfrastructureUpgrader.java
index 82413f21222..b051590ac5a 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/InfrastructureUpgrader.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/InfrastructureUpgrader.java
@@ -3,6 +3,7 @@ package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.component.Version;
import com.yahoo.config.provision.SystemName;
+import com.yahoo.config.provision.zone.NodeSlice;
import com.yahoo.config.provision.zone.UpgradePolicy;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.text.Text;
@@ -25,6 +26,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
/**
* Base class for maintainers that upgrade zone infrastructure.
@@ -57,22 +59,22 @@ public abstract class InfrastructureUpgrader<TARGET extends VersionTarget> exten
int failures = 0;
// Invert zone order if we're downgrading
UpgradePolicy policy = target.downgrade() ? upgradePolicy.inverted() : upgradePolicy;
- for (Set<ZoneApi> step : policy.steps()) {
+ for (UpgradePolicy.Step step : policy.steps()) {
boolean converged = true;
- for (ZoneApi zone : step) {
+ for (ZoneApi zone : step.zones()) {
try {
attempts++;
- converged &= upgradeAll(target, applications, zone);
+ converged &= upgradeAll(target, applications, zone, step.nodeSlice());
} catch (UnreachableNodeRepositoryException e) {
failures++;
converged = false;
log.warning(Text.format("%s: Failed to communicate with node repository in %s, continuing with next parallel zone: %s",
- this, zone, Exceptions.toMessageString(e)));
+ this, zone, Exceptions.toMessageString(e)));
} catch (Exception e) {
failures++;
converged = false;
log.warning(Text.format("%s: Failed to upgrade zone: %s, continuing with next parallel zone: %s",
- this, zone, Exceptions.toMessageString(e)));
+ this, zone, Exceptions.toMessageString(e)));
}
}
if (!converged) {
@@ -83,7 +85,7 @@ public abstract class InfrastructureUpgrader<TARGET extends VersionTarget> exten
}
/** Returns whether all applications have converged to the target version in zone */
- private boolean upgradeAll(TARGET target, List<SystemApplication> applications, ZoneApi zone) {
+ private boolean upgradeAll(TARGET target, List<SystemApplication> applications, ZoneApi zone, NodeSlice nodeSlice) {
Map<SystemApplication, Set<SystemApplication>> dependenciesByApplication = new HashMap<>();
if (target.downgrade()) { // Invert dependencies when we're downgrading
for (var application : applications) {
@@ -100,20 +102,17 @@ public abstract class InfrastructureUpgrader<TARGET extends VersionTarget> exten
for (var kv : dependenciesByApplication.entrySet()) {
SystemApplication application = kv.getKey();
Set<SystemApplication> dependencies = kv.getValue();
- if (convergedOn(target, dependencies, zone)) {
+ boolean allConverged = dependencies.stream().allMatch(app -> convergedOn(target, app, zone, nodeSlice));
+ if (allConverged) {
if (changeTargetTo(target, application, zone)) {
upgrade(target, application, zone);
}
- converged &= convergedOn(target, application, zone);
+ converged &= convergedOn(target, application, zone, nodeSlice);
}
}
return converged;
}
- private boolean convergedOn(TARGET target, Set<SystemApplication> applications, ZoneApi zone) {
- return applications.stream().allMatch(application -> convergedOn(target, application, zone));
- }
-
/** Returns whether target version for application in zone should be changed */
protected abstract boolean changeTargetTo(TARGET target, SystemApplication application, ZoneApi zone);
@@ -121,7 +120,7 @@ public abstract class InfrastructureUpgrader<TARGET extends VersionTarget> exten
protected abstract void upgrade(TARGET target, SystemApplication application, ZoneApi zone);
/** Returns whether application has converged to target version in zone */
- protected abstract boolean convergedOn(TARGET target, SystemApplication application, ZoneApi zone);
+ protected abstract boolean convergedOn(TARGET target, SystemApplication application, ZoneApi zone, NodeSlice nodeSlice);
/** Returns the version target for the component upgraded by this, if any */
protected abstract Optional<TARGET> target();
@@ -129,19 +128,34 @@ public abstract class InfrastructureUpgrader<TARGET extends VersionTarget> exten
/** Returns whether the upgrader should expect given node to upgrade */
protected abstract boolean expectUpgradeOf(Node node, SystemApplication application, ZoneApi zone);
- /** Find the minimum value of a version field in a zone by comparing all nodes */
- protected final Optional<Version> minVersion(ZoneApi zone, SystemApplication application, Function<Node, Version> versionField) {
+ /** Find the highest version used by nodes satisfying nodeSlice in zone. If no such slice exists, the lowest known version is returned */
+ protected final Optional<Version> versionOf(NodeSlice nodeSlice, ZoneApi zone, SystemApplication application, Function<Node, Version> versionField) {
try {
- return controller().serviceRegistry().configServer()
- .nodeRepository()
- .list(zone.getVirtualId(), NodeFilter.all().applications(application.id()))
- .stream()
- .filter(node -> expectUpgradeOf(node, application, zone))
- .map(versionField)
- .min(Comparator.naturalOrder());
+ Map<Version, Long> nodeCountByVersion = controller().serviceRegistry().configServer()
+ .nodeRepository()
+ .list(zone.getVirtualId(), NodeFilter.all().applications(application.id()))
+ .stream()
+ .filter(node -> expectUpgradeOf(node, application, zone))
+ .collect(Collectors.groupingBy(versionField,
+ Collectors.counting()));
+ long totalNodes = nodeCountByVersion.values().stream().reduce(Long::sum).orElse(0L);
+ Set<Version> versionsOfMatchingSlices = new HashSet<>();
+ for (var kv : nodeCountByVersion.entrySet()) {
+ long nodesOnVersion = kv.getValue();
+ if (nodeSlice.satisfiedBy(nodesOnVersion, totalNodes)) {
+ versionsOfMatchingSlices.add(kv.getKey());
+ }
+ }
+ if (!versionsOfMatchingSlices.isEmpty()) {
+ // Choose the highest version in case we have several matching slices
+ return versionsOfMatchingSlices.stream().max(Comparator.naturalOrder());
+ }
+ // No matching slices found, fall back to the lowest known version
+ return nodeCountByVersion.keySet().stream().min(Comparator.naturalOrder());
} catch (Exception e) {
throw new UnreachableNodeRepositoryException(Text.format("Failed to get version for %s in %s: %s",
- application.id(), zone, Exceptions.toMessageString(e)));
+ application.id(), zone,
+ Exceptions.toMessageString(e)));
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java
index 94ec4129744..cd48d6839f3 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunner.java
@@ -8,7 +8,6 @@ import com.yahoo.vespa.hosted.controller.deployment.InternalStepRunner;
import com.yahoo.vespa.hosted.controller.deployment.JobController;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.Step;
-import com.yahoo.vespa.hosted.controller.deployment.StepInfo;
import com.yahoo.vespa.hosted.controller.deployment.StepRunner;
import java.time.Duration;
@@ -75,18 +74,26 @@ public class JobRunner extends ControllerMaintainer {
}
}
- /** Advances each of the ready steps for the given run, or marks it as finished, and stashes it. Public for testing. */
public void advance(Run run) {
- if ( ! run.hasFailed()
- && controller().clock().instant().isAfter(run.sleepUntil().orElse(run.start()).plus(jobTimeout)))
- executors.execute(() -> {
- jobs.abort(run.id(), "job timeout of " + jobTimeout + " reached");
- advance(jobs.run(run.id()));
- });
- else if (run.readySteps().isEmpty())
- executors.execute(() -> finish(run.id()));
- else if (run.hasFailed() || run.sleepUntil().map(sleepUntil -> ! sleepUntil.isAfter(controller().clock().instant())).orElse(true))
- run.readySteps().forEach(step -> executors.execute(() -> advance(run.id(), step)));
+ advance(run.id());
+ }
+
+ /** Advances each of the ready steps for the given run, or marks it as finished, and stashes it. Public for testing. */
+ public void advance(RunId id) {
+ jobs.locked(id, run -> {
+ if ( ! run.hasFailed()
+ && controller().clock().instant().isAfter(run.sleepUntil().orElse(run.start()).plus(jobTimeout)))
+ executors.execute(() -> {
+ jobs.abort(run.id(), "job timeout of " + jobTimeout + " reached");
+ advance(run.id());
+ });
+ else if (run.readySteps().isEmpty())
+ executors.execute(() -> finish(run.id()));
+ else if (run.hasFailed() || run.sleepUntil().map(sleepUntil -> ! sleepUntil.isAfter(controller().clock().instant())).orElse(true))
+ run.readySteps().forEach(step -> executors.execute(() -> advance(run.id(), step)));
+
+ return null;
+ });
}
private void finish(RunId id) {
@@ -108,23 +115,24 @@ public class JobRunner extends ControllerMaintainer {
try {
AtomicBoolean changed = new AtomicBoolean(false);
jobs.locked(id.application(), id.type(), step, lockedStep -> {
- jobs.locked(id, run -> run); // Memory visibility.
- jobs.active(id).ifPresent(run -> { // The run may have become inactive, so we bail out.
+ jobs.locked(id, run -> {
if ( ! run.readySteps().contains(step)) {
changed.set(true);
- return; // Someone may have updated the run status, making this step obsolete, so we bail out.
+ return run; // Someone may have updated the run status, making this step obsolete, so we bail out.
}
- StepInfo stepInfo = run.stepInfo(lockedStep.get()).orElseThrow();
- if (stepInfo.startTime().isEmpty()) {
- jobs.setStartTimestamp(run.id(), controller().clock().instant(), lockedStep);
- }
+ if (run.stepInfo(lockedStep.get()).orElseThrow().startTime().isEmpty())
+ run = run.with(controller().clock().instant(), lockedStep);
- runner.run(lockedStep, run.id()).ifPresent(status -> {
- jobs.update(run.id(), status, lockedStep);
+ return run;
+ });
+
+ if ( ! changed.get()) {
+ runner.run(lockedStep, id).ifPresent(status -> {
+ jobs.update(id, status, lockedStep);
changed.set(true);
});
- });
+ }
});
if (changed.get())
jobs.active(id).ifPresent(this::advance);
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainer.java
index eadbdf74c3c..519b1001be4 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainer.java
@@ -51,14 +51,15 @@ public class MeteringMonitorMaintainer extends ControllerMaintainer {
return controller().applications().asList()
.stream()
.flatMap(app -> app.instances().values().stream())
- .flatMap(this::instancesToDeployments)
+ .flatMap(this::toProdDeployments)
.collect(Collectors.toSet());
}
- private Stream<DeploymentId> instancesToDeployments(Instance instance) {
+ private Stream<DeploymentId> toProdDeployments(Instance instance) {
return instance.deployments()
.keySet()
.stream()
+ .filter(deployment -> deployment.environment().isProduction())
.map(deployment -> new DeploymentId(instance.id(), deployment));
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeScheduler.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeScheduler.java
index 3bd1c7bb358..ddcfef23d86 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeScheduler.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeScheduler.java
@@ -9,10 +9,14 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.ArtifactRepo
import com.yahoo.vespa.hosted.controller.api.integration.deployment.OsRelease;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
+import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
+import java.time.LocalDate;
import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.Optional;
@@ -30,23 +34,24 @@ public class OsUpgradeScheduler extends ControllerMaintainer {
@Override
protected double maintain() {
Instant now = controller().clock().instant();
- if (!canTriggerAt(now)) return 1.0;
for (var cloud : controller().clouds()) {
- Release release = releaseIn(cloud);
- upgradeTo(release, cloud, now);
+ Optional<Change> change = changeIn(cloud);
+ if (change.isEmpty()) continue;
+ if (!change.get().scheduleAt(now)) continue;
+ controller().upgradeOsIn(cloud, change.get().version(), change.get().upgradeBudget(), false);
}
return 1.0;
}
- /** Upgrade to given release in cloud */
- private void upgradeTo(Release release, CloudName cloud, Instant now) {
+ /** Returns the wanted change for given cloud, if any */
+ public Optional<Change> changeIn(CloudName cloud) {
Optional<OsVersionTarget> currentTarget = controller().osVersionTarget(cloud);
- if (currentTarget.isEmpty()) return;
- if (upgradingToNewMajor(cloud)) return; // Skip further upgrades until major version upgrade is complete
+ if (currentTarget.isEmpty()) return Optional.empty();
+ if (upgradingToNewMajor(cloud)) return Optional.empty(); // Skip further upgrades until major version upgrade is complete
- Version version = release.version(currentTarget.get(), now);
- if (!version.isAfter(currentTarget.get().osVersion().version())) return;
- controller().upgradeOsIn(cloud, version, release.upgradeBudget(), false);
+ Release release = releaseIn(cloud);
+ Instant now = controller().clock().instant();
+ return release.change(currentTarget.get().version(), now);
}
private boolean upgradingToNewMajor(CloudName cloud) {
@@ -56,54 +61,69 @@ public class OsUpgradeScheduler extends ControllerMaintainer {
.count() > 1;
}
- private boolean canTriggerAt(Instant instant) {
- int hourOfDay = instant.atZone(ZoneOffset.UTC).getHour();
- int dayOfWeek = instant.atZone(ZoneOffset.UTC).getDayOfWeek().getValue();
- // Upgrade can only be scheduled between 07:00 (02:00 in CD systems) and 12:59 UTC, Monday-Thursday
- int startHour = controller().system().isCd() ? 2 : 7;
- return hourOfDay >= startHour && hourOfDay <= 12 && dayOfWeek < 5;
- }
-
private Release releaseIn(CloudName cloud) {
boolean useTaggedRelease = controller().zoneRegistry().zones().all().reprovisionToUpgradeOs().in(cloud)
- .zones().isEmpty();
+ .zones().isEmpty();
if (useTaggedRelease) {
return new TaggedRelease(controller().system(), controller().serviceRegistry().artifactRepository());
}
return new CalendarVersionedRelease(controller().system());
}
- private interface Release {
+ private static boolean canTriggerAt(Instant instant, boolean isCd) {
+ ZonedDateTime dateTime = instant.atZone(ZoneOffset.UTC);
+ int hourOfDay = dateTime.getHour();
+ int dayOfWeek = dateTime.getDayOfWeek().getValue();
+ // Upgrade can only be scheduled between 07:00 (02:00 in CD systems) and 12:59 UTC, Monday-Thursday
+ int startHour = isCd ? 2 : 7;
+ return hourOfDay >= startHour && hourOfDay <= 12 && dayOfWeek < 5;
+ }
- /** The version number of this */
- Version version(OsVersionTarget currentTarget, Instant now);
+ /** Returns the earliest time an upgrade can be scheduled on the day of instant, in given system */
+ private static Instant schedulingInstant(Instant instant, SystemName system) {
+ instant = instant.truncatedTo(ChronoUnit.DAYS);
+ while (!canTriggerAt(instant, system.isCd())) {
+ instant = instant.plus(Duration.ofHours(1));
+ }
+ return instant;
+ }
- /** The budget to use when upgrading to this */
- Duration upgradeBudget();
+ private interface Release {
+
+ /** The pending change for this release at given instant, if any */
+ Optional<Change> change(Version currentVersion, Instant instant);
}
- /** OS release based on a tag */
- private static class TaggedRelease implements Release {
+ /** OS version change, its budget and the earliest time it can be scheduled */
+ public record Change(Version version, Duration upgradeBudget, Instant scheduleAt) {
- private final SystemName system;
- private final ArtifactRepository artifactRepository;
+ public Change {
+ Objects.requireNonNull(version);
+ Objects.requireNonNull(upgradeBudget);
+ Objects.requireNonNull(scheduleAt);
+ }
- private TaggedRelease(SystemName system, ArtifactRepository artifactRepository) {
- this.system = Objects.requireNonNull(system);
- this.artifactRepository = Objects.requireNonNull(artifactRepository);
+ /** Returns whether this can be scheduled at given instant */
+ public boolean scheduleAt(Instant instant) {
+ return !instant.isBefore(scheduleAt);
}
- @Override
- public Version version(OsVersionTarget currentTarget, Instant now) {
- OsRelease release = artifactRepository.osRelease(currentTarget.osVersion().version().getMajor(), tag());
- boolean cooldownPassed = !release.taggedAt().plus(cooldown()).isAfter(now);
- return cooldownPassed ? release.version() : currentTarget.osVersion().version();
+ }
+
+ /** OS release based on a tag */
+ private record TaggedRelease(SystemName system, ArtifactRepository artifactRepository) implements Release {
+
+ public TaggedRelease {
+ Objects.requireNonNull(system);
+ Objects.requireNonNull(artifactRepository);
}
- @Override
- public Duration upgradeBudget() {
- return Duration.ZERO; // Upgrades to tagged releases happen in-place so no budget is required
+ public Optional<Change> change(Version currentVersion, Instant instant) {
+ OsRelease release = artifactRepository.osRelease(currentVersion.getMajor(), tag());
+ if (!release.version().isAfter(currentVersion)) return Optional.empty();
+ Instant scheduleAt = schedulingInstant(release.taggedAt().plus(cooldown()), system);
+ return Optional.of(new Change(release.version(), Duration.ZERO, scheduleAt));
}
/** Returns the release tag tracked by this system */
@@ -119,48 +139,65 @@ public class OsUpgradeScheduler extends ControllerMaintainer {
}
/** OS release based on calendar-versioning */
- private static class CalendarVersionedRelease implements Release {
+ record CalendarVersionedRelease(SystemName system) implements Release {
- /** The time to wait before scheduling upgrade to next version */
- private static final Duration SCHEDULING_INTERVAL = Duration.ofDays(45);
+ /** A fixed point in time which the release schedule is calculated from */
+ private static final Instant START_OF_SCHEDULE = LocalDate.of(2022, 1, 1)
+ .atStartOfDay()
+ .toInstant(ZoneOffset.UTC);
- /**
- * The interval at which new versions become available. We use this to avoid scheduling upgrades to a version
- * that has not been released yet. Example: Version N is the latest one and target is set to N+1. If N+1 does
- * not exist the zone will not converge until N+1 has been released and we may end up triggering multiple
- * rounds of upgrades.
- */
- private static final Duration AVAILABILITY_INTERVAL = Duration.ofDays(7);
+ /** The time that should elapse between versions */
+ private static final Duration SCHEDULING_STEP = Duration.ofDays(60);
- private static final DateTimeFormatter CALENDAR_VERSION_PATTERN = DateTimeFormatter.ofPattern("yyyyMMdd");
+ /** The day of week new releases are published */
+ private static final DayOfWeek RELEASE_DAY = DayOfWeek.MONDAY;
- private final SystemName system;
+ private static final DateTimeFormatter CALENDAR_VERSION_PATTERN = DateTimeFormatter.ofPattern("yyyyMMdd");
- public CalendarVersionedRelease(SystemName system) {
- this.system = Objects.requireNonNull(system);
+ public CalendarVersionedRelease {
+ Objects.requireNonNull(system);
}
@Override
- public Version version(OsVersionTarget currentTarget, Instant now) {
- Instant scheduledAt = currentTarget.scheduledAt();
- Version currentVersion = currentTarget.osVersion().version();
- if (scheduledAt.isBefore(now.minus(SCHEDULING_INTERVAL))) {
- String calendarVersion = now.minus(AVAILABILITY_INTERVAL)
- .atZone(ZoneOffset.UTC)
- .format(CALENDAR_VERSION_PATTERN);
- return new Version(currentVersion.getMajor(),
- currentVersion.getMinor(),
- currentVersion.getMicro(),
- calendarVersion);
+ public Optional<Change> change(Version currentVersion, Instant instant) {
+ Version wantedVersion = asVersion(dateOfWantedVersion(instant), currentVersion);
+ while (!wantedVersion.isAfter(currentVersion)) {
+ wantedVersion = asVersion(dateOfWantedVersion(instant), currentVersion);
+ instant = instant.plus(Duration.ofDays(1));
}
- return currentVersion; // New version should not be scheduled yet
+ return Optional.of(new Change(wantedVersion, upgradeBudget(), schedulingInstant(instant, system)));
}
- @Override
- public Duration upgradeBudget() {
+ private Duration upgradeBudget() {
return system.isCd() ? Duration.ZERO : Duration.ofDays(14);
}
+ /**
+ * Calculate the date of the wanted version relative to now. A given zone will choose the oldest release
+ * available which is not older than this date.
+ */
+ static LocalDate dateOfWantedVersion(Instant now) {
+ Instant candidate = START_OF_SCHEDULE;
+ while (!candidate.plus(SCHEDULING_STEP).isAfter(now)) {
+ candidate = candidate.plus(SCHEDULING_STEP);
+ }
+ LocalDate date = LocalDate.ofInstant(candidate, ZoneOffset.UTC);
+ return releaseDayOf(date);
+ }
+
+ private static LocalDate releaseDayOf(LocalDate date) {
+ int releaseDayDelta = RELEASE_DAY.getValue() - date.getDayOfWeek().getValue();
+ return date.plusDays(releaseDayDelta);
+ }
+
+ private static Version asVersion(LocalDate dateOfVersion, Version currentVersion) {
+ String calendarVersion = dateOfVersion.format(CALENDAR_VERSION_PATTERN);
+ return new Version(currentVersion.getMajor(),
+ currentVersion.getMinor(),
+ currentVersion.getMicro(),
+ calendarVersion);
+ }
+
}
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgrader.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgrader.java
index fa64a2677f4..f4dcf7f6088 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgrader.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgrader.java
@@ -3,6 +3,7 @@ package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
+import com.yahoo.config.provision.zone.NodeSlice;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.text.Text;
import com.yahoo.vespa.hosted.controller.Controller;
@@ -54,15 +55,16 @@ public class OsUpgrader extends InfrastructureUpgrader<OsVersionTarget> {
}
@Override
- protected boolean convergedOn(OsVersionTarget target, SystemApplication application, ZoneApi zone) {
- return !currentVersion(zone, application, target.osVersion().version()).isBefore(target.osVersion().version());
+ protected boolean convergedOn(OsVersionTarget target, SystemApplication application, ZoneApi zone, NodeSlice nodeSlice) {
+ Version currentVersion = versionOf(nodeSlice, zone, application, Node::currentOsVersion).orElse(target.osVersion().version());
+ return !currentVersion.isBefore(target.osVersion().version());
}
@Override
protected boolean expectUpgradeOf(Node node, SystemApplication application, ZoneApi zone) {
return cloud.equals(zone.getCloudName()) && // Cloud is managed by this upgrader
application.shouldUpgradeOs() && // Application should upgrade in this cloud
- canUpgrade(node); // Node is in an upgradable state
+ canUpgrade(node, false);
}
@Override
@@ -83,29 +85,23 @@ public class OsUpgrader extends InfrastructureUpgrader<OsVersionTarget> {
.orElse(true);
}
- private Version currentVersion(ZoneApi zone, SystemApplication application, Version defaultVersion) {
- return minVersion(zone, application, Node::currentOsVersion).orElse(defaultVersion);
- }
-
/** Returns the available upgrade budget for given zone */
private Duration zoneBudgetOf(Duration totalBudget, ZoneApi zone) {
if (!spendBudgetOn(zone)) return Duration.ZERO;
long consecutiveZones = upgradePolicy.steps().stream()
- .filter(parallelZones -> parallelZones.stream().anyMatch(this::spendBudgetOn))
+ .filter(step -> step.zones().stream().anyMatch(this::spendBudgetOn))
.count();
return totalBudget.dividedBy(consecutiveZones);
}
/** Returns whether to spend upgrade budget on given zone */
private boolean spendBudgetOn(ZoneApi zone) {
- if (!zone.getEnvironment().isProduction()) return false;
- if (controller().zoneRegistry().systemZone().getVirtualId().equals(zone.getVirtualId())) return false; // Controller zone
- return true;
+ return !controller().zoneRegistry().systemZone().getVirtualId().equals(zone.getVirtualId()); // Do not spend budget on controller zone
}
- /** Returns whether node is in a state where it can be upgraded */
- public static boolean canUpgrade(Node node) {
- return upgradableNodeStates.contains(node.state());
+ /** Returns whether node currently allows upgrades */
+ public static boolean canUpgrade(Node node, boolean includeDeferring) {
+ return (includeDeferring || !node.deferOsUpgrade()) && upgradableNodeStates.contains(node.state());
}
private static String name(CloudName cloud) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainer.java
index 892ad669e4b..205fb7e0e79 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainer.java
@@ -100,7 +100,7 @@ public class ResourceMeterMaintainer extends ControllerMaintainer {
}
if (systemName.isPublic()) reportResourceSnapshots(resourceSnapshots);
- if (systemName.isPublic() && systemName.isCd()) reportAllScalingEvents();
+ if (systemName.isPublic()) reportAllScalingEvents();
updateDeploymentCost(resourceSnapshots);
return 1.0;
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgrader.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgrader.java
index 8d5851be62f..8e74ef9a983 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgrader.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgrader.java
@@ -2,6 +2,7 @@
package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.component.Version;
+import com.yahoo.config.provision.zone.NodeSlice;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.text.Text;
@@ -39,12 +40,12 @@ public class SystemUpgrader extends InfrastructureUpgrader<VespaVersionTarget> {
}
@Override
- protected boolean convergedOn(VespaVersionTarget target, SystemApplication application, ZoneApi zone) {
- Optional<Version> minVersion = minVersion(zone, application, Node::currentVersion);
+ protected boolean convergedOn(VespaVersionTarget target, SystemApplication application, ZoneApi zone, NodeSlice nodeSlice) {
+ Optional<Version> currentVersion = versionOf(nodeSlice, zone, application, Node::currentVersion);
// Skip application convergence check if there are no nodes belonging to the application in the zone
- if (minVersion.isEmpty()) return true;
+ if (currentVersion.isEmpty()) return true;
- return minVersion.get().equals(target.version()) &&
+ return currentVersion.get().equals(target.version()) &&
application.configConvergedIn(zone.getId(), controller(), Optional.of(target.version()));
}
@@ -79,10 +80,9 @@ public class SystemUpgrader extends InfrastructureUpgrader<VespaVersionTarget> {
// the wanted version of each node.
boolean zoneHasSharedRouting = controller().zoneRegistry().routingMethods(zone.getId()).stream()
.anyMatch(RoutingMethod::isShared);
- return minVersion(zone, application, Node::wantedVersion)
+ return versionOf(NodeSlice.ALL, zone, application, Node::wantedVersion)
.map(wantedVersion -> !wantedVersion.equals(target.version()))
.orElse(zoneHasSharedRouting); // Always upgrade if zone uses shared routing, but has no nodes allocated yet
-
}
return controller().serviceRegistry().configServer().nodeRepository()
.targetVersionsOf(zone.getId())
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainer.java
index dad836ca2de..820c67f2d44 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainer.java
@@ -33,21 +33,15 @@ public class TenantRoleMaintainer extends ControllerMaintainer {
.map(Tenant::name)
.collect(Collectors.toList());
roleService.maintainRoles(tenantsWithRoles);
+
+ var deletedTenants = controller().tenants().asList(true).stream()
+ .filter(tenant -> tenant.type() == Tenant.Type.deleted)
+ .map(Tenant::name)
+ .toList();
+ roleService.cleanupRoles(deletedTenants);
+
return 1.0;
}
- private boolean hasProductionDeployment(TenantName tenant) {
- return controller().applications().asList(tenant).stream()
- .map(Application::productionInstances)
- .anyMatch(Predicate.not(Map::isEmpty));
- }
- private boolean hasPerfDeployment(TenantName tenant) {
- List<ZoneId> perfZones = controller().zoneRegistry().zones().controllerUpgraded().in(Environment.perf).ids();
- return controller().applications().asList(tenant).stream()
- .map(Application::instances)
- .flatMap(instances -> instances.values().stream())
- .flatMap(instance -> instance.deployments().values().stream())
- .anyMatch(x -> perfZones.contains(x.zone()));
- }
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/Upgrader.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/Upgrader.java
index d654f63fff2..1932dc65657 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/Upgrader.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/Upgrader.java
@@ -5,24 +5,27 @@ import com.yahoo.component.Version;
import com.yahoo.config.application.api.DeploymentSpec.UpgradePolicy;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.transaction.Mutex;
-import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.application.ApplicationList;
import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.InstanceList;
+import com.yahoo.vespa.hosted.controller.deployment.DeploymentStatusList;
+import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
+import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion.Confidence;
import java.time.Duration;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.OptionalInt;
import java.util.Random;
+import java.util.Set;
import java.util.function.UnaryOperator;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -58,18 +61,22 @@ public class Upgrader extends ControllerMaintainer {
cancelBrokenUpgrades(versionStatus);
OptionalInt targetMajorVersion = targetMajorVersion();
- InstanceList instances = instances(versionStatus);
+ DeploymentStatusList deploymentStatuses = deploymentStatuses(versionStatus);
for (UpgradePolicy policy : UpgradePolicy.values())
- updateTargets(versionStatus, instances, policy, targetMajorVersion);
+ updateTargets(versionStatus, deploymentStatuses, policy, targetMajorVersion);
return 1.0;
}
+ private DeploymentStatusList deploymentStatuses(VersionStatus versionStatus) {
+ return controller().jobController().deploymentStatuses(ApplicationList.from(controller().applications().readable())
+ .withProjectId(),
+ versionStatus);
+ }
+
/** Returns a list of all production application instances, except those which are pinned, which we should not manipulate here. */
- private InstanceList instances(VersionStatus versionStatus) {
- return InstanceList.from(controller().jobController().deploymentStatuses(ApplicationList.from(controller().applications().readable())
- .withProjectId(),
- versionStatus))
+ private InstanceList instances(DeploymentStatusList deploymentStatuses) {
+ return InstanceList.from(deploymentStatuses)
.withDeclaredJobs()
.shuffle(random)
.byIncreasingDeployedVersion()
@@ -78,7 +85,7 @@ public class Upgrader extends ControllerMaintainer {
private void cancelBrokenUpgrades(VersionStatus versionStatus) {
// Cancel upgrades to broken targets (let other ongoing upgrades complete to avoid starvation)
- InstanceList instances = instances(controller().readVersionStatus());
+ InstanceList instances = instances(deploymentStatuses(controller().readVersionStatus()));
for (VespaVersion version : versionStatus.versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(instances.upgradingTo(version.versionNumber()).not().with(UpgradePolicy.canary),
@@ -86,8 +93,12 @@ public class Upgrader extends ControllerMaintainer {
}
}
- private void updateTargets(VersionStatus versionStatus, InstanceList instances, UpgradePolicy policy, OptionalInt targetMajorVersion) {
+ private void updateTargets(VersionStatus versionStatus, DeploymentStatusList deploymentStatuses, UpgradePolicy policy, OptionalInt targetMajorVersion) {
+ InstanceList instances = instances(deploymentStatuses);
InstanceList remaining = instances.with(policy);
+ Instant failureThreshold = controller().clock().instant().minus(DeploymentTrigger.maxFailingRevisionTime);
+ Set<ApplicationId> failingRevision = InstanceList.from(deploymentStatuses.failingApplicationChangeSince(failureThreshold)).asSet();
+
List<Version> targetAndNewer = new ArrayList<>();
UnaryOperator<InstanceList> cancellationCriterion = policy == UpgradePolicy.canary ? i -> i.not().upgradingTo(targetAndNewer)
: i -> i.failing()
@@ -103,13 +114,16 @@ public class Upgrader extends ControllerMaintainer {
// Prefer the newest target for each instance.
remaining = remaining.not().matching(eligible.asList()::contains)
.not().hasCompleted(Change.of(version));
- for (ApplicationId id : outdated.and(eligible.not().upgrading()).not().changingRevision())
+ for (ApplicationId id : outdated.and(eligible.not().upgrading()))
targets.put(id, version);
}
int numberToUpgrade = policy == UpgradePolicy.canary ? instances.size() : numberOfApplicationsToUpgrade();
for (ApplicationId id : instances.matching(targets.keySet()::contains).first(numberToUpgrade)) {
log.log(Level.INFO, "Triggering upgrade to " + targets.get(id) + " for " + id);
+ if (failingRevision.contains(id))
+ controller().applications().deploymentTrigger().cancelChange(id, ChangesToCancel.APPLICATION);
+
controller().applications().deploymentTrigger().triggerChange(id, Change.of(targets.get(id)));
}
}
@@ -167,7 +181,7 @@ public class Upgrader extends ControllerMaintainer {
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
- public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
+ public void setTargetMajorVersion(OptionalInt targetMajorVersion) {
controller().applications().setTargetMajorVersion(targetMajorVersion);
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainer.java
index 551f803f368..daba7e74f34 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainer.java
@@ -5,6 +5,7 @@ import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.zone.ZoneId;
+import com.yahoo.jdisc.Metric;
import com.yahoo.text.Text;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
@@ -46,26 +47,28 @@ public class VcmrMaintainer extends ControllerMaintainer {
private static final Logger LOG = Logger.getLogger(VcmrMaintainer.class.getName());
private static final int DAYS_TO_RETIRE = 2;
private static final Duration ALLOWED_POSTPONEMENT_TIME = Duration.ofDays(7);
+ protected static final String TRACKED_CMRS_METRIC = "cmr.tracked";
private final CuratorDb curator;
private final NodeRepository nodeRepository;
private final ChangeRequestClient changeRequestClient;
private final SystemName system;
+ private final Metric metric;
- public VcmrMaintainer(Controller controller, Duration interval) {
+ public VcmrMaintainer(Controller controller, Duration interval, Metric metric) {
super(controller, interval, null, SystemName.allOf(Predicate.not(SystemName::isPublic)));
this.curator = controller.curator();
this.nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
this.changeRequestClient = controller.serviceRegistry().changeRequestClient();
this.system = controller.system();
+ this.metric = metric;
}
@Override
protected double maintain() {
var changeRequests = curator.readChangeRequests()
.stream()
- .filter(shouldUpdate())
- .collect(Collectors.toList());
+ .filter(shouldUpdate()).toList();
var nodesByZone = nodesByZone();
@@ -86,6 +89,7 @@ public class VcmrMaintainer extends ControllerMaintainer {
});
}
});
+ updateMetrics();
return 1.0;
}
@@ -357,4 +361,15 @@ public class VcmrMaintainer extends ControllerMaintainer {
return time;
}
+ private void updateMetrics() {
+ var cmrsByStatus = curator.readChangeRequests()
+ .stream()
+ .collect(Collectors.groupingBy(VespaChangeRequest::getStatus));
+
+ for (var status : Status.values()) {
+ var count = cmrsByStatus.getOrDefault(status, List.of()).size();
+ metric.set(TRACKED_CMRS_METRIC, count, metric.createContext(Map.of("status", status.name())));
+ }
+ }
+
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/notification/Notifier.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/notification/Notifier.java
index 49c819548fe..f2c9d55b2a2 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/notification/Notifier.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/notification/Notifier.java
@@ -29,6 +29,16 @@ import java.util.stream.Collectors;
* @author enygaard
*/
public class Notifier {
+ private static final String header = """
+ <div style="background: #00598c; height: 55px; width: 100%">
+ <img
+ src="https://vespa.ai/assets/vespa-logo.png"
+ style="width: auto; height: 34px; margin: 10px"
+ />
+ </div>
+ <br>
+ """;
+
private final CuratorDb curatorDb;
private final Mailer mailer;
private final FlagSource flagSource;
@@ -111,14 +121,15 @@ public class Notifier {
public Mail mailOf(FormattedNotification content, Collection<String> recipients) {
var notification = content.notification();
var subject = Text.format("[%s] %s Vespa Notification for %s", notification.level().toString().toUpperCase(), content.prettyType(), applicationIdSource(notification.source()));
- var body = new StringBuilder();
- body.append(content.messagePrefix()).append("\n")
+ String body = new StringBuilder()
+ .append(content.messagePrefix()).append("\n")
.append(notification.messages().stream().map(m -> " * " + m).collect(Collectors.joining("\n"))).append("\n")
.append("\n")
.append("Vespa Console link:\n")
- .append(content.uri().toString());
- var html = new StringBuilder();
- html.append(content.messagePrefix()).append("<br>\n")
+ .append(content.uri().toString()).toString();
+ String html = new StringBuilder()
+ .append(header)
+ .append(content.messagePrefix()).append("<br>\n")
.append("<ul>\n")
.append(notification.messages().stream()
.map(Notifier::linkify)
@@ -126,8 +137,8 @@ public class Notifier {
.collect(Collectors.joining("<br>\n")))
.append("</ul>\n")
.append("<br>\n")
- .append("<a href=\"" + content.uri() + "\">Vespa Console</a>");
- return new Mail(recipients, subject, body.toString(), html.toString());
+ .append("<a href=\"" + content.uri() + "\">Vespa Console</a>").toString();
+ return new Mail(recipients, subject, body, html);
}
@VisibleForTesting
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStore.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStore.java
index 9721026c628..ecb9db8195f 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStore.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStore.java
@@ -49,7 +49,7 @@ public class BufferedLogStore {
}
/** Appends to the log of the given, active run, reassigning IDs as counted here, and converting to Vespa log levels. */
- public void append(ApplicationId id, JobType type, Step step, List<LogEntry> entries) {
+ public void append(ApplicationId id, JobType type, Step step, List<LogEntry> entries, boolean forceLog) {
if (entries.isEmpty())
return;
@@ -58,7 +58,7 @@ public class BufferedLogStore {
long lastEntryId = buffer.readLastLogEntryId(id, type).orElse(-1L);
long lastChunkId = buffer.getLogChunkIds(id, type).max().orElse(0);
long numberOfChunks = Math.max(1, buffer.getLogChunkIds(id, type).count());
- if (numberOfChunks > maxLogSize / chunkSize)
+ if (numberOfChunks > maxLogSize / chunkSize && ! forceLog)
return; // Max size exceeded — store no more.
byte[] emptyChunk = "[]".getBytes();
@@ -72,8 +72,12 @@ public class BufferedLogStore {
buffer.writeLastLogEntryId(id, type, lastEntryId);
buffer.writeLog(id, type, lastChunkId, logSerializer.toJson(log));
lastChunkId = lastEntryId + 1;
- if (++numberOfChunks > maxLogSize / chunkSize) {
- log = Map.of(step, List.of(new LogEntry(++lastEntryId, entry.at(), LogEntry.Type.warning, "Max log size of " + (maxLogSize >> 20) + "Mb exceeded; further entries are discarded.")));
+ if (++numberOfChunks > maxLogSize / chunkSize && ! forceLog) {
+ log = Map.of(step, List.of(new LogEntry(++lastEntryId,
+ entry.at(),
+ LogEntry.Type.warning,
+ "Max log size of " + (maxLogSize >> 20) +
+ "Mb exceeded; further user entries are discarded.")));
break;
}
log = new HashMap<>();
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/CuratorDb.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/CuratorDb.java
index f02f49e7114..54e98877ba3 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/CuratorDb.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/CuratorDb.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.persistence;
-import com.yahoo.component.annotation.Inject;
import com.yahoo.collections.Pair;
import com.yahoo.component.Version;
+import com.yahoo.component.annotation.Inject;
import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.HostName;
@@ -41,6 +41,7 @@ import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
+
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
@@ -53,6 +54,7 @@ import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
+import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
@@ -271,9 +273,9 @@ public class CuratorDb {
return read(targetMajorVersionPath(), ByteBuffer::wrap).map(ByteBuffer::getInt);
}
- public void writeTargetMajorVersion(Optional<Integer> targetMajorVersion) {
+ public void writeTargetMajorVersion(OptionalInt targetMajorVersion) {
if (targetMajorVersion.isPresent())
- curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.get()).array());
+ curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.getAsInt()).array());
else
curator.delete(targetMajorVersionPath());
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializer.java
index e7cf0c34511..e91fbe8b1b7 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializer.java
@@ -81,6 +81,7 @@ public class TenantSerializer {
private static final String archiveAccessField = "archiveAccess";
private static final String awsArchiveAccessRoleField = "awsArchiveAccessRole";
private static final String gcpArchiveAccessMemberField = "gcpArchiveAccessMember";
+ private static final String invalidateUserSessionsBeforeField = "invalidateUserSessionsBefore";
private static final String awsIdField = "awsId";
private static final String roleField = "role";
@@ -123,6 +124,7 @@ public class TenantSerializer {
toSlime(tenant.info(), root);
toSlime(tenant.tenantSecretStores(), root);
toSlime(tenant.archiveAccess(), root);
+ tenant.invalidateUserSessionsBefore().ifPresent(instant -> root.setLong(invalidateUserSessionsBeforeField, instant.toEpochMilli()));
}
private void toSlime(ArchiveAccess archiveAccess, Cursor root) {
@@ -187,7 +189,8 @@ public class TenantSerializer {
TenantInfo info = tenantInfoFromSlime(tenantObject.field(tenantInfoField));
List<TenantSecretStore> tenantSecretStores = secretStoresFromSlime(tenantObject.field(secretStoresField));
ArchiveAccess archiveAccess = archiveAccessFromSlime(tenantObject);
- return new CloudTenant(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess);
+ Optional<Instant> invalidateUserSessionsBefore = SlimeUtils.optionalInstant(tenantObject.field(invalidateUserSessionsBeforeField));
+ return new CloudTenant(name, createdAt, lastLoginInfo, creator, developerKeys, info, tenantSecretStores, archiveAccess, invalidateUserSessionsBefore);
}
private DeletedTenant deletedTenantFrom(Inspector tenantObject) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java
index 670cb775c69..8d2fac84bc0 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiHandler.java
@@ -10,8 +10,8 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
-import com.yahoo.component.annotation.Inject;
import com.yahoo.component.Version;
+import com.yahoo.component.annotation.Inject;
import com.yahoo.config.application.api.DeploymentInstanceSpec;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
@@ -75,6 +75,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter;
import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore;
+import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
@@ -137,8 +138,6 @@ import java.security.PublicKey;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
-import java.time.LocalDateTime;
-import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
@@ -955,19 +954,24 @@ public class ApplicationApiHandler extends AuditLoggingRequestHandler {
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
- long build;
- String parameter = request.getProperty("build");
- if (parameter != null)
- try {
- build = Validation.requireAtLeast(Long.parseLong(request.getProperty("build")), "build number", 1L);
- }
- catch (NumberFormatException e) {
- throw new IllegalArgumentException("invalid value for request parameter 'build'", e);
- }
- else {
+ final long build;
+ String requestedBuild = request.getProperty("build");
+ if (requestedBuild != null) {
+ if (requestedBuild.equals("latestDeployed")) {
+ build = controller.applications().requireApplication(tenantAndApplication).latestDeployedRevision()
+ .map(RevisionId::number)
+ .orElseThrow(() -> new NotExistsException("no application package has been deployed in production for " + tenantAndApplication));
+ } else {
+ try {
+ build = Validation.requireAtLeast(Long.parseLong(request.getProperty("build")), "build number", 1L);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("invalid value for request parameter 'build'", e);
+ }
+ }
+ } else {
build = controller.applications().requireApplication(tenantAndApplication).revisions().last()
- .map(version -> version.id().number())
- .orElseThrow(() -> new NotExistsException("no application package has been submitted for " + tenantAndApplication));
+ .map(version -> version.id().number())
+ .orElseThrow(() -> new NotExistsException("no application package has been submitted for " + tenantAndApplication));
}
RevisionId revision = RevisionId.forProduction(build);
boolean tests = request.getBooleanProperty("tests");
@@ -1470,6 +1474,15 @@ public class ApplicationApiHandler extends AuditLoggingRequestHandler {
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
+ // JobType.fromJobName doesn't properly initiate test jobs. Triggering these without context isn't _really_
+ // necessary, but triggering a test in the default cloud is better than failing with a weird error.
+ ZoneRegistry zones = controller.zoneRegistry();
+ type = switch (type.environment()) {
+ case test -> JobType.systemTest(zones, zones.systemZone().getCloudName());
+ case staging -> JobType.stagingTest(zones, zones.systemZone().getCloudName());
+ default -> type;
+ };
+
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
@@ -1831,7 +1844,8 @@ public class ApplicationApiHandler extends AuditLoggingRequestHandler {
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
- else response.setString("status", "running");
+ else
+ response.setString("status", "running");
});
} else {
var deploymentRun = controller.jobController().last(deploymentId.applicationId(), JobType.deploymentTo(deploymentId.zoneId()));
@@ -2544,12 +2558,11 @@ public class ApplicationApiHandler extends AuditLoggingRequestHandler {
cloudTenant.tenantSecretStores());
try {
- var tenantQuota = controller.serviceRegistry().billingController().getQuota(tenant.name());
var usedQuota = applications.stream()
.map(Application::quotaUsage)
.reduce(QuotaUsage.none, QuotaUsage::add);
- toSlime(tenantQuota, usedQuota, object.setObject("quota"));
+ toSlime(object.setObject("quota"), usedQuota);
} catch (Exception e) {
log.warning(String.format("Failed to get quota for tenant %s: %s", tenant.name(), Exceptions.toMessageString(e)));
}
@@ -2592,15 +2605,8 @@ public class ApplicationApiHandler extends AuditLoggingRequestHandler {
archiveAccess.gcpMember().ifPresent(member -> object.setString("gcpMember", member));
}
- private void toSlime(Quota quota, QuotaUsage usage, Cursor object) {
- quota.budget().ifPresentOrElse(
- budget -> object.setDouble("budget", budget.doubleValue()),
- () -> object.setNix("budget")
- );
+ private void toSlime(Cursor object, QuotaUsage usage) {
object.setDouble("budgetUsed", usage.rate());
-
- // TODO: Retire when we no longer use maxClusterSize as a meaningful limit
- quota.maxClusterSize().ifPresent(maxClusterSize -> object.setLong("clusterSize", maxClusterSize));
}
private void toSlime(ClusterResources resources, Cursor object) {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelper.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelper.java
index e28bf89e734..25953c16bf0 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelper.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelper.java
@@ -115,6 +115,7 @@ class JobControllerApiHandlerHelper {
Run run = jobController.run(runId);
detailsObject.setBool("active", ! run.hasEnded());
detailsObject.setString("status", nameOf(run.status()));
+ run.reason().ifPresent(reason -> detailsObject.setString("reason", reason));
try {
jobController.updateTestLog(runId);
jobController.updateVespaLog(runId);
@@ -325,7 +326,7 @@ class JobControllerApiHandlerHelper {
"/job/" + job.type().jobName()).normalize();
stepObject.setString("url", baseUriForJob.toString());
stepObject.setString("environment", job.type().environment().value());
- stepObject.setString("region", job.type().zone().value());
+ if ( ! job.type().environment().isTest()) stepObject.setString("region", job.type().zone().value());
if (job.type().isProduction() && job.type().isDeployment()) {
status.deploymentFor(job).ifPresent(deployment -> {
@@ -421,6 +422,7 @@ class JobControllerApiHandlerHelper {
runObject.setLong("start", run.start().toEpochMilli());
run.end().ifPresent(end -> runObject.setLong("end", end.toEpochMilli()));
runObject.setString("status", run.status().name());
+ run.reason().ifPresent(reason -> runObject.setString("reason", reason));
toSlime(runObject.setObject("versions"), run.versions(), application);
Cursor runStepsArray = runObject.setArray("steps");
run.steps().forEach((step, info) -> {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2.java
index 44a8b636ae0..4532e0c2c18 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2.java
@@ -14,6 +14,7 @@ import com.yahoo.slime.Cursor;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Slime;
import com.yahoo.slime.Type;
+import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.ApplicationController;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.TenantController;
@@ -23,8 +24,10 @@ import com.yahoo.vespa.hosted.controller.api.integration.billing.CollectionMetho
import com.yahoo.vespa.hosted.controller.api.integration.billing.Plan;
import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanId;
import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanRegistry;
+import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
+import com.yahoo.vespa.hosted.controller.application.QuotaUsage;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
@@ -200,11 +203,13 @@ public class BillingApiHandlerV2 extends RestApiRequestHandler<BillingApiHandler
var response = new Slime();
var tenantsResponse = response.setObject().setArray("tenants");
+
tenants.asList().stream().sorted(Comparator.comparing(Tenant::name)).forEach(tenant -> {
var usage = Optional.ofNullable(usagePerTenant.get(tenant.name()));
var tenantResponse = tenantsResponse.addObject();
tenantResponse.setString("tenant", tenant.name().value());
toSlime(tenantResponse.setObject("plan"), planFor(tenant.name()));
+ toSlime(tenantResponse.setObject("quota"), billing.getQuota(tenant.name()));
tenantResponse.setString("collection", billing.getCollectionMethod(tenant.name()).name());
tenantResponse.setString("lastBill", usage.map(Bill::getStartDate).map(DateTimeFormatter.ISO_DATE::format).orElse(null));
tenantResponse.setString("unbilled", usage.map(Bill::sum).map(BigDecimal::toPlainString).orElse("0.00"));
@@ -357,6 +362,10 @@ public class BillingApiHandlerV2 extends RestApiRequestHandler<BillingApiHandler
cursor.setString("name", plan.displayName());
}
+ private void toSlime(Cursor cursor, Quota quota) {
+ cursor.setDouble("budget", quota.budget().map(BigDecimal::doubleValue).orElse(-1.0));
+ }
+
private Plan planFor(TenantName tenant) {
var planId = billing.getPlan(tenant);
return planRegistry.plan(planId)
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiHandler.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiHandler.java
index 25ac90ac0ea..776fcbfd03b 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiHandler.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiHandler.java
@@ -35,6 +35,7 @@ import java.security.Principal;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.Optional;
+import java.util.OptionalInt;
import java.util.Scanner;
import java.util.function.Function;
import java.util.logging.Level;
@@ -60,13 +61,13 @@ public class ControllerApiHandler extends AuditLoggingRequestHandler {
@Override
public HttpResponse auditAndHandle(HttpRequest request) {
try {
- switch (request.getMethod()) {
- case GET: return get(request);
- case POST: return post(request);
- case DELETE: return delete(request);
- case PATCH: return patch(request);
- default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
- }
+ return switch (request.getMethod()) {
+ case GET -> get(request);
+ case POST -> post(request);
+ case DELETE -> delete(request);
+ case PATCH -> patch(request);
+ default -> ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
+ };
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
@@ -165,8 +166,8 @@ public class ControllerApiHandler extends AuditLoggingRequestHandler {
if (inspect.field(upgradesPerMinuteField).valid()) {
upgrader.setUpgradesPerMinute(inspect.field(upgradesPerMinuteField).asDouble());
} else if (inspect.field(targetMajorVersionField).valid()) {
- int target = (int)inspect.field(targetMajorVersionField).asLong();
- upgrader.setTargetMajorVersion(Optional.ofNullable(target == 0 ? null : target)); // 0 is the default value
+ int target = (int) inspect.field(targetMajorVersionField).asLong();
+ upgrader.setTargetMajorVersion(target == 0 ? OptionalInt.empty() : OptionalInt.of(target)); // 0 is the default value
} else {
return ErrorResponse.badRequest("No such modifiable field(s)");
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/StatsResponse.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/StatsResponse.java
index 19f1ac5449f..96a3c9f177d 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/StatsResponse.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/controller/StatsResponse.java
@@ -30,6 +30,8 @@ public class StatsResponse extends SlimeJsonResponse {
if (stats.applicationStats().isEmpty()) continue; // skip empty zones
Cursor zoneObject = zonesArray.addObject();
zoneObject.setString("id", zone.toString());
+ zoneObject.setDouble("totalCost", stats.totalCost());
+ zoneObject.setDouble("totalAllocatedCost", stats.totalAllocatedCost());
toSlime(stats.load(), zoneObject.setObject("load"));
toSlime(stats.activeLoad(), zoneObject.setObject("activeLoad"));
Cursor applicationsArray = zoneObject.setArray("applications");
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiHandler.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiHandler.java
index 853739ee9c3..0e764b98514 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiHandler.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiHandler.java
@@ -22,6 +22,9 @@ import com.yahoo.slime.SlimeUtils;
import com.yahoo.slime.Type;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler;
+import com.yahoo.vespa.hosted.controller.maintenance.ControllerMaintenance;
+import com.yahoo.vespa.hosted.controller.maintenance.OsUpgradeScheduler;
+import com.yahoo.vespa.hosted.controller.maintenance.OsUpgradeScheduler.Change;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
import com.yahoo.yolean.Exceptions;
@@ -47,22 +50,24 @@ import java.util.stream.Collectors;
public class OsApiHandler extends AuditLoggingRequestHandler {
private final Controller controller;
+ private final OsUpgradeScheduler osUpgradeScheduler;
- public OsApiHandler(Context ctx, Controller controller) {
+ public OsApiHandler(Context ctx, Controller controller, ControllerMaintenance controllerMaintenance) {
super(ctx, controller.auditLogger());
this.controller = controller;
+ this.osUpgradeScheduler = controllerMaintenance.osUpgradeScheduler();
}
@Override
public HttpResponse auditAndHandle(HttpRequest request) {
try {
- switch (request.getMethod()) {
- case GET: return get(request);
- case POST: return post(request);
- case DELETE: return delete(request);
- case PATCH: return patch(request);
- default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is unsupported");
- }
+ return switch (request.getMethod()) {
+ case GET -> get(request);
+ case POST -> post(request);
+ case DELETE -> delete(request);
+ case PATCH -> patch(request);
+ default -> ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is unsupported");
+ };
} catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
} catch (RuntimeException e) {
@@ -159,8 +164,16 @@ public class OsApiHandler extends AuditLoggingRequestHandler {
currentVersionObject.setString("version", osVersion.version().toFullString());
Optional<OsVersionTarget> target = targets.stream().filter(t -> t.osVersion().equals(osVersion)).findFirst();
currentVersionObject.setBool("targetVersion", target.isPresent());
- target.ifPresent(t -> currentVersionObject.setString("upgradeBudget", t.upgradeBudget().toString()));
- target.ifPresent(t -> currentVersionObject.setLong("scheduledAt", t.scheduledAt().toEpochMilli()));
+ target.ifPresent(t -> {
+ currentVersionObject.setString("upgradeBudget", t.upgradeBudget().toString());
+ currentVersionObject.setLong("scheduledAt", t.scheduledAt().toEpochMilli());
+ Optional<Change> nextChange = osUpgradeScheduler.changeIn(t.osVersion().cloud());
+ nextChange.ifPresent(c -> {
+ currentVersionObject.setString("nextVersion", c.version().toFullString());
+ currentVersionObject.setLong("nextScheduledAt", c.scheduleAt().toEpochMilli());
+ });
+ });
+
currentVersionObject.setString("cloud", osVersion.cloud().value());
Cursor nodesArray = currentVersionObject.setArray("nodes");
nodeVersions.forEach(nodeVersion -> {
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiHandler.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiHandler.java
index fce2d283da2..a407e5aa211 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiHandler.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiHandler.java
@@ -111,7 +111,6 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/user/v1/tenant/{tenant}")) return addTenantRoleMember(path.get("tenant"), request);
- if (path.matches("/user/v1/tenant/{tenant}/application/{application}")) return addApplicationRoleMember(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError(Text.format("No '%s' handler at '%s'", request.getMethod(),
request.getUri().getPath()));
@@ -119,7 +118,6 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/user/v1/tenant/{tenant}")) return removeTenantRoleMember(path.get("tenant"), request);
- if (path.matches("/user/v1/tenant/{tenant}/application/{application}")) return removeApplicationRoleMember(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError(Text.format("No '%s' handler at '%s'", request.getMethod(),
request.getUri().getPath()));
@@ -255,21 +253,6 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
private HttpResponse addTenantRoleMember(String tenantName, HttpRequest request) {
Inspector requestObject = bodyInspector(request);
- if (requestObject.field("roles").valid()) {
- return addMultipleTenantRoleMembers(tenantName, requestObject);
- }
- return addTenantRoleMember(tenantName, requestObject);
- }
-
- private HttpResponse addTenantRoleMember(String tenantName, Inspector requestObject) {
- String roleName = require("roleName", Inspector::asString, requestObject);
- UserId user = new UserId(require("user", Inspector::asString, requestObject));
- Role role = Roles.toRole(TenantName.from(tenantName), roleName);
- users.addUsers(role, List.of(user));
- return new MessageResponse(user + " is now a member of " + role);
- }
-
- private HttpResponse addMultipleTenantRoleMembers(String tenantName, Inspector requestObject) {
var tenant = TenantName.from(tenantName);
var user = new UserId(require("user", Inspector::asString, requestObject));
var roles = SlimeStream.fromArray(requestObject.field("roles"), Inspector::asString)
@@ -280,37 +263,8 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
return new MessageResponse(user + " is now a member of " + roles.stream().map(Role::toString).collect(Collectors.joining(", ")));
}
- private HttpResponse addApplicationRoleMember(String tenantName, String applicationName, HttpRequest request) {
- Inspector requestObject = bodyInspector(request);
- String roleName = require("roleName", Inspector::asString, requestObject);
- UserId user = new UserId(require("user", Inspector::asString, requestObject));
- Role role = Roles.toRole(TenantName.from(tenantName), ApplicationName.from(applicationName), roleName);
- users.addUsers(role, List.of(user));
- return new MessageResponse(user + " is now a member of " + role);
- }
-
private HttpResponse removeTenantRoleMember(String tenantName, HttpRequest request) {
Inspector requestObject = bodyInspector(request);
- if (requestObject.field("roles").valid()) {
- return removeMultipleTenantRoleMembers(tenantName, requestObject);
- }
- return removeTenantRoleMember(tenantName, requestObject);
- }
-
- private HttpResponse removeTenantRoleMember(String tenantName, Inspector requestObject) {
- TenantName tenant = TenantName.from(tenantName);
- String roleName = require("roleName", Inspector::asString, requestObject);
- UserId user = new UserId(require("user", Inspector::asString, requestObject));
- List<Role> roles = Collections.singletonList(Roles.toRole(tenant, roleName));
-
- enforceLastAdminOfTenant(tenant, user, roles);
- removeDeveloperKey(tenant, user, roles);
- users.removeFromRoles(user, roles);
-
- return new MessageResponse(user + " is no longer a member of " + roles.stream().map(Role::toString).collect(Collectors.joining(", ")));
- }
-
- private HttpResponse removeMultipleTenantRoleMembers(String tenantName, Inspector requestObject) {
var tenant = TenantName.from(tenantName);
var user = new UserId(require("user", Inspector::asString, requestObject));
var roles = SlimeStream.fromArray(requestObject.field("roles"), Inspector::asString)
@@ -321,6 +275,11 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
removeDeveloperKey(tenant, user, roles);
users.removeFromRoles(user, roles);
+ controller.tenants().lockIfPresent(tenant, LockedTenant.class, lockedTenant -> {
+ if (lockedTenant instanceof LockedTenant.Cloud cloudTenant)
+ controller.tenants().store(cloudTenant.withInvalidateUserSessionsBefore(controller.clock().instant()));
+ });
+
return new MessageResponse(user + " is no longer a member of " + roles.stream().map(Role::toString).collect(Collectors.joining(", ")));
}
@@ -348,15 +307,6 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
}
}
- private HttpResponse removeApplicationRoleMember(String tenantName, String applicationName, HttpRequest request) {
- Inspector requestObject = bodyInspector(request);
- String roleName = require("roleName", Inspector::asString, requestObject);
- UserId user = new UserId(require("user", Inspector::asString, requestObject));
- Role role = Roles.toRole(TenantName.from(tenantName), ApplicationName.from(applicationName), roleName);
- users.removeUsers(role, List.of(user));
- return new MessageResponse(user + " is no longer a member of " + role);
- }
-
private boolean hasTrialCapacity() {
if (! controller.system().isPublic()) return true;
var existing = controller.tenants().asList().stream().map(Tenant::name).collect(Collectors.toList());
@@ -384,18 +334,12 @@ public class UserApiHandler extends ThreadedHttpRequestHandler {
}
private static Collection<TenantRole> filterTenantRoles(Role role) {
- if (!(role instanceof TenantRole))
- return Set.of();
-
- TenantRole tenantRole = (TenantRole) role;
- if (tenantRole.definition() == RoleDefinition.administrator
- || tenantRole.definition() == RoleDefinition.developer
- || tenantRole.definition() == RoleDefinition.reader)
- return Set.of(tenantRole);
-
- if (tenantRole.definition() == RoleDefinition.athenzTenantAdmin)
- return Roles.tenantRoles(tenantRole.tenant());
-
+ if (role instanceof TenantRole tenantRole) {
+ switch (tenantRole.definition()) {
+ case administrator, developer, reader, hostedDeveloper: return Set.of(tenantRole);
+ case athenzTenantAdmin: return Roles.tenantRoles(tenantRole.tenant());
+ }
+ }
return Set.of();
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManager.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManager.java
new file mode 100644
index 00000000000..e2b5083abae
--- /dev/null
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManager.java
@@ -0,0 +1,50 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.controller.security;
+
+import com.yahoo.config.provision.TenantName;
+import com.yahoo.vespa.flags.LongFlag;
+import com.yahoo.vespa.flags.PermanentFlags;
+import com.yahoo.vespa.hosted.controller.Controller;
+import com.yahoo.vespa.hosted.controller.TenantController;
+import com.yahoo.vespa.hosted.controller.api.integration.user.UserSessionManager;
+import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
+import com.yahoo.vespa.hosted.controller.api.role.TenantRole;
+import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
+
+import java.time.Instant;
+
+/**
+ * @author freva
+ */
+public class CloudUserSessionManager implements UserSessionManager {
+
+ private final TenantController tenantController;
+ private final LongFlag invalidateConsoleSessions;
+
+ public CloudUserSessionManager(Controller controller) {
+ this.tenantController = controller.tenants();
+ this.invalidateConsoleSessions = PermanentFlags.INVALIDATE_CONSOLE_SESSIONS.bindTo(controller.flagSource());
+ }
+
+ @Override
+ public boolean shouldExpireSessionFor(SecurityContext context) {
+ if (context.issuedAt().isBefore(Instant.ofEpochSecond(invalidateConsoleSessions.value())))
+ return true;
+
+ return context.roles().stream()
+ .filter(TenantRole.class::isInstance)
+ .map(TenantRole.class::cast)
+ .map(TenantRole::tenant)
+ .distinct()
+ .anyMatch(tenantName -> shouldExpireSessionFor(tenantName, context.issuedAt()));
+ }
+
+ private boolean shouldExpireSessionFor(TenantName tenantName, Instant contextIssuedAt) {
+ return tenantController.get(tenantName)
+ .filter(CloudTenant.class::isInstance)
+ .map(CloudTenant.class::cast)
+ .flatMap(CloudTenant::invalidateUserSessionsBefore)
+ .map(contextIssuedAt::isBefore)
+ .orElse(false);
+ }
+}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java
index 8ee891ae8a6..6f9888b79e0 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java
@@ -4,6 +4,7 @@ package com.yahoo.vespa.hosted.controller.versions;
import com.google.common.collect.ImmutableMap;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
+import com.yahoo.config.provision.zone.UpgradePolicy;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
@@ -66,7 +67,7 @@ public record OsVersionStatus(Map<OsVersion, List<NodeVersion>> versions) {
.orElse(Version.emptyVersion);
for (var node : controller.serviceRegistry().configServer().nodeRepository().list(zone.getVirtualId(), NodeFilter.all().applications(application.id()))) {
- if (!OsUpgrader.canUpgrade(node)) continue;
+ if (!OsUpgrader.canUpgrade(node, true)) continue;
Optional<Instant> suspendedAt = node.suspendedSince();
NodeVersion nodeVersion = new NodeVersion(node.hostname(), zone.getVirtualId(), node.currentOsVersion(),
targetOsVersion, suspendedAt);
@@ -83,6 +84,7 @@ public record OsVersionStatus(Map<OsVersion, List<NodeVersion>> versions) {
private static List<ZoneApi> zonesToUpgrade(Controller controller) {
return controller.zoneRegistry().osUpgradePolicies().stream()
.flatMap(upgradePolicy -> upgradePolicy.steps().stream())
+ .map(UpgradePolicy.Step::zones)
.flatMap(Collection::stream)
.toList();
}
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/VespaVersion.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/VespaVersion.java
index 7f33f612cd0..e078df0267f 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/VespaVersion.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/VespaVersion.java
@@ -15,7 +15,8 @@ import static com.yahoo.config.application.api.DeploymentSpec.UpgradePolicy;
/**
* Information about a particular Vespa version.
- * VespaVersions are identified by their version number and ordered by increasing version numbers.
+ *
+ * Vespa versions are identified by their version number and ordered by increasing version numbers.
*
* @author bratseth
*/
@@ -29,8 +30,11 @@ public record VespaVersion(Version version,
Confidence confidence) implements Comparable<VespaVersion> {
public static Confidence confidenceFrom(DeploymentStatistics statistics, Controller controller) {
+ int thisMajorVersion = statistics.version().getMajor();
+ int defaultMajorVersion = controller.applications().targetMajorVersion().orElse(thisMajorVersion);
InstanceList all = InstanceList.from(controller.jobController().deploymentStatuses(ApplicationList.from(controller.applications().asList())
- .withProductionDeployment()));
+ .withProductionDeployment()))
+ .allowingMajorVersion(thisMajorVersion, defaultMajorVersion);
// 'production on this': All production deployment jobs upgrading to this version have completed without failure
InstanceList productionOnThis = all.matching(instance -> statistics.productionSuccesses().stream().anyMatch(run -> run.id().application().equals(instance)))
.not().failingUpgrade()
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
index 28536f36e20..b5177cd1d3e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
@@ -49,7 +49,7 @@ import com.yahoo.vespa.hosted.controller.routing.context.DeploymentRoutingContex
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationLock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -69,13 +69,13 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.pro
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -86,7 +86,7 @@ public class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeployment() {
+ void testDeployment() {
// Setup system
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -97,14 +97,14 @@ public class ControllerTest {
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
- assertEquals("Application version is known from completion of initial job",
- ApplicationVersion.from(RevisionId.forProduction(1), DeploymentContext.defaultSourceRevision, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
- context.application().revisions().get(context.instance().change().revision().get()));
+ assertEquals(ApplicationVersion.from(RevisionId.forProduction(1), DeploymentContext.defaultSourceRevision, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
+ context.application().revisions().get(context.instance().change().revision().get()),
+ "Application version is known from completion of initial job");
context.runJob(systemTest);
context.runJob(stagingTest);
RevisionId applicationVersion = context.instance().change().revision().get();
- assertTrue("Application version has been set during deployment", applicationVersion.isProduction());
+ assertTrue(applicationVersion.isProduction(), "Application version has been set during deployment");
tester.triggerJobs();
// Causes first deployment job to be triggered
@@ -171,11 +171,11 @@ public class ControllerTest {
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
- ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
- e.getMessage());
+ ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
+ e.getMessage());
}
- assertNotNull("Zone was not removed",
- context.instance().deployments().get(productionUsWest1.zone()));
+ assertNotNull(context.instance().deployments().get(productionUsWest1.zone()),
+ "Zone was not removed");
// prod zone removal is allowed with override
applicationPackage = new ApplicationPackageBuilder()
@@ -184,14 +184,14 @@ public class ControllerTest {
.region("us-east-3")
.build();
context.submit(applicationPackage);
- assertNull("Zone was removed",
- context.instance().deployments().get(productionUsWest1.zone()));
- assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
+ assertNull(context.instance().deployments().get(productionUsWest1.zone()),
+ "Zone was removed");
+ assertNull(context.instanceJobs().get(productionUsWest1), "Deployment job was removed");
// Submission has stored application meta.
assertNotNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.instanceId())
- .get(tester.clock().instant()));
+ .getMeta(context.instanceId())
+ .get(tester.clock().instant()));
// Meta data tombstone placed on delete
tester.clock().advance(Duration.ofSeconds(1));
@@ -199,18 +199,18 @@ public class ControllerTest {
tester.clock().advance(Duration.ofSeconds(1));
context.submit(ApplicationPackage.deploymentRemoval());
tester.applications().deleteApplication(context.application().id(),
- tester.controllerTester().credentialsFor(context.instanceId().tenant()));
+ tester.controllerTester().credentialsFor(context.instanceId().tenant()));
assertArrayEquals(new byte[0],
- tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.instanceId())
- .get(tester.clock().instant()));
+ tester.controllerTester().serviceRegistry().applicationStore()
+ .getMeta(context.instanceId())
+ .get(tester.clock().instant()));
assertNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.deploymentIdIn(productionUsWest1.zone())));
+ .getMeta(context.deploymentIdIn(productionUsWest1.zone())));
}
@Test
- public void testGlobalRotationStatus() {
+ void testGlobalRotationStatus() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
@@ -238,7 +238,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForGlobalEndpoint() {
+ void testDnsUpdatesForGlobalEndpoint() {
var betaContext = tester.newDeploymentContext("tenant1", "app1", "beta");
var defaultContext = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -251,23 +251,23 @@ public class ControllerTest {
.region(usCentral.region()) // Two deployments should result in each DNS alias being registered once
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(List.of(ZoneApiMock.from(usWest), ZoneApiMock.from(usCentral)),
- RoutingMethod.sharedLayer4);
+ RoutingMethod.sharedLayer4);
betaContext.submit(applicationPackage).deploy();
{ // Expected rotation names are passed to beta instance deployments
Collection<Deployment> betaDeployments = betaContext.instance().deployments().values();
assertFalse(betaDeployments.isEmpty());
Set<ContainerEndpoint> containerEndpoints = Set.of(new ContainerEndpoint("foo",
- "global",
- List.of("beta.app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-01"),
- OptionalInt.empty(),
- RoutingMethod.sharedLayer4));
+ "global",
+ List.of("beta.app1.tenant1.global.vespa.oath.cloud",
+ "rotation-id-01"),
+ OptionalInt.empty(),
+ RoutingMethod.sharedLayer4));
for (Deployment deployment : betaDeployments) {
assertEquals(containerEndpoints,
- tester.configServer().containerEndpoints()
- .get(betaContext.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpoints()
+ .get(betaContext.deploymentIdIn(deployment.zone())));
}
betaContext.flushDnsUpdates();
}
@@ -276,20 +276,20 @@ public class ControllerTest {
Collection<Deployment> defaultDeployments = defaultContext.instance().deployments().values();
assertFalse(defaultDeployments.isEmpty());
Set<ContainerEndpoint> containerEndpoints = Set.of(new ContainerEndpoint("foo",
- "global",
- List.of("app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-02"),
- OptionalInt.empty(),
- RoutingMethod.sharedLayer4));
+ "global",
+ List.of("app1.tenant1.global.vespa.oath.cloud",
+ "rotation-id-02"),
+ OptionalInt.empty(),
+ RoutingMethod.sharedLayer4));
for (Deployment deployment : defaultDeployments) {
assertEquals(containerEndpoints,
- tester.configServer().containerEndpoints().get(defaultContext.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpoints().get(defaultContext.deploymentIdIn(deployment.zone())));
}
defaultContext.flushDnsUpdates();
}
Map<String, String> rotationCnames = Map.of("beta.app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-01.",
- "app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-02.");
+ "app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-02.");
rotationCnames.forEach((cname, data) -> {
var record = tester.controllerTester().findCname(cname);
assertTrue(record.isPresent());
@@ -298,20 +298,20 @@ public class ControllerTest {
});
Map<ApplicationId, Set<String>> globalDnsNamesByInstance = Map.of(betaContext.instanceId(), Set.of("beta.app1.tenant1.global.vespa.oath.cloud"),
- defaultContext.instanceId(), Set.of("app1.tenant1.global.vespa.oath.cloud"));
+ defaultContext.instanceId(), Set.of("app1.tenant1.global.vespa.oath.cloud"));
globalDnsNamesByInstance.forEach((instance, dnsNames) -> {
Set<String> actualDnsNames = tester.controller().routing().readDeclaredEndpointsOf(instance)
- .scope(Endpoint.Scope.global)
- .asList().stream()
- .map(Endpoint::dnsName)
- .collect(Collectors.toSet());
- assertEquals("Global DNS names for " + instance, dnsNames, actualDnsNames);
+ .scope(Endpoint.Scope.global)
+ .asList().stream()
+ .map(Endpoint::dnsName)
+ .collect(Collectors.toSet());
+ assertEquals(dnsNames, actualDnsNames, "Global DNS names for " + instance);
});
}
@Test
- public void testDnsUpdatesForGlobalEndpointLegacySyntax() {
+ void testDnsUpdatesForGlobalEndpointLegacySyntax() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
@@ -323,10 +323,10 @@ public class ControllerTest {
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
- assertEquals("Rotation names are passed to config server in " + deployment.zone(),
- Set.of("rotation-id-01",
+ assertEquals(Set.of("rotation-id-01",
"app1.tenant1.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())),
+ "Rotation names are passed to config server in " + deployment.zone());
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
@@ -337,15 +337,15 @@ public class ControllerTest {
assertEquals("rotation-fqdn-01.", record.get().data().asString());
List<String> globalDnsNames = tester.controller().routing().readDeclaredEndpointsOf(context.instanceId())
- .scope(Endpoint.Scope.global)
- .sortedBy(Comparator.comparing(Endpoint::dnsName))
- .mapToList(Endpoint::dnsName);
+ .scope(Endpoint.Scope.global)
+ .sortedBy(Comparator.comparing(Endpoint::dnsName))
+ .mapToList(Endpoint::dnsName);
assertEquals(List.of("app1.tenant1.global.vespa.oath.cloud"),
- globalDnsNames);
+ globalDnsNames);
}
@Test
- public void testDnsUpdatesForMultipleGlobalEndpoints() {
+ void testDnsUpdatesForMultipleGlobalEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.endpoint("foobar", "qrs", "us-west-1", "us-central-1") // Rotation 01
@@ -368,9 +368,9 @@ public class ControllerTest {
var west = Sets.union(notWest, Set.of("rotation-id-04", "west.app1.tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
- assertEquals("Rotation names are passed to config server in " + deployment.zone(),
- ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
- tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())));
+ assertEquals(ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())),
+ "Rotation names are passed to config server in " + deployment.zone());
}
context.flushDnsUpdates();
@@ -398,7 +398,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForGlobalEndpointChanges() {
+ void testDnsUpdatesForGlobalEndpointChanges() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
@@ -415,10 +415,10 @@ public class ControllerTest {
for (var zone : List.of(west, central)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
// Application is deployed with an additional endpoint
@@ -433,16 +433,16 @@ public class ControllerTest {
for (var zone : List.of(west, central)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
assertEquals(
- "Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(east))
- );
+ ,
+ "Zone " + east + " is a member of global endpoint");
// Application is deployed with default endpoint pointing to 3/3 zones
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
@@ -455,13 +455,13 @@ public class ControllerTest {
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud")
+ "rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
// Region is removed from an endpoint without override
@@ -477,11 +477,11 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
- "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
- "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
- "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
- "and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
- ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
+ "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
+ "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
+ "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
+ "and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
+ ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
// Entire endpoint is removed without override
@@ -496,10 +496,10 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
- "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
- "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
- "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
- ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
+ "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
+ "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
+ "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
+ ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
// ... override is added
@@ -514,7 +514,7 @@ public class ControllerTest {
}
@Test
- public void testUnassignRotations() {
+ void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.endpoint("default", "qrs", "us-west-1", "us-central-1")
@@ -540,7 +540,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesWithChangeInRotationAssignment() {
+ void testDnsUpdatesWithChangeInRotationAssignment() {
// Application 1 is deployed and deleted
String dnsName1 = "app1.tenant1.global.vespa.oath.cloud";
{
@@ -567,17 +567,17 @@ public class ControllerTest {
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
- tester.controllerTester().credentialsFor(context.application().id().tenant()));
+ tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
- assertTrue("Rotation is unassigned",
- tester.controller().routing().rotations().availableRotations(lock)
- .containsKey(new RotationId("rotation-id-01")));
+ assertTrue(tester.controller().routing().rotations().availableRotations(lock)
+ .containsKey(new RotationId("rotation-id-01")),
+ "Rotation is unassigned");
}
context.flushDnsUpdates();
// Record is removed
Optional<Record> record = tester.controllerTester().findCname(dnsName1);
- assertTrue(dnsName1 + " is removed", record.isEmpty());
+ assertTrue(record.isEmpty(), dnsName1 + " is removed");
}
// Application 2 is deployed and assigned same rotation as application 1 had before deletion
@@ -624,7 +624,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForApplicationEndpoint() {
+ void testDnsUpdatesForApplicationEndpoint() {
ApplicationId beta = ApplicationId.from("tenant1", "app1", "beta");
ApplicationId main = ApplicationId.from("tenant1", "app1", "main");
var context = tester.newDeploymentContext(beta);
@@ -633,14 +633,14 @@ public class ControllerTest {
.region("us-west-1")
.region("us-east-3")
.applicationEndpoint("a", "default", "us-west-1",
- Map.of(beta.instance(), 2,
- main.instance(), 8))
+ Map.of(beta.instance(), 2,
+ main.instance(), 8))
.applicationEndpoint("b", "default", "us-west-1",
- Map.of(beta.instance(), 1,
- main.instance(), 1))
+ Map.of(beta.instance(), 1,
+ main.instance(), 1))
.applicationEndpoint("c", "default", "us-east-3",
- Map.of(beta.instance(), 4,
- main.instance(), 6))
+ Map.of(beta.instance(), 4,
+ main.instance(), 6))
.build();
context.submit(applicationPackage).deploy();
@@ -649,63 +649,63 @@ public class ControllerTest {
// Expected container endpoints are passed to each deployment
Map<DeploymentId, Map<String, Integer>> deploymentEndpoints = Map.of(
new DeploymentId(beta, usWest), Map.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud", 2,
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
new DeploymentId(main, usWest), Map.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud", 8,
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
new DeploymentId(beta, usEast), Map.of("c.app1.tenant1.us-east-3-r.vespa.oath.cloud", 4),
new DeploymentId(main, usEast), Map.of("c.app1.tenant1.us-east-3-r.vespa.oath.cloud", 6)
);
deploymentEndpoints.forEach((deployment, endpoints) -> {
Set<ContainerEndpoint> expected = endpoints.entrySet().stream()
- .map(kv -> new ContainerEndpoint("default", "application",
- List.of(kv.getKey()),
- OptionalInt.of(kv.getValue()),
- RoutingMethod.sharedLayer4))
- .collect(Collectors.toSet());
- assertEquals("Endpoint names for " + deployment + " are passed to config server",
- expected,
- tester.configServer().containerEndpoints().get(deployment));
+ .map(kv -> new ContainerEndpoint("default", "application",
+ List.of(kv.getKey()),
+ OptionalInt.of(kv.getValue()),
+ RoutingMethod.sharedLayer4))
+ .collect(Collectors.toSet());
+ assertEquals(expected,
+ tester.configServer().containerEndpoints().get(deployment),
+ "Endpoint names for " + deployment + " are passed to config server");
});
context.flushDnsUpdates();
// DNS records are created for each endpoint
Set<Record> records = tester.controllerTester().nameService().records();
assertEquals(Set.of(new Record(Record.Type.CNAME,
- RecordName.from("a.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-west-1.")),
- new Record(Record.Type.CNAME,
- RecordName.from("b.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-west-1.")),
- new Record(Record.Type.CNAME,
- RecordName.from("c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-east-3."))),
- records);
+ RecordName.from("a.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-west-1.")),
+ new Record(Record.Type.CNAME,
+ RecordName.from("b.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-west-1.")),
+ new Record(Record.Type.CNAME,
+ RecordName.from("c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-east-3."))),
+ records);
List<String> endpointDnsNames = tester.controller().routing().declaredEndpointsOf(context.application())
- .scope(Endpoint.Scope.application)
- .mapToList(Endpoint::dnsName);
+ .scope(Endpoint.Scope.application)
+ .mapToList(Endpoint::dnsName);
assertEquals(List.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud",
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud",
- "c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
- endpointDnsNames);
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud",
+ "c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
+ endpointDnsNames);
}
@Test
- public void testDevDeployment() {
+ void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().build();
// Create application
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
- .setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.sharedLayer4);
+ .setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.sharedLayer4);
// Deploy
context.runJob(zone, applicationPackage);
- assertTrue("Application deployed and activated",
- tester.configServer().application(context.instanceId(), zone).get().activated());
- assertTrue("No job status added",
- context.instanceJobs().isEmpty());
- assertEquals("DeploymentSpec is not stored", DeploymentSpec.empty, context.application().deploymentSpec());
+ assertTrue(tester.configServer().application(context.instanceId(), zone).get().activated(),
+ "Application deployed and activated");
+ assertTrue(context.instanceJobs().isEmpty(),
+ "No job status added");
+ assertEquals(DeploymentSpec.empty, context.application().deploymentSpec(), "DeploymentSpec is not stored");
// Verify zone supports shared layer 4 and shared routing methods
Set<RoutingMethod> routingMethods = tester.controller().routing().readEndpointsOf(context.deploymentIdIn(zone))
@@ -717,20 +717,20 @@ public class ControllerTest {
// Deployment has stored application meta.
assertNotNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(new DeploymentId(context.instanceId(), zone))
- .get(tester.clock().instant()));
+ .getMeta(new DeploymentId(context.instanceId(), zone))
+ .get(tester.clock().instant()));
// Meta data tombstone placed on delete
tester.clock().advance(Duration.ofSeconds(1));
tester.controller().applications().deactivate(context.instanceId(), zone);
assertArrayEquals(new byte[0],
- tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(new DeploymentId(context.instanceId(), zone))
- .get(tester.clock().instant()));
+ tester.controllerTester().serviceRegistry().applicationStore()
+ .getMeta(new DeploymentId(context.instanceId(), zone))
+ .get(tester.clock().instant()));
}
@Test
- public void testDevDeploymentWithIncompatibleVersions() {
+ void testDevDeploymentWithIncompatibleVersions() {
Version version1 = new Version("7");
Version version2 = new Version("7.5");
Version version3 = new Version("8");
@@ -778,12 +778,12 @@ public class ControllerTest {
}
@Test
- public void testSuspension() {
+ void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
- .region("us-west-1")
- .region("us-east-3")
- .build();
+ .region("us-west-1")
+ .region("us-east-3")
+ .build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
@@ -798,7 +798,7 @@ public class ControllerTest {
// Application may already have been deleted, or deployment failed without response, test that deleting a
// second time will not fail
@Test
- public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
+ void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -811,7 +811,7 @@ public class ControllerTest {
}
@Test
- public void testDeployApplicationWithWarnings() {
+ void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -821,11 +821,11 @@ public class ControllerTest {
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
- .metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
+ .metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
- public void testDeploySelectivelyProvisionsCertificate() {
+ void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
// Create app1
@@ -835,22 +835,22 @@ public class ControllerTest {
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
- .region(prodZone.region())
- .build();
+ .region(prodZone.region())
+ .build();
// Deploy app1 in production
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
- assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
+ assertTrue(cert.isPresent(), "Provisions certificate in " + Environment.prod);
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
- "app1.tenant1.global.vespa.oath.cloud",
- "*.app1.tenant1.global.vespa.oath.cloud"),
- Stream.of(prodZone, testZone, stagingZone)
- .flatMap(zone -> Stream.of("", "*.")
- .map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
- (zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
- ".vespa.oath.cloud")))
- .collect(Collectors.toUnmodifiableSet()),
- Set.copyOf(tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId())));
+ "app1.tenant1.global.vespa.oath.cloud",
+ "*.app1.tenant1.global.vespa.oath.cloud"),
+ Stream.of(prodZone, testZone, stagingZone)
+ .flatMap(zone -> Stream.of("", "*.")
+ .map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
+ (zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
+ ".vespa.oath.cloud")))
+ .collect(Collectors.toUnmodifiableSet()),
+ Set.copyOf(tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId())));
// Next deployment reuses certificate
context1.submit(applicationPackage).deploy();
@@ -862,13 +862,13 @@ public class ControllerTest {
// Deploy app2 in a zone with shared routing
context2.runJob(devZone, applicationPackage);
- assertTrue("Application deployed and activated",
- tester.configServer().application(context2.instanceId(), devZone).get().activated());
- assertTrue("Provisions certificate also in zone with routing layer", certificate.apply(context2.instance()).isPresent());
+ assertTrue(tester.configServer().application(context2.instanceId(), devZone).get().activated(),
+ "Application deployed and activated");
+ assertTrue(certificate.apply(context2.instance()).isPresent(), "Provisions certificate also in zone with routing layer");
}
@Test
- public void testDeployWithGlobalEndpointsInMultipleClouds() {
+ void testDeployWithGlobalEndpointsInMultipleClouds() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("test.us-west-1"),
ZoneApiMock.fromId("staging.us-west-1"),
@@ -904,7 +904,7 @@ public class ControllerTest {
}
@Test
- public void testDeployWithoutSourceRevision() {
+ void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
@@ -913,12 +913,12 @@ public class ControllerTest {
// Submit without source revision
context.submit(applicationPackage, Optional.empty())
- .deploy();
- assertEquals("Deployed application", 1, context.instance().deployments().size());
+ .deploy();
+ assertEquals(1, context.instance().deployments().size(), "Deployed application");
}
@Test
- public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
+ void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
@@ -939,25 +939,25 @@ public class ControllerTest {
var expectedRecords = List.of(
// The weighted record for zone 2's region
new Record(Record.Type.ALIAS,
- RecordName.from("application.tenant.us-east-3-w.vespa.oath.cloud"),
- new WeightedAliasTarget(HostName.of("lb-0--tenant.application.default--prod.us-east-3"),
- "dns-zone-1", ZoneId.from("prod.us-east-3"), 1).pack()),
+ RecordName.from("application.tenant.us-east-3-w.vespa.oath.cloud"),
+ new WeightedAliasTarget(HostName.of("lb-0--tenant.application.default--prod.us-east-3"),
+ "dns-zone-1", ZoneId.from("prod.us-east-3"), 1).pack()),
// The 'east' global endpoint, pointing to the weighted record for zone 2's region
new Record(Record.Type.ALIAS,
- RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
- new LatencyAliasTarget(HostName.of("application.tenant.us-east-3-w.vespa.oath.cloud"),
- "dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
+ RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
+ new LatencyAliasTarget(HostName.of("application.tenant.us-east-3-w.vespa.oath.cloud"),
+ "dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
// The zone-scoped endpoint pointing to zone 2 with exclusive routing
new Record(Record.Type.CNAME,
- RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
- RecordData.from("lb-0--tenant.application.default--prod.us-east-3.")));
+ RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
+ RecordData.from("lb-0--tenant.application.default--prod.us-east-3.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
- public void testDeploymentDirectRouting() {
+ void testDeploymentDirectRouting() {
// Rotation-less system
DeploymentTester tester = new DeploymentTester(new ControllerTester(new RotationsConfig.Builder().build(), main));
var context = tester.newDeploymentContext();
@@ -965,7 +965,7 @@ public class ControllerTest {
var zone2 = ZoneId.from("prod", "us-east-3");
var zone3 = ZoneId.from("prod", "eu-west-1");
tester.controllerTester().zoneRegistry()
- .exclusiveRoutingIn(ZoneApiMock.from(zone1), ZoneApiMock.from(zone2), ZoneApiMock.from(zone3));
+ .exclusiveRoutingIn(ZoneApiMock.from(zone1), ZoneApiMock.from(zone2), ZoneApiMock.from(zone3));
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
@@ -979,20 +979,20 @@ public class ControllerTest {
// Deployment passes container endpoints to config server
for (var zone : List.of(zone1, zone2)) {
- assertEquals("Expected container endpoints in " + zone,
- Set.of("application.tenant.global.vespa.oath.cloud",
- "foo.application.tenant.global.vespa.oath.cloud",
- "us.application.tenant.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(zone)));
+ assertEquals(Set.of("application.tenant.global.vespa.oath.cloud",
+ "foo.application.tenant.global.vespa.oath.cloud",
+ "us.application.tenant.global.vespa.oath.cloud"),
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(zone)),
+ "Expected container endpoints in " + zone);
}
- assertEquals("Expected container endpoints in " + zone3,
- Set.of("application.tenant.global.vespa.oath.cloud",
- "foo.application.tenant.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(zone3)));
+ assertEquals(Set.of("application.tenant.global.vespa.oath.cloud",
+ "foo.application.tenant.global.vespa.oath.cloud"),
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(zone3)),
+ "Expected container endpoints in " + zone3);
}
@Test
- public void testChangeEndpointCluster() {
+ void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
@@ -1005,7 +1005,7 @@ public class ControllerTest {
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
- .rotations().get(0).clusterId());
+ .rotations().get(0).clusterId());
// Redeploy with endpoint cluster changed needs override
applicationPackage = new ApplicationPackageBuilder()
@@ -1018,12 +1018,12 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
- "'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
- "deployment.xml. Deploying given deployment.xml will remove " +
- "[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
- "[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
- "<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
- "https://docs.vespa.ai/en/reference/validation-overrides.html", e.getMessage());
+ "'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
+ "deployment.xml. Deploying given deployment.xml will remove " +
+ "[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
+ "[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
+ "<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
+ "https://docs.vespa.ai/en/reference/validation-overrides.html", e.getMessage());
}
// Redeploy with override succeeds
@@ -1035,26 +1035,26 @@ public class ControllerTest {
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
- .rotations().get(0).clusterId());
+ .rotations().get(0).clusterId());
}
@Test
- public void testReadableApplications() {
+ void testReadableApplications() {
var db = new MockCuratorDb(tester.controller().system());
var tester = new DeploymentTester(new ControllerTester(db));
// Create and deploy two applications
var app1 = tester.newDeploymentContext("t1", "a1", "default")
- .submit()
- .deploy();
+ .submit()
+ .deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
- .submit()
- .deploy();
+ .submit()
+ .deploy();
assertEquals(2, tester.applications().readable().size());
// Write invalid data to one application
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
- new byte[]{(byte) 0xDE, (byte) 0xAD});
+ new byte[]{(byte) 0xDE, (byte) 0xAD});
// Can read the remaining readable
assertEquals(1, tester.applications().readable().size());
@@ -1071,57 +1071,57 @@ public class ControllerTest {
}
@Test
- public void testClashingEndpointIdAndInstanceName() {
+ void testClashingEndpointIdAndInstanceName() {
String deploymentXml = "<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" +
- " <instance id=\"default\">\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " <endpoints>\n" +
- " <endpoint id=\"dev\" container-id=\"qrs\"/>\n" +
- " </endpoints>\n" +
- " </instance>\n" +
- " <instance id=\"dev\">\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " <endpoints>\n" +
- " <endpoint id=\"default\" container-id=\"qrs\"/>\n" +
- " </endpoints>\n" +
- " </instance>\n" +
- "</deployment>\n";
+ " <instance id=\"default\">\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " <endpoints>\n" +
+ " <endpoint id=\"dev\" container-id=\"qrs\"/>\n" +
+ " </endpoints>\n" +
+ " </instance>\n" +
+ " <instance id=\"dev\">\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " <endpoints>\n" +
+ " <endpoint id=\"default\" container-id=\"qrs\"/>\n" +
+ " </endpoints>\n" +
+ " </instance>\n" +
+ "</deployment>\n";
ApplicationPackage applicationPackage = ApplicationPackageBuilder.fromDeploymentXml(deploymentXml);
try {
tester.newDeploymentContext().submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint with ID 'default' in instance 'dev' clashes with endpoint 'dev' in instance 'default'",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void testTestPackageWarnings() {
+ void testTestPackageWarnings() {
String deploymentXml = "<deployment version='1.0'>\n" +
- " <prod>\n" +
- " <region>us-west-1</region>\n" +
- " </prod>\n" +
- "</deployment>\n";
+ " <prod>\n" +
+ " <region>us-west-1</region>\n" +
+ " </prod>\n" +
+ "</deployment>\n";
ApplicationPackage applicationPackage = ApplicationPackageBuilder.fromDeploymentXml(deploymentXml);
byte[] testPackage = ApplicationPackage.filesZip(Map.of("tests/staging-test/foo.json", new byte[0]));
var app = tester.newDeploymentContext();
tester.jobs().submit(app.application().id(), Submission.basic(applicationPackage, testPackage), 1);
assertEquals(List.of(new Notification(tester.clock().instant(),
- Type.testPackage,
- Level.warning,
- NotificationSource.from(app.application().id()),
- List.of("test package has staging tests, so it should also include staging setup",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"))),
- tester.controller().notificationsDb().listNotifications(NotificationSource.from(app.application().id()), true));
+ Type.testPackage,
+ Level.warning,
+ NotificationSource.from(app.application().id()),
+ List.of("test package has staging tests, so it should also include staging setup",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"))),
+ tester.controller().notificationsDb().listNotifications(NotificationSource.from(app.application().id()), true));
}
@Test
- public void testCompileVersion() {
+ void testCompileVersion() {
DeploymentContext context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
TenantAndApplicationId application = TenantAndApplicationId.from(context.instanceId());
@@ -1153,7 +1153,7 @@ public class ControllerTest {
assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.of(8)));
// Default major version is set to 8.
- tester.applications().setTargetMajorVersion(Optional.of(8));
+ tester.applications().setTargetMajorVersion(OptionalInt.of(8));
assertEquals(version1, tester.applications().compileVersion(application, OptionalInt.of(7)));
assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.empty()));
@@ -1166,10 +1166,27 @@ public class ControllerTest {
tester.applications().lockApplicationOrThrow(application, locked -> tester.applications().store(locked.withMajorVersion(8)));
assertEquals(version1, tester.applications().compileVersion(application, OptionalInt.of(7)));
assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.empty()));
+
+ // Application upgrades to major 8; only major version from deployment spec should cause a downgrade.
+ context.submit(new ApplicationPackageBuilder().region("us-west-1").compileVersion(version2).build()).deploy();
+ tester.applications().setTargetMajorVersion(OptionalInt.empty());
+ tester.applications().lockApplicationOrThrow(application, locked -> tester.applications().store(locked.withMajorVersion(null)));
+ assertEquals(version1, tester.applications().compileVersion(application, OptionalInt.of(7)));
+ assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.empty()));
+
+ // Default major version across all apps should not cause a downgrade.
+ tester.applications().setTargetMajorVersion(OptionalInt.of(7));
+ assertEquals(version1, tester.applications().compileVersion(application, OptionalInt.of(7)));
+ assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.empty()));
+
+ // Default major version for specific app should not cause a downgrade.
+ tester.applications().lockApplicationOrThrow(application, locked -> tester.applications().store(locked.withMajorVersion(7)));
+ assertEquals(version1, tester.applications().compileVersion(application, OptionalInt.of(7)));
+ assertEquals(version2, tester.applications().compileVersion(application, OptionalInt.empty()));
}
@Test
- public void testCloudAccount() {
+ void testCloudAccount() {
DeploymentContext context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "us-west-1");
String cloudAccount = "012345678912";
@@ -1180,7 +1197,8 @@ public class ControllerTest {
try {
context.submit(applicationPackage).deploy();
fail("Expected exception"); // Account invalid for tenant
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
tester.controllerTester().flagSource().withListFlag(PermanentFlags.CLOUD_ACCOUNTS.id(), List.of(cloudAccount), String.class);
context.submit(applicationPackage).deploy();
@@ -1188,7 +1206,7 @@ public class ControllerTest {
}
@Test
- public void testSubmitWithElementDeprecatedOnPreviousMajor() {
+ void testSubmitWithElementDeprecatedOnPreviousMajor() {
DeploymentContext context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.compileVersion(Version.fromString("8.1"))
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
index a2eefd47b56..10fd57ce032 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
@@ -74,9 +74,8 @@ import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Convenience methods for controller tests.
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
index 11b3ad0d45a..3163c8b6439 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
@@ -17,7 +17,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.ApplicationData;
import com.yahoo.vespa.hosted.controller.deployment.RevisionHistory;
import com.yahoo.vespa.hosted.controller.metric.ApplicationMetrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -29,13 +29,13 @@ import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class DeploymentQuotaCalculatorTest {
@Test
- public void quota_is_divided_among_prod_instances() {
+ void quota_is_divided_among_prod_instances() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited().withBudget(10), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(),
DeploymentSpec.fromXml(
"<deployment version='1.0'>\n" +
@@ -59,12 +59,12 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void quota_is_divided_among_prod_and_manual_instances() {
+ void quota_is_divided_among_prod_and_manual_instances() {
var existing_dev_deployment = new Application(TenantAndApplicationId.from(ApplicationId.defaultId()), Instant.EPOCH, DeploymentSpec.empty, ValidationOverrides.empty, Optional.empty(),
- Optional.empty(), Optional.empty(), OptionalInt.empty(), new ApplicationMetrics(1, 1), Set.of(), OptionalLong.empty(), RevisionHistory.empty(),
- List.of(new Instance(ApplicationId.defaultId()).withNewDeployment(ZoneId.from(Environment.dev, RegionName.defaultName()),
- RevisionId.forProduction(1), Version.emptyVersion, Instant.EPOCH, Map.of(), QuotaUsage.create(0.53d))));
+ Optional.empty(), Optional.empty(), OptionalInt.empty(), new ApplicationMetrics(1, 1), Set.of(), OptionalLong.empty(), RevisionHistory.empty(),
+ List.of(new Instance(ApplicationId.defaultId()).withNewDeployment(ZoneId.from(Environment.dev, RegionName.defaultName()),
+ RevisionId.forProduction(1), Version.emptyVersion, Instant.EPOCH, Map.of(), QuotaUsage.create(0.53d))));
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited().withBudget(2), List.of(existing_dev_deployment), ApplicationId.defaultId(), ZoneId.defaultId(),
DeploymentSpec.fromXml(
@@ -84,19 +84,19 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void unlimited_quota_remains_unlimited() {
+ void unlimited_quota_remains_unlimited() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited(), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(), DeploymentSpec.empty);
assertTrue(calculated.isUnlimited());
}
@Test
- public void zero_quota_remains_zero() {
+ void zero_quota_remains_zero() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.zero(), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(), DeploymentSpec.empty);
assertEquals(calculated.budget().orElseThrow().doubleValue(), 0, 1e-5);
}
@Test
- public void using_highest_resource_use() throws Exception {
+ void using_highest_resource_use() throws Exception {
var content = new String(Files.readAllBytes(Paths.get("src/test/java/com/yahoo/vespa/hosted/controller/application/response/application.json")));
var mapper = new ObjectMapper();
var application = mapper.readValue(content, ApplicationData.class).toApplication();
@@ -105,7 +105,7 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void tenant_quota_in_pipeline() {
+ void tenant_quota_in_pipeline() {
var tenantQuota = Quota.unlimited().withBudget(42);
var calculated = DeploymentQuotaCalculator.calculate(tenantQuota, List.of(), ApplicationId.defaultId(), ZoneId.from("test", "apac1"), DeploymentSpec.empty);
assertEquals(tenantQuota, calculated);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
index 81fc610d1f6..f3324e0c1f3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
@@ -8,12 +8,12 @@ import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.application.Endpoint.Port;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -26,7 +26,7 @@ public class EndpointTest {
private static final TenantAndApplicationId app2 = TenantAndApplicationId.from(instance2);
@Test
- public void global_endpoints() {
+ void global_endpoints() {
DeploymentId deployment1 = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
DeploymentId deployment2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
ClusterSpec.Id cluster = ClusterSpec.Id.from("default");
@@ -72,7 +72,7 @@ public class EndpointTest {
}
@Test
- public void global_endpoints_with_endpoint_id() {
+ void global_endpoints_with_endpoint_id() {
DeploymentId deployment1 = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
DeploymentId deployment2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
ClusterSpec.Id cluster = ClusterSpec.Id.from("default");
@@ -114,7 +114,7 @@ public class EndpointTest {
}
@Test
- public void zone_endpoints() {
+ void zone_endpoints() {
var cluster = ClusterSpec.Id.from("default"); // Always default for non-direct routing
var prodZone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var prodZone2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
@@ -172,7 +172,7 @@ public class EndpointTest {
}
@Test
- public void certificate_endpoints() {
+ void certificate_endpoints() {
var defaultCluster = ClusterSpec.Id.from("default");
var prodZone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var testZone = new DeploymentId(instance1, ZoneId.from("test", "us-north-2"));
@@ -237,7 +237,7 @@ public class EndpointTest {
}
@Test
- public void region_endpoints() {
+ void region_endpoints() {
var cluster = ClusterSpec.Id.from("default");
var prodZone = ZoneId.from("prod", "us-north-2");
Map<String, Endpoint> tests = Map.of(
@@ -268,42 +268,42 @@ public class EndpointTest {
);
tests.forEach((expected, endpoint) -> assertEquals(expected, endpoint.url().toString()));
- assertEquals("Availability zone is removed from region",
- "aws-us-north-1",
- tests.get("https://a1.t1.aws-us-north-1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value());
- assertEquals("Availability zone is removed from region",
- "gcp-us-south1",
- tests.get("https://a1.t1.gcp-us-south1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value());
+ assertEquals("aws-us-north-1",
+ tests.get("https://a1.t1.aws-us-north-1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value(),
+ "Availability zone is removed from region");
+ assertEquals("gcp-us-south1",
+ tests.get("https://a1.t1.gcp-us-south1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value(),
+ "Availability zone is removed from region");
}
@Test
- public void application_endpoints() {
+ void application_endpoints() {
Map<String, Endpoint> tests = Map.of(
"https://weighted.a1.t1.us-west-1.r.vespa-app.cloud/",
Endpoint.of(app1)
.targetApplication(EndpointId.of("weighted"), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
+ Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.Public),
"https://weighted.a1.t1.us-west-1.r.cd.vespa-app.cloud/",
Endpoint.of(app1)
.targetApplication(EndpointId.of("weighted"), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
+ Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.PublicCd),
"https://a2.t2.us-east-3-r.vespa.oath.cloud/",
Endpoint.of(app2)
.targetApplication(EndpointId.defaultId(), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
+ Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.main),
"https://cd.a2.t2.us-east-3-r.vespa.oath.cloud/",
Endpoint.of(app2)
.targetApplication(EndpointId.defaultId(), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
+ Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.cd)
@@ -312,7 +312,7 @@ public class EndpointTest {
}
@Test
- public void upstream_name() {
+ void upstream_name() {
var zone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var zone2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
var tests1 = Map.of(
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java
index 977304db3fb..a92c035b502 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.application.pkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.util.zip.ZipOutputStream;
import static com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackageDiff.diff;
import static com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackageDiff.diffAgainstEmpty;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -24,12 +24,12 @@ public class ApplicationPackageDiffTest {
private static final ApplicationPackage app2 = applicationPackage(Map.of("file1", "updated contents\nof the\nfirst file\nafter some changes", "dir/myfile2", "Second file", "dir/binary", "øøøø"));
@Test
- public void no_diff() {
+ void no_diff() {
assertEquals("No diff\n", new String(diff(app1, app1)));
}
@Test
- public void diff_against_empty() {
+ void diff_against_empty() {
assertEquals("--- dir/binary\n" +
"Diff skipped: File is binary (new file -> 8B)\n" +
"\n" +
@@ -45,7 +45,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void full_diff() {
+ void full_diff() {
// Even though dir/binary is binary file, we can see they are identical, so it should not print "Diff skipped"
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
@@ -66,7 +66,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_for_too_large_files() {
+ void skips_diff_for_too_large_files() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
@@ -81,7 +81,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_if_file_diff_is_too_large() {
+ void skips_diff_if_file_diff_is_too_large() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
@@ -96,7 +96,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_if_total_diff_is_too_large() {
+ void skips_diff_if_total_diff_is_too_large() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
index 0458f77fc00..ce7fa5784e8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.application.pkg;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.application.api.ValidationId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -13,10 +13,10 @@ import java.util.Map;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author valerijf
@@ -55,7 +55,7 @@ public class ApplicationPackageTest {
"</nodes>";
@Test
- public void test_createEmptyForDeploymentRemoval() {
+ void test_createEmptyForDeploymentRemoval() {
ApplicationPackage app = ApplicationPackage.deploymentRemoval();
assertEquals(DeploymentSpec.empty, app.deploymentSpec());
assertEquals(List.of(), app.trustedCertificates());
@@ -66,22 +66,22 @@ public class ApplicationPackageTest {
}
@Test
- public void testMetaData() {
+ void testMetaData() {
byte[] zip = ApplicationPackage.filesZip(Map.of("services.xml", servicesXml.getBytes(UTF_8),
- "jdisc.xml", jdiscXml.getBytes(UTF_8),
- "content/content.xml", contentXml.getBytes(UTF_8),
- "content/nodes.xml", nodesXml.getBytes(UTF_8),
- "gurba", "gurba".getBytes(UTF_8)));
+ "jdisc.xml", jdiscXml.getBytes(UTF_8),
+ "content/content.xml", contentXml.getBytes(UTF_8),
+ "content/nodes.xml", nodesXml.getBytes(UTF_8),
+ "gurba", "gurba".getBytes(UTF_8)));
assertEquals(Map.of("services.xml", servicesXml,
- "jdisc.xml", jdiscXml,
- "content/content.xml", contentXml,
- "content/nodes.xml", nodesXml),
- unzip(new ApplicationPackage(zip, false).metaDataZip()));
+ "jdisc.xml", jdiscXml,
+ "content/content.xml", contentXml,
+ "content/nodes.xml", nodesXml),
+ unzip(new ApplicationPackage(zip, false).metaDataZip()));
}
@Test
- public void testMetaDataWithMissingFiles() {
+ void testMetaDataWithMissingFiles() {
byte[] zip = ApplicationPackage.filesZip(Map.of("services.xml", servicesXml.getBytes(UTF_8)));
try {
@@ -94,7 +94,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testAbsoluteInclude() throws Exception {
+ void testAbsoluteInclude() throws Exception {
try {
getApplicationZip("include-absolute.zip");
fail("Should fail on include file outside zip");
@@ -105,7 +105,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testParentInclude() throws Exception {
+ void testParentInclude() throws Exception {
try {
getApplicationZip("include-parent.zip");
fail("Should fail on include file outside zip");
@@ -116,7 +116,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testBundleHashesAreSameWithDifferentDeploymentXml() throws Exception {
+ void testBundleHashesAreSameWithDifferentDeploymentXml() throws Exception {
var originalPackage = getApplicationZip("original.zip");
var changedServices = getApplicationZip("changed-services-xml.zip");
var changedDeploymentXml = getApplicationZip("changed-deployment-xml.zip");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
index 92137094f62..8d9f88ca0ca 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.application.pkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LinesComparatorTest {
private static final String text1 = "This part of the\n" +
@@ -64,7 +64,7 @@ public class LinesComparatorTest {
"to this document.";
@Test
- public void diff_test() {
+ void diff_test() {
assertDiff(null, "", "");
assertDiff(null, text1, text1);
assertDiff(text1.lines().map(line -> "- " + line).collect(Collectors.joining("\n", "@@ -1,24 +1,0 @@\n", "\n")), text1, "");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
index 8588bb9ea16..5bc1c386134 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.pkg.TestPackage.TestSummary;
import com.yahoo.vespa.hosted.controller.config.ControllerConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -22,7 +22,7 @@ import static com.yahoo.vespa.hosted.controller.api.integration.deployment.Teste
import static com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud.Suite.system;
import static com.yahoo.vespa.hosted.controller.application.pkg.TestPackage.validateTests;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -75,65 +75,65 @@ public class TestPackageTest {
}
@Test
- public void testBundleValidation() throws IOException {
+ void testBundleValidation() throws IOException {
byte[] testZip = ApplicationPackage.filesZip(Map.of("components/foo-tests.jar", testsJar("SystemTest", "StagingSetup", "ProductionTest"),
- "artifacts/key", new byte[0]));
+ "artifacts/key", new byte[0]));
TestSummary summary = validateTests(List.of(system), testZip);
assertEquals(List.of(system, staging_setup, production), summary.suites());
assertEquals(List.of("test package contains 'artifacts/key'; this conflicts with credentials used to run tests in Vespa Cloud",
- "test package has staging setup, so it should also include staging tests",
- "test package has production tests, but no production tests are declared in deployment.xml",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "test package has staging setup, so it should also include staging tests",
+ "test package has production tests, but no production tests are declared in deployment.xml",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void testFatTestsValidation() {
+ void testFatTestsValidation() {
byte[] testZip = ApplicationPackage.filesZip(Map.of("artifacts/foo-tests.jar", new byte[0]));
TestSummary summary = validateTests(List.of(staging, production), testZip);
assertEquals(List.of(staging, production), summary.suites());
assertEquals(List.of("test package has staging tests, so it should also include staging setup",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void testBasicTestsValidation() {
+ void testBasicTestsValidation() {
byte[] testZip = ApplicationPackage.filesZip(Map.of("tests/staging-test/foo.json", new byte[0],
- "tests/staging-setup/foo.json", new byte[0]));
+ "tests/staging-setup/foo.json", new byte[0]));
TestSummary summary = validateTests(List.of(system, production), testZip);
assertEquals(List.of(staging_setup, staging), summary.suites());
assertEquals(List.of("test package has no system tests, but <test /> is declared in deployment.xml",
- "test package has no production tests, but production tests are declared in deployment.xml",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "test package has no production tests, but production tests are declared in deployment.xml",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void generates_correct_tester_flavor() {
+ void generates_correct_tester_flavor() {
DeploymentSpec spec = DeploymentSpec.fromXml("<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" +
- " <instance id='first'>\n" +
- " <test tester-flavor=\"d-6-16-100\" />\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " <test>us-west-1</test>\n" +
- " </prod>\n" +
- " </instance>\n" +
- " <instance id='second'>\n" +
- " <test />\n" +
- " <staging />\n" +
- " <prod tester-flavor=\"d-6-16-100\">\n" +
- " <parallel>\n" +
- " <region active=\"true\">us-east-3</region>\n" +
- " <region active=\"true\">us-central-1</region>\n" +
- " </parallel>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " <test>us-west-1</test>\n" +
- " </prod>\n" +
- " </instance>\n" +
- "</deployment>\n");
+ " <instance id='first'>\n" +
+ " <test tester-flavor=\"d-6-16-100\" />\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " <test>us-west-1</test>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ " <instance id='second'>\n" +
+ " <test />\n" +
+ " <staging />\n" +
+ " <prod tester-flavor=\"d-6-16-100\">\n" +
+ " <parallel>\n" +
+ " <region active=\"true\">us-east-3</region>\n" +
+ " <region active=\"true\">us-central-1</region>\n" +
+ " </parallel>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " <test>us-west-1</test>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ "</deployment>\n");
NodeResources firstResources = TestPackage.testerResourcesFor(ZoneId.from("prod", "us-west-1"), spec.requireInstance("first"));
assertEquals(TestPackage.DEFAULT_TESTER_RESOURCES, firstResources);
@@ -145,13 +145,13 @@ public class TestPackageTest {
}
@Test
- public void generates_correct_services_xml() throws IOException {
+ void generates_correct_services_xml() throws IOException {
assertEquals(Files.readString(Paths.get("src/test/resources/test_runner_services.xml-cd")),
- new String(TestPackage.servicesXml(true,
- false,
- new NodeResources(2, 12, 75, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.local),
- new ControllerConfig.Steprunner.Testerapp.Builder().build()),
- UTF_8));
+ new String(TestPackage.servicesXml(true,
+ false,
+ new NodeResources(2, 12, 75, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.local),
+ new ControllerConfig.Steprunner.Testerapp.Builder().build()),
+ UTF_8));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
index 6908464640b..37062e1002b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
@@ -5,7 +5,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -16,7 +16,7 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -24,22 +24,22 @@ import static org.junit.Assert.assertEquals;
public class ZipEntriesTest {
@Test
- public void test_replacement() {
+ void test_replacement() {
ApplicationPackage applicationPackage = new ApplicationPackage(new byte[0]);
List<X509Certificate> certificates = IntStream.range(0, 3)
- .mapToObj(i -> {
- KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
- X500Principal subject = new X500Principal("CN=subject" + i);
- return X509CertificateBuilder.fromKeypair(keyPair,
- subject,
- Instant.now(),
- Instant.now().plusSeconds(1),
- SignatureAlgorithm.SHA512_WITH_ECDSA,
- BigInteger.valueOf(1))
- .build();
- })
- .collect(Collectors.toUnmodifiableList());
-
+ .mapToObj(i -> {
+ KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
+ X500Principal subject = new X500Principal("CN=subject" + i);
+ return X509CertificateBuilder.fromKeypair(keyPair,
+ subject,
+ Instant.now(),
+ Instant.now().plusSeconds(1),
+ SignatureAlgorithm.SHA512_WITH_ECDSA,
+ BigInteger.valueOf(1))
+ .build();
+ })
+ .collect(Collectors.toUnmodifiableList());
+
assertEquals(List.of(), applicationPackage.trustedCertificates());
for (int i = 0; i < certificates.size(); i++) {
applicationPackage = applicationPackage.withTrustedCertificate(certificates.get(i));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
index 4c3d76b1b17..081056e5184 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
@@ -7,7 +7,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
import org.apache.curator.shaded.com.google.common.collect.Streams;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Optional;
@@ -16,12 +16,12 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class CuratorArchiveBucketDbTest {
@Test
- public void archiveUriFor() {
+ void archiveUriFor() {
ControllerTester tester = new ControllerTester(SystemName.Public);
CuratorArchiveBucketDb bucketDb = new CuratorArchiveBucketDb(tester.controller());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
index 7a209b105b3..5c5abea0276 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
@@ -5,7 +5,7 @@ import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog.Entry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
@@ -15,8 +15,8 @@ import java.time.Instant;
import java.util.function.Supplier;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -27,11 +27,11 @@ public class AuditLoggerTest {
private final Supplier<AuditLog> log = () -> tester.controller().auditLogger().readLog();
@Test
- public void test_logging() {
+ void test_logging() {
{ // GET request is ignored
HttpRequest request = testRequest(Method.GET, URI.create("http://localhost:8080/os/v1/"), "");
tester.controller().auditLogger().log(request);
- assertTrue("Not logged", log.get().entries().isEmpty());
+ assertTrue(log.get().entries().isEmpty(), "Not logged");
}
{ // PATCH request is logged in audit log
@@ -47,7 +47,7 @@ public class AuditLoggerTest {
{ // Another PATCH request is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.PATCH, URI.create("http://localhost:8080/os/v1/"),
- "{\"cloud\":\"cloud9\",\"version\":\"43.0\"}");
+ "{\"cloud\":\"cloud9\",\"version\":\"43.0\"}");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PATCH, 2, "/os/v1/");
}
@@ -55,7 +55,7 @@ public class AuditLoggerTest {
{ // PUT is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.PUT, URI.create("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1/"),
- "");
+ "");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PUT, 3, "/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1/");
}
@@ -63,7 +63,7 @@ public class AuditLoggerTest {
{ // DELETE is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.DELETE, URI.create("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/node1"),
- "");
+ "");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.DELETE, 4, "/zone/v2/prod/us-north-1/nodes/v2/node/node1");
}
@@ -71,7 +71,7 @@ public class AuditLoggerTest {
{ // POST is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.POST, URI.create("http://localhost:8080/controller/v1/jobs/upgrader/confidence/6.42"),
- "6.42");
+ "6.42");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.POST, 5, "/controller/v1/jobs/upgrader/confidence/6.42");
}
@@ -79,7 +79,7 @@ public class AuditLoggerTest {
{ // 15 days pass and another PATCH request is logged. Older entries are removed due to expiry
tester.clock().advance(Duration.ofDays(15));
HttpRequest request = testRequest(Method.PATCH, URI.create("http://localhost:8080/os/v1/"),
- "{\"cloud\":\"cloud9\",\"version\":\"44.0\"}");
+ "{\"cloud\":\"cloud9\",\"version\":\"44.0\"}");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PATCH, 1, "/os/v1/");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
index 1691f902358..9a2d9eddba7 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.integration.SecretStoreMock;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
@@ -39,9 +39,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author andreer
@@ -105,7 +105,7 @@ public class EndpointCertificatesTest {
private final String testCertName = "testCertName";
private ZoneId testZone;
- @Before
+ @BeforeEach
public void setUp() {
tester.zoneRegistry().exclusiveRoutingIn(tester.zoneRegistry().zones().all().zones());
testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.prod).zones().stream().findFirst().orElseThrow().getId();
@@ -115,7 +115,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_dev() {
+ void provisions_new_certificate_in_dev() {
ZoneId testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.dev).zones().stream().findFirst().orElseThrow().getId();
Optional<EndpointCertificateMetadata> endpointCertificateMetadata = endpointCertificates.getMetadata(testInstance, testZone, DeploymentSpec.empty);
assertTrue(endpointCertificateMetadata.isPresent());
@@ -126,7 +126,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_prod() {
+ void provisions_new_certificate_in_prod() {
Optional<EndpointCertificateMetadata> endpointCertificateMetadata = endpointCertificates.getMetadata(testInstance, testZone, DeploymentSpec.empty);
assertTrue(endpointCertificateMetadata.isPresent());
assertTrue(endpointCertificateMetadata.get().keyName().matches("vespa.tls.default.default.*-key"));
@@ -136,7 +136,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_public_prod() {
+ void provisions_new_certificate_in_public_prod() {
ControllerTester tester = new ControllerTester(SystemName.Public);
EndpointCertificateValidatorImpl endpointCertificateValidator = new EndpointCertificateValidatorImpl(secretStore, clock);
EndpointCertificates endpointCertificates = new EndpointCertificates(tester.controller(), endpointCertificateMock, endpointCertificateValidator);
@@ -160,7 +160,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reuses_stored_certificate_metadata() {
+ void reuses_stored_certificate_metadata() {
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, 7, 0, "request_id", Optional.of("leaf-request-uuid"),
List.of("vt2ktgkqme5zlnp4tj4ttyor7fj3v7q5o.vespa.oath.cloud",
"default.default.global.vespa.oath.cloud",
@@ -178,7 +178,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reprovisions_certificate_when_necessary() {
+ void reprovisions_certificate_when_necessary() {
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, -1, 0, "root-request-uuid", Optional.of("leaf-request-uuid"), List.of(), "issuer", Optional.empty(), Optional.empty()));
secretStore.setSecret("vespa.tls.default.default.default-key", KeyUtils.toPem(testKeyPair.getPrivate()), 0);
secretStore.setSecret("vespa.tls.default.default.default-cert", X509CertificateUtils.toPem(testCertificate) + X509CertificateUtils.toPem(testCertificate), 0);
@@ -189,7 +189,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reprovisions_certificate_with_added_sans_when_deploying_to_new_zone() {
+ void reprovisions_certificate_with_added_sans_when_deploying_to_new_zone() {
ZoneId testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.prod).zones().stream().skip(1).findFirst().orElseThrow().getId();
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, -1, 0, "original-request-uuid", Optional.of("leaf-request-uuid"), expectedSans, "mockCa", Optional.empty(), Optional.empty()));
@@ -209,16 +209,19 @@ public class EndpointCertificatesTest {
}
@Test
- public void includes_zones_in_deployment_spec_when_deploying_to_staging() {
+ void includes_zones_in_deployment_spec_when_deploying_to_staging() {
DeploymentSpec deploymentSpec = new DeploymentSpecXmlReader(true).read(
- "<deployment version=\"1.0\">\n" +
- " <instance id=\"default\">\n" +
- " <prod>\n" +
- " <region active=\"true\">aws-us-east-1a</region>\n" +
- " <region active=\"true\">ap-northeast-1</region>\n" +
- " </prod>\n" +
- " </instance>\n" +
- "</deployment>\n");
+ """
+ <deployment version="1.0">
+ <instance id="default">
+ <prod>
+ <region active="true">aws-us-east-1a</region>
+ <region active="true">ap-northeast-1</region>
+ </prod>
+ </instance>
+ </deployment>
+ """
+ );
ZoneId testZone = tester.zoneRegistry().zones().all().in(Environment.staging).zones().stream().findFirst().orElseThrow().getId();
Optional<EndpointCertificateMetadata> endpointCertificateMetadata = endpointCertificates.getMetadata(testInstance, testZone, deploymentSpec);
@@ -230,7 +233,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void includes_application_endpoint_when_declared() {
+ void includes_application_endpoint_when_declared() {
Instance instance = new Instance(ApplicationId.from("t1", "a1", "default"));
ZoneId zone1 = ZoneId.from(Environment.prod, RegionName.from("aws-us-east-1c"));
ZoneId zone2 = ZoneId.from(Environment.prod, RegionName.from("aws-us-west-2a"));
@@ -239,14 +242,14 @@ public class EndpointCertificatesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a", "qrs", zone2.region().value(),
- Map.of(InstanceName.from("beta"), 2,
- InstanceName.from("main"), 8))
+ Map.of(InstanceName.from("beta"), 2,
+ InstanceName.from("main"), 8))
.applicationEndpoint("b", "qrs", zone2.region().value(),
- Map.of(InstanceName.from("beta"), 1,
- InstanceName.from("main"), 1))
+ Map.of(InstanceName.from("beta"), 1,
+ InstanceName.from("main"), 1))
.applicationEndpoint("c", "qrs", zone1.region().value(),
- Map.of(InstanceName.from("beta"), 4,
- InstanceName.from("main"), 6))
+ Map.of(InstanceName.from("beta"), 4,
+ InstanceName.from("main"), 6))
.build();
ControllerTester tester = new ControllerTester(SystemName.Public);
EndpointCertificateValidatorImpl endpointCertificateValidator = new EndpointCertificateValidatorImpl(secretStore, clock);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
index e9426e96a80..c1a8f77f2e9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
@@ -1,21 +1,23 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.concurrent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
*/
public class OnceTest {
- @Test(timeout = 60_000)
- public void test_run() throws Exception {
+ @Test
+ @Timeout(60_000)
+ void test_run() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
Once.after(Duration.ZERO, latch::countDown);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
index ad236fcd4de..934c6b07c29 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
@@ -59,11 +59,11 @@ import java.util.function.Supplier;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A deployment context for an application. This allows fine-grained control of the deployment of an application's
@@ -194,10 +194,10 @@ public class DeploymentContext {
/** Completely deploy the current change */
public DeploymentContext deploy() {
Application application = application();
- assertTrue("Application package submitted", application.revisions().last().isPresent());
- assertFalse("Submission is not already deployed", application.instances().values().stream()
+ assertTrue(application.revisions().last().isPresent(), "Application package submitted");
+ assertFalse(application.instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
- .anyMatch(deployment -> deployment.revision().equals(lastSubmission))));
+ .anyMatch(deployment -> deployment.revision().equals(lastSubmission))), "Submission is not already deployed");
completeRollout(application.deploymentSpec().instances().size() > 1);
for (var instance : application().instances().values()) {
assertFalse(instance.change().hasTargets());
@@ -249,8 +249,8 @@ public class DeploymentContext {
/** Flush all pending DNS updates */
public DeploymentContext flushDnsUpdates() {
flushDnsUpdates(Integer.MAX_VALUE);
- assertTrue("All name service requests dispatched",
- tester.controller().curator().readNameServiceQueue().requests().isEmpty());
+ assertTrue(tester.controller().curator().readNameServiceQueue().requests().isEmpty(),
+ "All name service requests dispatched");
return this;
}
@@ -362,12 +362,12 @@ public class DeploymentContext {
.filter(kv -> kv.getValue() == failed)
.map(Entry::getKey)
.findFirst();
- assertTrue("Found failing step", firstFailing.isPresent());
+ assertTrue(firstFailing.isPresent(), "Found failing step");
Optional<RunLog> details = jobs.details(id);
- assertTrue("Found log entries for run " + id, details.isPresent());
- assertTrue("Found log message containing '" + messagePart.get() + "'",
- details.get().get(firstFailing.get()).stream()
- .anyMatch(entry -> entry.message().contains(messagePart.get())));
+ assertTrue(details.isPresent(), "Found log entries for run " + id);
+ assertTrue(details.get().get(firstFailing.get()).stream()
+ .anyMatch(entry -> entry.message().contains(messagePart.get())),
+ "Found log message containing '" + messagePart.get() + "'");
}
return this;
}
@@ -400,7 +400,7 @@ public class DeploymentContext {
triggerJobs();
}
- assertFalse("Change should have no targets, but was " + instance().change(), instance().change().hasTargets());
+ assertFalse(instance().change().hasTargets(), "Change should have no targets, but was " + instance().change());
return this;
}
@@ -545,13 +545,13 @@ public class DeploymentContext {
}
public void assertRunning(JobType type) {
- assertTrue(jobId(type) + " should be among the active: " + jobs.active(),
- jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)));
+ assertTrue(jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)),
+ jobId(type) + " should be among the active: " + jobs.active());
}
public void assertNotRunning(JobType type) {
- assertFalse(jobId(type) + " should not be among the active: " + jobs.active(),
- jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)));
+ assertFalse(jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)),
+ jobId(type) + " should not be among the active: " + jobs.active());
}
/** Deploys tester and real app, and completes tester and initial staging installation first if needed. */
@@ -604,8 +604,8 @@ public class DeploymentContext {
Run run = jobs.last(job)
.filter(r -> r.id().type().equals(job.type()))
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
- assertFalse(run.id() + " should not have failed yet: " + run, run.hasFailed());
- assertFalse(run.id() + " should not have ended yet: " + run, run.hasEnded());
+ assertFalse(run.hasFailed(), run.id() + " should not have failed yet: " + run);
+ assertFalse(run.hasEnded(), run.id() + " should not have ended yet: " + run);
return run;
}
@@ -622,7 +622,7 @@ public class DeploymentContext {
assertTrue(jobs.run(id).hasEnded());
return;
}
- assertEquals("Status of " + id, succeeded, jobs.run(id).stepStatuses().get(Step.installReal));
+ assertEquals(succeeded, jobs.run(id).stepStatuses().get(Step.installReal), "Status of " + id);
}
/** Installs tester and starts tests. */
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
index 2b4a2baa17e..c9553ef5bf1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
@@ -27,7 +27,7 @@ import java.time.temporal.TemporalAdjusters;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
index e5000a85f71..62fafa12993 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
@@ -24,8 +24,7 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -61,10 +60,11 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.tes
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.ALL;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PLATFORM;
import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests a wide variety of deployment scenarios and configurations
@@ -78,7 +78,7 @@ public class DeploymentTriggerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testTriggerFailing() {
+ void testTriggerFailing() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.region("us-west-1")
@@ -95,7 +95,7 @@ public class DeploymentTriggerTest {
// staging-test fails deployment and is retried
app.failDeployment(stagingTest);
tester.triggerJobs();
- assertEquals("Retried dead job", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Retried dead job");
app.assertRunning(stagingTest);
app.runJob(stagingTest);
@@ -106,7 +106,7 @@ public class DeploymentTriggerTest {
// system-test fails and is retried
app.timeOutUpgrade(systemTest);
tester.triggerJobs();
- assertEquals("Job is retried on failure", 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), "Job is retried on failure");
app.runJob(systemTest);
tester.triggerJobs();
@@ -117,11 +117,11 @@ public class DeploymentTriggerTest {
tester.applications().store(locked.withProjectId(OptionalLong.empty())));
app.timeOutConvergence(productionUsWest1);
tester.triggerJobs();
- assertEquals("Job is not triggered when no projectId is present", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Job is not triggered when no projectId is present");
}
@Test
- public void revisionChangeWhenFailingMakesApplicationChangeWaitForPreviousToComplete() {
+ void revisionChangeWhenFailingMakesApplicationChangeWaitForPreviousToComplete() {
DeploymentContext app = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.revisionChange(null) // separate by default, but we override this in test builder
@@ -155,10 +155,10 @@ public class DeploymentTriggerTest {
}
@Test
- public void leadingUpgradeAllowsApplicationChangeWhileUpgrading() {
+ void leadingUpgradeAllowsApplicationChangeWhileUpgrading() {
var applicationPackage = new ApplicationPackageBuilder().region("us-east-3")
- .upgradeRollout("leading")
- .build();
+ .upgradeRollout("leading")
+ .build();
var app = tester.newDeploymentContext();
app.submit(applicationPackage).deploy();
@@ -176,11 +176,11 @@ public class DeploymentTriggerTest {
}
@Test
- public void abortsJobsOnNewApplicationChange() {
+ void abortsJobsOnNewApplicationChange() {
var app = tester.newDeploymentContext();
app.submit()
- .runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(systemTest)
+ .runJob(stagingTest);
tester.triggerJobs();
RunId id = tester.jobs().last(app.instanceId(), productionUsCentral1).get().id();
@@ -220,12 +220,12 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
tester.runner().run();
assertEquals(Set.of(productionUsCentral1), tester.jobs().active().stream()
- .map(run -> run.id().type())
- .collect(Collectors.toCollection(HashSet::new)));
+ .map(run -> run.id().type())
+ .collect(Collectors.toCollection(HashSet::new)));
}
@Test
- public void similarDeploymentSpecsAreNotRolledOut() {
+ void similarDeploymentSpecsAreNotRolledOut() {
ApplicationPackage firstPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.build();
@@ -234,8 +234,8 @@ public class DeploymentTriggerTest {
var version = app.lastSubmission();
assertEquals(version, app.instance().change().revision());
app.runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(stagingTest)
+ .runJob(productionUsEast3);
assertEquals(Change.empty(), app.instance().change());
// A similar application package is submitted. Since a new job is added, the original revision is again a target.
@@ -265,13 +265,13 @@ public class DeploymentTriggerTest {
}
@Test
- public void testOutstandingChangeWithNextRevisionTarget() {
+ void testOutstandingChangeWithNextRevisionTarget() {
ApplicationPackage appPackage = new ApplicationPackageBuilder().revisionTarget("next")
- .revisionChange("when-failing")
- .region("us-east-3")
- .build();
+ .revisionChange("when-failing")
+ .region("us-east-3")
+ .build();
DeploymentContext app = tester.newDeploymentContext()
- .submit(appPackage);
+ .submit(appPackage);
Optional<RevisionId> revision1 = app.lastSubmission();
app.submit(appPackage);
@@ -299,7 +299,7 @@ public class DeploymentTriggerTest {
// The second revision deploys completely, and the third starts rolling out.
app.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(productionUsEast3);
tester.outstandingChangeDeployer().run();
tester.outstandingChangeDeployer().run();
assertEquals(revision3, app.instance().change().revision());
@@ -314,8 +314,8 @@ public class DeploymentTriggerTest {
// Tests for outstanding change are relevant when current revision completes.
app.runJob(systemTest).runJob(systemTest)
- .jobAborted(stagingTest).runJob(stagingTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .jobAborted(stagingTest).runJob(stagingTest).runJob(stagingTest)
+ .runJob(productionUsEast3);
tester.outstandingChangeDeployer().run();
tester.outstandingChangeDeployer().run();
assertEquals(revision5, app.instance().change().revision());
@@ -324,7 +324,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void deploymentSpecWithDelays() {
+ void deploymentSpecWithDelays() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.systemTest()
.delay(Duration.ofSeconds(30))
@@ -362,27 +362,27 @@ public class DeploymentTriggerTest {
// Delayed trigger does nothing as not enough time has passed after us-west-1 completion
tester.triggerJobs();
- assertTrue("No more jobs triggered at this time", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No more jobs triggered at this time");
// 3 minutes pass, us-central-1 is still not triggered
tester.clock().advance(Duration.ofMinutes(3));
tester.triggerJobs();
- assertTrue("No more jobs triggered at this time", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No more jobs triggered at this time");
// 4 minutes pass, us-central-1 is triggered
tester.clock().advance(Duration.ofMinutes(1));
tester.triggerJobs();
app.runJob(productionUsCentral1);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
// Delayed trigger job runs again, with nothing to trigger
tester.clock().advance(Duration.ofMinutes(10));
tester.triggerJobs();
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void deploymentSpecWithParallelDeployments() {
+ void deploymentSpecWithParallelDeployments() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
@@ -415,11 +415,11 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionEuWest1);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testNoOtherChangesDuringSuspension() {
+ void testNoOtherChangesDuringSuspension() {
// Application is deployed in 3 regions:
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
@@ -432,9 +432,9 @@ public class DeploymentTriggerTest {
// A new change needs to be pushed out, but should not go beyond the suspended zone:
application.submit()
- .runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsCentral1);
+ .runJob(systemTest)
+ .runJob(stagingTest)
+ .runJob(productionUsCentral1);
tester.triggerJobs();
application.assertNotRunning(productionUsEast3);
application.assertNotRunning(productionUsWest1);
@@ -447,7 +447,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testBlockRevisionChange() {
+ void testBlockRevisionChange() {
// Tuesday, 17:30
tester.at(Instant.parse("2017-09-26T17:30:00.00Z"));
@@ -490,7 +490,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testCompletionOfPartOfChangeDuringBlockWindow() {
+ void testCompletionOfPartOfChangeDuringBlockWindow() {
// Tuesday, 17:30
tester.at(Instant.parse("2017-09-26T17:30:00.00Z"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -538,7 +538,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testJobPause() {
+ void testJobPause() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
.region("us-east-3")
@@ -548,9 +548,9 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
tester.deploymentTrigger().pauseJob(app.instanceId(), productionUsWest1,
- tester.clock().instant().plus(Duration.ofSeconds(1)));
+ tester.clock().instant().plus(Duration.ofSeconds(1)));
tester.deploymentTrigger().pauseJob(app.instanceId(), productionUsEast3,
- tester.clock().instant().plus(Duration.ofSeconds(3)));
+ tester.clock().instant().plus(Duration.ofSeconds(3)));
// us-west-1 does not trigger when paused.
app.runJob(systemTest).runJob(stagingTest);
@@ -577,11 +577,11 @@ public class DeploymentTriggerTest {
app.assertRunning(productionUsEast3);
assertFalse(app.instance().jobPause(productionUsEast3).isPresent());
assertEquals(app.deployment(productionUsEast3.zone()).version(),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
}
@Test
- public void applicationVersionIsNotDowngraded() {
+ void applicationVersionIsNotDowngraded() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.region("eu-west-1")
@@ -590,9 +590,9 @@ public class DeploymentTriggerTest {
// productionUsCentral1 fails after deployment, causing a mismatch between deployed and successful state.
app.submit(applicationPackage)
- .runJob(systemTest)
- .runJob(stagingTest)
- .timeOutUpgrade(productionUsCentral1);
+ .runJob(systemTest)
+ .runJob(stagingTest)
+ .timeOutUpgrade(productionUsCentral1);
RevisionId appVersion1 = app.lastSubmission().get();
assertEquals(appVersion1, app.deployment(ZoneId.from("prod.us-central-1")).revision());
@@ -628,7 +628,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void downgradingApplicationVersionWorks() {
+ void downgradingApplicationVersionWorks() {
var app = tester.newDeploymentContext().submit().deploy();
RevisionId appVersion0 = app.lastSubmission().get();
assertEquals(appVersion0, latestDeployed(app.instance()));
@@ -641,16 +641,16 @@ public class DeploymentTriggerTest {
tester.deploymentTrigger().forceChange(app.instanceId(), Change.of(appVersion0));
assertEquals(Change.of(appVersion0), app.instance().change());
app.runJob(stagingTest)
- .runJob(productionUsCentral1)
- .runJob(productionUsEast3)
- .runJob(productionUsWest1);
+ .runJob(productionUsCentral1)
+ .runJob(productionUsEast3)
+ .runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
assertEquals(appVersion0, app.instance().deployments().get(productionUsEast3.zone()).revision());
assertEquals(appVersion0, latestDeployed(app.instance()));
}
@Test
- public void settingANoOpChangeIsANoOp() {
+ void settingANoOpChangeIsANoOp() {
var app = tester.newDeploymentContext().submit();
app.deploy();
@@ -669,7 +669,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void stepIsCompletePreciselyWhenItShouldBe() {
+ void stepIsCompletePreciselyWhenItShouldBe() {
var app1 = tester.newDeploymentContext("tenant1", "app1", "default");
var app2 = tester.newDeploymentContext("tenant1", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -706,11 +706,11 @@ public class DeploymentTriggerTest {
tester.upgrader().overrideConfidence(version2, VespaVersion.Confidence.broken);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain(); // Cancel upgrades to broken version
- assertEquals("Change becomes latest non-broken version", Change.of(version1), app1.instance().change());
+ assertEquals(Change.of(version1), app1.instance().change(), "Change becomes latest non-broken version");
// version1 proceeds 'til the last job, where it fails; us-central-1 is skipped, as current change is strictly dominated by what's deployed there.
app1.runJob(systemTest).runJob(stagingTest)
- .failDeployment(productionEuWest1);
+ .failDeployment(productionEuWest1);
assertEquals(triggered, app1.instanceJobs().get(productionUsCentral1).lastTriggered().get().start());
// Roll out a new application version, which gives a dual change -- this should trigger us-central-1, but only as long as it hasn't yet deployed there.
@@ -718,9 +718,9 @@ public class DeploymentTriggerTest {
app1.submit(applicationPackage);
RevisionId revision2 = app1.lastSubmission().get();
app1.runJob(systemTest) // Tests for new revision on version2
- .runJob(stagingTest)
- .runJob(systemTest) // Tests for new revision on version1
- .runJob(stagingTest);
+ .runJob(stagingTest)
+ .runJob(systemTest) // Tests for new revision on version1
+ .runJob(stagingTest);
assertEquals(Change.of(version1).with(revision2), app1.instance().change());
tester.triggerJobs();
app1.assertRunning(productionUsCentral1);
@@ -741,14 +741,14 @@ public class DeploymentTriggerTest {
// Last job has a different deployment target, so tests need to run again.
app1.runJob(productionEuWest1) // Upgrade completes, and revision is the only change.
- .runJob(productionUsCentral1) // With only revision change, central should run to cover a previous failure.
- .runJob(productionEuWest1); // Finally, west changes revision.
+ .runJob(productionUsCentral1) // With only revision change, central should run to cover a previous failure.
+ .runJob(productionEuWest1); // Finally, west changes revision.
assertEquals(Change.empty(), app1.instance().change());
assertEquals(Optional.of(RunStatus.success), app1.instanceJobs().get(productionUsCentral1).lastStatus());
}
@Test
- public void eachParallelDeployTargetIsTested() {
+ void eachParallelDeployTargetIsTested() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.parallel("eu-west-1", "us-east-3")
.build();
@@ -788,14 +788,14 @@ public class DeploymentTriggerTest {
// Both jobs fail again, and must be re-triggered -- this is ok, as they are both already triggered on their current targets.
app.failDeployment(productionEuWest1).failDeployment(productionUsEast3)
- .runJob(productionEuWest1).runJob(productionUsEast3);
+ .runJob(productionEuWest1).runJob(productionUsEast3);
assertFalse(app.instance().change().hasTargets());
assertEquals(2, app.instanceJobs().get(productionEuWest1).lastSuccess().get().versions().targetRevision().number());
assertEquals(2, app.instanceJobs().get(productionUsEast3).lastSuccess().get().versions().targetRevision().number());
}
@Test
- public void retriesFailingJobs() {
+ void retriesFailingJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.build();
@@ -840,11 +840,11 @@ public class DeploymentTriggerTest {
// Another application change is deployed and fixes system-test. Change is triggered immediately as target changes
app.submit(applicationPackage).deploy();
- assertTrue("Deployment completed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "Deployment completed");
}
@Test
- public void testPlatformVersionSelection() {
+ void testPlatformVersionSelection() {
// Setup system
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -855,7 +855,7 @@ public class DeploymentTriggerTest {
// First deployment: An application change
app1.submit(applicationPackage).deploy();
- assertEquals("First deployment gets system version", version1, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version1, app1.application().oldestDeployedPlatform().get(), "First deployment gets system version");
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
// Application change after a new system version, and a region added
@@ -867,20 +867,19 @@ public class DeploymentTriggerTest {
.region("us-east-3")
.build();
app1.submit(applicationPackage).deploy();
- assertEquals("Application change preserves version, and new region gets oldest version too",
- version1, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version1, app1.application().oldestDeployedPlatform().get(), "Application change preserves version, and new region gets oldest version too");
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
- assertFalse("Change deployed", app1.instance().change().hasTargets());
+ assertFalse(app1.instance().change().hasTargets(), "Change deployed");
tester.upgrader().maintain();
app1.deployPlatform(version2);
- assertEquals("Version upgrade changes version", version2, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version2, app1.application().oldestDeployedPlatform().get(), "Version upgrade changes version");
assertEquals(version2, tester.configServer().lastPrepareVersion().get());
}
@Test
- public void requeueNodeAllocationFailureStagingJob() {
+ void requeueNodeAllocationFailureStagingJob() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.build();
@@ -979,14 +978,14 @@ public class DeploymentTriggerTest {
}
@Test
- public void testUserInstancesNotInDeploymentSpec() {
+ void testUserInstancesNotInDeploymentSpec() {
var app = tester.newDeploymentContext();
tester.controller().applications().createInstance(app.application().id().instance("user"));
app.submit().deploy();
}
@Test
- public void testMultipleInstancesWithDifferentChanges() {
+ void testMultipleInstancesWithDifferentChanges() {
DeploymentContext i1 = tester.newDeploymentContext("t", "a", "i1");
DeploymentContext i2 = tester.newDeploymentContext("t", "a", "i2");
DeploymentContext i3 = tester.newDeploymentContext("t", "a", "i3");
@@ -1097,7 +1096,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testMultipleInstancesWithRevisionCatchingUpToUpgrade() {
+ void testMultipleInstancesWithRevisionCatchingUpToUpgrade() {
String spec = """
<deployment>
<instance id='alpha'>
@@ -1160,28 +1159,28 @@ public class DeploymentTriggerTest {
beta.assertNotRunning(testUsEast3);
beta.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
assertEquals(Change.empty(), beta.instance().change());
}
@Test
- public void testMultipleInstances() {
+ void testMultipleInstances() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .completeRollout();
+ .submit(applicationPackage)
+ .completeRollout();
assertEquals(2, app.application().instances().size());
assertEquals(2, app.application().productionDeployments().values().stream()
- .mapToInt(Collection::size)
- .sum());
+ .mapToInt(Collection::size)
+ .sum());
}
@Test
- public void testDeclaredProductionTests() {
+ void testDeclaredProductionTests() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.delay(Duration.ofMinutes(1))
@@ -1198,8 +1197,8 @@ public class DeploymentTriggerTest {
tester.clock().advance(Duration.ofMinutes(1));
app.runJob(testUsEast3)
- .runJob(productionUsWest1).runJob(productionUsCentral1)
- .runJob(testUsCentral1).runJob(testUsWest1);
+ .runJob(productionUsWest1).runJob(productionUsCentral1)
+ .runJob(testUsCentral1).runJob(testUsWest1);
assertEquals(Change.empty(), app.instance().change());
// Application starts upgrade, but is confidence is broken cancelled after first zone. Tests won't run.
@@ -1249,7 +1248,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testDeployComplicatedDeploymentSpec() {
+ void testDeployComplicatedDeploymentSpec() {
String complicatedDeploymentSpec =
"""
<deployment version='1.0' athenz-domain='domain' athenz-service='service'>
@@ -1399,14 +1398,14 @@ public class DeploymentTriggerTest {
// Upgrade platform.
app2.runJob(systemTest);
app1.runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsEast3);
+ .runJob(productionUsWest1)
+ .runJob(productionUsEast3);
// Upgrade revision
tester.clock().advance(Duration.ofSeconds(1)); // Ensure we see revision as rolling after upgrade.
app2.runJob(systemTest); // R
app1.runJob(stagingTest) // R
- .runJob(productionUsWest1); // R
- // productionUsEast3 won't change revision before its production test has completed for the upgrade, which is one of the last jobs!
+ .runJob(productionUsWest1); // R
+ // productionUsEast3 won't change revision before its production test has completed for the upgrade, which is one of the last jobs!
tester.clock().advance(Duration.ofHours(2));
app1.runJob(productionEuWest1);
tester.clock().advance(Duration.ofHours(1));
@@ -1442,13 +1441,13 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
tester.outstandingChangeDeployer().run();
tester.triggerJobs();
- assertEquals(tester.jobs().active().toString(), 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), tester.jobs().active().toString());
assertEquals(Change.empty(), app1.instance().change());
assertEquals(Change.of(version), app2.instance().change());
assertEquals(Change.empty(), app3.instance().change());
app2.runJob(productionEuWest1)
- .failDeployment(testEuWest1);
+ .failDeployment(testEuWest1);
// Instance 2 failed the last job, and now exits block window, letting application change roll out with the upgrade.
tester.clock().advance(Duration.ofDays(1)); // Leave block window for revisions.
@@ -1461,7 +1460,7 @@ public class DeploymentTriggerTest {
assertEquals(Change.of(version).with(app1.application().revisions().last().get().id()), app2.instance().change());
app2.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
assertEquals(Change.empty(), app2.instance().change());
assertEquals(Change.empty(), app3.instance().change());
@@ -1485,12 +1484,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRevisionJoinsUpgradeWithSeparateRollout() {
+ void testRevisionJoinsUpgradeWithSeparateRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("separate")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("separate")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1511,20 +1510,20 @@ public class DeploymentTriggerTest {
// Upgrade got here first, so attempts to proceed alone, but the upgrade fails.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.timeOutConvergence(productionUsEast3);
// Revision is allowed to join.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.runJob(productionUsEast3);
// Platform and revision now proceed together.
app.runJob(stagingTest);
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
@@ -1538,23 +1537,23 @@ public class DeploymentTriggerTest {
app.submit(appPackage);
app.runJob(systemTest).runJob(stagingTest) // Tests run with combined upgrade.
- .runJob(productionUsCentral1) // Combined upgrade stays together.
- .runJob(productionUsEast3).runJob(productionUsWest1);
+ .runJob(productionUsCentral1) // Combined upgrade stays together.
+ .runJob(productionUsEast3).runJob(productionUsWest1);
assertEquals(Map.of(), app.deploymentStatus().jobsToRun());
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void testProductionTestBlockingDeploymentWithSeparateRollout() {
+ void testProductionTestBlockingDeploymentWithSeparateRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("us-west-1")
- .delay(Duration.ofHours(1))
- .test("us-east-3")
- .upgradeRollout("separate")
- .build();
+ .region("us-west-1")
+ .delay(Duration.ofHours(1))
+ .test("us-east-3")
+ .upgradeRollout("separate")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage)
- .runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(productionUsWest1);
+ .runJob(systemTest).runJob(stagingTest)
+ .runJob(productionUsEast3).runJob(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
app.runJob(testUsEast3);
assertEquals(Change.empty(), app.instance().change());
@@ -1578,13 +1577,13 @@ public class DeploymentTriggerTest {
// Upgrade got here first, so attempts to proceed alone, but the upgrade fails.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.timeOutConvergence(productionUsWest1).triggerJobs();
// Upgrade now fails between us-east-3 deployment and test, so test is abandoned, and revision unblocked.
app.assertRunning(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.runJob(productionUsEast3).triggerJobs()
.jobAborted(productionUsWest1).runJob(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
@@ -1593,15 +1592,15 @@ public class DeploymentTriggerTest {
}
@Test
- public void testProductionTestNotBlockingDeploymentWithSimultaneousRollout() {
+ void testProductionTestNotBlockingDeploymentWithSimultaneousRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("us-central-1")
- .region("us-west-1")
- .delay(Duration.ofHours(1))
- .test("us-east-3")
- .test("us-west-1")
- .upgradeRollout("simultaneous")
- .build();
+ .region("us-central-1")
+ .region("us-west-1")
+ .delay(Duration.ofHours(1))
+ .test("us-east-3")
+ .test("us-west-1")
+ .upgradeRollout("simultaneous")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage)
.runJob(systemTest).runJob(stagingTest)
.runJob(productionUsEast3).runJob(productionUsCentral1).runJob(productionUsWest1);
@@ -1628,7 +1627,7 @@ public class DeploymentTriggerTest {
// Revision deploys to first prod zone.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
tester.clock().advance(Duration.ofSeconds(1));
app.runJob(productionUsEast3);
@@ -1636,12 +1635,12 @@ public class DeploymentTriggerTest {
app.runJob(systemTest).runJob(stagingTest).runJob(stagingTest).triggerJobs();
app.jobAborted(productionUsCentral1).triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsCentral1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsCentral1).get().versions());
app.runJob(productionUsCentral1).triggerJobs();
// Revision proceeds alone in third prod zone, making test targets different for the two prod tests.
assertEquals(new Versions(version0, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
app.triggerJobs();
app.assertNotRunning(testUsEast3);
@@ -1655,7 +1654,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testVeryLengthyPipelineRevisions() {
+ void testVeryLengthyPipelineRevisions() {
String lengthyDeploymentSpec =
"""
<deployment version='1.0'>
@@ -1696,7 +1695,7 @@ public class DeploymentTriggerTest {
var revision2 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
assertEquals(Optional.empty(), alpha.instance().change().revision());
// revision3 is submitted when revision2 is half-way.
@@ -1715,7 +1714,7 @@ public class DeploymentTriggerTest {
// revision3 rolls to beta, then a couple of new revisions are submitted to alpha, and the latter is the new target.
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(revision3, beta.instance().change().revision());
@@ -1724,11 +1723,11 @@ public class DeploymentTriggerTest {
alpha.submit(appPackage, 3);
var revision4 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(productionUsEast3);
alpha.submit(appPackage, 2);
var revision5 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(revision3, beta.instance().change().revision());
@@ -1737,8 +1736,8 @@ public class DeploymentTriggerTest {
alpha.submit(appPackage, 6);
var revision6 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(productionUsEast3)
+ .runJob(testUsEast3);
beta.runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
@@ -1751,7 +1750,7 @@ public class DeploymentTriggerTest {
// revision 2 completes in gamma
gamma.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(Optional.empty(), gamma.instance().change().revision()); // no other revisions after 3 are ready, so gamma waits
@@ -1769,7 +1768,7 @@ public class DeploymentTriggerTest {
// revision 6 is next, once 3 is done
// revision 3 completes
gamma.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(revision6, gamma.instance().change().revision());
@@ -1800,7 +1799,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testVeryLengthyPipelineUpgrade() {
+ void testVeryLengthyPipelineUpgrade() {
String lengthyDeploymentSpec =
"""
<deployment version='1.0'>
@@ -1843,7 +1842,7 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
assertEquals(Change.empty(), alpha.instance().change());
tester.upgrader().maintain();
@@ -1859,12 +1858,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRevisionJoinsUpgradeWithLeadingRollout() {
+ void testRevisionJoinsUpgradeWithLeadingRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("leading")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("leading")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1885,7 +1884,7 @@ public class DeploymentTriggerTest {
// Upgrade got here first, and has triggered, but is now obsolete.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), productionUsEast3).get().status());
// Once staging tests verify the joint upgrade, the job is replaced with that.
@@ -1893,23 +1892,23 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.jobAborted(productionUsEast3).runJob(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
// Platform and revision now proceed together.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void testRevisionPassesUpgradeWithSimultaneousRollout() {
+ void testRevisionPassesUpgradeWithSimultaneousRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("simultaneous")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("simultaneous")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1931,7 +1930,7 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.assertRunning(productionUsEast3);
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), productionUsEast3).get().status());
// Once staging tests verify the joint upgrade, the job is replaced with that.
@@ -1939,27 +1938,27 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.jobAborted(productionUsEast3).runJob(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
// Revision now proceeds alone.
app.triggerJobs();
assertEquals(new Versions(version0, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
// Upgrade follows.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision1),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void mixedDirectAndPipelineJobsInProduction() {
+ void mixedDirectAndPipelineJobsInProduction() {
ApplicationPackage cdPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("aws-us-east-1a")
- .build();
+ .region("aws-us-east-1a")
+ .build();
ControllerTester wrapped = new ControllerTester(cd);
wrapped.upgradeSystem(Version.fromString("6.1"));
wrapped.computeVersionStatus();
@@ -1973,9 +1972,9 @@ public class DeploymentTriggerTest {
// Staging test requires unknown initial version, and is broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .abortJob(stagingTest) // Complete failing run.
- .runJob(stagingTest) // Run staging-test for production zone with no prior deployment.
- .runJob(productionAwsUsEast1a);
+ .abortJob(stagingTest) // Complete failing run.
+ .runJob(stagingTest) // Run staging-test for production zone with no prior deployment.
+ .runJob(productionAwsUsEast1a);
// Manually deploy to east again, then upgrade the system.
app.runJob(productionUsEast3, cdPackage);
@@ -1985,12 +1984,12 @@ public class DeploymentTriggerTest {
// System and staging tests both require unknown versions, and are broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .triggerJobs()
- .jobAborted(systemTest)
- .jobAborted(stagingTest)
- .runJob(systemTest) // Run test for aws zone again.
- .runJob(stagingTest) // Run test for aws zone again.
- .runJob(productionAwsUsEast1a);
+ .triggerJobs()
+ .jobAborted(systemTest)
+ .jobAborted(stagingTest)
+ .runJob(systemTest) // Run test for aws zone again.
+ .runJob(stagingTest) // Run test for aws zone again.
+ .runJob(productionAwsUsEast1a);
// Deploy manually again, then submit new package.
app.runJob(productionUsEast3, cdPackage);
@@ -1999,13 +1998,13 @@ public class DeploymentTriggerTest {
// Staging test requires unknown initial version, and is broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .jobAborted(stagingTest)
- .runJob(stagingTest)
- .runJob(productionAwsUsEast1a);
+ .jobAborted(stagingTest)
+ .runJob(stagingTest)
+ .runJob(productionAwsUsEast1a);
}
@Test
- public void testsInSeparateInstance() {
+ void testsInSeparateInstance() {
String deploymentSpec =
"""
<deployment version='1.0' athenz-domain='domain' athenz-service='service'>
@@ -2028,30 +2027,30 @@ public class DeploymentTriggerTest {
var conservative = tester.newDeploymentContext("t", "a", "default");
canary.runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(stagingTest);
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
canary.submit(applicationPackage)
- .runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(systemTest)
+ .runJob(stagingTest);
tester.outstandingChangeDeployer().run();
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
tester.controllerTester().upgradeSystem(new Version("7.7.7"));
tester.upgrader().maintain();
canary.runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(stagingTest);
tester.upgrader().maintain();
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
}
@Test
- public void testEagerTests() {
+ void testEagerTests() {
var app = tester.newDeploymentContext().submit().deploy();
// Start upgrade, then receive new submission.
@@ -2068,24 +2067,24 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
app.assertRunning(stagingTest);
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetPlatform());
+ app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetPlatform());
assertEquals(build1,
- app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetRevision());
+ app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetRevision());
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourcePlatform().get());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourcePlatform().get());
assertEquals(build1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourceRevision().get());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourceRevision().get());
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetPlatform());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetPlatform());
assertEquals(build2,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetRevision());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetRevision());
// App completes upgrade, and outstanding change is triggered. This should let relevant, running jobs finish.
app.runJob(systemTest)
- .runJob(productionUsCentral1)
- .runJob(productionUsEast3)
- .runJob(productionUsWest1);
+ .runJob(productionUsCentral1)
+ .runJob(productionUsEast3)
+ .runJob(productionUsWest1);
tester.outstandingChangeDeployer().run();
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), stagingTest).get().status());
@@ -2095,12 +2094,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testTriggeringOfIdleTestJobsWhenFirstDeploymentIsOnNewerVersionThanChange() {
+ void testTriggeringOfIdleTestJobsWhenFirstDeploymentIsOnNewerVersionThanChange() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().systemTest()
- .stagingTest()
- .region("us-east-3")
- .region("us-west-1")
- .build();
+ .stagingTest()
+ .region("us-east-3")
+ .region("us-west-1")
+ .build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
var appToAvoidVersionGC = tester.newDeploymentContext("g", "c", "default").submit().deploy();
@@ -2121,9 +2120,9 @@ public class DeploymentTriggerTest {
assertEquals(Optional.of(version2), app.instance().change().platform());
app.runJob(systemTest)
- .runJob(productionUsEast3)
- .runJob(stagingTest)
- .runJob(productionUsWest1);
+ .runJob(productionUsEast3)
+ .runJob(stagingTest)
+ .runJob(productionUsWest1);
assertEquals(version3, app.instanceJobs().get(productionUsEast3).lastSuccess().get().versions().targetPlatform());
assertEquals(version2, app.instanceJobs().get(productionUsWest1).lastSuccess().get().versions().targetPlatform());
@@ -2133,7 +2132,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRetriggerQueue() {
+ void testRetriggerQueue() {
var app = tester.newDeploymentContext().submit().deploy();
app.submit();
tester.triggerJobs();
@@ -2143,44 +2142,59 @@ public class DeploymentTriggerTest {
tester.deploymentTrigger().reTriggerOrAddToQueue(app.deploymentIdIn(ZoneId.from("prod", "us-east-3")), null);
List<RetriggerEntry> retriggerEntries = tester.controller().curator().readRetriggerEntries();
- Assert.assertEquals(1, retriggerEntries.size());
+ assertEquals(1, retriggerEntries.size());
}
@Test
- public void testOrchestrationWithIncompatibleVersionPairs() {
+ void testOrchestrationWithIncompatibleVersionPairs() {
Version version1 = new Version("7");
Version version2 = new Version("8");
tester.controllerTester().flagSource().withListFlag(PermanentFlags.INCOMPATIBLE_VERSIONS.id(), List.of("8"), String.class);
+ // App deploys on version1.
tester.controllerTester().upgradeSystem(version1);
DeploymentContext app = tester.newDeploymentContext()
- .submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version1)
- .build())
- .deploy();
+ .submit(new ApplicationPackageBuilder().region("us-east-3")
+ .compileVersion(version1)
+ .build())
+ .deploy();
+ // System upgrades to version2, but the app is not upgraded.
tester.controllerTester().upgradeSystem(version2);
tester.upgrader().run();
assertEquals(Change.empty(), app.instance().change());
+ // App compiles against version2, and upgrades.
app.submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version2)
- .build());
+ .compileVersion(version2)
+ .build());
app.deploy();
assertEquals(version2, tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
assertEquals(version2, app.application().revisions().get(tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetRevision()).compileVersion().get());
+
+ // App specifies version1 in deployment spec, compiles against version1, pins to version1, and then downgrades.
+ app.submit(new ApplicationPackageBuilder().region("us-east-3")
+ .majorVersion(7)
+ .compileVersion(version1)
+ .build());
+ tester.deploymentTrigger().forceChange(app.instanceId(), app.instance().change().withPin());
+ app.deploy();
+ assertEquals(version1, tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
+ assertEquals(version1, app.application().revisions().get(tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetRevision()).compileVersion().get());
+
+ // A new app, compiled against version1, is deployed on version1.
DeploymentContext newApp = tester.newDeploymentContext("new", "app", "default")
- .submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version1)
- .build())
- .deploy();
+ .submit(new ApplicationPackageBuilder().region("us-east-3")
+ .compileVersion(version1)
+ .build())
+ .deploy();
assertEquals(version1, tester.jobs().last(newApp.instanceId(), productionUsEast3).get().versions().targetPlatform());
assertEquals(version1, newApp.application().revisions().get(tester.jobs().last(newApp.instanceId(), productionUsEast3).get().versions().targetRevision()).compileVersion().get());
}
@Test
- public void testInstanceWithOnlySystemTestInTwoClouds() {
+ void testInstanceWithOnlySystemTestInTwoClouds() {
String spec = """
<deployment>
<instance id='tests'>
@@ -2256,7 +2270,7 @@ public class DeploymentTriggerTest {
Version version3 = new Version("9");
tester.controllerTester().upgradeSystem(version3);
tests.runJob(systemTest) // Success in default cloud.
- .failDeployment(systemTest); // Failure in centauri cloud.
+ .failDeployment(systemTest); // Failure in centauri cloud.
tester.upgrader().run();
assertEquals(Change.of(version3), tests.instance().change());
@@ -2353,7 +2367,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testNoTests() {
+ void testNoTests() {
DeploymentContext app = tester.newDeploymentContext();
app.submit(new ApplicationPackageBuilder().systemTest().region("us-east-3").build());
@@ -2365,7 +2379,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testJobNames() {
+ void testJobNames() {
ZoneRegistryMock zones = new ZoneRegistryMock(SystemName.main);
List<ZoneApi> existing = new ArrayList<>(zones.zones().all().zones());
existing.add(ZoneApiMock.newBuilder().withCloud("pink-clouds").withId("test.zone").build());
@@ -2382,10 +2396,14 @@ public class DeploymentTriggerTest {
assertEquals(defaultSystemTest, JobType.fromJobName("system-test", zones));
assertEquals(ZoneId.from("test", "us-east-1"), defaultSystemTest.zone());
- assertEquals(ZoneId.from("staging", "us-east-3"), JobType.stagingTest(zones, null).zone());
+ assertEquals(ZoneId.from("staging", "us-east-3"), JobType.stagingTest(zones, zones.systemZone().getCloudName()).zone());
assertEquals(ZoneId.from("test", "zone"), pinkSystemTest.zone());
assertEquals(ZoneId.from("staging", "us-east-3"), JobType.stagingTest(zones, CloudName.from("pink-clouds")).zone());
+
+ assertThrows(IllegalStateException.class, JobType.systemTest(zones, null)::zone);
+ assertThrows(IllegalStateException.class, JobType.fromJobName("system-test", zones)::zone);
+ assertThrows(IllegalStateException.class, JobType.fromJobName("staging-test", zones)::zone);
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
index d781b1f1d3f..493c0945ecc 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunner;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.security.cert.X509Certificate;
import java.time.Duration;
@@ -51,10 +51,10 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
import static java.time.temporal.ChronoUnit.SECONDS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -65,7 +65,7 @@ public class InternalStepRunnerTest {
private DeploymentTester tester;
private DeploymentContext app;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
app = tester.newDeploymentContext();
@@ -358,7 +358,8 @@ public class InternalStepRunnerTest {
// Test sleeps for a while.
tester.runner().run();
assertEquals(unfinished, tester.jobs().run(id).stepStatuses().get(Step.deployTester));
- tester.clock().advance(Duration.ofSeconds(899));
+ Instant nextAttemptAt = tester.clock().instant().plusSeconds(1800);
+ tester.clock().advance(Duration.ofSeconds(1799));
tester.runner().run();
assertEquals(unfinished, tester.jobs().run(id).stepStatuses().get(Step.deployTester));
@@ -380,8 +381,8 @@ public class InternalStepRunnerTest {
assertTestLogEntries(id, Step.endTests,
new LogEntry(lastId1 + 1, Instant.ofEpochMilli(123), info, "Not enough data!"),
- new LogEntry(lastId1 + 2, instant1, info, "Tests were inconclusive, and will run again in 15 minutes."),
- new LogEntry(lastId1 + 15, instant1, info, "### Run will reset, and start over at " + instant1.plusSeconds(900).truncatedTo(SECONDS)),
+ new LogEntry(lastId1 + 2, instant1, info, "Tests were inconclusive, and will run again at " + nextAttemptAt + "."),
+ new LogEntry(lastId1 + 15, instant1, info, "### Run will reset, and start over at " + nextAttemptAt),
new LogEntry(lastId1 + 16, instant1, info, ""),
new LogEntry(lastId2 + 1, tester.clock().instant(), info, "Tests completed successfully."));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
index 772d65fa80e..44ca248614b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
@@ -2,9 +2,9 @@
package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.config.provision.zone.ZoneId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author ogronnesby
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class QuotaUsageTest {
@Test
- public void testQuotaUsageIsPersisted() {
+ void testQuotaUsageIsPersisted() {
var tester = new DeploymentTester();
var context = tester.newDeploymentContext().submit().deploy();
assertEquals(1.304, context.deployment(ZoneId.from("prod.us-west-1")).quota().rate(), 0.01);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
index 67583891765..6493eafcde5 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.EndpointId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -21,7 +21,7 @@ import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTester.instanceId;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -29,24 +29,24 @@ import static org.junit.Assert.assertEquals;
public class TestConfigSerializerTest {
@Test
- public void testConfig() throws IOException {
+ void testConfig() throws IOException {
ZoneId zone = DeploymentContext.systemTest.zone();
byte[] json = new TestConfigSerializer(SystemName.PublicCd).configJson(instanceId,
- DeploymentContext.systemTest,
- true,
- Version.fromString("1.2.3"),
- RevisionId.forProduction(321),
- Instant.ofEpochMilli(222),
- Map.of(zone, List.of(Endpoint.of(ApplicationId.defaultId())
- .target(EndpointId.of("ai"), ClusterSpec.Id.from("qrs"),
- List.of(new DeploymentId(ApplicationId.defaultId(),
- ZoneId.defaultId())))
- .on(Endpoint.Port.tls())
- .in(SystemName.main))),
- Map.of(zone, List.of("facts")));
+ DeploymentContext.systemTest,
+ true,
+ Version.fromString("1.2.3"),
+ RevisionId.forProduction(321),
+ Instant.ofEpochMilli(222),
+ Map.of(zone, List.of(Endpoint.of(ApplicationId.defaultId())
+ .target(EndpointId.of("ai"), ClusterSpec.Id.from("qrs"),
+ List.of(new DeploymentId(ApplicationId.defaultId(),
+ ZoneId.defaultId())))
+ .on(Endpoint.Port.tls())
+ .in(SystemName.main))),
+ Map.of(zone, List.of("facts")));
byte[] expected = Files.readAllBytes(Paths.get("src/test/resources/testConfig.json"));
assertEquals(new String(SlimeUtils.toJsonBytes(SlimeUtils.jsonToSlime(expected))),
- new String(json));
+ new String(json));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java
index f48658af7e3..8fe48f805df 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.deployment;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -13,7 +13,7 @@ import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class ZipBuilderTest {
@Test
- public void test() {
+ void test() {
Map<String, String> expected = new HashMap<>();
expected.put("dir/myfile", "my content");
expected.put("rootfile", "this is root");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
index b5fd3d750ef..efb04615125 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.dns.Record;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordData;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordName;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue.Priority;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -23,18 +23,18 @@ import static org.junit.Assert.assertTrue;
public class NameServiceQueueTest {
@Test
- public void test_queue() {
+ void test_queue() {
var nameService = new MemoryNameService();
var r1 = new Record(Record.Type.CNAME, RecordName.from("cname.vespa.oath.cloud"), RecordData.from("example.com"));
var r2 = new Record(Record.Type.TXT, RecordName.from("txt.example.com"), RecordData.from("text"));
var r3 = List.of(new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias1"),
- "dns-zone-01",
- ZoneId.from("prod", "us-north-1")).pack()),
- new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias2"),
- "dns-zone-02",
- ZoneId.from("prod", "us-north-2")).pack()));
+ new LatencyAliasTarget(HostName.of("alias1"),
+ "dns-zone-01",
+ ZoneId.from("prod", "us-north-1")).pack()),
+ new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
+ new LatencyAliasTarget(HostName.of("alias2"),
+ "dns-zone-02",
+ ZoneId.from("prod", "us-north-2")).pack()));
var req1 = new CreateRecord(r1);
var req2 = new CreateRecords(List.of(r2));
var req3 = new CreateRecords(r3);
@@ -64,17 +64,17 @@ public class NameServiceQueueTest {
// Dispatch removals
queue = queue.with(req4).with(req5).dispatchTo(nameService, 2);
- assertTrue("Removed " + r2, nameService.findRecords(r2.type(), r2.name()).isEmpty());
- assertTrue("Removed " + r3, nameService.findRecords(Record.Type.ALIAS, r3.get(0).name()).isEmpty());
+ assertTrue(nameService.findRecords(r2.type(), r2.name()).isEmpty(), "Removed " + r2);
+ assertTrue(nameService.findRecords(Record.Type.ALIAS, r3.get(0).name()).isEmpty(), "Removed " + r3);
// Dispatch removals by data
queue = queue.with(req6).dispatchTo(nameService, 1);
assertTrue(queue.requests().isEmpty());
- assertTrue("Removed " + r1, nameService.findRecords(Record.Type.CNAME, r1.name()).isEmpty());
+ assertTrue(nameService.findRecords(Record.Type.CNAME, r1.name()).isEmpty(), "Removed " + r1);
// Keep n last requests
queue = queue.with(req1).with(req2).with(req3).with(req4).with(req6)
- .last(2);
+ .last(2);
assertEquals(List.of(req4, req6), List.copyOf(queue.requests()));
assertSame(queue, queue.last(2));
assertSame(queue, queue.last(10));
@@ -82,7 +82,7 @@ public class NameServiceQueueTest {
// Keep n first requests
queue = NameServiceQueue.EMPTY.with(req1).with(req2).with(req3).with(req4).with(req6)
- .first(3);
+ .first(3);
assertEquals(List.of(req1, req2, req3), List.copyOf(queue.requests()));
assertSame(queue, queue.first(3));
assertSame(queue, queue.first(10));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java
index 3f1ca3f9706..93ebdcf3171 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/NodeRepositoryMock.java
@@ -107,7 +107,7 @@ public class NodeRepositoryMock implements NodeRepository {
.collect(Collectors.toList())
: List.of();
- return new NodeRepoStats(Load.zero(), Load.zero(), applicationStats);
+ return new NodeRepoStats(0.0, 0.0, Load.zero(), Load.zero(), applicationStats);
}
@Override
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ZoneApiMock.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ZoneApiMock.java
index d173fcb0e18..4bb35d748db 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ZoneApiMock.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/integration/ZoneApiMock.java
@@ -76,6 +76,11 @@ public class ZoneApiMock implements ZoneApi {
return Objects.hash(id);
}
+ @Override
+ public String toString() {
+ return id.toString();
+ }
+
public static class Builder {
private SystemName systemName = SystemName.defaultSystem();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
index 1e258e8febc..b643d3e90d2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
@@ -9,17 +9,17 @@ import com.yahoo.vespa.hosted.controller.api.integration.organization.IssueId;
import com.yahoo.vespa.hosted.controller.api.integration.organization.OwnershipIssues;
import com.yahoo.vespa.hosted.controller.api.integration.organization.User;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTester.appId;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -30,7 +30,7 @@ public class ApplicationOwnershipConfirmerTest {
private ApplicationOwnershipConfirmer confirmer;
private DeploymentTester tester;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
issues = new MockOwnershipIssues();
@@ -38,7 +38,7 @@ public class ApplicationOwnershipConfirmerTest {
}
@Test
- public void testConfirmation() {
+ void testConfirmation() {
Optional<Contact> contact = Optional.of(tester.controllerTester().serviceRegistry().contactRetrieverMock().contact());
var app = tester.newDeploymentContext();
tester.controller().tenants().lockOrThrow(appId.tenant(), LockedTenant.Athenz.class, tenant ->
@@ -48,55 +48,55 @@ public class ApplicationOwnershipConfirmerTest {
var appWithoutContact = tester.newDeploymentContext("other", "application", "default");
appWithoutContact.submit().deploy();
- assertFalse("No issue is initially stored for a new application.", app.application().ownershipIssueId().isPresent());
- assertFalse("No issue is initially stored for a new application.", appWithoutContact.application().ownershipIssueId().isPresent());
- assertFalse("No escalation has been attempted for a new application", issues.escalated);
+ assertFalse(app.application().ownershipIssueId().isPresent(), "No issue is initially stored for a new application.");
+ assertFalse(appWithoutContact.application().ownershipIssueId().isPresent(), "No issue is initially stored for a new application.");
+ assertFalse(issues.escalated, "No escalation has been attempted for a new application");
// Set response from the issue mock, which will be obtained by the maintainer on issue filing.
Optional<IssueId> issueId = Optional.of(IssueId.from("1"));
issues.response = issueId;
confirmer.maintain();
- assertFalse("No issue is stored for an application newer than 3 months.", app.application().ownershipIssueId().isPresent());
- assertFalse("No issue is stored for an application newer than 3 months.", appWithoutContact.application().ownershipIssueId().isPresent());
+ assertFalse(app.application().ownershipIssueId().isPresent(), "No issue is stored for an application newer than 3 months.");
+ assertFalse(appWithoutContact.application().ownershipIssueId().isPresent(), "No issue is stored for an application newer than 3 months.");
tester.clock().advance(Duration.ofDays(91));
confirmer.maintain();
- assertEquals("Confirmation issue has been filed for application with contact.", issueId, app.application().ownershipIssueId());
- assertTrue("The confirmation issue response has been ensured.", issues.escalated);
- assertEquals("No confirmation issue has been filed for application without contact.", Optional.empty(), appWithoutContact.application().ownershipIssueId());
+ assertEquals(issueId, app.application().ownershipIssueId(), "Confirmation issue has been filed for application with contact.");
+ assertTrue(issues.escalated, "The confirmation issue response has been ensured.");
+ assertEquals(Optional.empty(), appWithoutContact.application().ownershipIssueId(), "No confirmation issue has been filed for application without contact.");
// No new issue is created, so return empty now.
issues.response = Optional.empty();
confirmer.maintain();
- assertEquals("Confirmation issue reference is not updated when no issue id is returned.", issueId, app.application().ownershipIssueId());
+ assertEquals(issueId, app.application().ownershipIssueId(), "Confirmation issue reference is not updated when no issue id is returned.");
// Time has passed, and a new confirmation issue is in order for the property which is still in production.
Optional<IssueId> issueId2 = Optional.of(IssueId.from("2"));
issues.response = issueId2;
confirmer.maintain();
- assertEquals("A new confirmation issue id is stored when something is returned to the maintainer.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "A new confirmation issue id is stored when something is returned to the maintainer.");
- assertFalse("No owner is stored for application", app.application().owner().isPresent());
+ assertFalse(app.application().owner().isPresent(), "No owner is stored for application");
issues.owner = Optional.of(User.from("username"));
confirmer.maintain();
- assertEquals("Owner has been added to application", app.application().owner().get().username(), "username");
+ assertEquals(app.application().owner().get().username(), "username", "Owner has been added to application");
// The app deletes all production deployments — see that the issue is forgotten.
- assertEquals("Confirmation issue for application is still open.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "Confirmation issue for application is still open.");
app.application().productionDeployments().values().stream().flatMap(List::stream)
- .forEach(deployment -> tester.controller().applications().deactivate(app.instanceId(), deployment.zone()));
- assertTrue("No production deployments are listed for user.", app.application().require(InstanceName.defaultName()).productionDeployments().isEmpty());
+ .forEach(deployment -> tester.controller().applications().deactivate(app.instanceId(), deployment.zone()));
+ assertTrue(app.application().require(InstanceName.defaultName()).productionDeployments().isEmpty(), "No production deployments are listed for user.");
confirmer.maintain();
// Time has passed, and a new confirmation issue is in order for the property which is still in production.
issues.response = Optional.of(IssueId.from("3"));
confirmer.maintain();
- assertEquals("Confirmation issue for application without production deployments has not been filed.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "Confirmation issue for application without production deployments has not been filed.");
}
private static class MockOwnershipIssues implements OwnershipIssues {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
index 3535417c586..c10b77d853a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
import com.yahoo.vespa.hosted.controller.api.integration.archive.MockArchiveService;
import com.yahoo.vespa.hosted.controller.tenant.ArchiveAccess;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
@@ -19,8 +19,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author andreer
@@ -28,7 +27,7 @@ import static org.junit.Assert.assertNull;
public class ArchiveAccessMaintainerTest {
@Test
- public void grantsRoleAccess() {
+ void grantsRoleAccess() {
var tester = new ControllerTester(SystemName.Public);
String tenant1role = "arn:aws:iam::123456789012:role/my-role";
@@ -49,10 +48,10 @@ public class ArchiveAccessMaintainerTest {
assertEquals(new ArchiveAccess().withAWSRole(tenant2role), archiveService.authorizeAccessByTenantName.get(tenant2));
var expected = Map.of("archive.bucketCount",
- tester.controller().zoneRegistry().zonesIncludingSystem().all().ids().stream()
- .collect(Collectors.toMap(
- zone -> Map.of("zone", zone.value(), "cloud", "default"),
- zone -> zone.equals(testZone) ? 1d : 0d)));
+ tester.controller().zoneRegistry().zonesIncludingSystem().all().ids().stream()
+ .collect(Collectors.toMap(
+ zone -> Map.of("zone", zone.value(), "cloud", "default"),
+ zone -> zone.equals(testZone) ? 1d : 0d)));
assertEquals(expected, metric.metrics());
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
index d208657c1c4..cb5a84654d0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
@@ -21,7 +21,7 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -31,7 +31,7 @@ public class ArchiveUriUpdaterTest {
private final DeploymentTester tester = new DeploymentTester(new ControllerTester(SystemName.Public));
@Test
- public void archive_uri_test() {
+ void archive_uri_test() {
var updater = new ArchiveUriUpdater(tester.controller(), Duration.ofDays(1));
var tenant1 = TenantName.from("tenant1");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
index 7703266c9ba..c0f0322d192 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.api.integration.artifact.Artifact;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ArtifactRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class ArtifactExpirerTest {
@Test
- public void maintain() {
+ void maintain() {
DeploymentTester tester = new DeploymentTester();
ArtifactExpirer expirer = new ArtifactExpirer(tester.controller(), Duration.ofDays(1));
ArtifactRegistryMock registry = tester.controllerTester().serviceRegistry().artifactRegistry(CloudName.defaultName()).orElseThrow();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
index add1a319384..084fd243769 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
@@ -7,14 +7,14 @@ import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author smorgrav
@@ -24,7 +24,7 @@ public class ChangeManagementAssessorTest {
private final ChangeManagementAssessor changeManagementAssessor = new ChangeManagementAssessor(new NodeRepositoryMock());
@Test
- public void empty_input_variations() {
+ void empty_input_variations() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = new ArrayList<>();
List<Node> allNodesInZone = new ArrayList<>();
@@ -36,16 +36,16 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_host_one_cluster_no_groups() {
+ void one_host_one_cluster_no_groups() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = Collections.singletonList("host1");
List<Node> allNodesInZone = new ArrayList<>();
- allNodesInZone.add(createNode("node1", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node2", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node3", "host1", "default", 0 ));
+ allNodesInZone.add(createNode("node1", "host1", "default", 0));
+ allNodesInZone.add(createNode("node2", "host1", "default", 0));
+ allNodesInZone.add(createNode("node3", "host1", "default", 0));
// Add an not impacted hosts
- allNodesInZone.add(createNode("node4", "host2", "default", 0 ));
+ allNodesInZone.add(createNode("node4", "host2", "default", 0));
// Add tenant hosts
allNodesInZone.add(createHost("host1", NodeType.host));
@@ -67,27 +67,27 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_of_two_groups_in_one_of_two_clusters() {
+ void one_of_two_groups_in_one_of_two_clusters() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = List.of("host1", "host2", "host5");
List<Node> allNodesInZone = new ArrayList<>();
// Two impacted nodes on host1
- allNodesInZone.add(createNode("node1", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node2", "host1", "default", 0 ));
+ allNodesInZone.add(createNode("node1", "host1", "default", 0));
+ allNodesInZone.add(createNode("node2", "host1", "default", 0));
// One impacted nodes on host2
- allNodesInZone.add(createNode("node3", "host2", "default", 0 ));
+ allNodesInZone.add(createNode("node3", "host2", "default", 0));
// Another group on hosts not impacted
- allNodesInZone.add(createNode("node4", "host3", "default", 1 ));
- allNodesInZone.add(createNode("node5", "host3", "default", 1 ));
- allNodesInZone.add(createNode("node6", "host3", "default", 1 ));
+ allNodesInZone.add(createNode("node4", "host3", "default", 1));
+ allNodesInZone.add(createNode("node5", "host3", "default", 1));
+ allNodesInZone.add(createNode("node6", "host3", "default", 1));
// Another cluster on hosts not impacted - this one also with three different groups (should all be ignored here)
- allNodesInZone.add(createNode("node4", "host4", "myman", 4 ));
- allNodesInZone.add(createNode("node5", "host4", "myman", 5 ));
- allNodesInZone.add(createNode("node6", "host4", "myman", 6 ));
+ allNodesInZone.add(createNode("node4", "host4", "myman", 4));
+ allNodesInZone.add(createNode("node5", "host4", "myman", 5));
+ allNodesInZone.add(createNode("node6", "host4", "myman", 6));
// Add tenant hosts
allNodesInZone.add(createHost("host1", NodeType.host));
@@ -114,14 +114,14 @@ public class ChangeManagementAssessorTest {
assertEquals(2, hostAssessments.size());
assertTrue(hostAssessments.stream().anyMatch(hostAssessment ->
hostAssessment.hostName.equals("host1") &&
- hostAssessment.switchName.equals("switch1") &&
- hostAssessment.numberOfChildren == 2 &&
- hostAssessment.numberOfProblematicChildren == 2
+ hostAssessment.switchName.equals("switch1") &&
+ hostAssessment.numberOfChildren == 2 &&
+ hostAssessment.numberOfProblematicChildren == 2
));
}
@Test
- public void two_config_nodes() {
+ void two_config_nodes() {
var zone = ZoneId.from("prod", "eu-trd");
var hostNames = List.of("config1", "config2");
var allNodesInZone = new ArrayList<Node>();
@@ -139,7 +139,7 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_of_three_proxy_nodes() {
+ void one_of_three_proxy_nodes() {
var zone = ZoneId.from("prod", "eu-trd");
var hostNames = List.of("routing1");
var allNodesInZone = new ArrayList<Node>();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
index 7607a4f602d..a20a2e26d22 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSourc
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSource.Status;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.MockChangeRequestClient;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -26,7 +26,7 @@ public class ChangeRequestMaintainerTest {
private final ChangeRequestMaintainer changeRequestMaintainer = new ChangeRequestMaintainer(tester.controller(), Duration.ofMinutes(1));
@Test
- public void updates_status_time_and_approval() {
+ void updates_status_time_and_approval() {
var time = ZonedDateTime.now();
var persistedChangeRequest = persistedChangeRequest("some-id", time.minusDays(5), Status.WAITING_FOR_APPROVAL);
tester.curator().writeChangeRequest(persistedChangeRequest);
@@ -43,7 +43,7 @@ public class ChangeRequestMaintainerTest {
}
@Test
- public void deletes_old_change_requests() {
+ void deletes_old_change_requests() {
var now = ZonedDateTime.now();
var before = now.minus(Duration.ofDays(8));
var newChangeRequest = persistedChangeRequest("new", now, Status.CLOSED);
@@ -60,7 +60,7 @@ public class ChangeRequestMaintainerTest {
}
@Test
- public void approves_change_request_if_non_prod() {
+ void approves_change_request_if_non_prod() {
var time = ZonedDateTime.now();
var prodChangeRequest = newChangeRequest("id1", ChangeRequest.Approval.REQUESTED, time, Status.WAITING_FOR_APPROVAL);
var nonProdApprovalRequested = newChangeRequest("id2", "unknown-node", ChangeRequest.Approval.REQUESTED, time, Status.WAITING_FOR_APPROVAL);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
index 187b8f932cf..c5c70998624 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
@@ -9,16 +9,15 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanId;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author ogronnesby
@@ -30,63 +29,63 @@ public class CloudTrialExpirerTest {
private final CloudTrialExpirer expirer = new CloudTrialExpirer(tester.controller(), Duration.ofMinutes(5));
@Test
- public void expire_inactive_tenant() {
+ void expire_inactive_tenant() {
registerTenant("trial-tenant", "trial", Duration.ofDays(14).plusMillis(1));
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("trial-tenant", "none");
}
@Test
- public void tombstone_inactive_none() {
- registerTenant("none-tenant", "none", Duration.ofDays(365).plusMillis(1));
- expirer.maintain();
+ void tombstone_inactive_none() {
+ registerTenant("none-tenant", "none", Duration.ofDays(183).plusMillis(1));
+ assertEquals(1.0, expirer.maintain());
assertEquals(Tenant.Type.deleted, tester.controller().tenants().get(TenantName.from("none-tenant"), true).get().type());
}
@Test
- public void keep_inactive_nontrial_tenants() {
+ void keep_inactive_nontrial_tenants() {
registerTenant("not-a-trial-tenant", "pay-as-you-go", Duration.ofDays(30));
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("not-a-trial-tenant", "pay-as-you-go");
}
@Test
- public void keep_active_trial_tenants() {
+ void keep_active_trial_tenants() {
registerTenant("active-trial-tenant", "trial", Duration.ofHours(14).minusMillis(1));
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("active-trial-tenant", "trial");
}
@Test
- public void keep_inactive_exempt_tenants() {
+ void keep_inactive_exempt_tenants() {
registerTenant("exempt-trial-tenant", "trial", Duration.ofDays(40));
((InMemoryFlagSource) tester.controller().flagSource()).withListFlag(PermanentFlags.EXTENDED_TRIAL_TENANTS.id(), List.of("exempt-trial-tenant"), String.class);
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("exempt-trial-tenant", "trial");
}
@Test
- public void keep_inactive_trial_tenants_with_deployments() {
+ void keep_inactive_trial_tenants_with_deployments() {
registerTenant("with-deployments", "trial", Duration.ofDays(30));
registerDeployment("with-deployments", "my-app", "default");
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("with-deployments", "trial");
}
@Test
- public void delete_tenants_with_applications_with_no_deployments() {
- registerTenant("with-apps", "trial", Duration.ofDays(366));
+ void delete_tenants_with_applications_with_no_deployments() {
+ registerTenant("with-apps", "trial", Duration.ofDays(184));
tester.createApplication("with-apps", "app1", "instance1");
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertPlan("with-apps", "none");
- expirer.maintain();
+ assertEquals(1.0, expirer.maintain());
assertTrue(tester.controller().tenants().get("with-apps").isEmpty());
}
@Test
- public void keep_tenants_without_applications_that_are_idle() {
- registerTenant("active", "none", Duration.ofDays(364));
- expirer.maintain();
+ void keep_tenants_without_applications_that_are_idle() {
+ registerTenant("active", "none", Duration.ofDays(182));
+ assertEquals(1.0, expirer.maintain());
assertPlan("active", "none");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
index 37b138527fe..f0c11c0ddbd 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
@@ -6,8 +6,8 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.identifiers.PropertyId;
import com.yahoo.vespa.hosted.controller.api.integration.organization.Contact;
import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
@@ -16,8 +16,8 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author mpolden
@@ -27,30 +27,32 @@ public class ContactInformationMaintainerTest {
private ControllerTester tester;
private ContactInformationMaintainer maintainer;
- @Before
+ @BeforeEach
public void before() {
tester = new ControllerTester();
maintainer = new ContactInformationMaintainer(tester.controller(), Duration.ofDays(1));
}
@Test
- public void updates_contact_information() {
+ void updates_contact_information() {
PropertyId propertyId1 = new PropertyId("1");
PropertyId propertyId2 = new PropertyId("2");
TenantName name1 = tester.createTenant("tenant1", "domain1", 1L);
TenantName name2 = tester.createTenant("zenant1", "domain2", 2L);
Supplier<AthenzTenant> tenant1 = () -> (AthenzTenant) tester.controller().tenants().require(name1);
Supplier<AthenzTenant> tenant2 = () -> (AthenzTenant) tester.controller().tenants().require(name2);
- assertFalse("No contact information initially", tenant1.get().contact().isPresent());
- assertFalse("No contact information initially", tenant2.get().contact().isPresent());
+ assertFalse(tenant1.get().contact().isPresent(), "No contact information initially");
+ assertFalse(tenant2.get().contact().isPresent(), "No contact information initially");
Contact contact = testContact();
- tester.serviceRegistry().contactRetriever().addContact(propertyId1, () -> { throw new RuntimeException("ERROR"); });
+ tester.serviceRegistry().contactRetriever().addContact(propertyId1, () -> {
+ throw new RuntimeException("ERROR");
+ });
tester.serviceRegistry().contactRetriever().addContact(propertyId2, () -> contact);
maintainer.maintain();
- assertEquals("No contact information added due to error", Optional.empty(), tenant1.get().contact());
- assertEquals("Contact information added", Optional.of(contact), tenant2.get().contact());
+ assertEquals(Optional.empty(), tenant1.get().contact(), "No contact information added due to error");
+ assertEquals(Optional.of(contact), tenant2.get().contact(), "Contact information added");
}
private static Contact testContact() {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
index a452d550488..63e2c99cb6e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
@@ -5,14 +5,14 @@ import com.yahoo.config.provision.SystemName;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -21,13 +21,13 @@ public class ControllerMaintainerTest {
private ControllerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ControllerTester();
}
@Test
- public void only_runs_in_permitted_systems() {
+ void only_runs_in_permitted_systems() {
AtomicInteger executions = new AtomicInteger();
new TestControllerMaintainer(tester.controller(), SystemName.cd, executions).run();
new TestControllerMaintainer(tester.controller(), SystemName.main, executions).run();
@@ -35,7 +35,7 @@ public class ControllerMaintainerTest {
}
@Test
- public void records_metric() {
+ void records_metric() {
TestControllerMaintainer maintainer = new TestControllerMaintainer(tester.controller(), SystemName.main, new AtomicInteger());
maintainer.run();
assertEquals(1.0, successFactorMetric(), 0.0000001);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
index 294272041b6..7cfe5dee3de 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
@@ -7,13 +7,13 @@ import com.yahoo.vespa.hosted.controller.api.identifiers.Property;
import com.yahoo.vespa.hosted.controller.api.integration.resource.CostReportConsumerMock;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author ldalves
@@ -23,7 +23,7 @@ public class CostReportMaintainerTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void maintain() {
+ void maintain() {
tester.clock().setInstant(Instant.EPOCH);
tester.zoneRegistry().setZones(
ZoneApiMock.newBuilder().withId("prod.us-east-3").withCloud("yahoo").build(),
@@ -35,9 +35,9 @@ public class CostReportMaintainerTest {
CostReportConsumerMock costReportConsumer = new CostReportConsumerMock(
(csv) -> assertEquals(
"Date,Property,Reserved Cpu Cores,Reserved Memory GB,Reserved Disk Space GB,Usage Fraction\n" +
- "1970-01-01,Property1,96.0,96.0,2000.0,0.3055555555555555\n" +
- "1970-01-01,Property3,128.0,96.0,2000.0,0.3333333333333333\n" +
- "1970-01-01,Property2,160.0,96.0,2000.0,0.3611111111111111",
+ "1970-01-01,Property1,96.0,96.0,2000.0,0.3055555555555555\n" +
+ "1970-01-01,Property3,128.0,96.0,2000.0,0.3333333333333333\n" +
+ "1970-01-01,Property2,160.0,96.0,2000.0,0.3611111111111111",
csv),
Map.of(new Property("Property3"), new ResourceAllocation(256, 192, 4000, NodeResources.Architecture.getDefault()))
);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
index 10a8bb79c2e..0c238ea7c9d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
@@ -12,13 +12,13 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.RunStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author bratseth
@@ -28,7 +28,7 @@ public class DeploymentExpirerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeploymentExpiry() {
+ void testDeploymentExpiry() {
ZoneId devZone = ZoneId.from(Environment.dev, RegionName.from("us-east-1"));
tester.controllerTester().zoneRegistry().setDeploymentTimeToLive(devZone, Duration.ofDays(14));
DeploymentExpirer expirer = new DeploymentExpirer(tester.controller(), Duration.ofDays(1));
@@ -59,9 +59,10 @@ public class DeploymentExpirerTest {
Run lastRun = tester.jobs().last(devApp.instanceId(), DeploymentContext.devUsEast1).get();
assertSame(RunStatus.error, lastRun.status());
Deployment deployment = tester.applications().requireInstance(devApp.instanceId())
- .deployments().get(devZone);
- assertEquals("Time of last run is after time of deployment", Duration.ofDays(12),
- Duration.between(deployment.at(), lastRun.end().get()));
+ .deployments().get(devZone);
+ assertEquals(Duration.ofDays(12),
+ Duration.between(deployment.at(), lastRun.end().get()),
+ "Time of last run is after time of deployment");
// Dev application does not expire based on time of successful deployment
tester.clock().advance(Duration.ofDays(2));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
index 637a8832533..2f84b58dbae 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashMap;
@@ -27,9 +27,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.sys
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.maxFailureAge;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.maxInactivity;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.upgradeGracePeriod;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -48,7 +48,7 @@ public class DeploymentIssueReporterTest {
private DeploymentIssueReporter reporter;
private MockDeploymentIssues issues;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
issues = new MockDeploymentIssues();
@@ -56,7 +56,7 @@ public class DeploymentIssueReporterTest {
}
@Test
- public void nonProductionAppGetsNoIssues() {
+ void nonProductionAppGetsNoIssues() {
tester.controllerTester().upgradeSystem(Version.fromString("6.2"));
var app = tester.newDeploymentContext("application", "tenant", "default");
Contact contact = tester.controllerTester().serviceRegistry().contactRetrieverMock().contact();
@@ -68,11 +68,11 @@ public class DeploymentIssueReporterTest {
// Advance to where deployment issues should be detected.
tester.clock().advance(maxFailureAge.plus(Duration.ofDays(1)));
- assertFalse("No issues are produced for app.", issues.isOpenFor(app.application().id()));
+ assertFalse(issues.isOpenFor(app.application().id()), "No issues are produced for app.");
}
@Test
- public void testDeploymentFailureReporting() {
+ void testDeploymentFailureReporting() {
tester.controllerTester().upgradeSystem(Version.fromString("6.2"));
// Create and deploy one application for each of three tenants.
@@ -102,7 +102,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertEquals("No deployments are detected as failing for a long time initially.", 0, issues.size());
+ assertEquals(0, issues.size(), "No deployments are detected as failing for a long time initially.");
// Advance to where deployment issues should be detected.
@@ -110,18 +110,18 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertTrue("One issue is produced for app1.", issues.isOpenFor(app1.application().id()));
- assertFalse("No issues are produced for app2.", issues.isOpenFor(app2.application().id()));
- assertTrue("One issue is produced for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app1.application().id()), "One issue is produced for app1.");
+ assertFalse(issues.isOpenFor(app2.application().id()), "No issues are produced for app2.");
+ assertTrue(issues.isOpenFor(app3.application().id()), "One issue is produced for app3.");
// app3 closes their issue prematurely; see that it is refiled.
issues.closeFor(app3.application().id());
- assertFalse("No issue is open for app3.", issues.isOpenFor(app3.application().id()));
+ assertFalse(issues.isOpenFor(app3.application().id()), "No issue is open for app3.");
reporter.maintain();
reporter.maintain();
- assertTrue("Issue is re-filed for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app3.application().id()), "Issue is re-filed for app3.");
// Some time passes; tenant1 leaves her issue unattended, while tenant3 starts work and updates the issue.
tester.clock().advance(maxInactivity.plus(maxFailureAge));
@@ -129,7 +129,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertEquals("The issue for app1 is escalated once.", 1, issues.escalationLevelFor(app1.application().id()));
+ assertEquals(1, issues.escalationLevelFor(app1.application().id()), "The issue for app1 is escalated once.");
// app3 fixes their problems, but the ticket for app3 is left open; see the resolved ticket is not escalated when another escalation period has passed.
@@ -138,9 +138,9 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertFalse("We no longer have a platform issue.", issues.platformIssue());
- assertEquals("The issue for app1 is escalated once more.", 2, issues.escalationLevelFor(app1.application().id()));
- assertEquals("The issue for app3 is not escalated.", 0, issues.escalationLevelFor(app3.application().id()));
+ assertFalse(issues.platformIssue(), "We no longer have a platform issue.");
+ assertEquals(2, issues.escalationLevelFor(app1.application().id()), "The issue for app1 is escalated once more.");
+ assertEquals(0, issues.escalationLevelFor(app3.application().id()), "The issue for app3 is not escalated.");
// app3 now has a new failure past max failure age; see that a new issue is filed.
@@ -149,7 +149,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertTrue("A new issue is filed for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app3.application().id()), "A new issue is filed for app3.");
// app2 is changed to be a canary
@@ -167,15 +167,15 @@ public class DeploymentIssueReporterTest {
tester.controllerTester().upgradeSystem(version);
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
- assertFalse("We have no platform issues initially.", issues.platformIssue());
+ assertFalse(issues.platformIssue(), "We have no platform issues initially.");
reporter.maintain();
reporter.maintain();
- assertFalse("We have no platform issue before the grace period is out for the failing canary.", issues.platformIssue());
+ assertFalse(issues.platformIssue(), "We have no platform issue before the grace period is out for the failing canary.");
tester.clock().advance(upgradeGracePeriod.plus(upgradeGracePeriod));
reporter.maintain();
reporter.maintain();
- assertTrue("We get a platform issue when confidence is broken", issues.platformIssue());
- assertFalse("No deployment issue is filed for app2, which has a version upgrade failure.", issues.isOpenFor(app2.application().id()));
+ assertTrue(issues.platformIssue(), "We get a platform issue when confidence is broken");
+ assertFalse(issues.isOpenFor(app2.application().id()), "No deployment issue is filed for app2, which has a version upgrade failure.");
app2.runJob(systemTest);
tester.controllerTester().upgradeSystem(version);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
index 112519bb717..6ac0509c0f8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -23,8 +23,8 @@ import java.util.Map;
import java.util.function.Supplier;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author smorgrav
@@ -35,7 +35,7 @@ public class DeploymentMetricsMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void updates_metrics() {
+ void updates_metrics() {
var application = tester.newDeploymentContext();
application.runJob(DeploymentContext.devUsEast1, new ApplicationPackage(new byte[0]), Version.fromString("7.1"));
@@ -46,17 +46,17 @@ public class DeploymentMetricsMaintainerTest {
// No metrics gathered yet
assertEquals(0, app.get().metrics().queryServiceQuality(), 0);
assertEquals(0, deployment.get().metrics().documentCount(), 0);
- assertFalse("No timestamp set", deployment.get().metrics().instant().isPresent());
- assertFalse("Never received any queries", deployment.get().activity().lastQueried().isPresent());
- assertFalse("Never received any writes", deployment.get().activity().lastWritten().isPresent());
+ assertFalse(deployment.get().metrics().instant().isPresent(), "No timestamp set");
+ assertFalse(deployment.get().activity().lastQueried().isPresent(), "Never received any queries");
+ assertFalse(deployment.get().activity().lastWritten().isPresent(), "Never received any writes");
// Metrics are gathered and saved to application
application.runJob(DeploymentContext.devUsEast1, new ApplicationPackage(new byte[0]), Version.fromString("7.5.5"));
var metrics0 = Map.of(ClusterMetrics.QUERIES_PER_SECOND, 1D,
- ClusterMetrics.FEED_PER_SECOND, 2D,
- ClusterMetrics.DOCUMENT_COUNT, 3D,
- ClusterMetrics.QUERY_LATENCY, 4D,
- ClusterMetrics.FEED_LATENCY, 5D);
+ ClusterMetrics.FEED_PER_SECOND, 2D,
+ ClusterMetrics.DOCUMENT_COUNT, 3D,
+ ClusterMetrics.QUERY_LATENCY, 4D,
+ ClusterMetrics.FEED_LATENCY, 5D);
setMetrics(application.application().id().defaultInstance(), metrics0);
maintainer.maintain();
Instant t1 = tester.clock().instant().truncatedTo(MILLIS);
@@ -107,7 +107,7 @@ public class DeploymentMetricsMaintainerTest {
}
@Test
- public void cluster_metric_aggregation_test() {
+ void cluster_metric_aggregation_test() {
List<ClusterMetrics> clusterMetrics = List.of(
new ClusterMetrics("niceCluster", "container", Map.of("queriesPerSecond", 23.0, "queryLatency", 1337.0), Map.of()),
new ClusterMetrics("alsoNiceCluster", "container", Map.of("queriesPerSecond", 11.0, "queryLatency", 12.0), Map.of()));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
index 653ad2bb08a..df0afda838e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -17,8 +17,8 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.dev
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentUpgrader.mostLikelyWeeHour;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -28,7 +28,7 @@ public class DeploymentUpgraderTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeploymentUpgrading() {
+ void testDeploymentUpgrading() {
ZoneId devZone = ZoneId.from(Environment.dev, RegionName.from("us-east-1"));
DeploymentUpgrader upgrader = new DeploymentUpgrader(tester.controller(), Duration.ofDays(1));
var devApp = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -76,11 +76,11 @@ public class DeploymentUpgraderTest {
}
@Test
- public void testNight() {
- assertEquals(16, mostLikelyWeeHour(new int[]{ 0, 1, 2, 3, 4, 5, 6 }));
- assertEquals(14, mostLikelyWeeHour(new int[]{ 22, 23, 0, 1, 2, 3, 4 }));
- assertEquals(18, mostLikelyWeeHour(new int[]{ 6, 5, 4, 3, 2, 1, 0 }));
- assertEquals(20, mostLikelyWeeHour(new int[]{ 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 11 }));
+ void testNight() {
+ assertEquals(16, mostLikelyWeeHour(new int[]{0, 1, 2, 3, 4, 5, 6}));
+ assertEquals(14, mostLikelyWeeHour(new int[]{22, 23, 0, 1, 2, 3, 4}));
+ assertEquals(18, mostLikelyWeeHour(new int[]{6, 5, 4, 3, 2, 1, 0}));
+ assertEquals(20, mostLikelyWeeHour(new int[]{0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 11}));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
index 6bcb4284a14..47a1b44d196 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
@@ -1,26 +1,39 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.maintenance;
+import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
+import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateMetadata;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateMock;
+import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
+import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
+import com.yahoo.vespa.hosted.controller.application.Deployment;
+import com.yahoo.vespa.hosted.controller.application.DeploymentActivity;
+import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics;
+import com.yahoo.vespa.hosted.controller.application.QuotaUsage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.SecretStoreMock;
-import org.junit.Test;
+import org.jetbrains.annotations.NotNull;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
+import java.util.OptionalDouble;
+import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author andreer
@@ -33,14 +46,14 @@ public class EndpointCertificateMaintainerTest {
private final EndpointCertificateMetadata exampleMetadata = new EndpointCertificateMetadata("keyName", "certName", 0, 0, "root-request-uuid", Optional.of("leaf-request-uuid"), List.of(), "issuer", Optional.empty(), Optional.empty());
@Test
- public void old_and_unused_cert_is_deleted() {
+ void old_and_unused_cert_is_deleted() {
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), exampleMetadata);
assertEquals(1.0, maintainer.maintain(), 0.0000001);
assertTrue(tester.curator().readEndpointCertificateMetadata(ApplicationId.defaultId()).isEmpty());
}
@Test
- public void unused_but_recently_used_cert_is_not_deleted() {
+ void unused_but_recently_used_cert_is_not_deleted() {
EndpointCertificateMetadata recentlyRequestedCert = exampleMetadata.withLastRequested(tester.clock().instant().minusSeconds(3600).getEpochSecond());
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), recentlyRequestedCert);
assertEquals(1.0, maintainer.maintain(), 0.0000001);
@@ -48,7 +61,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void refreshed_certificate_is_updated() {
+ void refreshed_certificate_is_updated() {
EndpointCertificateMetadata recentlyRequestedCert = exampleMetadata.withLastRequested(tester.clock().instant().minusSeconds(3600).getEpochSecond());
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), recentlyRequestedCert);
@@ -63,7 +76,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void certificate_in_use_is_not_deleted() {
+ void certificate_in_use_is_not_deleted() {
var appId = ApplicationId.from("tenant", "application", "default");
DeploymentTester deploymentTester = new DeploymentTester(tester);
@@ -82,7 +95,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void refreshed_certificate_is_discovered_and_after_four_days_deployed() {
+ void refreshed_certificate_is_discovered_and_after_four_days_deployed() {
var appId = ApplicationId.from("tenant", "application", "default");
DeploymentTester deploymentTester = new DeploymentTester(tester);
@@ -111,7 +124,7 @@ public class EndpointCertificateMaintainerTest {
deploymentContext.assertNotRunning(productionUsWest1);
var updatedMetadata = tester.curator().readEndpointCertificateMetadata(appId).orElseThrow();
assertNotEquals(originalMetadata.leafRequestId().orElseThrow(), updatedMetadata.leafRequestId().orElseThrow());
- assertEquals(updatedMetadata.version(), originalMetadata.version()+1);
+ assertEquals(updatedMetadata.version(), originalMetadata.version() + 1);
// after another 4 days, we should force trigger deployment if it hasn't already happened
tester.clock().advance(Duration.ofDays(4).plusSeconds(1));
@@ -121,7 +134,22 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void unmaintained_cert_is_deleted() {
+ void testEligibleSorting() {
+ EndpointCertificateMaintainer.EligibleJob oldestDeployment = makeDeploymentAtAge(5);
+ assertEquals(
+ oldestDeployment,
+ Stream.of(makeDeploymentAtAge(2), oldestDeployment, makeDeploymentAtAge(4)).min(maintainer.oldestFirst).get());
+ }
+
+ @NotNull
+ private EndpointCertificateMaintainer.EligibleJob makeDeploymentAtAge(int ageInDays) {
+ var deployment = new Deployment(ZoneId.defaultId(), RevisionId.forProduction(1), Version.emptyVersion,
+ Instant.now().minus(ageInDays, ChronoUnit.DAYS), DeploymentMetrics.none, DeploymentActivity.none, QuotaUsage.none, OptionalDouble.empty());
+ return new EndpointCertificateMaintainer.EligibleJob(deployment, ApplicationId.defaultId(), JobType.prod("somewhere"));
+ }
+
+ @Test
+ void unmaintained_cert_is_deleted() {
EndpointCertificateMock endpointCertificateProvider = (EndpointCertificateMock) tester.controller().serviceRegistry().endpointCertificateProvider();
ApplicationId unknown = ApplicationId.fromSerializedForm("applicationid:is:unknown");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
index 890f0b41098..1ef32b8e347 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
@@ -8,15 +8,15 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.entity.NodeEntity;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class HostInfoUpdaterTest {
@Test
- public void maintain() {
+ void maintain() {
ControllerTester tester = new ControllerTester();
tester.serviceRegistry().configServer().nodeRepository().allowPatching(true);
addNodeEntities(tester);
@@ -36,8 +36,8 @@ public class HostInfoUpdaterTest {
List<Node> nodes = allNodes(tester);
assertFalse(nodes.isEmpty());
for (var node : nodes) {
- assertEquals("Node " + node.hostname().value() + (node.type().isHost() ? " has" : " does not have")
- + " switch hostname", node.type().isHost(), node.switchHostname().isPresent());
+ assertEquals(node.type().isHost(), node.switchHostname().isPresent(), "Node " + node.hostname().value() + (node.type().isHost() ? " has" : " does not have")
+ + " switch hostname");
if (node.type().isHost()) {
assertEquals("tor-" + node.hostname().value(), node.switchHostname().get());
}
@@ -85,18 +85,18 @@ public class HostInfoUpdaterTest {
ZoneId zone = tester.zoneRegistry().zones().controllerUpgraded().all().ids().get(0);
String hostnameSuffix = ".prod." + zone.value();
Node configNode = Node.builder().hostname(HostName.of("cfg3" + hostnameSuffix))
- .type(NodeType.config)
- .build();
+ .type(NodeType.config)
+ .build();
Node configHost = Node.builder().hostname(HostName.of("cfghost3" + hostnameSuffix))
- .type(NodeType.confighost)
- .build();
+ .type(NodeType.confighost)
+ .build();
tester.serviceRegistry().configServer().nodeRepository().putNodes(zone, List.of(configNode, configHost));
String switchHostname = switchHostname(configHost);
NodeEntity configNodeEntity = new NodeEntity("cfg3" + hostnameSuffix, "RD350G", "Lenovo", switchHostname);
tester.serviceRegistry().entityService().addNodeEntity(configNodeEntity);
maintainer.maintain();
assertEquals(switchHostname, getNode(configHost.hostname(), tester).switchHostname().get());
- assertTrue("Switch hostname is not set for non-host", getNode(configNode.hostname(), tester).switchHostname().isEmpty());
+ assertTrue(getNode(configNode.hostname(), tester).switchHostname().isEmpty(), "Switch hostname is not set for non-host");
}
private static Node getNode(HostName hostname, ControllerTester tester) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
index b9ced334e5a..e7e542d2b82 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
@@ -21,7 +21,7 @@ import com.yahoo.vespa.hosted.controller.deployment.StepRunner;
import com.yahoo.vespa.hosted.controller.deployment.Submission;
import com.yahoo.vespa.hosted.controller.deployment.Versions;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
@@ -63,12 +63,12 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.installReal;
import static com.yahoo.vespa.hosted.controller.deployment.Step.installTester;
import static com.yahoo.vespa.hosted.controller.deployment.Step.report;
import static com.yahoo.vespa.hosted.controller.deployment.Step.startTests;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author jonmv
@@ -82,10 +82,10 @@ public class JobRunnerTest {
Optional.empty());
@Test
- public void multiThreadedExecutionFinishes() {
+ void multiThreadedExecutionFinishes() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
- StepRunner stepRunner = (step, id) -> id.type().equals(stagingTest) && step.get() == startTests? Optional.of(error) : Optional.of(running);
+ StepRunner stepRunner = (step, id) -> id.type().equals(stagingTest) && step.get() == startTests ? Optional.of(error) : Optional.of(running);
Phaser phaser = new Phaser(1);
JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), phasedExecutor(phaser), stepRunner);
@@ -98,7 +98,8 @@ public class JobRunnerTest {
start(jobs, id, systemTest);
fail("Job is already running, so this should not be allowed!");
}
- catch (IllegalArgumentException ignored) { }
+ catch (IllegalArgumentException ignored) {
+ }
start(jobs, id, stagingTest);
assertTrue(jobs.last(id, systemTest).get().stepStatuses().values().stream().allMatch(unfinished::equals));
@@ -118,7 +119,7 @@ public class JobRunnerTest {
}
@Test
- public void stepLogic() {
+ void stepLogic() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -225,7 +226,7 @@ public class JobRunnerTest {
}
@Test
- public void locksAndGarbage() throws InterruptedException, BrokenBarrierException {
+ void locksAndGarbage() throws InterruptedException, BrokenBarrierException {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
// Hang during tester deployment, until notified.
@@ -242,10 +243,12 @@ public class JobRunnerTest {
runner.maintain();
barrier.await();
try {
- jobs.locked(id, systemTest, deactivateTester, step -> { });
+ jobs.locked(id, systemTest, deactivateTester, step -> {
+ });
fail("deployTester step should still be locked!");
}
- catch (TimeoutException ignored) { }
+ catch (TimeoutException ignored) {
+ }
// Thread is still trying to deploy tester -- delete application, and see all data is garbage collected.
assertEquals(Collections.singletonList(runId), jobs.active().stream().map(run -> run.id()).collect(Collectors.toList()));
@@ -264,7 +267,7 @@ public class JobRunnerTest {
}
@Test
- public void historyPruning() {
+ void historyPruning() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), inThreadExecutor(), (id, step) -> Optional.of(running));
@@ -341,7 +344,7 @@ public class JobRunnerTest {
}
@Test
- public void onlySuccessfulRunExpiresThenAnotherFails() {
+ void onlySuccessfulRunExpiresThenAnotherFails() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
var app = tester.newDeploymentContext().submit();
@@ -360,7 +363,7 @@ public class JobRunnerTest {
}
@Test
- public void timeout() {
+ void timeout() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -378,7 +381,7 @@ public class JobRunnerTest {
}
@Test
- public void jobMetrics() throws TimeoutException {
+ void jobMetrics() throws TimeoutException {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -401,10 +404,10 @@ public class JobRunnerTest {
}
Map<String, String> context = Map.of("applicationId", "tenant.real.default",
- "tenantName", "tenant",
- "app", "real.default",
- "test", "true",
- "zone", "test.us-east-1");
+ "tenantName", "tenant",
+ "app", "real.default",
+ "test", "true",
+ "zone", "test.us-east-1");
MetricsMock metric = ((MetricsMock) tester.controller().metric());
assertEquals(RunStatus.values().length - 2, metric.getMetric(context::equals, JobMetrics.start).get().intValue());
assertEquals(1, metric.getMetric(context::equals, JobMetrics.abort).get().intValue());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
index 225b7cb1d5e..65dab67663e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
@@ -8,15 +8,15 @@ import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanRegistryMoc
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceDatabaseClientMock;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -31,7 +31,7 @@ public class MeteringMonitorMaintainerTest {
private final ApplicationId applicationId = ApplicationId.from("foo", "bar", "default");
private final ZoneId zone = ZoneId.from("prod.aws-us-east-1c");
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester(SystemName.Public);
deploymentTester = new DeploymentTester(tester);
@@ -39,8 +39,9 @@ public class MeteringMonitorMaintainerTest {
database = new ResourceDatabaseClientMock(new PlanRegistryMock());
maintainer = new MeteringMonitorMaintainer(tester.controller(), Duration.ofMinutes(5), database, metrics);
}
+
@Test
- public void finds_stale_data() {
+ void finds_stale_data() {
deploymentTester.newDeploymentContext(applicationId).submit().deploy();
maintainer.maintain();
var now = tester.clock().instant().getEpochSecond();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
index 215c03030a9..b41c17fcd33 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
@@ -28,7 +28,7 @@ import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -43,9 +43,9 @@ import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mortent
@@ -56,7 +56,7 @@ public class MetricsReporterTest {
private final ZmsClientMock zmsClient = new ZmsClientMock(new AthenzDbMock(), AthenzIdentities.from("mock.identity"));
@Test
- public void audit_log_metric() {
+ void audit_log_metric() {
var tester = new ControllerTester();
MetricsReporter metricsReporter = createReporter(tester.controller());
@@ -114,7 +114,7 @@ public class MetricsReporterTest {
}
@Test
- public void deployment_fail_ratio() {
+ void deployment_fail_ratio() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -147,7 +147,7 @@ public class MetricsReporterTest {
}
@Test
- public void deployment_average_duration() {
+ void deployment_average_duration() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -156,8 +156,8 @@ public class MetricsReporterTest {
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.newDeploymentContext()
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId())); // An exceptionally fast deployment :-)
@@ -180,19 +180,19 @@ public class MetricsReporterTest {
// Another deployment starts and stalls for 12 hours
context.submit(applicationPackage)
- .triggerJobs();
+ .triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12) // hanging system-test
- .plus(Duration.ofHours(12)) // hanging staging-test
- .plus(Duration.ofMinutes(90)) // previous production job
- .dividedBy(3), // Total number of orchestrated jobs
- getAverageDeploymentDuration(context.instanceId()));
+ .plus(Duration.ofHours(12)) // hanging staging-test
+ .plus(Duration.ofMinutes(90)) // previous production job
+ .dividedBy(3), // Total number of orchestrated jobs
+ getAverageDeploymentDuration(context.instanceId()));
}
@Test
- public void deployments_failing_upgrade() {
+ void deployments_failing_upgrade() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -208,40 +208,40 @@ public class MetricsReporterTest {
// Failing application change is not counted
context.submit(applicationPackage)
- .triggerJobs()
- .failDeployment(systemTest);
+ .triggerJobs()
+ .failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
// Application change completes
context.deploy();
- assertFalse("Change deployed", context.instance().change().hasTargets());
+ assertFalse(context.instance().change().hasTargets(), "Change deployed");
// New versions is released and upgrade fails in test environments
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.failDeployment(systemTest)
- .failDeployment(stagingTest);
+ .failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
// Test and staging pass and upgrade fails in production
context.runJob(systemTest)
- .runJob(stagingTest)
- .failDeployment(productionUsWest1);
+ .runJob(stagingTest)
+ .failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
// Upgrade eventually succeeds
context.runJob(productionUsWest1);
- assertFalse("Upgrade deployed", context.instance().change().hasTargets());
+ assertFalse(context.instance().change().hasTargets(), "Upgrade deployed");
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
- public void deployment_warnings_metric() {
+ void deployment_warnings_metric() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -257,22 +257,22 @@ public class MetricsReporterTest {
}
@Test
- public void build_time_reporting() {
+ void build_time_reporting() {
var tester = new DeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.newDeploymentContext()
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
assertEquals(1000, context.application().revisions().get(context.lastSubmission().get()).buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
- getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
+ getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
- public void name_service_queue_size_metric() {
+ void name_service_queue_size_metric() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("default")
@@ -281,21 +281,21 @@ public class MetricsReporterTest {
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.newDeploymentContext()
- .deferDnsUpdates();
+ .deferDnsUpdates();
reporter.maintain();
- assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Queue is empty initially");
context.submit(applicationPackage).deploy();
reporter.maintain();
- assertEquals("Deployment queues name services requests", 2, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(2, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Deployment queues name services requests");
context.flushDnsUpdates();
reporter.maintain();
- assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Queue consumed");
}
@Test
- public void platform_change_duration() {
+ void platform_change_duration() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneId.from("prod.eu-west-1");
@@ -326,11 +326,12 @@ public class MetricsReporterTest {
assertPlatformChangeDuration(Duration.ZERO, hosts);
// 1/3 nodes upgrade within timeout
- assertEquals("Wanted version is raised for all nodes", version,
- getNodes(zone, hosts, tester).stream()
- .map(Node::wantedVersion)
- .min(Comparator.naturalOrder())
- .get());
+ assertEquals(version,
+ getNodes(zone, hosts, tester).stream()
+ .map(Node::wantedVersion)
+ .min(Comparator.naturalOrder())
+ .get(),
+ "Wanted version is raised for all nodes");
suspend(hosts, zone, tester);
var firstHost = hosts.get(0);
upgradeTo(version, List.of(firstHost), zone, tester);
@@ -351,7 +352,7 @@ public class MetricsReporterTest {
}
@Test
- public void os_change_duration() {
+ void os_change_duration() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneId.from("prod.eu-west-1");
@@ -389,12 +390,13 @@ public class MetricsReporterTest {
assertOsChangeDuration(Duration.ZERO, hosts);
// Nodes are told to upgrade, but do not suspend yet
- assertEquals("Wanted OS version is raised for all nodes", nextVersion,
- tester.configServer().nodeRepository().list(zone, NodeFilter.all().applications(SystemApplication.tenantHost.id())).stream()
- .map(Node::wantedOsVersion).min(Comparator.naturalOrder()).get());
- assertTrue("No nodes are suspended", tester.controller().serviceRegistry().configServer()
- .nodeRepository().list(zone, NodeFilter.all()).stream()
- .noneMatch(node -> node.serviceState() == Node.ServiceState.allowedDown));
+ assertEquals(nextVersion,
+ tester.configServer().nodeRepository().list(zone, NodeFilter.all().applications(SystemApplication.tenantHost.id())).stream()
+ .map(Node::wantedOsVersion).min(Comparator.naturalOrder()).get(),
+ "Wanted OS version is raised for all nodes");
+ assertTrue(tester.controller().serviceRegistry().configServer()
+ .nodeRepository().list(zone, NodeFilter.all()).stream()
+ .noneMatch(node -> node.serviceState() == Node.ServiceState.allowedDown), "No nodes are suspended");
// Another 30 minutes pass
tester.clock().advance(Duration.ofMinutes(30));
@@ -440,19 +442,19 @@ public class MetricsReporterTest {
// Dimensions used for node count metric are only known OS versions
Set<Version> versionDimensions = metrics.getMetrics((dimensions) -> true)
- .entrySet()
- .stream()
- .filter(kv -> kv.getValue().containsKey(MetricsReporter.OS_NODE_COUNT))
- .map(kv -> kv.getKey().getDimensions())
- .map(dimensions -> dimensions.get("currentVersion"))
- .map(Version::fromString)
- .collect(Collectors.toSet());
- assertTrue("Reports only OS versions", allVersions.containsAll(versionDimensions));
+ .entrySet()
+ .stream()
+ .filter(kv -> kv.getValue().containsKey(MetricsReporter.OS_NODE_COUNT))
+ .map(kv -> kv.getKey().getDimensions())
+ .map(dimensions -> dimensions.get("currentVersion"))
+ .map(Version::fromString)
+ .collect(Collectors.toSet());
+ assertTrue(allVersions.containsAll(versionDimensions), "Reports only OS versions");
}
}
@Test
- public void broken_system_version() {
+ void broken_system_version() {
var tester = new DeploymentTester().atMondayMorning();
var ctx = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder().upgradePolicy("canary").region("us-west-1").build();
@@ -485,7 +487,7 @@ public class MetricsReporterTest {
}
@Test
- public void tenant_counter() {
+ void tenant_counter() {
var tester = new ControllerTester(SystemName.Public);
tester.createTenant("foo", Tenant.Type.cloud);
tester.createTenant("bar", Tenant.Type.cloud);
@@ -501,17 +503,17 @@ public class MetricsReporterTest {
}
@Test
- public void overdue_upgrade_metric() {
+ void overdue_upgrade_metric() {
ApplicationPackage pkg = new ApplicationPackageBuilder().region("us-west-1")
- // window 1
- .blockChange(false, true, "mon-tue", "2-9", "CET")
- // window 2
- .blockChange(false, true, "mon-tue", "1-8,11-12", "CET")
- // window 3
- .blockChange(false, true, "wed-thu", "0-23", "CET")
- // window 4 (does not apply to upgrade)
- .blockChange(true, false, "mon-sun", "0-7", "CET")
- .build();
+ // window 1
+ .blockChange(false, true, "mon-tue", "2-9", "CET")
+ // window 2
+ .blockChange(false, true, "mon-tue", "1-8,11-12", "CET")
+ // window 3
+ .blockChange(false, true, "wed-thu", "0-23", "CET")
+ // window 4 (does not apply to upgrade)
+ .blockChange(true, false, "mon-sun", "0-7", "CET")
+ .build();
Instant mondayNight = Instant.parse("2021-12-13T23:30:00.00Z");
DeploymentTester tester = new DeploymentTester().at(mondayNight);
@@ -519,8 +521,8 @@ public class MetricsReporterTest {
DeploymentContext context = tester.newDeploymentContext();
Supplier<Duration> metric = () -> {
reporter.maintain();
- return Duration.ofSeconds(metrics.getMetric(context.instanceId(),MetricsReporter.DEPLOYMENT_OVERDUE_UPGRADE)
- .get().longValue());
+ return Duration.ofSeconds(metrics.getMetric(context.instanceId(), MetricsReporter.DEPLOYMENT_OVERDUE_UPGRADE)
+ .get().longValue());
};
// Deploy completely once
@@ -532,33 +534,33 @@ public class MetricsReporterTest {
// Start production job for upgrade, without completing it
context.runJob(systemTest)
- .runJob(stagingTest)
- .triggerJobs()
- .assertRunning(productionUsWest1);
- assertEquals("Upgrade is not overdue yet", Duration.ZERO, metric.get());
+ .runJob(stagingTest)
+ .triggerJobs()
+ .assertRunning(productionUsWest1);
+ assertEquals(Duration.ZERO, metric.get(), "Upgrade is not overdue yet");
// Upgrade continues into block window
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 00:30 (01:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(0).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(0).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 01:30 (02:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(1).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(1).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 02:30 (03:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(2).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(2).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(6)); // Tuesday at 08:30 (09:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 1", Duration.ofHours(8).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(8).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 1");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 09:30 (10:30 CET)
- assertEquals("Upgrade is no longer overdue", Duration.ZERO, metric.get());
+ assertEquals(Duration.ZERO, metric.get(), "Upgrade is no longer overdue");
tester.clock().advance(Duration.ofDays(2)); // Thursday at 10:30 (11:30 CET)
- assertEquals("Upgrade is overdue measure relative to window 3", Duration.ofHours(34).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(34).plusMinutes(30), metric.get(), "Upgrade is overdue measure relative to window 3");
}
@Test
- public void zms_quota_metrics() {
+ void zms_quota_metrics() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
reporter.maintain();
@@ -576,7 +578,7 @@ public class MetricsReporterTest {
.map(Number::longValue)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Expected to find metric for version " + version));
- assertEquals("Expected number of nodes are on " + version.toFullString(), n, nodeCount);
+ assertEquals(n, nodeCount, "Expected number of nodes are on " + version.toFullString());
}
private void assertPlatformNodeCount(int n, Version version) {
@@ -647,15 +649,13 @@ public class MetricsReporterTest {
private void assertPlatformChangeDuration(Duration duration, List<Node> nodes) {
for (var node : nodes) {
- assertEquals("Platform change duration of " + node.hostname(),
- duration, getChangeDuration(MetricsReporter.PLATFORM_CHANGE_DURATION, node.hostname()));
+ assertEquals(duration, getChangeDuration(MetricsReporter.PLATFORM_CHANGE_DURATION, node.hostname()), "Platform change duration of " + node.hostname());
}
}
private void assertOsChangeDuration(Duration duration, List<Node> nodes) {
for (var node : nodes) {
- assertEquals("OS change duration of " + node.hostname(),
- duration, getChangeDuration(MetricsReporter.OS_CHANGE_DURATION, node.hostname()));
+ assertEquals(duration, getChangeDuration(MetricsReporter.OS_CHANGE_DURATION, node.hostname()), "OS change duration of " + node.hostname());
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
index 300aa86b5ea..5ed441398fd 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
@@ -9,14 +9,20 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.OsRelease;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
import java.util.List;
+import java.util.Map;
+import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -24,10 +30,10 @@ import static org.junit.Assert.assertTrue;
public class OsUpgradeSchedulerTest {
@Test
- public void schedule_calendar_versioned_release() {
+ void schedule_calendar_versioned_release() {
ControllerTester tester = new ControllerTester();
OsUpgradeScheduler scheduler = new OsUpgradeScheduler(tester.controller(), Duration.ofDays(1));
- Instant t0 = Instant.parse("2021-01-23T00:00:00.00Z"); // Outside trigger period
+ Instant t0 = Instant.parse("2022-01-16T00:00:00.00Z"); // Outside trigger period
tester.clock().setInstant(t0);
CloudName cloud = CloudName.from("cloud");
@@ -36,10 +42,10 @@ public class OsUpgradeSchedulerTest {
// Initial run does nothing as the cloud does not have a target
scheduler.maintain();
- assertTrue("No target set", tester.controller().osVersionTarget(cloud).isEmpty());
+ assertTrue(tester.controller().osVersionTarget(cloud).isEmpty(), "No target set");
- // Target is set
- Version version0 = Version.fromString("7.0.0.20210123190005");
+ // Target is set manually
+ Version version0 = Version.fromString("7.0.0.20220101");
tester.controller().upgradeOsIn(cloud, version0, Duration.ofDays(1), false);
// Target remains unchanged as it hasn't expired yet
@@ -49,27 +55,40 @@ public class OsUpgradeSchedulerTest {
assertEquals(version0, tester.controller().osVersionTarget(cloud).get().osVersion().version());
}
- // Just over 45 days pass, and a new target replaces the expired one
- Version version1 = Version.fromString("7.0.0.20210302");
- tester.clock().advance(Duration.ofDays(15).plus(Duration.ofSeconds(1)));
+ // Enough days pass that the next release is triggered
+ Version version1 = Version.fromString("7.0.0.20220228");
+ tester.clock().advance(Duration.ofDays(30));
scheduler.maintain();
- assertEquals("Target is unchanged because we're outside trigger period", version0,
- tester.controller().osVersionTarget(cloud).get().osVersion().version());
- tester.clock().advance(Duration.ofHours(7)); // Put us inside the trigger period
+ assertEquals(version0,
+ tester.controller().osVersionTarget(cloud).get().osVersion().version(),
+ "Target is unchanged because we're outside trigger period");
+ tester.clock().advance(Duration.ofHours(9).plusMinutes(5)); // Put us inside the trigger period
+ assertEquals("2022-03-17T09:05:00", formatInstant(tester.clock().instant()));
+ Optional<OsUpgradeScheduler.Change> change = scheduler.changeIn(cloud);
+ assertTrue(change.isPresent());
+ assertEquals("2022-03-17T07:00:00", formatInstant(change.get().scheduleAt()));
scheduler.maintain();
- assertEquals("New target set", version1,
- tester.controller().osVersionTarget(cloud).get().osVersion().version());
+ assertEquals(version1,
+ tester.controller().osVersionTarget(cloud).get().osVersion().version(),
+ "New target set");
- // A few days pass and target remains unchanged
+ // A few more days pass and target remains unchanged
tester.clock().advance(Duration.ofDays(2));
scheduler.maintain();
assertEquals(version1, tester.controller().osVersionTarget(cloud).get().osVersion().version());
+
+ // Estimate next change
+ Optional<OsUpgradeScheduler.Change> nextChange = scheduler.changeIn(cloud);
+ assertTrue(nextChange.isPresent());
+ assertEquals("7.0.0.20220425", nextChange.get().version().toFullString());
+ assertEquals("2022-05-02T07:00:00", formatInstant(nextChange.get().scheduleAt()));
}
@Test
- public void schedule_stable_release() {
+ void schedule_stable_release() {
ControllerTester tester = new ControllerTester();
- Instant t0 = Instant.parse("2021-06-21T07:00:00.00Z"); // Inside trigger period
+ OsUpgradeScheduler scheduler = new OsUpgradeScheduler(tester.controller(), Duration.ofDays(1));
+ Instant t0 = Instant.parse("2021-06-21T06:00:00.00Z"); // Outside trigger period
tester.clock().setInstant(t0);
// Set initial target
@@ -77,23 +96,27 @@ public class OsUpgradeSchedulerTest {
Version version0 = Version.fromString("8.0");
tester.controller().upgradeOsIn(cloud, version0, Duration.ZERO, false);
- // Stable release is scheduled immediately
+ // Stable release is scheduled once trigger period opens
Version version1 = Version.fromString("8.1");
tester.serviceRegistry().artifactRepository().addRelease(new OsRelease(version1, OsRelease.Tag.stable,
- tester.clock().instant()));
- scheduleUpgradeAfter(Duration.ZERO, version1, tester);
+ tester.clock().instant()));
+ scheduleUpgradeAfter(Duration.ZERO, version0, scheduler, tester);
+ assertEquals(version1, scheduler.changeIn(cloud).get().version(), "Change available");
+ scheduleUpgradeAfter(Duration.ofHours(1), version1, scheduler, tester); // Inside trigger period
// A newer version is triggered manually
Version version3 = Version.fromString("8.3");
tester.controller().upgradeOsIn(cloud, version3, Duration.ZERO, false);
// Nothing happens in next iteration as tagged release is older than manually triggered version
- scheduleUpgradeAfter(Duration.ofDays(7), version3, tester);
+ scheduleUpgradeAfter(Duration.ofDays(7), version3, scheduler, tester);
+ assertTrue(scheduler.changeIn(cloud).isEmpty());
}
@Test
- public void schedule_latest_release_in_cd() {
+ void schedule_latest_release_in_cd() {
ControllerTester tester = new ControllerTester(SystemName.cd);
+ OsUpgradeScheduler scheduler = new OsUpgradeScheduler(tester.controller(), Duration.ofDays(1));
Instant t0 = Instant.parse("2021-06-21T07:00:00.00Z"); // Inside trigger period
tester.clock().setInstant(t0);
@@ -105,25 +128,47 @@ public class OsUpgradeSchedulerTest {
// Latest release is not scheduled immediately
Version version1 = Version.fromString("8.1");
tester.serviceRegistry().artifactRepository().addRelease(new OsRelease(version1, OsRelease.Tag.latest,
- tester.clock().instant()));
- scheduleUpgradeAfter(Duration.ZERO, version0, tester);
+ tester.clock().instant()));
+ assertEquals(version1, scheduler.changeIn(cloud).get().version(), "Change available");
+ scheduleUpgradeAfter(Duration.ZERO, version0, scheduler, tester);
// Cooldown period passes and latest release is scheduled
- scheduleUpgradeAfter(Duration.ofDays(1), version1, tester);
+ scheduleUpgradeAfter(Duration.ofDays(1), version1, scheduler, tester);
+ }
+
+ @Test
+ void schedule_of_calender_versioned_releases() {
+ Map<String, String> tests = Map.of("2022-01-01", "2021-12-27",
+ "2022-03-01", "2021-12-27",
+ "2022-03-02", "2022-02-28",
+ "2022-04-30", "2022-02-28",
+ "2022-05-01", "2022-04-25",
+ "2022-06-29", "2022-04-25",
+ "2022-07-01", "2022-06-27",
+ "2022-08-28", "2022-06-27",
+ "2022-08-29", "2022-08-29");
+ tests.forEach((now, expectedVersion) -> {
+ Instant instant = LocalDate.parse(now).atStartOfDay().toInstant(ZoneOffset.UTC);
+ LocalDate dateOfWantedVersion = OsUpgradeScheduler.CalendarVersionedRelease.dateOfWantedVersion(instant);
+ assertEquals(LocalDate.parse(expectedVersion), dateOfWantedVersion, "scheduled wanted version at " + now);
+ });
}
- private void scheduleUpgradeAfter(Duration duration, Version version, ControllerTester tester) {
+ private void scheduleUpgradeAfter(Duration duration, Version version, OsUpgradeScheduler scheduler, ControllerTester tester) {
tester.clock().advance(duration);
- new OsUpgradeScheduler(tester.controller(), Duration.ofDays(1)).maintain();
+ scheduler.maintain();
CloudName cloud = tester.controller().clouds().iterator().next();
OsVersionTarget target = tester.controller().osVersionTarget(cloud).get();
assertEquals(version, target.osVersion().version());
- assertEquals("No budget when scheduling a tagged release",
- Duration.ZERO, target.upgradeBudget());
+ assertEquals(Duration.ZERO, target.upgradeBudget(), "No budget when scheduling a tagged release");
}
private static ZoneApi zone(String id, CloudName cloud) {
return ZoneApiMock.newBuilder().withId(id).with(cloud).build();
}
+ private static String formatInstant(Instant instant) {
+ return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME);
+ }
+
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
index 3c3f0053e91..1c8a7ac641d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
@@ -3,7 +3,9 @@ package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
+import com.yahoo.config.provision.zone.NodeSlice;
import com.yahoo.config.provision.zone.UpgradePolicy;
+import com.yahoo.config.provision.zone.UpgradePolicy.Step;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.ControllerTester;
@@ -13,16 +15,18 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
+import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -33,7 +37,7 @@ public class OsUpgraderTest {
private final OsVersionStatusUpdater statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1));
@Test
- public void upgrade_os() {
+ void upgrade_os() {
CloudName cloud1 = CloudName.from("c1");
CloudName cloud2 = CloudName.from("c2");
ZoneApi zone0 = zone("prod.us-north-42", "prod.controller", cloud1);
@@ -45,25 +49,26 @@ public class OsUpgraderTest {
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
.upgrade(zone0)
.upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
+ .upgrade(Step.of(zone2, zone3).require(NodeSlice.minCount(1)))
.upgrade(zone5) // Belongs to a different cloud and is ignored by this upgrader
.upgrade(zone4)
.build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud1, false);
// Bootstrap system
- List<ZoneId> nonControllerZones = List.of(zone1, zone2, zone3, zone4, zone5).stream()
- .map(ZoneApi::getVirtualId)
- .collect(Collectors.toList());
+ List<ZoneId> nonControllerZones = Stream.of(zone1, zone2, zone3, zone4, zone5)
+ .map(ZoneApi::getVirtualId)
+ .collect(Collectors.toList());
tester.configServer().bootstrap(nonControllerZones, List.of(SystemApplication.tenantHost));
tester.configServer().addNodes(List.of(zone0.getVirtualId()), List.of(SystemApplication.controllerHost));
// Add system application that exists in a real system, but isn't eligible for OS upgrades
tester.configServer().addNodes(nonControllerZones, List.of(SystemApplication.configServer));
- // Fail a few nodes. Failed nodes should not affect versions
+ // Change state of a few nodes. These should not affect convergence
failNodeIn(zone1, SystemApplication.tenantHost);
failNodeIn(zone3, SystemApplication.tenantHost);
+ Node nodeDeferringOsUpgrade = deferOsUpgradeIn(zone2, SystemApplication.tenantHost);
// New OS version released
Version version1 = Version.fromString("7.1");
@@ -100,8 +105,14 @@ public class OsUpgraderTest {
// zone 4: still on previous version
assertWanted(Version.emptyVersion, SystemApplication.tenantHost, zone4);
- // zone 2 and 3: completes upgrade
- completeUpgrade(version1, SystemApplication.tenantHost, zone2, zone3);
+ // zone 2 and 3: enough nodes upgrade to satisfy node slice of this step
+ completeUpgrade(1, version1, SystemApplication.tenantHost, zone2);
+ completeUpgrade(1, version1, SystemApplication.tenantHost, zone3);
+ assertEquals(Version.emptyVersion,
+ nodeRepository().list(zone2.getVirtualId(), NodeFilter.all().hostnames(nodeDeferringOsUpgrade.hostname()))
+ .get(0)
+ .currentOsVersion(),
+ "Current version is unchanged for node deferring OS upgrade");
// zone 4: begins upgrading
osUpgrader.maintain();
@@ -110,16 +121,21 @@ public class OsUpgraderTest {
// zone 4: completes upgrade
completeUpgrade(version1, SystemApplication.tenantHost, zone4);
+ // zone 2 and 3: stragglers complete upgrade
+ completeUpgrade(version1, SystemApplication.tenantHost, zone2, zone3);
+
// Next run does nothing as all zones are upgraded
osUpgrader.maintain();
assertWanted(version1, SystemApplication.tenantHost, zone1, zone2, zone3, zone4);
statusUpdater.maintain();
- assertTrue("All nodes on target version", tester.controller().osVersionStatus().nodesIn(cloud1).stream()
- .allMatch(node -> node.currentVersion().equals(version1)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud1).stream()
+ .filter(node -> !node.hostname().equals(nodeDeferringOsUpgrade.hostname()))
+ .allMatch(node -> node.currentVersion().equals(version1)),
+ "All non-deferring nodes are on target version");
}
@Test
- public void upgrade_os_with_budget() {
+ void upgrade_os_with_budget() {
CloudName cloud = CloudName.from("cloud");
ZoneApi zone0 = zone("prod.us-north-42", "prod.controller", cloud);
ZoneApi zone1 = zone("dev.us-east-1", cloud);
@@ -127,17 +143,17 @@ public class OsUpgraderTest {
ZoneApi zone3 = zone("prod.us-central-1", cloud);
ZoneApi zone4 = zone("prod.eu-west-1", cloud);
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
- .upgrade(zone0)
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build();
+ .upgrade(zone0)
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud, true);
// Bootstrap system
List<SystemApplication> nodeTypes = List.of(SystemApplication.configServerHost, SystemApplication.tenantHost);
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId(), zone3.getId(), zone4.getId()),
- nodeTypes);
+ nodeTypes);
tester.configServer().addNodes(List.of(zone0.getVirtualId()), List.of(SystemApplication.controllerHost));
// Upgrade with budget
@@ -150,7 +166,7 @@ public class OsUpgraderTest {
// Controllers upgrade first
osUpgrader.maintain();
assertWanted(version, SystemApplication.controllerHost, zone0);
- assertEquals("Controller zone gets a zero budget", Duration.ZERO, upgradeBudget(zone0, SystemApplication.controllerHost, version));
+ assertEquals(Duration.ZERO, upgradeBudget(zone0, SystemApplication.controllerHost, version), "Controller zone gets a zero budget");
completeUpgrade(version, SystemApplication.controllerHost, zone0);
statusUpdater.maintain();
assertEquals(3, nodesOn(version).size());
@@ -158,16 +174,17 @@ public class OsUpgraderTest {
// First zone upgrades
osUpgrader.maintain();
for (var nodeType : nodeTypes) {
- assertEquals("Dev zone gets a zero budget", Duration.ZERO, upgradeBudget(zone1, nodeType, version));
+ assertEquals(Duration.ofHours(4), upgradeBudget(zone1, nodeType, version));
completeUpgrade(version, nodeType, zone1);
}
// Next set of zones upgrade
osUpgrader.maintain();
- for (var zone : List.of(zone2, zone3)) {
+ for (var zone : List.of(zone1, zone2, zone3)) {
for (var nodeType : nodeTypes) {
- assertEquals("Parallel prod zones share the budget of a single zone", Duration.ofHours(6),
- upgradeBudget(zone, nodeType, version));
+ assertEquals(Duration.ofHours(4),
+ upgradeBudget(zone, nodeType, version),
+ "Parallel prod zones share the budget of a single zone");
completeUpgrade(version, nodeType, zone);
}
}
@@ -175,31 +192,32 @@ public class OsUpgraderTest {
// Last zone upgrades
osUpgrader.maintain();
for (var nodeType : nodeTypes) {
- assertEquals(nodeType + " in last prod zone gets the budget of a single zone", Duration.ofHours(6),
- upgradeBudget(zone4, nodeType, version));
+ assertEquals(Duration.ofHours(4),
+ upgradeBudget(zone4, nodeType, version),
+ nodeType + " in last prod zone gets the budget of a single zone");
completeUpgrade(version, nodeType, zone4);
}
// All host applications upgraded
statusUpdater.maintain();
- assertTrue("All nodes on target version", tester.controller().osVersionStatus().nodesIn(cloud).stream()
- .allMatch(node -> node.currentVersion().equals(version)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud).stream()
+ .allMatch(node -> node.currentVersion().equals(version)), "All nodes on target version");
}
@Test
- public void upgrade_os_nodes_choose_newer_version() {
+ void upgrade_os_nodes_choose_newer_version() {
CloudName cloud = CloudName.from("cloud");
ZoneApi zone1 = zone("dev.us-east-1", cloud);
ZoneApi zone2 = zone("prod.us-west-1", cloud);
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
- .upgrade(zone1)
- .upgrade(zone2)
- .build();
+ .upgrade(zone1)
+ .upgrade(zone2)
+ .build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud, false);
// Bootstrap system
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId()),
- List.of(SystemApplication.tenantHost));
+ List.of(SystemApplication.tenantHost));
// New OS version released
Version version = Version.fromString("7.1");
@@ -211,28 +229,28 @@ public class OsUpgraderTest {
osUpgrader.maintain();
assertWanted(version, SystemApplication.tenantHost, zone1);
Version chosenVersion = Version.fromString("7.1.1"); // Upgrade mechanism chooses a slightly newer version
- completeUpgrade(version, chosenVersion, SystemApplication.tenantHost, zone1);
+ completeUpgrade(Integer.MAX_VALUE, version, chosenVersion, SystemApplication.tenantHost, zone1);
statusUpdater.maintain();
assertEquals(3, nodesOn(chosenVersion).size());
// zone 2 upgrades
osUpgrader.maintain();
assertWanted(version, SystemApplication.tenantHost, zone2);
- completeUpgrade(version, chosenVersion, SystemApplication.tenantHost, zone2);
+ completeUpgrade(Integer.MAX_VALUE, version, chosenVersion, SystemApplication.tenantHost, zone2);
statusUpdater.maintain();
assertEquals(6, nodesOn(chosenVersion).size());
// No more upgrades
osUpgrader.maintain();
assertWanted(version, SystemApplication.tenantHost, zone1, zone2);
- assertTrue("All nodes on target version or newer", tester.controller().osVersionStatus().nodesIn(cloud).stream()
- .noneMatch(node -> node.currentVersion().isBefore(version)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud).stream()
+ .noneMatch(node -> node.currentVersion().isBefore(version)), "All nodes on target version or newer");
}
private Duration upgradeBudget(ZoneApi zone, SystemApplication application, Version version) {
var upgradeBudget = tester.configServer().nodeRepository().osUpgradeBudget(zone.getVirtualId(), application.nodeType(), version);
- assertTrue("Expected budget for upgrade to " + version + " of " + application.id() + " in " + zone.getVirtualId(),
- upgradeBudget.isPresent());
+ assertTrue(upgradeBudget.isPresent(),
+ "Expected budget for upgrade to " + version + " of " + application.id() + " in " + zone.getVirtualId());
return upgradeBudget.get();
}
@@ -249,9 +267,10 @@ public class OsUpgraderTest {
private void assertWanted(Version version, SystemApplication application, ZoneApi... zones) {
for (var zone : zones) {
- assertEquals("Target version set for " + application + " in " + zone.getVirtualId(), version,
+ assertEquals(version,
nodeRepository().targetVersionsOf(zone.getVirtualId()).osVersion(application.nodeType())
- .orElse(Version.emptyVersion));
+ .orElse(Version.emptyVersion),
+ "Target version set for " + application + " in " + zone.getVirtualId());
}
}
@@ -259,7 +278,7 @@ public class OsUpgraderTest {
ZoneApi... zones) {
for (ZoneApi zone : zones) {
for (Node node : nodesRequiredToUpgrade(zone, application)) {
- assertEquals(application + " version in " + zone, version, versionField.apply(node));
+ assertEquals(version, versionField.apply(node), application + " version in " + zone.getId());
}
}
}
@@ -267,33 +286,55 @@ public class OsUpgraderTest {
private List<Node> nodesRequiredToUpgrade(ZoneApi zone, SystemApplication application) {
return nodeRepository().list(zone.getVirtualId(), NodeFilter.all().applications(application.id()))
.stream()
- .filter(OsUpgrader::canUpgrade)
+ .filter(node -> OsUpgrader.canUpgrade(node, false))
.collect(Collectors.toList());
}
- private void failNodeIn(ZoneApi zone, SystemApplication application) {
+ private Node failNodeIn(ZoneApi zone, SystemApplication application) {
+ return patchOneNodeIn(zone, application, (node) -> Node.builder(node).state(Node.State.failed).build());
+ }
+
+ private Node deferOsUpgradeIn(ZoneApi zone, SystemApplication application) {
+ return patchOneNodeIn(zone, application, (node) -> Node.builder(node).deferOsUpgrade(true).build());
+ }
+
+ private Node patchOneNodeIn(ZoneApi zone, SystemApplication application, UnaryOperator<Node> patcher) {
List<Node> nodes = nodeRepository().list(zone.getVirtualId(), NodeFilter.all().applications(application.id()));
if (nodes.isEmpty()) {
throw new IllegalArgumentException("No nodes allocated to " + application.id());
}
Node node = nodes.get(0);
- nodeRepository().putNodes(zone.getVirtualId(), Node.builder(node).state(Node.State.failed).build());
+ Node newNode = patcher.apply(node);
+ nodeRepository().putNodes(zone.getVirtualId(), newNode);
+ return newNode;
}
/** Simulate OS upgrade of nodes allocated to application. In a real system this is done by the node itself */
private void completeUpgrade(Version version, SystemApplication application, ZoneApi... zones) {
- completeUpgrade(version, version, application, zones);
+ completeUpgrade(-1, version, application, zones);
}
- private void completeUpgrade(Version wantedVersion, Version version, SystemApplication application, ZoneApi... zones) {
+ private void completeUpgrade(int nodeCount, Version version, SystemApplication application, ZoneApi... zones) {
+ completeUpgrade(nodeCount, version, version, application, zones);
+ }
+
+ private void completeUpgrade(int nodeCount, Version wantedVersion, Version version, SystemApplication application, ZoneApi... zones) {
assertWanted(wantedVersion, application, zones);
for (ZoneApi zone : zones) {
- for (Node node : nodesRequiredToUpgrade(zone, application)) {
+ int nodesUpgraded = 0;
+ List<Node> nodes = nodesRequiredToUpgrade(zone, application);
+ for (Node node : nodes) {
+ if (node.currentVersion().equals(wantedVersion)) continue;
nodeRepository().putNodes(zone.getVirtualId(), Node.builder(node).wantedOsVersion(version)
.currentOsVersion(version)
.build());
+ if (++nodesUpgraded == nodeCount) {
+ break;
+ }
+ }
+ if (nodesUpgraded == nodes.size()) {
+ assertCurrent(version, application, zone);
}
- assertCurrent(version, application, zone);
}
}
@@ -302,7 +343,7 @@ public class OsUpgraderTest {
}
private OsUpgrader osUpgrader(UpgradePolicy upgradePolicy, CloudName cloud, boolean reprovisionToUpgradeOs) {
- var zones = upgradePolicy.steps().stream().flatMap(Collection::stream).collect(Collectors.toList());
+ var zones = upgradePolicy.steps().stream().map(Step::zones).flatMap(Collection::stream).collect(Collectors.toList());
tester.zoneRegistry()
.setZones(zones)
.setOsUpgradePolicy(cloud, upgradePolicy);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
index f2d738bd2e1..0bd3810e9a4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
@@ -8,14 +8,14 @@ import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class OsVersionStatusUpdaterTest {
@Test
- public void test_update() {
+ void test_update() {
ControllerTester tester = new ControllerTester();
OsVersionStatusUpdater statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1)
);
@@ -45,8 +45,8 @@ public class OsVersionStatusUpdaterTest {
var osVersions = tester.controller().osVersionStatus().versions();
assertEquals(2, osVersions.size());
- assertFalse("All nodes on unknown version", osVersions.get(new OsVersion(Version.emptyVersion, cloud)).isEmpty());
- assertTrue("No nodes on current target", osVersions.get(new OsVersion(version1, cloud)).isEmpty());
+ assertFalse(osVersions.get(new OsVersion(Version.emptyVersion, cloud)).isEmpty(), "All nodes on unknown version");
+ assertTrue(osVersions.get(new OsVersion(version1, cloud)).isEmpty(), "No nodes on current target");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
index e989486c595..9b2a1607e76 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue;
public class OutstandingChangeDeployerTest {
@Test
- public void testChangeDeployer() {
+ void testChangeDeployer() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
index 53e7dd7ca58..b0601dcd880 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
@@ -6,7 +6,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing.Cluster;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -22,13 +22,13 @@ import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.THURSDAY;
import static java.time.DayOfWeek.TUESDAY;
import static java.time.DayOfWeek.WEDNESDAY;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ReindexingTriggererTest {
@Test
- public void testWindowOfOpportunity() {
+ void testWindowOfOpportunity() {
Duration interval = Duration.ofHours(1);
Instant now = Instant.now();
Instant doom = now.plus(ReindexingTriggerer.reindexingPeriod);
@@ -43,42 +43,42 @@ public class ReindexingTriggererTest {
now = now.plus(interval);
}
// Summer/winter time :'(
- assertTrue("Should be in window of opportunity three to five times each period", 3 <= triggered && triggered <= 5);
+ assertTrue(3 <= triggered && triggered <= 5, "Should be in window of opportunity three to five times each period");
}
@Test
- public void testReindexingIsReady() {
+ void testReindexingIsReady() {
Instant then = Instant.now();
ApplicationReindexing reindexing = new ApplicationReindexing(true,
- Map.of("c", new Cluster(Map.of(), Map.of("d", new Status(then)))));
+ Map.of("c", new Cluster(Map.of(), Map.of("d", new Status(then)))));
Instant now = then;
- assertFalse("Should not be ready less than one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready less than one half-period after last triggering");
now = now.plus(reindexingPeriod.dividedBy(2));
- assertFalse("Should not be ready one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready one half-period after last triggering");
now = now.plusMillis(1);
- assertTrue("Should be ready more than one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertTrue(reindexingIsReady(reindexing, now),
+ "Should be ready more than one half-period after last triggering");
reindexing = new ApplicationReindexing(true,
- Map.of("cluster",
- new Cluster(Map.of(),
- Map.of("type",
- new Status(then, then, null, null, null, null, 1.0)))));
- assertFalse("Should not be ready when reindexing is already running",
- reindexingIsReady(reindexing, now));
+ Map.of("cluster",
+ new Cluster(Map.of(),
+ Map.of("type",
+ new Status(then, then, null, null, null, null, 1.0)))));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready when reindexing is already running");
reindexing = new ApplicationReindexing(true,
- Map.of("cluster",
- new Cluster(Map.of("type", 123L),
- Map.of("type",
- new Status(then, then, now, null, null, null, 1.0)))));
- assertTrue("Should be ready when reindexing is no longer running",
- reindexingIsReady(reindexing, now));
+ Map.of("cluster",
+ new Cluster(Map.of("type", 123L),
+ Map.of("type",
+ new Status(then, then, now, null, null, null, 1.0)))));
+ assertTrue(reindexingIsReady(reindexing, now),
+ "Should be ready when reindexing is no longer running");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
index a8d39438654..1f92c7f6e41 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
@@ -18,7 +18,7 @@ import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -29,9 +29,9 @@ import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author olaa
@@ -45,7 +45,7 @@ public class ResourceMeterMaintainerTest {
new ResourceMeterMaintainer(tester.controller(), Duration.ofMinutes(5), metrics, resourceClient);
@Test
- public void updates_deployment_costs() {
+ void updates_deployment_costs() {
ApplicationId app1 = ApplicationId.from("t1", "a1", "default");
ApplicationId app2 = ApplicationId.from("t2", "a1", "default");
ZoneId z1 = ZoneId.from("prod.aws-us-east-1c");
@@ -79,13 +79,13 @@ public class ResourceMeterMaintainerTest {
assertEquals(1.72,
(Double) metrics.getMetric(context ->
z1.value().equals(context.get("zoneId")) &&
- app1.tenant().value().equals(context.get("tenant")),
+ app1.tenant().value().equals(context.get("tenant")),
"metering.cost.hourly").get(),
Double.MIN_VALUE);
}
@Test
- public void testMaintainer() {
+ void testMaintainer() {
setUpZones();
long lastRefreshTime = tester.clock().millis();
tester.curator().writeMeteringRefreshTime(lastRefreshTime);
@@ -105,7 +105,7 @@ public class ResourceMeterMaintainerTest {
assertEquals(24, app2.getMemoryGb(), Double.MIN_VALUE);
assertEquals(500, app2.getDiskGb(), Double.MIN_VALUE);
- assertEquals(tester.clock().millis()/1000, metrics.getMetric("metering_last_reported"));
+ assertEquals(tester.clock().millis() / 1000, metrics.getMetric("metering_last_reported"));
assertEquals(2224.0d, (Double) metrics.getMetric("metering_total_reported"), Double.MIN_VALUE);
assertEquals(24d, (Double) metrics.getMetric(context -> "tenant1".equals(context.get("tenant")), "metering.vcpu").get(), Double.MIN_VALUE);
assertEquals(40d, (Double) metrics.getMetric(context -> "tenant2".equals(context.get("tenant")), "metering.vcpu").get(), Double.MIN_VALUE);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
index 1a6976034c5..0068f15ed46 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
@@ -10,14 +10,14 @@ import com.yahoo.vespa.hosted.controller.api.integration.aws.MockResourceTagger;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.controller.maintenance.ResourceTagMaintainer.SHARED_HOST_APPLICATION;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -27,12 +27,12 @@ public class ResourceTagMaintainerTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void maintain() {
+ void maintain() {
setUpZones();
MockResourceTagger mockResourceTagger = new MockResourceTagger();
ResourceTagMaintainer resourceTagMaintainer = new ResourceTagMaintainer(tester.controller(),
- Duration.ofMinutes(5),
- mockResourceTagger);
+ Duration.ofMinutes(5),
+ mockResourceTagger);
resourceTagMaintainer.maintain();
assertEquals(2, mockResourceTagger.getValues().size());
Map<HostName, ApplicationId> applicationForHost = mockResourceTagger.getValues().get(ZoneId.from("prod.region-2"));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
index bebecf8b52b..69301ea91ef 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.deployment.RetriggerEntry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -25,7 +25,7 @@ public class RetriggerMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void processes_queue() throws IOException {
+ void processes_queue() throws IOException {
RetriggerMaintainer maintainer = new RetriggerMaintainer(tester.controller(), Duration.ofDays(1));
ApplicationId applicationId = ApplicationId.from("tenant", "app", "default");
var devApp = tester.newDeploymentContext(applicationId);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
index c09d3ec3a92..7426e0dd23b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
@@ -19,9 +19,9 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -36,19 +36,19 @@ public class SystemUpgraderTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void upgrade_system() {
+ void upgrade_system() {
SystemUpgrader systemUpgrader = systemUpgrader(
UpgradePolicy.builder()
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build()
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build()
);
Version version1 = Version.fromString("6.5");
// Bootstrap a system without host applications
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId(), zone3.getId(), zone4.getId()),
- SystemApplication.configServer, SystemApplication.proxy);
+ SystemApplication.configServer, SystemApplication.proxy);
// Fail a few nodes. Failed nodes should not affect versions
failNodeIn(zone1, SystemApplication.configServer);
failNodeIn(zone3, SystemApplication.proxy);
@@ -68,58 +68,63 @@ public class SystemUpgraderTest {
assertWantedVersion(SystemApplication.configServer, version2, zone1);
// Other zones remain on previous version
assertWantedVersion(SystemApplication.configServer, version1, zone2, zone3, zone4);
- // Zone application is not upgraded yet
+ // Proxy application is not upgraded yet
assertWantedVersion(SystemApplication.proxy, version1, zone1, zone2, zone3, zone4);
- // zone1: zone-config-server upgrades
+ // zone1: config server upgrades and proxy application
completeUpgrade(SystemApplication.configServer, version2, zone1);
+ systemUpgrader.maintain();
- // zone 1: proxy-application upgrades
+ // zone 1: proxy application upgrades
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.proxy, version2, zone1);
completeUpgrade(SystemApplication.proxy, version2, zone1);
- assertTrue("Deployed proxy application",
- tester.configServer().application(SystemApplication.proxy.id(), zone1.getId()).isPresent());
+ assertTrue(tester.configServer().application(SystemApplication.proxy.id(), zone1.getId()).isPresent(),
+ "Deployed proxy application");
// zone 2, 3 and 4: still targets old version
assertWantedVersion(SystemApplication.configServer, version1, zone2, zone3, zone4);
assertWantedVersion(SystemApplication.proxy, version1, zone2, zone3, zone4);
- // zone 2 and 3: upgrade does not start until zone 1 zone-application config converges
+ // zone 2 and 3: upgrade does not start until zone 1 proxy application config converges
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.configServer, version1, zone2, zone3);
convergeServices(SystemApplication.proxy, zone1);
- // zone 2 and 3: zone-config-server upgrades, first in zone 2, then in zone 3
+ // zone 2 and 3: config server upgrades, first in zone 2, then in zone 3
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.configServer, version2, zone2, zone3);
assertWantedVersion(SystemApplication.configServer, version1, zone4);
assertWantedVersion(SystemApplication.proxy, version1, zone2, zone3, zone4);
completeUpgrade(SystemApplication.configServer, version2, zone2);
- // zone-application starts upgrading in zone 2, while zone-config-server completes upgrade in zone 3
+ // proxy application starts upgrading in zone 2, while config server completes upgrade in zone 3
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.proxy, version2, zone2);
assertWantedVersion(SystemApplication.proxy, version1, zone3);
completeUpgrade(SystemApplication.configServer, version2, zone3);
- // zone 2 and 3: proxy-application upgrades in parallel
+ // zone 2 and 3: proxy application upgrades in parallel
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.proxy, version2, zone2, zone3);
completeUpgrade(SystemApplication.proxy, version2, zone2, zone3);
convergeServices(SystemApplication.proxy, zone2, zone3);
- // zone 4: zone-config-server upgrades
+ // zone 4: config server upgrades
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.configServer, version2, zone4);
assertWantedVersion(SystemApplication.proxy, version1, zone4);
- completeUpgrade(SystemApplication.configServer, version2, zone4);
+ // zone 4: proxy application does not upgrade until all config servers are done
+ completeUpgrade(2, SystemApplication.configServer, version2, zone4);
+ systemUpgrader.maintain();
+ assertWantedVersion(SystemApplication.proxy, version1, zone4);
+ completeUpgrade(1, SystemApplication.configServer, version2, zone4);
// System version remains unchanged until final application upgrades
tester.computeVersionStatus();
assertSystemVersion(version1);
- // zone 4: proxy-application upgrades
+ // zone 4: proxy application upgrades
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.proxy, version2, zone4);
completeUpgrade(SystemApplication.proxy, version2, zone4);
@@ -138,12 +143,12 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_controller_with_non_converging_application() {
+ void upgrade_controller_with_non_converging_application() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).build());
// Bootstrap system
tester.configServer().bootstrap(List.of(zone1.getId()), SystemApplication.configServer,
- SystemApplication.proxy);
+ SystemApplication.proxy);
Version version1 = Version.fromString("6.5");
tester.upgradeSystem(version1);
@@ -157,7 +162,7 @@ public class SystemUpgraderTest {
systemUpgrader.maintain();
completeUpgrade(SystemApplication.proxy, version2, zone1);
tester.computeVersionStatus();
- assertSystemVersion(version1); // Unchanged until proxy-application converges
+ assertSystemVersion(version1); // Unchanged until proxy application converges
// Controller upgrades again
Version version3 = Version.fromString("6.7");
@@ -165,7 +170,7 @@ public class SystemUpgraderTest {
assertSystemVersion(version1);
assertControllerVersion(version3);
- // zone 1: proxy-application converges and system version changes
+ // zone 1: proxy application converges and system version changes
convergeServices(SystemApplication.proxy, zone1);
tester.computeVersionStatus();
assertSystemVersion(version2);
@@ -173,13 +178,13 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_system_containing_host_applications() {
+ void upgrade_system_containing_host_applications() {
SystemUpgrader systemUpgrader = systemUpgrader(
UpgradePolicy.builder()
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build()
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build()
);
Version version1 = Version.fromString("6.5");
@@ -196,9 +201,9 @@ public class SystemUpgraderTest {
// System upgrades in zone 1:
systemUpgrader.maintain();
List<SystemApplication> allExceptZone = List.of(SystemApplication.configServerHost,
- SystemApplication.configServer,
- SystemApplication.proxyHost,
- SystemApplication.tenantHost);
+ SystemApplication.configServer,
+ SystemApplication.proxyHost,
+ SystemApplication.tenantHost);
completeUpgrade(allExceptZone, version2, zone1);
systemUpgrader.maintain();
completeUpgrade(SystemApplication.proxy, version2, zone1);
@@ -225,7 +230,7 @@ public class SystemUpgraderTest {
}
@Test
- public void downgrading_controller_never_downgrades_system() {
+ void downgrading_controller_never_downgrades_system() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).build());
Version version = Version.fromString("6.5");
@@ -244,7 +249,7 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_halts_on_broken_version() {
+ void upgrade_halts_on_broken_version() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).build());
// Initial system version
@@ -252,11 +257,11 @@ public class SystemUpgraderTest {
tester.upgradeSystem(version1);
systemUpgrader.maintain();
assertCurrentVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy),
- version1, zone1);
+ SystemApplication.configServer, SystemApplication.proxy),
+ version1, zone1);
assertCurrentVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy),
- version1, zone2);
+ SystemApplication.configServer, SystemApplication.proxy),
+ version1, zone2);
// System starts upgrading to next version
Version version2 = Version.fromString("6.6");
@@ -273,13 +278,13 @@ public class SystemUpgraderTest {
overrideConfidence(version2, VespaVersion.Confidence.broken);
systemUpgrader.maintain();
assertWantedVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy), version1, zone2);
+ SystemApplication.configServer, SystemApplication.proxy), version1, zone2);
}
@Test
- public void does_not_deploy_proxy_app_in_zone_without_shared_routing() {
+ void does_not_deploy_proxy_app_in_zone_without_shared_routing() {
var applications = List.of(SystemApplication.configServerHost, SystemApplication.configServer,
- SystemApplication.tenantHost);
+ SystemApplication.tenantHost);
tester.configServer().bootstrap(List.of(zone1.getId()), applications);
tester.configServer().disallowConvergenceCheck(SystemApplication.proxy.id());
tester.zoneRegistry().exclusiveRoutingIn(zone1);
@@ -301,7 +306,7 @@ public class SystemUpgraderTest {
}
@Test
- public void downgrade_from_aborted_version() {
+ void downgrade_from_aborted_version() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).upgrade(zone3).build());
Version version1 = Version.fromString("6.5");
@@ -319,9 +324,9 @@ public class SystemUpgraderTest {
for (var zone : List.of(zone1, zone2)) {
systemUpgrader.maintain();
completeUpgrade(List.of(SystemApplication.tenantHost,
- SystemApplication.proxyHost,
- SystemApplication.configServerHost),
- version2, zone);
+ SystemApplication.proxyHost,
+ SystemApplication.configServerHost),
+ version2, zone);
completeUpgrade(SystemApplication.configServer, version2, zone);
systemUpgrader.maintain();
completeUpgrade(SystemApplication.proxy, version2, zone);
@@ -336,12 +341,12 @@ public class SystemUpgraderTest {
for (var zone : List.of(zone2, zone1)) {
systemUpgrader.maintain();
completeUpgrade(List.of(SystemApplication.tenantHost,
- SystemApplication.configServerHost,
- SystemApplication.proxy),
- version1, zone);
+ SystemApplication.configServerHost,
+ SystemApplication.proxy),
+ version1, zone);
convergeServices(SystemApplication.proxy, zone);
List<SystemApplication> lastToDowngrade = List.of(SystemApplication.configServer,
- SystemApplication.proxyHost);
+ SystemApplication.proxyHost);
assertWantedVersion(lastToDowngrade, version2, zone);
// ... and then configserver and proxyhost
@@ -359,7 +364,8 @@ public class SystemUpgraderTest {
try {
overrideConfidence(version3, VespaVersion.Confidence.aborted);
fail("Expected exception");
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.notController(), version3, zone1, zone2, zone3);
}
@@ -369,16 +375,28 @@ public class SystemUpgraderTest {
tester.computeVersionStatus();
}
- /** Simulate upgrade of nodes allocated to given application. In a real system this is done by the node itself */
private void completeUpgrade(SystemApplication application, Version version, ZoneApi first, ZoneApi... rest) {
+ completeUpgrade(-1, application, version, first, rest);
+ }
+
+ /** Simulate upgrade of nodes allocated to given application. In a real system this is done by the node itself */
+ private void completeUpgrade(int nodeCount, SystemApplication application, Version version, ZoneApi first, ZoneApi... rest) {
assertWantedVersion(application, version, first, rest);
Stream.concat(Stream.of(first), Stream.of(rest)).forEach(zone -> {
- for (Node node : listNodes(zone, application)) {
+ int nodesUpgraded = 0;
+ List<Node> nodes = listNodes(zone, application);
+ for (Node node : nodes) {
+ if (node.currentVersion().equals(node.wantedVersion())) continue;
nodeRepository().putNodes(
zone.getId(),
Node.builder(node).currentVersion(node.wantedVersion()).build());
+ if (++nodesUpgraded == nodeCount) {
+ break;
+ }
+ }
+ if (nodesUpgraded == nodes.size()) {
+ assertCurrentVersion(application, version, zone);
}
- assertCurrentVersion(application, version, zone);
});
}
@@ -414,8 +432,9 @@ public class SystemUpgraderTest {
private void assertWantedVersion(SystemApplication application, Version version, ZoneApi first, ZoneApi... rest) {
Stream.concat(Stream.of(first), Stream.of(rest)).forEach(zone -> {
if (!application.hasApplicationPackage()) {
- assertEquals("Target version set for " + application + " in " + zone.getId(), version,
- nodeRepository().targetVersionsOf(zone.getId()).vespaVersion(application.nodeType()).orElse(Version.emptyVersion));
+ assertEquals(version,
+ nodeRepository().targetVersionsOf(zone.getId()).vespaVersion(application.nodeType()).orElse(Version.emptyVersion),
+ "Target version set for " + application + " in " + zone.getId());
}
assertVersion(application, version, Node::wantedVersion, zone);
});
@@ -437,7 +456,7 @@ public class SystemUpgraderTest {
ZoneApi first, ZoneApi... rest) {
Stream.concat(Stream.of(first), Stream.of(rest)).forEach(zone -> {
for (Node node : listNodes(zone, application)) {
- assertEquals("Version of " + application.id() + " in " + zone.getId(), version, versionField.apply(node));
+ assertEquals(version, versionField.apply(node), "Version of " + application.id() + " in " + zone.getId());
}
});
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
index 7026d975010..97656583d04 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mortent
@@ -25,11 +25,11 @@ public class TenantRoleMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void maintains_iam_roles_for_tenants_in_production() {
+ void maintains_iam_roles_for_tenants_in_production() {
var devAppTenant1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodAppTenant2 = tester.newDeploymentContext("tenant2", "app2", "default");
- var devAppTenant2 = tester.newDeploymentContext("tenant2","app3","default");
- var perfAppTenant1 = tester.newDeploymentContext("tenant3","app1","default");
+ var devAppTenant2 = tester.newDeploymentContext("tenant2", "app3", "default");
+ var perfAppTenant1 = tester.newDeploymentContext("tenant3", "app1", "default");
ApplicationPackage appPackage = new ApplicationPackageBuilder()
.region("us-west-1")
.build();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
index c59155cb162..07ea04b4c84 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
@@ -10,12 +10,12 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the traffic fraction updater. This also tests its dependency on DeploymentMetricsMaintainer.
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertEquals;
public class TrafficShareUpdaterTest {
@Test
- public void testTrafficUpdater() {
+ void testTrafficUpdater() {
DeploymentTester tester = new DeploymentTester();
var application = tester.newDeploymentContext();
var deploymentMetricsMaintainer = new DeploymentMetricsMaintainer(tester.controller(), Duration.ofDays(1));
@@ -70,7 +70,7 @@ public class TrafficShareUpdaterTest {
assertTrafficFraction(0.47, 0.50, application.instanceId(), prod2, tester);
assertTrafficFraction(0.00, 0.50, application.instanceId(), prod3, tester);
// - all hot
- setQpsMetric( 50.0, application.application().id().defaultInstance(), prod1, tester);
+ setQpsMetric(50.0, application.application().id().defaultInstance(), prod1, tester);
setQpsMetric(25.0, application.application().id().defaultInstance(), prod2, tester);
setQpsMetric(25.0, application.application().id().defaultInstance(), prod3, tester);
deploymentMetricsMaintainer.maintain();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
index 3b21d3a017e..b24b6c8e99b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
@@ -13,9 +13,10 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
+import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -37,9 +38,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.sys
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.ALL;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PIN;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PLATFORM;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -49,13 +50,13 @@ public class UpgraderTest {
private final DeploymentTester tester = new DeploymentTester().atMondayMorning();
@Test
- public void testUpgrading() {
+ void testUpgrading() {
// --- Setup
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No applications: Nothing to do");
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -67,7 +68,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "All already on the right version: Nothing to do");
// --- Next version released - everything goes smoothly
Version version1 = Version.fromString("6.3");
@@ -76,14 +77,14 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version1);
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version1);
@@ -91,7 +92,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
+ assertEquals(6, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.deployPlatform(version1);
default1.deployPlatform(version1);
@@ -101,13 +102,13 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.high, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Normals done: Should upgrade conservatives");
conservative0.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Nothing to do");
// --- Next version released - which fails a Canary
Version version2 = Version.fromString("6.4");
@@ -116,7 +117,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.runJob(systemTest);
canary0.failDeployment(stagingTest);
@@ -124,7 +125,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Version broken, but Canaries should keep trying", 3, tester.jobs().active().size());
+ assertEquals(3, tester.jobs().active().size(), "Version broken, but Canaries should keep trying");
// --- Next version released - which repairs the Canary app and fails a default
Version version3 = Version.fromString("6.5");
@@ -136,14 +137,14 @@ public class UpgraderTest {
canary1.abortJob(stagingTest);
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version3);
assertEquals(version3, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version3);
@@ -152,7 +153,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
+ assertEquals(6, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.runJob(systemTest);
default0.failDeployment(stagingTest);
@@ -160,11 +161,10 @@ public class UpgraderTest {
default2.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
- assertEquals("Not enough evidence to mark this as neither broken nor high",
- VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
+ assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence(), "Not enough evidence to mark this as neither broken nor high");
tester.triggerJobs();
- assertEquals("Upgrade with error should retry", 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), "Upgrade with error should retry");
// --- Failing application is repaired by changing the application, causing confidence to move above 'high' threshold
// Deploy application change
@@ -175,13 +175,13 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.high, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Normals done: Should upgrade conservatives");
conservative0.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Applications are on " + version3 + " - nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Applications are on " + version3 + " - nothing to do");
// --- Starting upgrading to a new version which breaks, causing upgrades to commence on the previous version
var default3 = createAndDeploy("default3", "default");
@@ -197,7 +197,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade of defaults are scheduled");
for (var context : List.of(default0, default1, default2, default3, default4))
assertEquals(version4, context.instance().change().platform().get());
@@ -215,7 +215,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade of defaults are scheduled");
assertEquals(version5, default0.instance().change().platform().get());
for (var context : List.of(default1, default2, default3, default4))
assertEquals(version4, context.instance().change().platform().get());
@@ -253,17 +253,17 @@ public class UpgraderTest {
}
@Test
- public void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
+ void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
// --- Setup
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No system version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No system version: Nothing to do");
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No applications: Nothing to do");
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -281,7 +281,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "All already on the right version: Nothing to do");
// --- A new version is released
version = Version.fromString("6.3");
@@ -290,14 +290,14 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version);
assertEquals(version, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version);
@@ -305,7 +305,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 20, tester.jobs().active().size());
+ assertEquals(20, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.deployPlatform(version);
for (var context : List.of(default1, default2, default3, default4))
@@ -317,7 +317,7 @@ public class UpgraderTest {
tester.abortAll();
tester.triggerJobs();
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
- assertEquals("Upgrades are cancelled", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Upgrades are cancelled");
}
// Scenario:
@@ -327,7 +327,7 @@ public class UpgraderTest {
// V2 is marked as broken and upgrade of A to V2 is cancelled.
// Upgrade of A to V1 is scheduled: Should skip the zone on V2 but upgrade the next zone to V1
@Test
- public void testVersionIsBrokenAfterAZoneIsLive() {
+ void testVersionIsBrokenAfterAZoneIsLive() {
Version v0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v0);
@@ -382,8 +382,8 @@ public class UpgraderTest {
// Applications with default policy start upgrading to V2
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade scheduled for remaining apps", 10, tester.jobs().active().size());
- assertEquals("default4 is still upgrading to 6.3", v1, default4.instance().change().platform().get());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade scheduled for remaining apps");
+ assertEquals(v1, default4.instance().change().platform().get(), "default4 is still upgrading to 6.3");
// 4/5 applications fail (in the last prod zone) and lowers confidence
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
@@ -399,20 +399,19 @@ public class UpgraderTest {
tester.abortAll();
tester.triggerJobs();
- assertEquals("Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2");
// prod zone on 5.2 (usWest1) is skipped, but we still trigger the next zone from triggerReadyJobs:
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
// Resulting state:
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
- assertEquals("Last zone is upgraded to v1",
- v1, default0.deployment(ZoneId.from("prod.us-east-3")).version());
+ assertEquals(v1, default0.deployment(ZoneId.from("prod.us-east-3")).version(), "Last zone is upgraded to v1");
assertFalse(default0.instance().change().hasTargets());
}
@Test
- public void testConfidenceIgnoresFailingApplicationChanges() {
+ void testConfidenceIgnoresFailingApplicationChanges() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -458,7 +457,7 @@ public class UpgraderTest {
}
@Test
- public void testBlockVersionChange() {
+ void testBlockVersionChange() {
// Tuesday, 18:00
tester.at(Instant.parse("2017-09-26T18:00:00.00Z"));
Version version = Version.fromString("6.2");
@@ -480,25 +479,25 @@ public class UpgraderTest {
// Application is not upgraded at this time
tester.upgrader().maintain();
tester.triggerJobs();
- assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No jobs scheduled");
// One hour passes, time is 19:00, still no upgrade
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
- assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No jobs scheduled");
// Two hours pass in total, time is 20:00 and application upgrades
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
- assertFalse("Job is scheduled", tester.jobs().active().isEmpty());
+ assertFalse(tester.jobs().active().isEmpty(), "Job is scheduled");
app.deployPlatform(version);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockVersionChangeHalfwayThough() {
+ void testBlockVersionChangeHalfwayThough() {
// Tuesday, 17:00
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -531,11 +530,11 @@ public class UpgraderTest {
assertEquals(1, tester.jobs().active().size()); // Next job triggered because upgrade is already rolling out.
app.runJob(productionUsCentral1).runJob(productionUsEast3);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockVersionChangeHalfwayThroughThenNewRevision() {
+ void testBlockVersionChangeHalfwayThroughThenNewRevision() {
// Friday, 16:00
tester.at(Instant.parse("2017-09-29T16:00:00.00Z"));
@@ -599,12 +598,12 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsCentral1)
- .runJob(stagingTest)
- .runJob(productionUsEast3);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ .runJob(stagingTest)
+ .runJob(productionUsWest1)
+ .runJob(productionUsCentral1)
+ .runJob(stagingTest)
+ .runJob(productionUsEast3);
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
// App is completely upgraded to the latest version
for (Deployment deployment : app.instance().deployments().values())
@@ -612,7 +611,7 @@ public class UpgraderTest {
}
@Test
- public void testThrottlesUpgrades() {
+ void testThrottlesUpgrades() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -631,7 +630,7 @@ public class UpgraderTest {
// Dev deployment which should be ignored
var dev0 = tester.newDeploymentContext("tenant1", "dev0", "default")
- .runJob(devUsEast1, DeploymentContext.applicationPackage());
+ .runJob(devUsEast1, DeploymentContext.applicationPackage());
// New version is released and canaries upgrade
version = Version.fromString("6.3");
@@ -660,13 +659,13 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInDeploymentXml() {
+ void testPinningMajorVersionInDeploymentXml() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version6ApplicationPackage = new ApplicationPackageBuilder().majorVersion(6)
- .region("us-west-1")
- .build();
+ .region("us-west-1")
+ .build();
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -692,7 +691,7 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInApplication() {
+ void testPinningMajorVersionInApplication() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -700,7 +699,7 @@ public class UpgraderTest {
var canary0 = createAndDeploy("canary", "canary");
var default0 = tester.newDeploymentContext().submit().deploy();
tester.applications().lockApplicationOrThrow(default0.application().id(),
- a -> tester.applications().store(a.withMajorVersion(6)));
+ a -> tester.applications().store(a.withMajorVersion(6)));
assertEquals(OptionalInt.of(6), default0.application().majorVersion());
// New major version is released
@@ -723,20 +722,20 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInUpgrader() {
+ void testPinningMajorVersionInUpgrader() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version7CanaryApplicationPackage = new ApplicationPackageBuilder()
- .majorVersion(7)
- .upgradePolicy("canary")
- .region("us-west-1")
- .build();
+ .majorVersion(7)
+ .upgradePolicy("canary")
+ .region("us-west-1")
+ .build();
ApplicationPackage version7DefaultApplicationPackage = new ApplicationPackageBuilder()
- .majorVersion(7)
- .upgradePolicy("default")
- .region("us-west-1")
- .build();
+ .majorVersion(7)
+ .upgradePolicy("default")
+ .region("us-west-1")
+ .build();
// Setup applications
var canary0 = tester.newDeploymentContext("tenant1", "canary0", "default").submit(version7CanaryApplicationPackage).deploy();
@@ -744,7 +743,7 @@ public class UpgraderTest {
var default1 = tester.newDeploymentContext("tenant1", "default1", "default").submit(DeploymentContext.applicationPackage()).deploy();
// New major version is released, but we don't want to upgrade to it yet
- tester.upgrader().setTargetMajorVersion(Optional.of(6));
+ tester.upgrader().setTargetMajorVersion(OptionalInt.of(6));
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().readVersionStatus().systemVersion().get().versionNumber());
@@ -769,7 +768,7 @@ public class UpgraderTest {
assertEquals(0, tester.jobs().active().size());
// Now we want to upgrade the latest application
- tester.upgrader().setTargetMajorVersion(Optional.empty());
+ tester.upgrader().setTargetMajorVersion(OptionalInt.empty());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
@@ -777,7 +776,7 @@ public class UpgraderTest {
}
@Test
- public void testAllowApplicationChangeDuringFailingUpgrade() {
+ void testAllowApplicationChangeDuringFailingUpgrade() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -796,15 +795,15 @@ public class UpgraderTest {
RevisionId revision = app.lastSubmission().get();
// Application change recorded together with ongoing upgrade
- assertTrue("Change contains both upgrade and application change",
- app.instance().change().platform().get().equals(version) &&
- app.instance().change().revision().get().equals(revision));
+ assertTrue(app.instance().change().platform().get().equals(version) &&
+ app.instance().change().revision().get().equals(revision),
+ "Change contains both upgrade and application change");
// Deployment completes
app.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsEast3);
- assertEquals("All jobs consumed", List.of(), tester.jobs().active());
+ .runJob(productionUsWest1)
+ .runJob(productionUsEast3);
+ assertEquals(List.of(), tester.jobs().active(), "All jobs consumed");
for (Deployment deployment : app.instance().deployments().values()) {
assertEquals(version, deployment.version());
@@ -813,7 +812,7 @@ public class UpgraderTest {
}
@Test
- public void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
+ void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
// Tuesday, 17:00.
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -851,11 +850,11 @@ public class UpgraderTest {
// Upgrade may start, now that revision is rolled out.
tester.upgrader().maintain();
app.deployPlatform(version);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
+ void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
// Tuesday, 17:00.
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -900,7 +899,7 @@ public class UpgraderTest {
}
@Test
- public void testPinning() {
+ void testPinning() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
@@ -938,7 +937,7 @@ public class UpgraderTest {
// Application fails upgrade after one zone is complete, and is pinned again to the old version.
context.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1)
- .timeOutUpgrade(productionUsWest1);
+ .timeOutUpgrade(productionUsWest1);
tester.deploymentTrigger().cancelChange(context.instanceId(), ALL);
tester.deploymentTrigger().forceChange(context.instanceId(), Change.of(version0).withPin());
assertEquals(version0, context.instance().change().platform().get());
@@ -952,12 +951,12 @@ public class UpgraderTest {
}
@Test
- public void upgradesToLatestAllowedMajor() {
+ void upgradesToLatestAllowedMajor() {
Version version0 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(version0);
// Apps target 6 by default
- tester.upgrader().setTargetMajorVersion(Optional.of(6));
+ tester.upgrader().setTargetMajorVersion(OptionalInt.of(6));
// All applications deploy on current version
var app1 = createAndDeploy("app1", "default");
@@ -966,7 +965,7 @@ public class UpgraderTest {
// Keep app 1 on current version
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.with(app1.instance().name(),
- instance -> instance.withChange(instance.change().withPin()))));
+ instance -> instance.withChange(instance.change().withPin()))));
// New version is released
Version version1 = Version.fromString("6.2");
@@ -988,14 +987,69 @@ public class UpgraderTest {
// App 1 is unpinned and upgrades to latest 6
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.with(app1.instance().name(),
- instance -> instance.withChange(instance.change().withoutPin()))));
+ instance -> instance.withChange(instance.change().withoutPin()))));
tester.upgrader().maintain();
- assertEquals("Application upgrades to latest allowed major", version1,
- app1.instance().change().platform().orElseThrow());
+ assertEquals(version1,
+ app1.instance().change().platform().orElseThrow(),
+ "Application upgrades to latest allowed major");
+ }
+
+ @Test
+ void testSettingFailingRevisionAside() {
+ DeploymentContext app = tester.newDeploymentContext().submit().deploy();
+
+ // New revision fails.
+ app.submit();
+ Optional<RevisionId> revision1 = app.lastSubmission();
+ app.failDeployment(systemTest);
+
+ // New version is not targeted.
+ Version version1 = new Version("7");
+ tester.controllerTester().upgradeSystem(version1);
+ assertEquals(Change.of(revision1.get()), app.instance().change());
+
+ tester.upgrader().run();
+ assertEquals(Change.of(revision1.get()), app.instance().change());
+
+ // Broken revision is replaced by a new attempt, which also fails, and cancellation is not yet triggered.
+ tester.clock().advance(DeploymentTrigger.maxFailingRevisionTime.plusSeconds(1));
+ app.submit();
+ Optional<RevisionId> revision2 = app.lastSubmission();
+ app.failDeployment(systemTest);
+ tester.upgrader().run();
+ assertEquals(Change.of(revision2.get()), app.instance().change());
+
+ // Broken revision is cancelled, and new version targeted, after some time.
+ tester.clock().advance(DeploymentTrigger.maxFailingRevisionTime.plusSeconds(1));
+ tester.upgrader().run();
+ assertEquals(Change.of(version1), app.instance().change());
+
+ // Broken revision is not targeted again.
+ app.triggerJobs();
+ tester.upgrader().run();
+ tester.outstandingChangeDeployer().run();
+ assertEquals(Change.of(version1), app.instance().change());
+
+ app.failDeployment(systemTest);
+ tester.upgrader().run();
+ tester.outstandingChangeDeployer().run();
+ assertEquals(Change.of(version1), app.instance().change());
+
+ // Revision gets a second change when upgrade fixes the failing job.
+ tester.clock().advance(Duration.ofDays(12)); // Time for retries.
+ app.runJob(systemTest).jobAborted(stagingTest).runJob(stagingTest).runJob(productionUsCentral1);
+ tester.upgrader().run();
+ tester.outstandingChangeDeployer().run();
+
+ assertEquals(Change.of(version1).with(revision2.get()), app.instance().change());
+ app.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1); // Revision rolls.
+ app.runJob(productionUsEast3).runJob(productionUsWest1); // Upgrade completes.
+ app.runJob(productionUsEast3).runJob(productionUsWest1); // Revision completes.
+ assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void testsEachUpgradeCombinationWithFailingDeployments() {
+ void testsEachUpgradeCombinationWithFailingDeployments() {
Version v1 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(v1);
@@ -1050,11 +1104,11 @@ public class UpgraderTest {
// Upgrade completes
application.runJob(productionUsEast3);
- assertTrue("Upgrade complete", application.instance().change().isEmpty());
+ assertTrue(application.instance().change().isEmpty(), "Upgrade complete");
}
@Test
- public void testUpgradesPerMinute() {
+ void testUpgradesPerMinute() {
assertEquals(0, Upgrader.numberOfApplicationsToUpgrade(10, 0, 0));
for (long now = 0; now < 60_000; now++)
@@ -1075,17 +1129,17 @@ public class UpgraderTest {
}
@Test
- public void testUpgradeShuffling() {
+ void testUpgradeShuffling() {
// Deploy applications on initial version
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var applications = Map.of(default0.instanceId(), default0,
- default1.instanceId(), default1,
- default2.instanceId(), default2);
+ default1.instanceId(), default1,
+ default2.instanceId(), default2);
// Throttle upgrades per run
- ((ManualClock) tester.controller().clock()).setInstant(Instant.ofEpochMilli(1589787109000L)); // Fixed random seed
+ ((ManualClock) tester.controller().clock()).setInstant(Instant.ofEpochMilli(1589787107000L)); // Fixed random seed
Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10));
upgrader.setUpgradesPerMinute(0.1);
@@ -1102,10 +1156,10 @@ public class UpgraderTest {
upgrader.maintain();
tester.triggerJobs();
Set<ApplicationId> triggered = tester.jobs().active().stream()
- .map(Run::id)
- .map(RunId::application)
- .collect(Collectors.toSet());
- assertEquals("Expected number of applications is triggered", 1, triggered.size());
+ .map(Run::id)
+ .map(RunId::application)
+ .collect(Collectors.toSet());
+ assertEquals(1, triggered.size(), "Expected number of applications is triggered");
ApplicationId application = triggered.iterator().next();
upgraderOrder.add(application);
applications.get(application).completeRollout();
@@ -1113,7 +1167,7 @@ public class UpgraderTest {
}
upgradeOrders.add(upgraderOrder);
}
- assertEquals("Upgrade orders are distinct", versions.size(), upgradeOrders.size());
+ assertEquals(versions.size(), upgradeOrders.size(), "Upgrade orders are distinct");
}
private static final ApplicationPackage canaryApplicationPackage =
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
index c1a9559ac46..4fe04b25577 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.config.provision.SystemName;
import com.yahoo.vespa.hosted.controller.ControllerTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -19,7 +19,7 @@ public class UserManagementMaintainerTest {
private final String APP_NAME = "some-app";
@Test
- public void deletes_tenant_when_not_public() {
+ void deletes_tenant_when_not_public() {
var tester = createTester(SystemName.main);
var maintainer = new UserManagementMaintainer(tester.controller(), Duration.ofMinutes(5), tester.serviceRegistry().roleMaintainer());
maintainer.maintain();
@@ -32,7 +32,7 @@ public class UserManagementMaintainerTest {
}
@Test
- public void no_tenant_deletion_in_public() {
+ void no_tenant_deletion_in_public() {
var tester = createTester(SystemName.Public);
var maintainer = new UserManagementMaintainer(tester.controller(), Duration.ofMinutes(5), tester.serviceRegistry().roleMaintainer());
maintainer.maintain();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
index bfbd3836ce7..52bd8e9c618 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
@@ -14,9 +14,10 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.HostAction.State;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VcmrReport;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest.Status;
+import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.DayOfWeek;
import java.time.Duration;
@@ -25,9 +26,10 @@ import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static com.yahoo.vespa.hosted.controller.maintenance.VcmrMaintainer.TRACKED_CMRS_METRIC;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author olaa
@@ -37,6 +39,7 @@ public class VcmrMaintainerTest {
private ControllerTester tester;
private VcmrMaintainer maintainer;
private NodeRepositoryMock nodeRepo;
+ private MetricsMock metrics;
private final ZoneId zoneId = ZoneId.from("prod.us-east-3");
private final ZoneId zone2 = ZoneId.from("prod.us-west-1");
private final HostName host1 = HostName.of("host1");
@@ -44,23 +47,24 @@ public class VcmrMaintainerTest {
private final HostName host3 = HostName.of("host3");
private final String changeRequestId = "id123";
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester();
- maintainer = new VcmrMaintainer(tester.controller(), Duration.ofMinutes(1));
+ metrics = new MetricsMock();
+ maintainer = new VcmrMaintainer(tester.controller(), Duration.ofMinutes(1), metrics);
nodeRepo = tester.serviceRegistry().configServer().nodeRepository().allowPatching(true);
}
@Test
- public void recycle_hosts_after_completion() {
+ void recycle_hosts_after_completion() {
var vcmrReport = new VcmrReport();
vcmrReport.addVcmr("id123", ZonedDateTime.now(), ZonedDateTime.now());
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, true);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
var reports = vcmrReport.toNodeReports();
parkedNode = Node.builder(parkedNode)
- .reports(reports)
- .build();
+ .reports(reports)
+ .build();
nodeRepo.putNodes(zoneId, List.of(parkedNode, failedNode));
@@ -79,7 +83,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void infrastructure_hosts_require_maunal_intervention() {
+ void infrastructure_hosts_require_maunal_intervention() {
var configNode = createNode(host1, NodeType.config, Node.State.active, false);
var activeNode = createNode(host2, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, List.of(configNode, activeNode));
@@ -99,7 +103,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void retires_hosts_when_near_vcmr() {
+ void retires_hosts_when_near_vcmr() {
var activeNode = createNode(host1, NodeType.host, Node.State.active, false);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
nodeRepo.putNodes(zoneId, List.of(activeNode, failedNode));
@@ -121,7 +125,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void no_spare_capacity_requires_operator_action() {
+ void no_spare_capacity_requires_operator_action() {
var activeNode = createNode(host1, NodeType.host, Node.State.active, false);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
nodeRepo.putNodes(zoneId, List.of(activeNode, failedNode));
@@ -143,7 +147,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void updates_status_when_retiring_host_is_parked() {
+ void updates_status_when_retiring_host_is_parked() {
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, true);
nodeRepo.putNodes(zoneId, parkedNode);
nodeRepo.hasSpareCapacity(true);
@@ -158,7 +162,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void pending_retirement_when_vcmr_is_far_ahead() {
+ void pending_retirement_when_vcmr_is_far_ahead() {
var activeNode = createNode(host2, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, List.of(activeNode));
nodeRepo.hasSpareCapacity(true);
@@ -177,13 +181,13 @@ public class VcmrMaintainerTest {
activeNode = nodeRepo.list(zoneId, NodeFilter.all().hostnames(host2)).get(0);
var report = VcmrReport.fromReports(activeNode.reports());
var reportAdded = report.getVcmrs().stream()
- .filter(vcmr -> vcmr.getId().equals(changeRequestId))
- .count() == 1;
+ .filter(vcmr -> vcmr.getId().equals(changeRequestId))
+ .count() == 1;
assertTrue(reportAdded);
}
@Test
- public void recycles_nodes_if_vcmr_is_postponed() {
+ void recycles_nodes_if_vcmr_is_postponed() {
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, false);
var retiringNode = createNode(host2, NodeType.host, Node.State.active, true);
nodeRepo.putNodes(zoneId, List.of(parkedNode, retiringNode));
@@ -206,7 +210,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void handle_multizone_vcmr() {
+ void handle_multizone_vcmr() {
var configNode = createNode(host1, NodeType.config, Node.State.active, false);
var tenantNode1 = createNode(host2, NodeType.host, Node.State.active, false);
var tenantNode2 = createNode(host3, NodeType.host, Node.State.active, false);
@@ -230,7 +234,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void out_of_sync_when_manual_reactivation() {
+ void out_of_sync_when_manual_reactivation() {
var nonRetiringNode = createNode(host1, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, nonRetiringNode);
@@ -244,10 +248,12 @@ public class VcmrMaintainerTest {
assertEquals(State.OUT_OF_SYNC, action.getState());
assertEquals(Status.OUT_OF_SYNC, writtenChangeRequest.getStatus());
+ assertEquals(1, metrics.getMetric(context -> "OUT_OF_SYNC".equals(context.get("status")), TRACKED_CMRS_METRIC).get());
+ assertEquals(0, metrics.getMetric(context -> "REQUIRES_OPERATOR_ACTION".equals(context.get("status")), TRACKED_CMRS_METRIC).get());
}
@Test
- public void retirement_start_time_ignores_weekends() {
+ void retirement_start_time_ignores_weekends() {
var plannedStartTime = ZonedDateTime.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));
var retirementStartTime = maintainer.getRetirementStartTime(plannedStartTime);
assertEquals(plannedStartTime.minusDays(2), retirementStartTime);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
index d85ec868d56..e6f46e0630d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
@@ -5,15 +5,15 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.organization.SystemMonitor;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -23,7 +23,7 @@ public class VersionStatusUpdaterTest {
/** Test that this job updates the status. Test of the content of the update is in
* {@link com.yahoo.vespa.hosted.controller.versions.VersionStatusTest} */
@Test
- public void testVersionUpdating() {
+ void testVersionUpdating() {
ControllerTester tester = new ControllerTester();
tester.controller().updateVersionStatus(new VersionStatus(Collections.emptyList()));
assertFalse(tester.controller().readVersionStatus().systemVersion().isPresent());
@@ -35,7 +35,7 @@ public class VersionStatusUpdaterTest {
}
@Test
- public void testConfidenceConversion() {
+ void testConfidenceConversion() {
List.of(VespaVersion.Confidence.values()).forEach(VersionStatusUpdater::convert);
assertEquals(SystemMonitor.Confidence.broken, VersionStatusUpdater.convert(VespaVersion.Confidence.broken));
assertEquals(SystemMonitor.Confidence.low, VersionStatusUpdater.convert(VespaVersion.Confidence.low));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
index c643a612f00..164df0a27f5 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
@@ -13,12 +13,12 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author enygaard
@@ -35,7 +35,7 @@ public class NotificationFormatterTest {
private final NotificationFormatter formatter = new NotificationFormatter(zoneRegistry);
@Test
- public void applicationPackage() {
+ void applicationPackage() {
var notification = new Notification(Instant.now(), Notification.Type.applicationPackage, Notification.Level.warning, NotificationSource.from(applicationId), List.of("1", "2"));
var content = formatter.format(notification);
assertEquals("Application package", content.prettyType());
@@ -44,7 +44,7 @@ public class NotificationFormatterTest {
}
@Test
- public void deployment() {
+ void deployment() {
var runId = new RunId(applicationId, JobType.prod(RegionName.defaultName()), 1001);
var notification = new Notification(Instant.now(), Notification.Type.deployment, Notification.Level.warning, NotificationSource.from(runId), List.of("1"));
var content = formatter.format(notification);
@@ -54,7 +54,7 @@ public class NotificationFormatterTest {
}
@Test
- public void deploymentError() {
+ void deploymentError() {
var runId = new RunId(applicationId, JobType.prod(RegionName.defaultName()), 1001);
var notification = new Notification(Instant.now(), Notification.Type.deployment, Notification.Level.error, NotificationSource.from(runId), List.of("1"));
var content = formatter.format(notification);
@@ -64,7 +64,7 @@ public class NotificationFormatterTest {
}
@Test
- public void testPackage() {
+ void testPackage() {
var notification = new Notification(Instant.now(), Notification.Type.testPackage, Notification.Level.warning, NotificationSource.from(TenantAndApplicationId.from(applicationId)), List.of("1"));
var content = formatter.format(notification);
assertEquals("Test package", content.prettyType());
@@ -73,7 +73,7 @@ public class NotificationFormatterTest {
}
@Test
- public void reindex() {
+ void reindex() {
var notification = new Notification(Instant.now(), Notification.Type.reindex, Notification.Level.info, NotificationSource.from(deploymentId, cluster), List.of("1"));
var content = formatter.format(notification);
assertEquals("Reindex", content.prettyType());
@@ -82,7 +82,7 @@ public class NotificationFormatterTest {
}
@Test
- public void feedBlock() {
+ void feedBlock() {
var notification = new Notification(Instant.now(), Notification.Type.feedBlock, Notification.Level.warning, NotificationSource.from(deploymentId, cluster), List.of("1"));
var content = formatter.format(notification);
assertEquals("Nearly feed blocked", content.prettyType());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
index 5666f8bafd8..4c1344650f8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -39,9 +39,9 @@ import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Level;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Type;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -61,7 +61,8 @@ public class NotificationsDbTest {
List.of(TenantContacts.Audience.NOTIFICATIONS),
email)))),
List.of(),
- new ArchiveAccess());
+ new ArchiveAccess(),
+ Optional.empty());
private static final List<Notification> notifications = List.of(
notification(1001, Type.deployment, Level.error, NotificationSource.from(tenant), "tenant msg"),
notification(1101, Type.applicationPackage, Level.warning, NotificationSource.from(TenantAndApplicationId.from(tenant.value(), "app1")), "app msg"),
@@ -77,7 +78,7 @@ public class NotificationsDbTest {
private final NotificationsDb notificationsDb = new NotificationsDb(clock, curatorDb, new Notifier(curatorDb, new ZoneRegistryMock(SystemName.cd), mailer, flagSource));
@Test
- public void list_test() {
+ void list_test() {
assertEquals(notifications, notificationsDb.listNotifications(NotificationSource.from(tenant), false));
assertEquals(notificationIndices(0, 1, 2, 3), notificationsDb.listNotifications(NotificationSource.from(tenant), true));
assertEquals(notificationIndices(2, 3), notificationsDb.listNotifications(NotificationSource.from(TenantAndApplicationId.from(tenant.value(), "app2")), false));
@@ -87,7 +88,7 @@ public class NotificationsDbTest {
}
@Test
- public void add_test() {
+ void add_test() {
Notification notification1 = notification(12345, Type.deployment, Level.warning, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg #2");
Notification notification2 = notification(12345, Type.deployment, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), "instance msg #3");
@@ -103,11 +104,11 @@ public class NotificationsDbTest {
}
@Test
- public void notifier_test() {
+ void notifier_test() {
Notification notification1 = notification(12345, Type.deployment, Level.warning, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg #2");
Notification notification2 = notification(12345, Type.applicationPackage, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), "instance msg #3");
Notification notification3 = notification(12345, Type.reindex, Level.warning, NotificationSource.from(new DeploymentId(ApplicationId.from(tenant.value(), "app2", "instance2"), ZoneId.defaultId()), new ClusterSpec.Id("content")), "instance msg #2");
-;
+ ;
var a = notifications.get(0);
notificationsDb.setNotification(a.source(), a.type(), a.level(), a.messages());
assertEquals(0, mailer.inbox(email).size());
@@ -126,7 +127,7 @@ public class NotificationsDbTest {
}
@Test
- public void remove_single_test() {
+ void remove_single_test() {
// Remove the 3rd notification
notificationsDb.removeNotification(NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), Type.deployment);
@@ -137,7 +138,7 @@ public class NotificationsDbTest {
}
@Test
- public void remove_multiple_test() {
+ void remove_multiple_test() {
// Remove the 3rd notification
notificationsDb.removeNotifications(NotificationSource.from(ApplicationId.from(tenant.value(), "app1", "instance1")));
assertEquals(notificationIndices(0, 1, 2, 3), curatorDb.readNotifications(tenant));
@@ -149,7 +150,7 @@ public class NotificationsDbTest {
}
@Test
- public void deployment_metrics_notify_test() {
+ void deployment_metrics_notify_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
List<Notification> expected = new ArrayList<>(notifications);
@@ -172,7 +173,7 @@ public class NotificationsDbTest {
}
@Test
- public void feed_blocked_single_cluster_test() {
+ void feed_blocked_single_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
List<Notification> expected = new ArrayList<>(notifications);
@@ -207,7 +208,7 @@ public class NotificationsDbTest {
}
@Test
- public void deployment_metrics_multiple_cluster_test() {
+ void deployment_metrics_multiple_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
NotificationSource sourceCluster2 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster2"));
@@ -231,7 +232,7 @@ public class NotificationsDbTest {
assertEquals(expected, curatorDb.readNotifications(tenant));
}
- @Before
+ @BeforeEach
public void init() {
curatorDb.writeNotifications(tenant, notifications);
curatorDb.writeTenant(cloudTenant);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
index 8bf0e584892..7c07192d633 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
@@ -16,17 +16,15 @@ import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NotifierTest {
private static final TenantName tenant = TenantName.from("tenant1");
@@ -43,18 +41,19 @@ public class NotifierTest {
List.of(TenantContacts.Audience.NOTIFICATIONS),
email)))),
List.of(),
- new ArchiveAccess());
+ new ArchiveAccess(),
+ Optional.empty());
MockCuratorDb curatorDb = new MockCuratorDb(SystemName.Public);
- @Before
+ @BeforeEach
public void init() {
curatorDb.writeTenant(cloudTenant);
}
@Test
- public void dispatch() {
+ void dispatch() {
var mailer = new MockMailer();
var flagSource = new InMemoryFlagSource().withBooleanFlag(Flags.NOTIFICATION_DISPATCH_FLAG.id(), true);
var notifier = new Notifier(curatorDb, new ZoneRegistryMock(SystemName.cd), mailer, flagSource);
@@ -68,20 +67,28 @@ public class NotifierTest {
var mail = mailer.inbox(email).get(0);
assertEquals("[WARNING] Test package Vespa Notification for tenant1.default.default", mail.subject());
- assertEquals("There are problems with tests for default.default<br>\n" +
- "<ul>\n" +
- "<li>test package has production tests, but no production tests are declared in deployment.xml</li><br>\n" +
- "<li>see <a href=\"https://docs.vespa.ai/en/testing.html\">https://docs.vespa.ai/en/testing.html</a> for details on how to write system tests for Vespa</li></ul>\n" +
- "<br>\n" +
- "<a href=\"https://dashboard.tld/tenant1/default\">Vespa Console</a>",
+ assertEquals("""
+ <div style="background: #00598c; height: 55px; width: 100%">
+ <img
+ src="https://vespa.ai/assets/vespa-logo.png"
+ style="width: auto; height: 34px; margin: 10px"
+ />
+ </div>
+ <br>
+ There are problems with tests for default.default<br>
+ <ul>
+ <li>test package has production tests, but no production tests are declared in deployment.xml</li><br>
+ <li>see <a href="https://docs.vespa.ai/en/testing.html">https://docs.vespa.ai/en/testing.html</a> for details on how to write system tests for Vespa</li></ul>
+ <br>
+ <a href="https://dashboard.tld/tenant1/default">Vespa Console</a>""",
mail.htmlMessage().get());
}
@Test
- public void linkify() {
+ void linkify() {
var data = Map.of(
"Hello. https://example.com/foo/bar.html is a nice place.", "Hello. <a href=\"https://example.com/foo/bar.html\">https://example.com/foo/bar.html</a> is a nice place.",
"No url.", "No url.");
data.forEach((input, expected) -> assertEquals(expected, Notifier.linkify(input)));
}
-} \ No newline at end of file
+}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
index e60325a140a..88da698b3f2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
@@ -30,7 +30,7 @@ import com.yahoo.vespa.hosted.controller.metric.ApplicationMetrics;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationState;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -47,7 +47,7 @@ import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -70,18 +70,18 @@ public class ApplicationSerializerTest {
@Test
- public void testSerialization() throws Exception {
+ void testSerialization() throws Exception {
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml("<deployment version='1.0'>\n" +
- " <staging/>\n" +
- " <instance id=\"i1\">\n" +
- " <prod global-service-id=\"default\">\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " </instance>\n" +
- "</deployment>");
+ " <staging/>\n" +
+ " <instance id=\"i1\">\n" +
+ " <prod global-service-id=\"default\">\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ "</deployment>");
ValidationOverrides validationOverrides = ValidationOverrides.fromXml("<validation-overrides version='1.0'>" +
- " <allow until='2017-06-15'>deployment-removal</allow>" +
- "</validation-overrides>");
+ " <allow until='2017-06-15'>deployment-removal</allow>" +
+ "</validation-overrides>");
OptionalLong projectId = OptionalLong.of(123L);
@@ -89,69 +89,69 @@ public class ApplicationSerializerTest {
ApplicationId id3 = ApplicationId.from("t1", "a1", "i3");
List<Deployment> deployments = new ArrayList<>();
ApplicationVersion applicationVersion1 = new ApplicationVersion(RevisionId.forProduction(31),
- Optional.of(new SourceRevision("git@github:org/repo.git", "branch1", "commit1")),
- Optional.of("william@shakespeare"),
- Optional.of(Version.fromString("1.2.3")),
- Optional.of(Instant.ofEpochMilli(666)),
- Optional.empty(),
- Optional.of("best commit"),
- Optional.of("hash1"),
- true,
- false,
- Optional.of("~(˘▾˘)~"),
- 3);
+ Optional.of(new SourceRevision("git@github:org/repo.git", "branch1", "commit1")),
+ Optional.of("william@shakespeare"),
+ Optional.of(Version.fromString("1.2.3")),
+ Optional.of(Instant.ofEpochMilli(666)),
+ Optional.empty(),
+ Optional.of("best commit"),
+ Optional.of("hash1"),
+ true,
+ false,
+ Optional.of("~(˘▾˘)~"),
+ 3);
assertEquals("https://github/org/repo/tree/commit1", applicationVersion1.sourceUrl().get());
ApplicationVersion applicationVersion2 = ApplicationVersion.from(RevisionId.forDevelopment(31, new JobId(id1, DeploymentContext.productionUsEast3)),
- new SourceRevision("repo1", "branch1", "commit1"), "a@b",
- Version.fromString("6.3.1"),
- Instant.ofEpochMilli(496));
+ new SourceRevision("repo1", "branch1", "commit1"), "a@b",
+ Version.fromString("6.3.1"),
+ Instant.ofEpochMilli(496));
Instant activityAt = Instant.parse("2018-06-01T10:15:30.00Z");
deployments.add(new Deployment(zone1, applicationVersion1.id(), Version.fromString("1.2.3"), Instant.ofEpochMilli(3),
- DeploymentMetrics.none, DeploymentActivity.none, QuotaUsage.none, OptionalDouble.empty()));
+ DeploymentMetrics.none, DeploymentActivity.none, QuotaUsage.none, OptionalDouble.empty()));
deployments.add(new Deployment(zone2, applicationVersion2.id(), Version.fromString("1.2.3"), Instant.ofEpochMilli(5),
- new DeploymentMetrics(2, 3, 4, 5, 6,
- Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)),
- Map.of(DeploymentMetrics.Warning.all, 3)),
- DeploymentActivity.create(Optional.of(activityAt), Optional.of(activityAt),
- OptionalDouble.of(200), OptionalDouble.of(10)),
- QuotaUsage.create(OptionalDouble.of(23.5)),
- OptionalDouble.of(12.3)));
+ new DeploymentMetrics(2, 3, 4, 5, 6,
+ Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)),
+ Map.of(DeploymentMetrics.Warning.all, 3)),
+ DeploymentActivity.create(Optional.of(activityAt), Optional.of(activityAt),
+ OptionalDouble.of(200), OptionalDouble.of(10)),
+ QuotaUsage.create(OptionalDouble.of(23.5)),
+ OptionalDouble.of(12.3)));
var rotationStatus = RotationStatus.from(Map.of(new RotationId("my-rotation"),
- new RotationStatus.Targets(
- Map.of(ZoneId.from("prod", "us-west-1"), RotationState.in,
- ZoneId.from("prod", "us-east-3"), RotationState.out),
- Instant.ofEpochMilli(42))));
+ new RotationStatus.Targets(
+ Map.of(ZoneId.from("prod", "us-west-1"), RotationState.in,
+ ZoneId.from("prod", "us-east-3"), RotationState.out),
+ Instant.ofEpochMilli(42))));
RevisionHistory revisions = RevisionHistory.ofRevisions(List.of(applicationVersion1),
- Map.of(new JobId(id1, DeploymentContext.productionUsEast3), List.of(applicationVersion2)));
+ Map.of(new JobId(id1, DeploymentContext.productionUsEast3), List.of(applicationVersion2)));
List<Instance> instances = List.of(new Instance(id1,
- deployments,
- Map.of(DeploymentContext.systemTest, Instant.ofEpochMilli(333)),
- List.of(AssignedRotation.fromStrings("foo", "default", "my-rotation", Set.of("us-west-1"))),
- rotationStatus,
- Change.of(new Version("6.1"))),
- new Instance(id3,
- List.of(),
- Map.of(),
- List.of(),
- RotationStatus.EMPTY,
- Change.of(Version.fromString("6.7")).withPin()));
+ deployments,
+ Map.of(DeploymentContext.systemTest, Instant.ofEpochMilli(333)),
+ List.of(AssignedRotation.fromStrings("foo", "default", "my-rotation", Set.of("us-west-1"))),
+ rotationStatus,
+ Change.of(new Version("6.1"))),
+ new Instance(id3,
+ List.of(),
+ Map.of(),
+ List.of(),
+ RotationStatus.EMPTY,
+ Change.of(Version.fromString("6.7")).withPin()));
Application original = new Application(TenantAndApplicationId.from(id1),
- Instant.now().truncatedTo(ChronoUnit.MILLIS),
- deploymentSpec,
- validationOverrides,
- Optional.of(IssueId.from("4321")),
- Optional.of(IssueId.from("1234")),
- Optional.of(User.from("by-username")),
- OptionalInt.of(7),
- new ApplicationMetrics(0.5, 0.9),
- Set.of(publicKey, otherPublicKey),
- projectId,
- revisions,
- instances
+ Instant.now().truncatedTo(ChronoUnit.MILLIS),
+ deploymentSpec,
+ validationOverrides,
+ Optional.of(IssueId.from("4321")),
+ Optional.of(IssueId.from("1234")),
+ Optional.of(User.from("by-username")),
+ OptionalInt.of(7),
+ new ApplicationMetrics(0.5, 0.9),
+ Set.of(publicKey, otherPublicKey),
+ projectId,
+ revisions,
+ instances
);
Application serialized = APPLICATION_SERIALIZER.fromSlime(SlimeUtils.toJsonBytes(APPLICATION_SERIALIZER.toSlime(original)));
@@ -189,9 +189,9 @@ public class ApplicationSerializerTest {
assertEquals(original.require(id1.instance()).deployments().get(zone2), serialized.require(id1.instance()).deployments().get(zone2));
assertEquals(original.require(id1.instance()).jobPause(DeploymentContext.systemTest),
- serialized.require(id1.instance()).jobPause(DeploymentContext.systemTest));
+ serialized.require(id1.instance()).jobPause(DeploymentContext.systemTest));
assertEquals(original.require(id1.instance()).jobPause(DeploymentContext.stagingTest),
- serialized.require(id1.instance()).jobPause(DeploymentContext.stagingTest));
+ serialized.require(id1.instance()).jobPause(DeploymentContext.stagingTest));
assertEquals(original.ownershipIssueId(), serialized.ownershipIssueId());
assertEquals(original.owner(), serialized.owner());
@@ -220,7 +220,7 @@ public class ApplicationSerializerTest {
}
@Test
- public void testCompleteApplicationDeserialization() throws Exception {
+ void testCompleteApplicationDeserialization() throws Exception {
byte[] applicationJson = Files.readAllBytes(testData.resolve("complete-application.json"));
APPLICATION_SERIALIZER.fromSlime(applicationJson);
// ok if no error
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
index a3e4f6e6f89..82c5a6fc0c1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
@@ -3,16 +3,16 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.config.provision.TenantName;
import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedHashSet;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArchiveBucketsSerializerTest {
@Test
- public void serdes() {
+ void serdes() {
var testTenants = new LinkedHashSet<TenantName>();
testTenants.add(TenantName.from("tenant1"));
testTenants.add(TenantName.from("tenant2"));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
index c047f31e171..4508372738f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -10,8 +10,8 @@ import java.time.Instant;
import java.util.List;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class AuditLogSerializerTest {
@Test
- public void test_serialization() {
+ void test_serialization() {
Instant i1 = Instant.now();
Instant i2 = i1.minus(Duration.ofHours(1));
Instant i3 = i1.minus(Duration.ofHours(2));
@@ -27,20 +27,20 @@ public class AuditLogSerializerTest {
AuditLog log = new AuditLog(List.of(
new AuditLog.Entry(i1, "bar", AuditLog.Entry.Method.POST,
- "/bar/baz/",
- "0".repeat(2048).getBytes(StandardCharsets.UTF_8)),
+ "/bar/baz/",
+ "0".repeat(2048).getBytes(StandardCharsets.UTF_8)),
new AuditLog.Entry(i2, "foo", AuditLog.Entry.Method.POST,
- "/foo/bar/",
- "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8)),
+ "/foo/bar/",
+ "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8)),
new AuditLog.Entry(i3, "baz", AuditLog.Entry.Method.POST,
- "/foo/baz/",
- new byte[0]),
+ "/foo/baz/",
+ new byte[0]),
new AuditLog.Entry(i4, "baz", AuditLog.Entry.Method.POST,
- "/foo/baz/",
- "000\ufdff\ufeff\uffff000".getBytes(StandardCharsets.UTF_8)), // non-ascii
+ "/foo/baz/",
+ "000\ufdff\ufeff\uffff000".getBytes(StandardCharsets.UTF_8)), // non-ascii
new AuditLog.Entry(i4, "quux", AuditLog.Entry.Method.POST,
- "/foo/quux/",
- new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF}) // garbage
+ "/foo/quux/",
+ new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF}) // garbage
));
AuditLogSerializer serializer = new AuditLogSerializer();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
index 0f7f97d333a..eb5422f5cff 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.stubs.MockRunDataStore;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.RunLog;
import com.yahoo.vespa.hosted.controller.deployment.Step;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -20,21 +20,21 @@ import java.util.Optional;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toUnmodifiableList;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class BufferedLogStoreTest {
@Test
- public void chunkingAndFlush() {
+ void chunkingAndFlush() {
int chunkSize = 1 << 10;
int maxChunks = 1 << 5;
CuratorDb buffer = new MockCuratorDb(SystemName.main);
RunDataStore store = new MockRunDataStore();
BufferedLogStore logs = new BufferedLogStore(chunkSize, chunkSize * maxChunks, buffer, store);
RunId id = new RunId(ApplicationId.from("tenant", "application", "instance"),
- DeploymentContext.productionUsWest1,
- 123);
+ DeploymentContext.productionUsWest1,
+ 123);
byte[] manyBytes = new byte[chunkSize / 2 + 1]; // One fits, and two (over-)fills.
Arrays.fill(manyBytes, (byte) 'O');
@@ -50,29 +50,29 @@ public class BufferedLogStoreTest {
assertEquals(Optional.empty(), logs.readFinished(id, -1));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), -1));
- logs.append(id.application(), id.type(), Step.deployReal, List.of(entry));
+ logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(List.of(entry0),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 0));
- logs.append(id.application(), id.type(), Step.deployReal, List.of(entry));
+ logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(List.of(entry0, entry1),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(List.of(entry1),
- logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 1));
- logs.append(id.application(), id.type(), Step.deployReal, List.of(entry, entry, entry));
+ logs.append(id.application(), id.type(), Step.deployReal, List.of(entry, entry, entry), false);
assertEquals(List.of(entry0, entry1, entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(List.of(entry1, entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
assertEquals(List.of(entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), 1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 1).get(Step.deployReal));
assertEquals(List.of(entry3, entry4),
- logs.readActive(id.application(), id.type(), 2).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 2).get(Step.deployReal));
assertEquals(List.of(entry4),
- logs.readActive(id.application(), id.type(), 3).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 3).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 4));
// We should now have three chunks, with two, two, and one entries.
@@ -86,40 +86,51 @@ public class BufferedLogStoreTest {
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), -1));
assertEquals(List.of(entry0, entry1, entry2, entry3, entry4),
- logs.readFinished(id, -1).get().get(Step.deployReal));
+ logs.readFinished(id, -1).get().get(Step.deployReal));
assertEquals(List.of(entry1, entry2, entry3, entry4),
- logs.readFinished(id, 0).get().get(Step.deployReal));
+ logs.readFinished(id, 0).get().get(Step.deployReal));
assertEquals(List.of(entry2, entry3, entry4),
- logs.readFinished(id, 1).get().get(Step.deployReal));
+ logs.readFinished(id, 1).get().get(Step.deployReal));
assertEquals(List.of(entry3, entry4),
- logs.readFinished(id, 2).get().get(Step.deployReal));
+ logs.readFinished(id, 2).get().get(Step.deployReal));
assertEquals(List.of(entry4),
- logs.readFinished(id, 3).get().get(Step.deployReal));
+ logs.readFinished(id, 3).get().get(Step.deployReal));
assertEquals(List.of(), logs.readFinished(id, 4).get().get(Step.deployReal));
// Logging a large entry enough times to reach the maximum size causes no further entries to be stored.
List<LogEntry> monsterLog = IntStream.range(0, 2 * maxChunks + 3)
- .mapToObj(i -> new LogEntry(i, entry.at(), entry.type(), entry.message()))
- .collect(toUnmodifiableList());
+ .mapToObj(i -> new LogEntry(i, entry.at(), entry.type(), entry.message()))
+ .collect(toUnmodifiableList());
List<LogEntry> logged = new ArrayList<>(monsterLog);
logged.remove(logged.size() - 1);
logged.remove(logged.size() - 1);
logged.remove(logged.size() - 1);
- logged.add(new LogEntry(2 * maxChunks, entry.at(), LogEntry.Type.warning, "Max log size of " + ((chunkSize * maxChunks) >> 20) + "Mb exceeded; further entries are discarded."));
+ logged.add(new LogEntry(2 * maxChunks, entry.at(), LogEntry.Type.warning, "Max log size of " + ((chunkSize * maxChunks) >> 20) + "Mb exceeded; further user entries are discarded."));
- logs.append(id.application(), id.type(), Step.deployReal, monsterLog);
+ logs.append(id.application(), id.type(), Step.deployReal, monsterLog, false);
assertEquals(logged.size(),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
assertEquals(logged,
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ // An additional, forced entry is appended.
+ LogEntry forced = new LogEntry(logged.size(), entry.at(), entry.type(), entry.message());
+ logs.append(id.application(), id.type(), Step.deployReal, List.of(forced), true);
+ logged.add(forced);
+ assertEquals(logged.size(),
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ assertEquals(logged,
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logged.remove(logged.size() - 1);
+
+ // Flushing the buffer clears it again, and makes it ready for reuse.
logs.flush(id);
for (int i = 0; i < 2 * maxChunks + 3; i++)
- logs.append(id.application(), id.type(), Step.deployReal, List.of(entry));
+ logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(logged.size(),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
assertEquals(logged,
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
index a52a6b81eb9..77686467336 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequest;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSource;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.HostAction;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class ChangeRequestSerializerTest {
@Test
- public void reserialization_equality() {
+ void reserialization_equality() {
var source = new ChangeRequestSource("aws", "id321", "url", ChangeRequestSource.Status.STARTED, ZonedDateTime.now(), ZonedDateTime.now());
var actionPlan = List.of(
new HostAction("host1", HostAction.State.RETIRING, Instant.now()),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
index 20cc82f0143..a7188cfa93e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.component.Version;
import com.yahoo.vespa.hosted.controller.api.identifiers.ControllerVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -17,7 +17,7 @@ public class ControllerVersionSerializerTest {
private final ControllerVersionSerializer serializer = new ControllerVersionSerializer();
@Test
- public void serialization() {
+ void serialization() {
var version = new ControllerVersion(Version.fromString("7.42.1"), "badc0ffee", Instant.ofEpochSecond(1565876112));
var serialized = serializer.fromSlime(serializer.toSlime(version));
assertEquals(version.version(), serialized.version());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
index c4aa2b5a18b..819d9282618 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateMetadata;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class EndpointCertificateMetadataSerializerTest {
@@ -18,21 +18,21 @@ public class EndpointCertificateMetadataSerializerTest {
new EndpointCertificateMetadata("keyName", "certName", 1, 0, "rootRequestId", Optional.empty(), List.of("SAN1", "SAN2"), "issuer", Optional.empty(), Optional.empty());
@Test
- public void serialize_with_optional_fields() {
+ void serialize_with_optional_fields() {
assertEquals(
"{\"keyName\":\"keyName\",\"certName\":\"certName\",\"version\":1,\"lastRequested\":0,\"requestId\":\"rootRequestId\",\"leafRequestId\":\"leafRequestId\",\"requestedDnsSans\":[\"SAN1\",\"SAN2\"],\"issuer\":\"issuer\",\"expiry\":1628000000,\"lastRefreshed\":1612000000}",
EndpointCertificateMetadataSerializer.toSlime(sampleWithOptionalFieldsSet).toString());
}
@Test
- public void serialize_without_optional_fields() {
+ void serialize_without_optional_fields() {
assertEquals(
"{\"keyName\":\"keyName\",\"certName\":\"certName\",\"version\":1,\"lastRequested\":0,\"requestId\":\"rootRequestId\",\"requestedDnsSans\":[\"SAN1\",\"SAN2\"],\"issuer\":\"issuer\"}",
EndpointCertificateMetadataSerializer.toSlime(sampleWithoutOptionalFieldsSet).toString());
}
@Test
- public void deserialize_from_json_with_optional_fields() {
+ void deserialize_from_json_with_optional_fields() {
assertEquals(
sampleWithOptionalFieldsSet,
EndpointCertificateMetadataSerializer.fromJsonString(
@@ -40,7 +40,7 @@ public class EndpointCertificateMetadataSerializerTest {
}
@Test
- public void deserialize_from_json_without_optional_fields() {
+ void deserialize_from_json_without_optional_fields() {
assertEquals(
sampleWithoutOptionalFieldsSet,
EndpointCertificateMetadataSerializer.fromJsonString(
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
index 1e63b87e7c6..d03a17edde2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.api.integration.LogEntry;
import com.yahoo.vespa.hosted.controller.deployment.Step;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -17,7 +17,7 @@ import java.util.Map;
import static com.yahoo.vespa.hosted.controller.deployment.Step.deployReal;
import static com.yahoo.vespa.hosted.controller.deployment.Step.deployTester;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -28,7 +28,7 @@ public class LogSerializerTest {
private static final Path logsFile = Paths.get("src/test/java/com/yahoo/vespa/hosted/controller/persistence/testdata/logs.json");
@Test
- public void testSerialization() throws IOException {
+ void testSerialization() throws IOException {
for (LogEntry.Type type : LogEntry.Type.values())
assertEquals(type, LogSerializer.typeOf(LogSerializer.valueOf(type)));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
index 5ecc22ffc5e..6f0a36690ed 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
@@ -11,11 +11,11 @@ import com.yahoo.vespa.hosted.controller.dns.CreateRecord;
import com.yahoo.vespa.hosted.controller.dns.CreateRecords;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue;
import com.yahoo.vespa.hosted.controller.dns.RemoveRecords;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -25,20 +25,20 @@ public class NameServiceQueueSerializerTest {
private final NameServiceQueueSerializer serializer = new NameServiceQueueSerializer();
@Test
- public void test_serialization() {
+ void test_serialization() {
var record1 = new Record(Record.Type.CNAME, RecordName.from("cname.example.com"), RecordData.from("example.com"));
var record2 = new Record(Record.Type.TXT, RecordName.from("txt.example.com"), RecordData.from("text"));
var requests = List.of(
new CreateRecord(record1),
new CreateRecords(List.of(record2)),
new CreateRecords(List.of(new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias1"),
- "dns-zone-01",
- ZoneId.from("prod", "us-north-1")).pack()),
- new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias2"),
- "dns-zone-02",
- ZoneId.from("prod", "us-north-2")).pack()))
+ new LatencyAliasTarget(HostName.of("alias1"),
+ "dns-zone-01",
+ ZoneId.from("prod", "us-north-1")).pack()),
+ new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
+ new LatencyAliasTarget(HostName.of("alias2"),
+ "dns-zone-02",
+ ZoneId.from("prod", "us-north-2")).pack()))
),
new RemoveRecords(record1.type(), record1.name()),
new RemoveRecords(record2.type(), record2.data())
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
index 370b1cbe02c..c9755672232 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
@@ -10,13 +10,13 @@ import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.notification.Notification;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class NotificationsSerializerTest {
@Test
- public void serialization_test() throws IOException {
+ void serialization_test() throws IOException {
NotificationsSerializer serializer = new NotificationsSerializer();
TenantName tenantName = TenantName.from("tenant1");
List<Notification> notifications = List.of(
@@ -42,20 +42,20 @@ public class NotificationsSerializerTest {
Slime serialized = serializer.toSlime(notifications);
assertEquals("{\"notifications\":[" +
"{" +
- "\"at\":1234000," +
- "\"type\":\"applicationPackage\"," +
- "\"level\":\"warning\"," +
- "\"messages\":[\"Something something deprecated...\"]," +
- "\"application\":\"app1\"" +
+ "\"at\":1234000," +
+ "\"type\":\"applicationPackage\"," +
+ "\"level\":\"warning\"," +
+ "\"messages\":[\"Something something deprecated...\"]," +
+ "\"application\":\"app1\"" +
"},{" +
- "\"at\":2345000," +
- "\"type\":\"deployment\"," +
- "\"level\":\"error\"," +
- "\"messages\":[\"Failed to deploy: Node allocation failure\"]," +
- "\"application\":\"app1\"," +
- "\"instance\":\"instance1\"," +
- "\"jobId\":\"test.us-east-1\"," +
- "\"runNumber\":12" +
+ "\"at\":2345000," +
+ "\"type\":\"deployment\"," +
+ "\"level\":\"error\"," +
+ "\"messages\":[\"Failed to deploy: Node allocation failure\"]," +
+ "\"application\":\"app1\"," +
+ "\"instance\":\"instance1\"," +
+ "\"jobId\":\"test.us-east-1\"," +
+ "\"runNumber\":12" +
"}]}", new String(SlimeUtils.toJsonBytes(serialized)));
List<Notification> deserialized = serializer.fromSlime(tenantName, serialized);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
index c722b3bbb96..568b17817a1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
@@ -5,11 +5,11 @@ import com.google.common.collect.ImmutableSet;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionSerializerTest {
@Test
- public void test_serialization() {
+ void test_serialization() {
OsVersionSerializer serializer = new OsVersionSerializer();
Set<OsVersion> osVersions = ImmutableSet.of(
new OsVersion(Version.fromString("7.1"), CloudName.defaultName()),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
index d50c071d98e..7461bf6516c 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.LinkedHashMap;
@@ -16,7 +16,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionStatusSerializerTest {
@Test
- public void serialization() {
+ void serialization() {
Version version1 = Version.fromString("7.1");
Version version2 = Version.fromString("7.2");
Map<OsVersion, List<NodeVersion>> versions = new LinkedHashMap<>();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
index 1af4465528d..654703b36c0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionTargetSerializerTest {
@Test
- public void serialization() {
+ void serialization() {
OsVersionTargetSerializer serializer = new OsVersionTargetSerializer(new OsVersionSerializer());
Set<OsVersionTarget> targets = ImmutableSet.of(
new OsVersionTarget(new OsVersion(Version.fromString("7.1"), CloudName.defaultName()), Duration.ZERO, Instant.ofEpochMilli(123)),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
index 2e8ba84d4ff..3df459513d7 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.application.EndpointId;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicy;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicyId;
import com.yahoo.vespa.hosted.controller.routing.RoutingStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Iterator;
@@ -17,7 +17,7 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -27,34 +27,34 @@ public class RoutingPolicySerializerTest {
private final RoutingPolicySerializer serializer = new RoutingPolicySerializer();
@Test
- public void serialization() {
+ void serialization() {
var owner = ApplicationId.defaultId();
var instanceEndpoints = Set.of(EndpointId.of("r1"), EndpointId.of("r2"));
var applicationEndpoints = Set.of(EndpointId.of("a1"));
var id1 = new RoutingPolicyId(owner,
- ClusterSpec.Id.from("my-cluster1"),
- ZoneId.from("prod", "us-north-1"));
+ ClusterSpec.Id.from("my-cluster1"),
+ ZoneId.from("prod", "us-north-1"));
var id2 = new RoutingPolicyId(owner,
- ClusterSpec.Id.from("my-cluster2"),
- ZoneId.from("prod", "us-north-2"));
+ ClusterSpec.Id.from("my-cluster2"),
+ ZoneId.from("prod", "us-north-2"));
var policies = List.of(new RoutingPolicy(id1,
- HostName.of("long-and-ugly-name"),
- Optional.of("zone1"),
- instanceEndpoints,
- applicationEndpoints,
- new RoutingPolicy.Status(true, RoutingStatus.DEFAULT)),
- new RoutingPolicy(id2,
- HostName.of("long-and-ugly-name-2"),
- Optional.empty(),
- instanceEndpoints,
- Set.of(),
- new RoutingPolicy.Status(false,
- new RoutingStatus(RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant,
- Instant.ofEpochSecond(123)))));
+ HostName.of("long-and-ugly-name"),
+ Optional.of("zone1"),
+ instanceEndpoints,
+ applicationEndpoints,
+ new RoutingPolicy.Status(true, RoutingStatus.DEFAULT)),
+ new RoutingPolicy(id2,
+ HostName.of("long-and-ugly-name-2"),
+ Optional.empty(),
+ instanceEndpoints,
+ Set.of(),
+ new RoutingPolicy.Status(false,
+ new RoutingStatus(RoutingStatus.Value.out,
+ RoutingStatus.Agent.tenant,
+ Instant.ofEpochSecond(123)))));
var serialized = serializer.fromSlime(owner, serializer.toSlime(policies));
assertEquals(policies.size(), serialized.size());
- for (Iterator<RoutingPolicy> it1 = policies.iterator(), it2 = serialized.iterator(); it1.hasNext();) {
+ for (Iterator<RoutingPolicy> it1 = policies.iterator(), it2 = serialized.iterator(); it1.hasNext(); ) {
var expected = it1.next();
var actual = it2.next();
assertEquals(expected.id(), actual.id());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
index 6a01a70eb98..644f26e888a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.RunStatus;
import com.yahoo.vespa.hosted.controller.deployment.Step;
import com.yahoo.vespa.hosted.controller.deployment.StepInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -46,9 +46,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.startStagingSetu
import static com.yahoo.vespa.hosted.controller.deployment.Step.startTests;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class RunSerializerTest {
@@ -60,7 +60,7 @@ public class RunSerializerTest {
private static final Instant start = Instant.parse("2007-12-03T10:15:30.00Z");
@Test
- public void testSerialization() throws IOException {
+ void testSerialization() throws IOException {
for (Step step : Step.values())
assertEquals(step, RunSerializer.stepOf(RunSerializer.valueOf(step)));
@@ -89,16 +89,16 @@ public class RunSerializerTest {
assertEquals(new Version(1, 2, 2), run.versions().sourcePlatform().get());
assertEquals(revision2, run.versions().sourceRevision().get());
assertEquals(Optional.of(new ConvergenceSummary(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233)),
- run.convergenceSummary());
+ run.convergenceSummary());
assertEquals(X509CertificateUtils.fromPem("-----BEGIN CERTIFICATE-----\n" +
- "MIIBEzCBu6ADAgECAgEBMAoGCCqGSM49BAMEMBQxEjAQBgNVBAMTCW15c2Vydmlj\n" +
- "ZTAeFw0xOTA5MDYwNzM3MDZaFw0xOTA5MDcwNzM3MDZaMBQxEjAQBgNVBAMTCW15\n" +
- "c2VydmljZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABM0JhD8fV2DlAkjQOGX3\n" +
- "Y50ryMBr3g2+v/uFiRoxJ1muuSOWYrW7HCQIGuzc04fa0QwtaX/voAZKCV51t6jF\n" +
- "0fwwCgYIKoZIzj0EAwQDRwAwRAIgVbQ3Co1H4X0gmRrtXSyTU0HgBQu9PXHMmX20\n" +
- "5MyyPSoCIBltOcmaPfdN03L3zqbqZ6PgUBWsvAHgiBzL3hrtJ+iy\n" +
- "-----END CERTIFICATE-----"),
- run.testerCertificate().get());
+ "MIIBEzCBu6ADAgECAgEBMAoGCCqGSM49BAMEMBQxEjAQBgNVBAMTCW15c2Vydmlj\n" +
+ "ZTAeFw0xOTA5MDYwNzM3MDZaFw0xOTA5MDcwNzM3MDZaMBQxEjAQBgNVBAMTCW15\n" +
+ "c2VydmljZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABM0JhD8fV2DlAkjQOGX3\n" +
+ "Y50ryMBr3g2+v/uFiRoxJ1muuSOWYrW7HCQIGuzc04fa0QwtaX/voAZKCV51t6jF\n" +
+ "0fwwCgYIKoZIzj0EAwQDRwAwRAIgVbQ3Co1H4X0gmRrtXSyTU0HgBQu9PXHMmX20\n" +
+ "5MyyPSoCIBltOcmaPfdN03L3zqbqZ6PgUBWsvAHgiBzL3hrtJ+iy\n" +
+ "-----END CERTIFICATE-----"),
+ run.testerCertificate().get());
assertEquals(ImmutableMap.<Step, StepInfo>builder()
.put(deployInitialReal, new StepInfo(deployInitialReal, unfinished, Optional.empty()))
.put(installInitialReal, new StepInfo(installInitialReal, failed, Optional.of(Instant.ofEpochMilli(1196676940000L))))
@@ -118,10 +118,10 @@ public class RunSerializerTest {
run.steps());
run = run.with(1L << 50)
- .with(Instant.now().truncatedTo(MILLIS))
- .noNodesDownSince(Instant.now().truncatedTo(MILLIS))
- .aborted()
- .finished(Instant.now().truncatedTo(MILLIS));
+ .with(Instant.now().truncatedTo(MILLIS))
+ .noNodesDownSince(Instant.now().truncatedTo(MILLIS))
+ .aborted()
+ .finished(Instant.now().truncatedTo(MILLIS));
assertEquals(aborted, run.status());
assertTrue(run.hasEnded());
@@ -140,7 +140,7 @@ public class RunSerializerTest {
assertEquals(run.reason(), phoenix.reason());
assertEquals(new String(SlimeUtils.toJsonBytes(serializer.toSlime(run).get(), false), UTF_8),
- new String(SlimeUtils.toJsonBytes(serializer.toSlime(phoenix).get(), false), UTF_8));
+ new String(SlimeUtils.toJsonBytes(serializer.toSlime(phoenix).get(), false), UTF_8));
Run initial = Run.initial(id, run.versions(), run.isRedeployment(), run.start(), JobProfile.production, Optional.empty());
assertEquals(initial, serializer.runFromSlime(serializer.toSlime(initial)));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
index 8b2c291f751..8aa53fb5cd4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.slime.Slime;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccess;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccessGrant;
import org.intellij.lang.annotations.Language;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayOutputStream;
@@ -22,7 +22,7 @@ import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class SupportAccessSerializerTest {
@@ -78,70 +78,70 @@ public class SupportAccessSerializerTest {
}
@Test
- public void serialize_default() {
+ void serialize_default() {
var slime = SupportAccessSerializer.serializeCurrentState(SupportAccess.DISALLOWED_NO_HISTORY, Instant.EPOCH);
assertSerialized(slime, "{\n" +
- " \"state\": {\n" +
- " \"supportAccess\": \"NOT_ALLOWED\"\n" +
- " },\n" +
- " \"history\": [ ],\n" +
- " \"grants\": [ ]\n" +
- "}\n");
+ " \"state\": {\n" +
+ " \"supportAccess\": \"NOT_ALLOWED\"\n" +
+ " },\n" +
+ " \"history\": [ ],\n" +
+ " \"grants\": [ ]\n" +
+ "}\n");
}
@Test
- public void serialize_with_certificates() {
+ void serialize_with_certificates() {
var slime = SupportAccessSerializer.toSlime(supportAccessExample);
assertSerialized(slime, expectedWithCertificates);
}
@Test
- public void serialize_with_status() {
+ void serialize_with_status() {
var slime = SupportAccessSerializer.serializeCurrentState(supportAccessExample, hour(12));
assertSerialized(slime,
- "{\n"
- + " \"state\": {\n"
- + " \"supportAccess\": \"ALLOWED\",\n"
- + " \"until\": \"1970-01-02T12:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " \"history\": [\n"
- + " {\n"
- + " \"state\": \"allowed\",\n"
- + " \"at\": \"1970-01-02T06:00:00Z\",\n"
- + " \"until\": \"1970-01-02T12:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"disallowed\",\n"
- + " \"at\": \"1970-01-01T22:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"allowed\",\n"
- + " \"at\": \"1970-01-01T02:00:00Z\",\n"
- + " \"until\": \"1970-01-02T00:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"grant\",\n"
- + " \"at\": \"1970-01-01T03:00:00Z\",\n"
- + " \"until\": \"1970-01-01T04:00:00Z\",\n"
- + " \"by\": \"mortent\"\n"
- + " }\n"
- + " ],\n"
- + " \"grants\": [\n"
- + " {\n"
- + " \"requestor\": \"mortent\",\n"
- + " \"notBefore\": \"1970-01-01T07:00:00Z\",\n"
- + " \"notAfter\": \"1970-01-01T19:00:00Z\"\n"
- + " }\n"
- + " ]\n"
- + "}\n");
+ "{\n"
+ + " \"state\": {\n"
+ + " \"supportAccess\": \"ALLOWED\",\n"
+ + " \"until\": \"1970-01-02T12:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " \"history\": [\n"
+ + " {\n"
+ + " \"state\": \"allowed\",\n"
+ + " \"at\": \"1970-01-02T06:00:00Z\",\n"
+ + " \"until\": \"1970-01-02T12:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"disallowed\",\n"
+ + " \"at\": \"1970-01-01T22:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"allowed\",\n"
+ + " \"at\": \"1970-01-01T02:00:00Z\",\n"
+ + " \"until\": \"1970-01-02T00:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"grant\",\n"
+ + " \"at\": \"1970-01-01T03:00:00Z\",\n"
+ + " \"until\": \"1970-01-01T04:00:00Z\",\n"
+ + " \"by\": \"mortent\"\n"
+ + " }\n"
+ + " ],\n"
+ + " \"grants\": [\n"
+ + " {\n"
+ + " \"requestor\": \"mortent\",\n"
+ + " \"notBefore\": \"1970-01-01T07:00:00Z\",\n"
+ + " \"notAfter\": \"1970-01-01T19:00:00Z\"\n"
+ + " }\n"
+ + " ]\n"
+ + "}\n");
}
@Test
- public void deserialize() {
+ void deserialize() {
var slime = SupportAccessSerializer.toSlime(supportAccessExample);
assertSerialized(slime, expectedWithCertificates);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
index a9e633a78d6..636620acf07 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
@@ -23,7 +23,7 @@ import com.yahoo.vespa.hosted.controller.tenant.TenantBilling;
import com.yahoo.vespa.hosted.controller.tenant.TenantContact;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.security.PublicKey;
@@ -33,9 +33,9 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -53,12 +53,12 @@ public class TenantSerializerTest {
"-----END PUBLIC KEY-----\n");
@Test
- public void athenz_tenant() {
+ void athenz_tenant() {
AthenzTenant tenant = AthenzTenant.create(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.of(new PropertyId("1")),
- Instant.ofEpochMilli(1234L));
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.of(new PropertyId("1")),
+ Instant.ofEpochMilli(1234L));
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.name(), serialized.name());
assertEquals(tenant.domain(), serialized.domain());
@@ -69,42 +69,42 @@ public class TenantSerializerTest {
}
@Test
- public void athenz_tenant_without_property_id() {
+ void athenz_tenant_without_property_id() {
AthenzTenant tenant = AthenzTenant.create(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.empty(),
- Instant.EPOCH);
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.empty(),
+ Instant.EPOCH);
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertFalse(serialized.propertyId().isPresent());
assertEquals(tenant.propertyId(), serialized.propertyId());
}
@Test
- public void athenz_tenant_with_contact() {
+ void athenz_tenant_with_contact() {
AthenzTenant tenant = new AthenzTenant(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.of(new PropertyId("1")),
- Optional.of(contact()),
- Instant.EPOCH,
- lastLoginInfo(321L, 654L, 987L));
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.of(new PropertyId("1")),
+ Optional.of(contact()),
+ Instant.EPOCH,
+ lastLoginInfo(321L, 654L, 987L));
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.contact(), serialized.contact());
}
@Test
- public void cloud_tenant() {
+ void cloud_tenant() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
- Instant.ofEpochMilli(1234L),
- lastLoginInfo(123L, 456L, null),
- Optional.of(new SimplePrincipal("foobar-user")),
- ImmutableBiMap.of(publicKey, new SimplePrincipal("joe"),
- otherPublicKey, new SimplePrincipal("jane")),
- TenantInfo.empty(),
- List.of(),
- new ArchiveAccess()
- );
+ Instant.ofEpochMilli(1234L),
+ lastLoginInfo(123L, 456L, null),
+ Optional.of(new SimplePrincipal("foobar-user")),
+ ImmutableBiMap.of(publicKey, new SimplePrincipal("joe"),
+ otherPublicKey, new SimplePrincipal("jane")),
+ TenantInfo.empty(),
+ List.of(),
+ new ArchiveAccess(),
+ Optional.empty());
CloudTenant serialized = (CloudTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.name(), serialized.name());
assertEquals(tenant.creator(), serialized.creator());
@@ -113,7 +113,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_info() {
+ void cloud_tenant_with_info() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
Instant.EPOCH,
lastLoginInfo(null, 789L, 654L),
@@ -125,15 +125,16 @@ public class TenantSerializerTest {
new TenantSecretStore("ss1", "123", "role1"),
new TenantSecretStore("ss2", "124", "role2")
),
- new ArchiveAccess().withAWSRole("arn:aws:iam::123456789012:role/my-role")
- );
+ new ArchiveAccess().withAWSRole("arn:aws:iam::123456789012:role/my-role"),
+ Optional.of(Instant.ofEpochMilli(1234567)));
CloudTenant serialized = (CloudTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.info(), serialized.info());
assertEquals(tenant.tenantSecretStores(), serialized.tenantSecretStores());
+ assertEquals(tenant.invalidateUserSessionsBefore(), serialized.invalidateUserSessionsBefore());
}
@Test
- public void cloud_tenant_with_old_archive_access_serialization() {
+ void cloud_tenant_with_old_archive_access_serialization() {
var json = "{\n" +
" \"name\": \"elderly-lady\",\n" +
" \"type\": \"cloud\",\n" +
@@ -165,7 +166,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_archive_access() {
+ void cloud_tenant_with_archive_access() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
Instant.ofEpochMilli(1234L),
lastLoginInfo(123L, 456L, null),
@@ -174,15 +175,15 @@ public class TenantSerializerTest {
otherPublicKey, new SimplePrincipal("jane")),
TenantInfo.empty(),
List.of(),
- new ArchiveAccess().withAWSRole("arn:aws:iam::123456789012:role/my-role").withGCPMember("user:foo@example.com")
- );
+ new ArchiveAccess().withAWSRole("arn:aws:iam::123456789012:role/my-role").withGCPMember("user:foo@example.com"),
+ Optional.empty());
CloudTenant serialized = (CloudTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(serialized.archiveAccess().awsRole().get(), "arn:aws:iam::123456789012:role/my-role");
assertEquals(serialized.archiveAccess().gcpMember().get(), "user:foo@example.com");
}
@Test
- public void cloud_tenant_with_tenant_info_partial() {
+ void cloud_tenant_with_tenant_info_partial() {
TenantInfo partialInfo = TenantInfo.empty()
.withAddress(TenantAddress.empty().withCity("Hønefoss"));
@@ -193,7 +194,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_tenant_info_full() {
+ void cloud_tenant_with_tenant_info_full() {
TenantInfo fullInfo = TenantInfo.empty()
.withName("My Company")
.withEmail("email@mycomp.any")
@@ -222,7 +223,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_tenant_info_contacts() {
+ void cloud_tenant_with_tenant_info_contacts() {
TenantInfo tenantInfo = TenantInfo.empty()
.withContacts(new TenantContacts(List.of(
new TenantContacts.EmailContact(List.of(TenantContacts.Audience.TENANT), "email1@email.com"),
@@ -235,7 +236,7 @@ public class TenantSerializerTest {
}
@Test
- public void deleted_tenant() {
+ void deleted_tenant() {
DeletedTenant tenant = new DeletedTenant(
TenantName.from("tenant1"), Instant.ofEpochMilli(1234L), Instant.ofEpochMilli(2345L));
DeletedTenant serialized = (DeletedTenant) serializer.tenantFrom(serializer.toSlime(tenant));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
index 73cfc6ad2f3..618c33835bd 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
@@ -7,7 +7,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -15,7 +15,7 @@ import java.util.List;
import java.util.Optional;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -23,15 +23,15 @@ import static org.junit.Assert.assertEquals;
public class VersionStatusSerializerTest {
@Test
- public void testSerialization() {
+ void testSerialization() {
List<VespaVersion> vespaVersions = new ArrayList<>();
Version version = Version.fromString("5.0");
vespaVersions.add(new VespaVersion(version, "dead", Instant.now(), false, false,
- true, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
- "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
+ true, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
+ "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
vespaVersions.add(new VespaVersion(version, "cafe", Instant.now(), true, true,
- false, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
- "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
+ false, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
+ "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
VersionStatus status = new VersionStatus(vespaVersions);
VersionStatusSerializer serializer = new VersionStatusSerializer(new NodeVersionSerializer());
VersionStatus deserialized = serializer.fromSlime(serializer.toSlime(status));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
index 234de233571..f524f4a2d4f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.routing.RoutingStatus;
import com.yahoo.vespa.hosted.controller.routing.ZoneRoutingPolicy;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertEquals;
public class ZoneRoutingPolicySerializerTest {
@Test
- public void serialization() {
+ void serialization() {
var serializer = new ZoneRoutingPolicySerializer(new RoutingPolicySerializer());
var zone = ZoneId.from("prod", "us-north-1");
var policy = new ZoneRoutingPolicy(zone,
- RoutingStatus.create(RoutingStatus.Value.out, RoutingStatus.Agent.operator,
- Instant.ofEpochMilli(123)));
+ RoutingStatus.create(RoutingStatus.Value.out, RoutingStatus.Agent.operator,
+ Instant.ofEpochMilli(123)));
var serialized = serializer.fromSlime(zone, serializer.toSlime(policy));
assertEquals(policy, serialized);
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
index f5926e799af..5214ded0904 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
@@ -10,8 +10,8 @@ import com.yahoo.yolean.concurrent.Sleeper;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayOutputStream;
@@ -25,21 +25,21 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
*/
public class ConfigServerRestExecutorImplTest {
- @Rule
- public final WireMockRule wireMock = new WireMockRule(options().dynamicPort(), true);
+ @RegisterExtension
+ public final WireMockExtension wireMock = WireMockExtension.newInstance().options(options().dynamicPort()).failOnUnmatchedRequests(true).build();
@Test
- public void proxy_with_retries() throws Exception {
+ void proxy_with_retries() throws Exception {
var connectionReuseStrategy = new CountingConnectionReuseStrategy(Set.of("127.0.0.1"));
var proxy = new ConfigServerRestExecutorImpl(new SSLConnectionSocketFactory(SSLContext.getDefault()),
- Sleeper.NOOP, connectionReuseStrategy);
+ Sleeper.NOOP, connectionReuseStrategy);
URI url = url();
String path = url.getPath();
@@ -61,10 +61,10 @@ public class ConfigServerRestExecutorImplTest {
}
@Test
- public void proxy_without_connection_reuse() throws Exception {
+ void proxy_without_connection_reuse() throws Exception {
var connectionReuseStrategy = new CountingConnectionReuseStrategy(Set.of());
var proxy = new ConfigServerRestExecutorImpl(new SSLConnectionSocketFactory(SSLContext.getDefault()),
- Sleeper.NOOP, connectionReuseStrategy);
+ Sleeper.NOOP, connectionReuseStrategy);
URI url = url();
String path = url.getPath();
@@ -79,7 +79,7 @@ public class ConfigServerRestExecutorImplTest {
}
private URI url() {
- return URI.create("http://127.0.0.1:" + wireMock.port() + "/");
+ return URI.create("http://127.0.0.1:" + wireMock.getPort() + "/");
}
private void stubRequests(String path) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
index e6de60c859b..d851eb56890 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
import com.yahoo.jdisc.http.HttpRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Haakon Dybdahl
@@ -18,14 +18,14 @@ import static org.junit.Assert.assertThrows;
public class ProxyRequestTest {
@Test
- public void testBadUri() {
+ void testBadUri() {
assertEquals("Request path '/path' does not end with proxy path '/zone/v2/'",
- assertThrows(IllegalArgumentException.class,
- () -> testRequest("http://domain.tld/path", "/zone/v2/")).getMessage());
+ assertThrows(IllegalArgumentException.class,
+ () -> testRequest("http://domain.tld/path", "/zone/v2/")).getMessage());
}
@Test
- public void testUris() {
+ void testUris() {
{
// Root request
ProxyRequest request = testRequest("http://controller.domain.tld/my/path", "");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
index 845d007c154..08164de6a8e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
import com.yahoo.jdisc.http.HttpRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
@@ -11,7 +11,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Haakon Dybdahl
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class ProxyResponseTest {
@Test
- public void testRewriteUrl() throws Exception {
+ void testRewriteUrl() throws Exception {
ProxyRequest request = new ProxyRequest(HttpRequest.Method.GET, URI.create("http://domain.tld/zone/v2/dev/us-north-1/configserver"),
Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
ProxyResponse proxyResponse = new ProxyResponse(
@@ -37,9 +37,9 @@ public class ProxyResponseTest {
}
@Test
- public void testRewriteSecureUrl() throws Exception {
+ void testRewriteSecureUrl() throws Exception {
ProxyRequest request = new ProxyRequest(HttpRequest.Method.GET, URI.create("https://domain.tld/zone/v2/prod/eu-south-3/configserver"),
- Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
+ Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
ProxyResponse proxyResponse = new ProxyResponse(
request,
"response link is http://configserver:4443/bla/bla/",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
index 07f00e8c989..539d6cff06d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
@@ -28,8 +28,8 @@ import java.util.Optional;
import java.util.function.Supplier;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Provides testing of JSON container responses
@@ -123,7 +123,7 @@ public class ContainerTester {
catch (IOException e) {
fail("failed writing JSON: " + e);
}
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
public void assertResponse(Supplier<Request> request, String expectedResponse) {
@@ -154,7 +154,7 @@ public class ContainerTester {
} catch (Exception e) {
throw new RuntimeException(e);
}
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
// Hack to run request filters as part of the request processing chain.
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
index 87fe8dd17fe..404dcca87c0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.athenz.api.OAuthCredentials;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactoryMock;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import static com.yahoo.vespa.hosted.controller.integration.AthenzFilterMock.IDENTITY_HEADER_NAME;
import static com.yahoo.vespa.hosted.controller.integration.AthenzFilterMock.OKTA_ACCESS_TOKEN_HEADER_NAME;
@@ -33,7 +33,7 @@ public class ControllerContainerTest {
protected JDisc container;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(controllerServicesXml(), networking());
addUserToHostedOperatorRole(hostedOperator);
@@ -41,7 +41,7 @@ public class ControllerContainerTest {
protected Networking networking() { return Networking.disable; }
- @After
+ @AfterEach
public void stopContainer() { container.close(); }
private String controllerServicesXml() {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
index 26dd6335ab8..674424fbdd9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
@@ -27,8 +27,8 @@ import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
import com.yahoo.vespa.hosted.controller.security.Credentials;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
@@ -40,10 +40,10 @@ import static com.yahoo.application.container.handler.Request.Method.GET;
import static com.yahoo.application.container.handler.Request.Method.POST;
import static com.yahoo.application.container.handler.Request.Method.PUT;
import static com.yahoo.vespa.hosted.controller.restapi.application.ApplicationApiTest.createApplicationSubmissionData;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author oyving
@@ -57,7 +57,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
private static final TenantName tenantName = TenantName.from("scoober");
private static final ApplicationName applicationName = ApplicationName.from("albums");
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -66,7 +66,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void test_missing_security_clients_pem() {
+ void test_missing_security_clients_pem() {
var application = prodBuilder().build();
var deployRequest = request("/application/v4/tenant/scoober/application/albums/submit", POST)
@@ -80,7 +80,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_profile() {
+ void tenant_info_profile() {
var request = request("/application/v4/tenant/scoober/info/profile", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{}", 200);
@@ -94,7 +94,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_billing() {
+ void tenant_info_billing() {
var request = request("/application/v4/tenant/scoober/info/billing", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{}", 200);
@@ -111,7 +111,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_contacts() {
+ void tenant_info_contacts() {
var request = request("/application/v4/tenant/scoober/info/contacts", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{\"contacts\":[]}", 200);
@@ -126,10 +126,10 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_workflow() {
+ void tenant_info_workflow() {
var infoRequest =
request("/application/v4/tenant/scoober/info", GET)
- .roles(Set.of(Role.reader(tenantName)));
+ .roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(infoRequest, "{}", 200);
String partialInfo = "{\"contactName\":\"newName\", \"contactEmail\": \"foo@example.com\", \"billingContact\":{\"name\":\"billingName\"}}";
@@ -166,7 +166,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_missing_fields() {
+ void tenant_info_missing_fields() {
// tenants can be created with empty tenant info - they're not part of the POST to v4/tenant
var infoRequest =
request("/application/v4/tenant/scoober/info", GET)
@@ -255,7 +255,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void trial_tenant_limit_reached() {
+ void trial_tenant_limit_reached() {
((InMemoryFlagSource) tester.controller().flagSource()).withIntFlag(PermanentFlags.MAX_TRIAL_TENANTS.id(), 1);
tester.controller().serviceRegistry().billingController().setPlan(tenantName, PlanId.from("pay-as-you-go"), false, false);
@@ -273,7 +273,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void test_secret_store_configuration() {
+ void test_secret_store_configuration() {
var secretStoreRequest =
request("/application/v4/tenant/scoober/secret-store/some-name", PUT)
.data("{" +
@@ -303,7 +303,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void validate_secret_store() {
+ void validate_secret_store() {
deployApplication();
var secretStoreRequest =
request("/application/v4/tenant/scoober/secret-store/secret-foo/validate?aws-region=us-west-1&parameter-name=foo&application-id=scoober.albums.default&zone=prod.aws-us-east-1c", GET)
@@ -326,7 +326,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void delete_secret_store() {
+ void delete_secret_store() {
var deleteRequest =
request("/application/v4/tenant/scoober/secret-store/secret-foo", DELETE)
.roles(Set.of(Role.developer(tenantName)));
@@ -347,18 +347,18 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void archive_uri_test() {
+ void archive_uri_test() {
ControllerTester wrapped = new ControllerTester(tester);
wrapped.upgradeSystem(Version.fromString("7.1"));
new DeploymentTester(wrapped).newDeploymentContext(ApplicationId.from(tenantName, applicationName, InstanceName.defaultName()))
- .submit()
- .deploy();
+ .submit()
+ .deploy();
tester.assertResponse(request("/application/v4/tenant/scoober", GET).roles(Role.reader(tenantName)),
(response) -> assertFalse(response.getBodyAsString().contains("archiveAccessRole")),
200);
tester.assertResponse(request("/application/v4/tenant/scoober/archive-access", PUT)
- .data("{\"role\":\"dummy\"}").roles(Role.administrator(tenantName)),
+ .data("{\"role\":\"dummy\"}").roles(Role.administrator(tenantName)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid archive access role 'dummy': Must match expected pattern: 'arn:aws:iam::\\\\d{12}:.+'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/scoober/archive-access/aws", PUT)
@@ -411,7 +411,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void create_application_on_deploy() {
+ void create_application_on_deploy() {
var application = ApplicationName.from("unique");
var applicationPackage = new ApplicationPackageBuilder().withoutAthenzIdentity().build();
@@ -420,15 +420,15 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
tester.assertResponse(
request("/application/v4/tenant/scoober/application/unique/instance/default/deploy/dev-aws-us-east-1c", POST)
- .data(createApplicationDeployData(Optional.of(applicationPackage), Optional.empty(), true))
- .roles(Set.of(Role.developer(tenantName))),
+ .data(createApplicationDeployData(Optional.of(applicationPackage), Optional.empty(), true))
+ .roles(Set.of(Role.developer(tenantName))),
"{\"message\":\"Deployment started in run 1 of dev-aws-us-east-1c for scoober.unique. This may take about 15 minutes the first time.\",\"run\":1}");
assertTrue(tester.controller().applications().getApplication(TenantAndApplicationId.from(tenantName, application)).isPresent());
}
@Test
- public void create_application_on_submit() {
+ void create_application_on_submit() {
var application = ApplicationName.from("unique");
var applicationPackage = new ApplicationPackageBuilder()
.trustDefaultCertificate()
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
index 2c0ab97c00e..e3292700432 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
@@ -70,8 +70,8 @@ import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
import com.yahoo.yolean.Exceptions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.File;
@@ -100,9 +100,9 @@ import static com.yahoo.application.container.handler.Request.Method.PUT;
import static java.net.URLEncoder.encode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -153,7 +153,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
private ContainerTester tester;
private DeploymentTester deploymentTester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
@@ -161,24 +161,24 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testApplicationApi() {
+ void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID); // (Necessary but not provided in this API)
// GET API root
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
- new File("root.json"));
+ new File("root.json"));
// POST (add) a tenant without property ID
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"));
// PUT (modify) a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ new File("tenant-without-applications.json"));
// Add another Athens domain, so we can try to create more tenants
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID); // New domain to test tenant w/property ID
@@ -187,59 +187,59 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (add) a tenant with property ID
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
- new File("tenant-without-applications-with-id.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
+ new File("tenant-without-applications-with-id.json"));
// PUT (modify) a tenant with property ID
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
- new File("tenant-without-applications-with-id.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
+ new File("tenant-without-applications-with-id.json"));
// GET a tenant with property ID and contact information
updateContactInformation();
tester.controller().tenants().updateLastLogin(TenantName.from("tenant2"),
List.of(LastLoginInfo.UserLevel.user, LastLoginInfo.UserLevel.administrator), Instant.ofEpochMilli(1234));
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
- new File("tenant2.json"));
+ new File("tenant2.json"));
// POST (create) an application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"));
// GET a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
- new File("tenant-with-application.json"));
+ new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("activeInstances", "true")),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("activeInstances", "true")),
+ new File("tenant-without-applications.json"));
// GET tenant applications
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
- new File("application-list.json"));
+ new File("application-list.json"));
// GET tenant application instances for application that does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1/application/fake-app/instance/", GET).userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Application 'fake-app' does not exist\"}", 404);
// GET tenant applications (instances of "application1" only)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
- new File("application-list.json"));
+ new File("application-list.json"));
// GET at a tenant, with "&recursive=true&production=true", recurses over no instances yet, as they are not in deployment spec.
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("recursive", "true",
- "production", "true")),
- new File("tenant-with-empty-application.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("recursive", "true",
+ "production", "true")),
+ new File("tenant-with-empty-application.json"));
// GET at an application, with "&recursive=true&production=true", recurses over no instances yet, as they are not in deployment spec.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("recursive", "true",
- "production", "true")),
- new File("application-without-instances.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("recursive", "true",
+ "production", "true")),
+ new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
@@ -249,87 +249,87 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) an application to start a manual deployment in prod is not allowed
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
// POST (deploy) an application to start a manual deployment in prod is allowed for operators
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
- .data(entity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(DeploymentContext.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
// POST (deploy) an application to start a manual deployment to dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(DeploymentContext.devUsEast1);
// POST (deploy) a job to restart a manual deployment to dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered dev-us-east-1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered dev-us-east-1 for tenant1.application1.instance1\"}");
app1.runJob(DeploymentContext.devUsEast1);
// GET dev application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
- .userIdentity(USER_ID),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
- },
- 200);
+ .userIdentity(USER_ID),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
+ },
+ 200);
// POST an application package is not generally allowed under user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
- .userIdentity(OTHER_USER_ID)
- .data(createApplicationDeployData(applicationPackageInstance1)),
- accessDenied,
- 403);
+ .userIdentity(OTHER_USER_ID)
+ .data(createApplicationDeployData(applicationPackageInstance1)),
+ accessDenied,
+ 403);
// DELETE a dev deployment is not generally allowed under user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
- .userIdentity(OTHER_USER_ID),
- accessDenied,
- 403);
+ .userIdentity(OTHER_USER_ID),
+ accessDenied,
+ 403);
// When the user is a tenant admin, user instances are allowed.
// POST an application package is not allowed under user instance for tenant admins
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
- .userIdentity(USER_ID)
- .data(createApplicationDeployData(applicationPackageInstance1)),
- new File("deployment-job-accepted-2.json"));
+ .userIdentity(USER_ID)
+ .data(createApplicationDeployData(applicationPackageInstance1)),
+ new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/job/dev-us-east-1/diff/1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> assertTrue(response.getBodyAsString(),
- response.getBodyAsString().contains("--- schemas/test.sd\n" +
+ (response) -> assertTrue(response.getBodyAsString().contains("--- schemas/test.sd\n" +
"@@ -1,0 +1,1 @@\n" +
- "+ search test { }\n")),
+ "+ search test { }\n"),
+ response.getBodyAsString()),
200);
// DELETE a dev deployment is allowed under user instance for tenant admins
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
// DELETE a user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
- ATHENZ_TENANT_DOMAIN,
- id.application());
+ ATHENZ_TENANT_DOMAIN,
+ id.application());
// POST an application package and a test jar, submitting a new application for production deployment.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(DeploymentContext.systemTest).runJob(DeploymentContext.stagingTest).runJob(DeploymentContext.productionUsCentral1);
@@ -344,102 +344,102 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (create) another application
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference-2.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
- ATHENZ_TENANT_DOMAIN_2,
- id2.application());
+ ATHENZ_TENANT_DOMAIN_2,
+ id2.application());
// POST an application package and a test jar, submitting a new application for production deployment.
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(applicationPackage, 1000)),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(applicationPackage, 1000)),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
// POST a triggering to force a production job to start without successful tests
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
- .data("{ \"skipTests\": true, \"skipRevision\": true, \"skipUpgrade\": true }")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1, without revision and platform upgrade\"}");
+ .data("{ \"skipTests\": true, \"skipRevision\": true, \"skipUpgrade\": true }")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1, without revision and platform upgrade\"}");
app2.runJob(DeploymentContext.productionUsWest1);
// POST a re-triggering to force a production job to start with previous parameters
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
- .data("{\"reTrigger\":true}")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
+ .data("{\"reTrigger\":true}")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
// DELETE manually deployed prod deployment again
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
// GET application having both change and outstanding change
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .screwdriverIdentity(SCREWDRIVER_ID),
- new File("application2.json"));
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ new File("application2.json"));
// PATCH in a major version override
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
- .userIdentity(USER_ID)
- .data("{\"majorVersion\":7}"),
- "{\"message\":\"Set major version to 7\"}");
+ .userIdentity(USER_ID)
+ .data("{\"majorVersion\":7}"),
+ "{\"message\":\"Set major version to 7\"}");
// POST a pem deploy key
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
- .userIdentity(USER_ID)
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
+ .userIdentity(USER_ID)
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
// PATCH in a pem deploy key at deprecated path
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
- .userIdentity(USER_ID)
- .data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
- "{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
+ .userIdentity(USER_ID)
+ .data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
+ "{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
// GET an application with a major version override
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .userIdentity(USER_ID),
- new File("application2-with-patches.json"));
+ .userIdentity(USER_ID),
+ new File("application2-with-patches.json"));
// PATCH in removal of the application major version override removal
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
- .userIdentity(USER_ID)
- .data("{\"majorVersion\":null}"),
- "{\"message\":\"Set major version to empty\"}");
+ .userIdentity(USER_ID)
+ .data("{\"majorVersion\":null}"),
+ "{\"message\":\"Set major version to empty\"}");
// GET compile version for an application
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
- .userIdentity(USER_ID),
- "{\"compileVersion\":\"6.1.0\"}");
+ .userIdentity(USER_ID),
+ "{\"compileVersion\":\"6.1.0\"}");
// DELETE the pem deploy key
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
- .userIdentity(USER_ID)
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"keys\":[]}");
+ .userIdentity(USER_ID)
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .userIdentity(USER_ID),
- new File("application2.json"));
+ .userIdentity(USER_ID),
+ new File("application2.json"));
// DELETE instance 1 of 2
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant2.application2.default\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant2.application2.default\"}");
// DELETE application with only one instance left
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant2.application2\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant2.application2\"}");
// Set version 6.1 to broken to change compile version for.
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
@@ -448,44 +448,44 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET tenant application deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("instance.json"));
+ .userIdentity(USER_ID),
+ new File("instance.json"));
// GET an application deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment.json"));
+ .userIdentity(USER_ID),
+ new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
// GET at root, with "&recursive=deployment", returns info about all tenants, their applications and their deployments
tester.assertResponse(request("/application/v4/", GET)
- .userIdentity(USER_ID)
- .recursive("deployment"),
- new File("recursive-root.json"));
+ .userIdentity(USER_ID)
+ .recursive("deployment"),
+ new File("recursive-root.json"));
// GET at root, with "&recursive=tenant", returns info about all tenants, with limited info about their applications.
tester.assertResponse(request("/application/v4/", GET)
- .userIdentity(USER_ID)
- .recursive("tenant"),
- new File("recursive-until-tenant-root.json"));
+ .userIdentity(USER_ID)
+ .recursive("tenant"),
+ new File("recursive-until-tenant-root.json"));
// GET at a tenant, with "&recursive=true", returns full info about their applications and their deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
- .userIdentity(USER_ID)
- .recursive("true"),
- new File("tenant1-recursive.json"));
+ .userIdentity(USER_ID)
+ .recursive("true"),
+ new File("tenant1-recursive.json"));
// GET at an application, with "&recursive=true", returns full info about its deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID)
- .recursive("true"),
- new File("instance1-recursive.json"));
+ .userIdentity(USER_ID)
+ .recursive("true"),
+ new File("instance1-recursive.json"));
// GET nodes
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
- .userIdentity(USER_ID),
- new File("application-nodes.json"));
+ .userIdentity(USER_ID),
+ new File("application-nodes.json"));
// GET clusters
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
- .userIdentity(USER_ID),
- new File("application-clusters.json"));
+ .userIdentity(USER_ID),
+ new File("application-clusters.json"));
// GET logs
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-east-1/instance/default/logs?from=1233&to=3214", GET)
@@ -494,12 +494,12 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET controller logs
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/prod/region/controller/instance/default/logs?from=1233&to=3214", GET)
- .userIdentity(USER_ID),
- "INFO - All good");
+ .userIdentity(USER_ID),
+ "INFO - All good");
// Get content/../foo
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/instance/default/environment/dev/region/us-east-1/content/%2E%2E%2Ffoo", GET).userIdentity(USER_ID),
- accessDenied, 403);
+ accessDenied, 403);
// Get content - root
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/instance/default/environment/dev/region/us-east-1/content/", GET).userIdentity(USER_ID),
"{\"path\":\"/\"}");
@@ -513,121 +513,121 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET metrics
tester.assertJsonResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-east-1/instance/default/metrics", GET)
.userIdentity(USER_ID),
- new File("proton-metrics.json"));
+ new File("proton-metrics.json"));
// POST a roll-out of the latest application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/application", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
// POST a roll-out of a given revision
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/application", POST)
- .data("{ \"build\": 1 }")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
+ .data("{ \"build\": 1 }")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
// DELETE (cancel) ongoing change
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Changed deployment from 'revision change to build 1' to 'no change' for tenant1.application1.instance1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Changed deployment from 'revision change to build 1' to 'no change' for tenant1.application1.instance1\"}");
// DELETE (cancel) again is a no-op
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
- .userIdentity(USER_ID)
- .data("{\"cancel\":\"all\"}"),
- "{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
+ .userIdentity(USER_ID)
+ .data("{\"cancel\":\"all\"}"),
+ "{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
// POST pinning to a given version to an application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
- .userIdentity(USER_ID)
- .data("6.1.0"),
- "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
- assertTrue("Action is logged to audit log",
- tester.controller().auditLogger().readLog().entries().stream()
- .anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
+ .userIdentity(USER_ID)
+ .data("6.1.0"),
+ "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
+ assertTrue(tester.controller().auditLogger().readLog().entries().stream()
+ .anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")),
+ "Action is logged to audit log");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
// DELETE only the pin to a given version
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
// POST pinning again
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
- .userIdentity(USER_ID)
- .data("6.1"),
- "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID)
+ .data("6.1"),
+ "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
// DELETE only the version, but leave the pin
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"pinned\":true}");
// DELETE also the pin to a given version
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{}");
+ .userIdentity(USER_ID), "{}");
// POST a pause to a production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
// DELETE a pause of a production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
// POST a triggering to the same production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
// POST a 'reindex application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("indexedOnly", "true",
- "speed", "10"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, for indexed types, with speed 10.0\"}");
+ .properties(Map.of("indexedOnly", "true",
+ "speed", "10"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, for indexed types, with speed 10.0\"}");
// POST a 'reindex application' command with cluster filter
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("clusterId", "boo,moo"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo\"}");
+ .properties(Map.of("clusterId", "boo,moo"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo\"}");
// POST a 'reindex application' command with cluster and document type filters
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("clusterId", "boo,moo",
- "documentType", "foo,boo"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo, for types foo, boo\"}");
+ .properties(Map.of("clusterId", "boo,moo",
+ "documentType", "foo,boo"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo, for types foo, boo\"}");
// POST to enable reindexing
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Enabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Enabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
// DELETE to disable reindexing
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Disabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Disabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
// GET to get reindexing status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", GET)
- .userIdentity(USER_ID),
- "{\"enabled\":true,\"clusters\":[{\"name\":\"cluster\",\"pending\":[{\"type\":\"type\",\"requiredGeneration\":100}],\"ready\":[{\"type\":\"type\",\"readyAtMillis\":345,\"startedAtMillis\":456,\"endedAtMillis\":567,\"state\":\"failed\",\"message\":\"(#`д´)ノ\",\"progress\":0.1,\"speed\":1.0}]}]}");
+ .userIdentity(USER_ID),
+ "{\"enabled\":true,\"clusters\":[{\"name\":\"cluster\",\"pending\":[{\"type\":\"type\",\"requiredGeneration\":100}],\"ready\":[{\"type\":\"type\",\"readyAtMillis\":345,\"startedAtMillis\":456,\"endedAtMillis\":567,\"state\":\"failed\",\"message\":\"(#`д´)ノ\",\"progress\":0.1,\"speed\":1.0}]}]}");
// POST to request a service dump
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/node/host-tenant1.application1.instance1-prod.us-central-1/service-dump", POST)
@@ -643,112 +643,122 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST a 'restart application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
// POST a 'restart application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
// POST a 'restart application' in staging environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/restart", POST)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-east-3\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-east-3\"}");
// POST a 'restart application' in test environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/restart", POST)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-east-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-east-1\"}");
// POST a 'restart application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1/restart", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'restart application' command with a host filter (other filters not supported yet)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
+ .properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
// POST a 'suspend application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/dev/region/us-east-1/suspend", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Suspended orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Suspended orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'resume application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/dev/region/us-east-1/suspend", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Resumed orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Resumed orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'suspend application' in prod environment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/suspend", POST)
- .userIdentity(USER_ID),
- accessDenied, 403);
+ .userIdentity(USER_ID),
+ accessDenied, 403);
// GET suspended
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
- .userIdentity(USER_ID),
- new File("suspended.json"));
+ .userIdentity(USER_ID),
+ new File("suspended.json"));
// GET service/state/v1
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/service/storagenode/host.com/state/v1/?foo=bar", GET)
- .userIdentity(USER_ID),
- new File("service"));
+ .userIdentity(USER_ID),
+ new File("service"));
// GET orchestrator
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/orchestrator", GET)
- .userIdentity(USER_ID),
- "{\"json\":\"thank you very much\"}");
+ .userIdentity(USER_ID),
+ "{\"json\":\"thank you very much\"}");
+
+ // GET application package which has been deployed to production
+ tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
+ .properties(Map.of("build", "latestDeployed"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
+ },
+ 200);
// DELETE application with active deployments fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("delete-with-active-deployments.json"), 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("delete-with-active-deployments.json"), 400);
// DELETE (deactivate) a deployment - dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
// DELETE (deactivate) a deployment - prod
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
// DELETE (deactivate) a deployment is idempotent
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
// Setup for test config tests
tester.controller().jobController().deploy(ApplicationId.from("tenant1", "application1", "default"),
- DeploymentContext.productionUsCentral1,
- Optional.empty(),
- applicationPackageDefault);
+ DeploymentContext.productionUsCentral1,
+ Optional.empty(),
+ applicationPackageDefault);
tester.controller().jobController().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
- DeploymentContext.devUsEast1,
- Optional.empty(),
- applicationPackageDefault);
+ DeploymentContext.devUsEast1,
+ Optional.empty(),
+ applicationPackageDefault);
// GET test-config for local tests against a dev deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
- .userIdentity(USER_ID),
- new File("test-config-dev.json"));
+ .userIdentity(USER_ID),
+ new File("test-config-dev.json"));
// GET test-config for local tests against a prod deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
- .userIdentity(USER_ID),
- new File("test-config.json"));
+ .userIdentity(USER_ID),
+ new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
- ZoneId.from("prod", "us-central-1"));
+ ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
- ZoneId.from("dev", "us-east-1"));
+ ZoneId.from("dev", "us-east-1"));
// teardown for test config tests
// Second attempt has a service under a different domain than the tenant of the application, and fails.
@@ -759,9 +769,9 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
// Third attempt has a service under the domain of the tenant, and also succeeds.
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
@@ -773,54 +783,54 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(packageWithService, 123)),
- "{\"message\":\"application build 2, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(packageWithService, 123)),
+ "{\"message\":\"application build 2, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/diff/2", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> assertTrue(response.getBodyAsString(),
- response.getBodyAsString().contains("+ <deployment version='1.0' athenz-domain='domain1' athenz-service='service'>\n" +
- "- <deployment version='1.0' >\n")),
- 200);
+ (response) -> assertTrue(response.getBodyAsString().contains("+ <deployment version='1.0' athenz-domain='domain1' athenz-service='service'>\n" +
+ "- <deployment version='1.0' >\n"),
+ response.getBodyAsString()),
+ 200);
// GET last submitted application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(packageWithService.zippedContent(), response.getBody());
- },
- 200);
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(packageWithService.zippedContent(), response.getBody());
+ },
+ 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR).properties(Map.of("tests", "true")),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-tests2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals("content".getBytes(UTF_8), response.getBody());
- },
- 200);
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-tests2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals("content".getBytes(UTF_8), response.getBody());
+ },
+ 200);
// GET application package for specific build
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "2"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(packageWithService.zippedContent(), response.getBody());
- },
- 200);
+ .properties(Map.of("build", "2"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(packageWithService.zippedContent(), response.getBody());
+ },
+ 200);
// Fourth attempt has a wrong content hash in a header, and fails.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .header("X-Content-Hash", "not/the/right/hash")
- .data(createApplicationSubmissionData(packageWithService, 123)),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .header("X-Content-Hash", "not/the/right/hash")
+ .data(createApplicationSubmissionData(packageWithService, 123)),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
// Fifth attempt has the right content hash in a header, and succeeds.
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
- .data(streamer),
- "{\"message\":\"application build 3, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
+ .data(streamer),
+ "{\"message\":\"application build 3, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
// Sixth attempt has a multi-instance deployment spec, and is accepted.
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
@@ -831,53 +841,53 @@ public class ApplicationApiTest extends ControllerContainerTest {
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(multiInstanceSpec, 123)),
- "{\"message\":\"application build 4, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(multiInstanceSpec, 123)),
+ "{\"message\":\"application build 4, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
// DELETE submitted build, to mark it as non-deployable
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/2", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Marked build '2' as non-deployable\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Marked build '2' as non-deployable\"}");
// GET deployment job overview, after triggering system and staging test jobs.
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs().triggered());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
- .userIdentity(USER_ID),
- new File("jobs.json"));
+ .userIdentity(USER_ID),
+ new File("jobs.json"));
// GET deployment job overview for whole application.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
- .userIdentity(USER_ID),
- new File("deployment-overview.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-overview.json"));
// GET system test job overview.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
- .userIdentity(USER_ID),
- new File("system-test-job.json"));
+ .userIdentity(USER_ID),
+ new File("system-test-job.json"));
// GET system test run 1 details.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
- .userIdentity(USER_ID),
- new File("system-test-details.json"));
+ .userIdentity(USER_ID),
+ new File("system-test-details.json"));
// DELETE a running job to have it aborted.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
// GET compile version for specific major
deploymentTester.controllerTester().upgradeSystem(Version.fromString("7.0"));
deploymentTester.controllerTester().flagSource().withListFlag(PermanentFlags.INCOMPATIBLE_VERSIONS.id(), List.of("*"), String.class);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/compile-version", GET)
- .userIdentity(USER_ID).properties(Map.of("allowMajor", "7")),
- "{\"compileVersion\":\"7.0.0\"}");
+ .userIdentity(USER_ID).properties(Map.of("allowMajor", "7")),
+ "{\"compileVersion\":\"7.0.0\"}");
// OPTIONS return 200 OK
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
- .userIdentity(USER_ID),
- "");
+ .userIdentity(USER_ID),
+ "");
addNotifications(TenantName.from("tenant1"));
addNotifications(TenantName.from("tenant2"));
@@ -892,14 +902,14 @@ public class ApplicationApiTest extends ControllerContainerTest {
// DELETE the application which no longer has any deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant1.application1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant1.application1\"}");
// DELETE an empty tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted tenant tenant1\"}");
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted tenant tenant1\"}");
// The tenant is not found
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID)
@@ -937,7 +947,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testRotationOverride() {
+ void testRotationOverride() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
@@ -955,60 +965,60 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Invalid application fails
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
- 400);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
+ 400);
// Invalid deployment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
+ 404);
// Change status of non-existing deployment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
- 404);
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
+ 404);
// GET global rotation status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .userIdentity(USER_ID),
- new File("global-rotation.json"));
+ .userIdentity(USER_ID),
+ new File("global-rotation.json"));
// GET global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
- .userIdentity(USER_ID),
- new File("global-rotation-get.json"));
+ .userIdentity(USER_ID),
+ new File("global-rotation-get.json"));
// SET global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-put.json"));
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-put.json"));
// Status of routing policy is changed
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
// DELETE global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-delete.json"));
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
// SET global rotation override status by operator
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
- .userIdentity(HOSTED_VESPA_OPERATOR)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-put.json"));
+ .userIdentity(HOSTED_VESPA_OPERATOR)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.out, RoutingStatus.Agent.operator);
}
@Test
- public void multiple_endpoints() {
+ void multiple_endpoints() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -1026,34 +1036,34 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET global rotation status without specifying endpointId fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
- 400);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
+ 400);
// GET global rotation status for us-west-1 in default endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "default"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "default"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
// GET global rotation status for us-west-1 in eu endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "eu"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "eu"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
// GET global rotation status for eu-west-1 in eu endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "eu"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "eu"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
}
@Test
- public void testDeployWithApplicationPackage() {
+ void testDeployWithApplicationPackage() {
// Setup
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
deploymentTester.controllerTester().upgradeController(new Version("6.2"));
@@ -1061,22 +1071,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) a system application with an application package
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
- .data(noAppEntity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
- 400);
+ .data(noAppEntity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
+ 400);
deploymentTester.controllerTester()
- .upgradeSystem(deploymentTester.controller().readVersionStatus().controllerVersion().get()
- .versionNumber());
+ .upgradeSystem(deploymentTester.controller().readVersionStatus().controllerVersion().get()
+ .versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
- .data(noAppEntity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- new File("deploy-result.json"));
+ .data(noAppEntity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ new File("deploy-result.json"));
}
@Test
- public void testRemovingAllDeployments() {
+ void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
@@ -1106,100 +1116,100 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testErrorResponses() {
+ void testErrorResponses() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
// PUT (update) non-existing tenant returns 403 as tenant access cannot be determined when the tenant does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- accessDenied,
- 403);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ accessDenied,
+ 403);
// GET non-existing tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
+ 404);
// GET non-existing tenant's applications
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
+ 404);
// GET non-existing application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
+ 404);
// GET non-existing deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
+ 404);
// POST (add) a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"));
// POST (add) another tenant under the same domain
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
+ 400);
// Add the same tenant again
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
+ 400);
// POST (add) an Athenz tenant with underscore in name
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
+ 400);
// POST (add) an Athenz tenant with a reserved name
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
+ 400);
// POST (create) an (empty) application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"));
// Create the same application again
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
- 400);
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
+ 400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, "Failed to prepare application", "Invalid application package"));
// GET non-existent application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"no application package has been submitted for tenant1.application1\"}",
- 404);
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"no application package has been submitted for tenant1.application1\"}",
+ 404);
// GET non-existent application package of specific build
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
@@ -1208,63 +1218,63 @@ public class ApplicationApiTest extends ControllerContainerTest {
.data(createApplicationSubmissionData(applicationPackageInstance1, 1000)),
"{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "42"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"No build 42 found for tenant1.application1\"}",
- 404);
+ .properties(Map.of("build", "42"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"No build 42 found for tenant1.application1\"}",
+ 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE).userIdentity(USER_ID).oAuthCredentials(OKTA_CREDENTIALS),
"{\"message\":\"All deployments removed\"}");
// GET non-existent application package of invalid build
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "foobar"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"invalid value for request parameter 'build': For input string: \\\"foobar\\\"\"}",
- 400);
-
+ .properties(Map.of("build", "foobar"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"invalid value for request parameter 'build': For input string: \\\"foobar\\\"\"}",
+ 400);
+
// POST (deploy) an application to legacy deploy path
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1/deploy", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of tenant1.application1.instance1 is not supported through this API\"}", 400);
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of tenant1.application1.instance1 is not supported through this API\"}", 400);
// DELETE tenant which has an application
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
- 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
+ 400);
// DELETE application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
// DELETE application again - should produce 404
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
- 404);
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
+ 404);
// DELETE and forget an application as non-operator
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).properties(Map.of("forget", "true"))
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"Only operators can forget a tenant\"}",
- 403);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"Only operators can forget a tenant\"}",
+ 403);
// DELETE tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted tenant tenant1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted tenant tenant1\"}");
// DELETE tenant again returns 403 as tenant access cannot be determined when the tenant does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID),
- accessDenied,
- 403);
+ .userIdentity(USER_ID),
+ accessDenied,
+ 403);
// Create legacy tenant name containing underscores
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
@@ -1272,116 +1282,116 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (add) a Athenz tenant with dashes duplicates existing one with underscores
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
+ 400);
}
@Test
- public void testAuthorization() {
+ void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
-
+
// Mutation without an user is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "{\n \"message\" : \"Not authenticated\"\n}",
- 401);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "{\n \"message\" : \"Not authenticated\"\n}",
+ 401);
// ... but read methods are allowed for authenticated user
tester.assertResponse(request("/application/v4/tenant/", GET)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "[]",
- 200);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "[]",
+ 200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
// Creating a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(unauthorizedUser),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
- 403);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(unauthorizedUser),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
+ 403);
// (Create it with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"),
- 200);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"),
+ 200);
// Creating an application for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(unauthorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ accessDenied,
+ 403);
// (Create it with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"),
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"),
+ 200);
// Deploy to an authorized zone by a user tenant is disallowed
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
- .data(entity)
- .userIdentity(USER_ID),
- accessDenied,
- 403);
+ .data(entity)
+ .userIdentity(USER_ID),
+ accessDenied,
+ 403);
// Deleting an application for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
// Create another instance under the application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference-default.json"),
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference-default.json"),
+ 200);
// (Deleting the application with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant1.application1\"}",
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant1.application1\"}",
+ 200);
// Updating a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
-
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
+
// Change Athens domain
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant1.json"),
- 200);
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant1.json"),
+ 200);
// Deleting a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
}
@Test
- public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
+ void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
@@ -1397,10 +1407,10 @@ public class ApplicationApiTest extends ControllerContainerTest {
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
// Submit a package with a service under a different Athenz domain from that of the tenant
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
- 400);
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
+ 400);
// Set the correct domain in the application package, but do not yet allow Vespa to launch the service.
applicationPackage = new ApplicationPackageBuilder()
@@ -1410,22 +1420,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
- 400);
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
+ 400);
// Allow Vespa to launch the Athenz service.
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
- public void personal_deployment_with_athenz_service_requires_user_is_admin() {
+ void personal_deployment_with_athenz_service_requires_user_is_admin() {
// Setup
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
@@ -1440,26 +1450,26 @@ public class ApplicationApiTest extends ControllerContainerTest {
MultiPartStreamer entity = createApplicationDeployData(applicationPackage);
// POST (deploy) an application to dev through a deployment job, with user instance and a proper tenant
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
- .data(entity)
- .userIdentity(userId),
- accessDenied,
- 403);
+ .data(entity)
+ .userIdentity(userId),
+ accessDenied,
+ 403);
// Add "new-user" to the admin role, to allow service launches.
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
- .admin(HostedAthenzIdentities.from(userId));
+ .admin(HostedAthenzIdentities.from(userId));
// POST (deploy) an application to dev through a deployment job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
- .data(entity)
- .userIdentity(userId),
- "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(userId),
+ "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
- @Test
// Deploy to sandbox tenant launching a service from another domain.
- public void developers_can_deploy_when_privileged() {
+ @Test
+ void developers_can_deploy_when_privileged() {
// Create an athenz domain where the developer is not yet authorized
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
@@ -1493,7 +1503,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Allow developer launch privilege to domain1.service. Deployment now completes.
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
- domainMock.withPolicy("launch-" +developer.id(), "user." + developer.id(), "launch", "service.service");
+ domainMock.withPolicy("launch-" + developer.id(), "user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
@@ -1516,25 +1526,25 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) an application package as content type application/zip — not multipart
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
- .data(applicationPackageInstance1.zippedContent())
- .contentType("application/zip")
- .userIdentity(developer2),
- "{\"message\":\"Deployment started in run 3 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":3}");
+ .data(applicationPackageInstance1.zippedContent())
+ .contentType("application/zip")
+ .userIdentity(developer2),
+ "{\"message\":\"Deployment started in run 3 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":3}");
// POST (deploy) an application package not as content type application/zip — not multipart — is disallowed
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
- .data(applicationPackageInstance1.zippedContent())
- .contentType("application/gzip")
- .userIdentity(developer2),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Expected a multipart or application/zip message, but got Content-Type: application/gzip\"}", 400);
+ .data(applicationPackageInstance1.zippedContent())
+ .contentType("application/gzip")
+ .userIdentity(developer2),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Expected a multipart or application/zip message, but got Content-Type: application/gzip\"}", 400);
}
@Test
- public void applicationWithRoutingPolicy() {
+ void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
- RoutingMethod.exclusive);
+ RoutingMethod.exclusive);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.instances("instance1")
@@ -1545,22 +1555,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("instance-with-routing-policy.json"));
+ .userIdentity(USER_ID),
+ new File("instance-with-routing-policy.json"));
// GET deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment-with-routing-policy.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-with-routing-policy.json"));
// GET deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment-without-shared-endpoints.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-without-shared-endpoints.json"));
}
@Test
- public void support_access() {
+ void support_access() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.exclusive);
@@ -1591,15 +1601,15 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Grant access to support user
X509Certificate support_cert = grantCertificate(now, now.plusSeconds(3600));
- String grantPayload= "{\n" +
- " \"applicationId\": \"tenant1:application1:instance1\",\n" +
- " \"zone\": \"prod.us-west-1\",\n" +
- " \"certificate\":\""+X509CertificateUtils.toPem(support_cert)+ "\"\n" +
- "}";
- tester.assertResponse(request("/controller/v1/access/grants/"+HOSTED_VESPA_OPERATOR.id(), POST)
- .data(grantPayload)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Operator user.johnoperator granted access and job production-us-west-1 triggered\"}");
+ String grantPayload = "{\n" +
+ " \"applicationId\": \"tenant1:application1:instance1\",\n" +
+ " \"zone\": \"prod.us-west-1\",\n" +
+ " \"certificate\":\"" + X509CertificateUtils.toPem(support_cert) + "\"\n" +
+ "}";
+ tester.assertResponse(request("/controller/v1/access/grants/" + HOSTED_VESPA_OPERATOR.id(), POST)
+ .data(grantPayload)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Operator user.johnoperator granted access and job production-us-west-1 triggered\"}");
// GET shows grant
String grantResponse = allowedResponse.replaceAll("\"grants\":\\[]",
@@ -1621,7 +1631,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
// DELETE removes access
String disallowedResponse = grantResponse
.replaceAll("ALLOWED\".*?}", "NOT_ALLOWED\"}")
- .replace("history\":[", "history\":[{\"state\":\"disallowed\",\"at\":\""+ serializeInstant(now) +"\",\"by\":\"user.myuser\"},");
+ .replace("history\":[", "history\":[{\"state\":\"disallowed\",\"at\":\"" + serializeInstant(now) + "\",\"by\":\"user.myuser\"},");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/access/support", DELETE)
.userIdentity(USER_ID),
disallowedResponse, 200
@@ -1636,7 +1646,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void create_application_on_deploy() {
+ void create_application_on_deploy() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
@@ -1658,7 +1668,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.oAuthCredentials(OKTA_CREDENTIALS)
-
+
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
index 5a4d47e0db5..4166ce8b81e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
@@ -3,8 +3,8 @@ package com.yahoo.vespa.hosted.controller.restapi.application;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* @author mpolden
@@ -13,13 +13,13 @@ public class CliApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/");
}
@Test
- public void root() {
+ void root() {
tester.assertResponse(authenticatedRequest("http://localhost:8080/cli/v1/"), "{\"minVersion\":\"7.547.18\"}");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
index d2698afdc48..233b460333e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.notification.Notification.Type;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
@@ -40,7 +40,7 @@ import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.deploymentF
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.installationFailed;
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.running;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -49,7 +49,7 @@ import static org.junit.Assert.assertEquals;
public class JobControllerApiHandlerHelperTest {
@Test
- public void testResponses() {
+ void testResponses() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.stagingTest()
.blockChange(true, true, "mon,tue", "7-13", "UTC")
@@ -100,7 +100,7 @@ public class JobControllerApiHandlerHelperTest {
// Revision 3 starts.
app.submit(applicationPackage)
- .runJob(systemTest).runJob(stagingTest);
+ .runJob(systemTest).runJob(stagingTest);
tester.triggerJobs(); // Starts runs for us-central-1 and a new staging test run.
tester.runner().run();
assertEquals(running, tester.jobs().last(app.instanceId(), productionUsCentral1).get().status());
@@ -147,7 +147,7 @@ public class JobControllerApiHandlerHelperTest {
}
@Test
- public void testDevResponses() {
+ void testDevResponses() {
DeploymentTester tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -167,7 +167,7 @@ public class JobControllerApiHandlerHelperTest {
}
@Test
- public void testResponsesWithDirectDeployment() {
+ void testResponsesWithDirectDeployment() {
var tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -176,11 +176,11 @@ public class JobControllerApiHandlerHelperTest {
// Deploy directly to production zone, like integration tests.
tester.controller().jobController().deploy(tester.instance().id(), productionUsWest1, Optional.empty(), applicationPackage);
assertResponse(JobControllerApiHandlerHelper.jobTypeResponse(tester.controller(), app.instanceId(), URI.create("https://some.url:43/root/")),
- "jobs-direct-deployment.json");
+ "jobs-direct-deployment.json");
}
@Test
- public void testResponsesWithDryRunDeployment() {
+ void testResponsesWithDryRunDeployment() {
var tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -189,7 +189,7 @@ public class JobControllerApiHandlerHelperTest {
// Deploy directly to production zone, like integration tests, with dryRun.
tester.controller().jobController().deploy(tester.instance().id(), productionUsWest1, Optional.empty(), applicationPackage, true);
assertResponse(JobControllerApiHandlerHelper.jobTypeResponse(tester.controller(), app.instanceId(), URI.create("https://some.url:43/root/")),
- "jobs-direct-deployment.json");
+ "jobs-direct-deployment.json");
}
private void assertResponse(HttpResponse response, String fileName) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
index 12a0a00713c..37f4c19e27a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
@@ -7,16 +7,16 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -24,25 +24,25 @@ import static org.junit.Assert.fail;
public class MultipartParserTest {
@Test
- public void parser() {
+ void parser() {
String data =
"Content-Type: multipart/form-data; boundary=AaB03x\r\n" +
- "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
- "\r\n" +
- "Larry\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- "House 1\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- "... contents of file1.txt ...\r\n" +
- "--AaB03x--\r\n";
+ "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
+ "\r\n" +
+ "Larry\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ "House 1\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ "... contents of file1.txt ...\r\n" +
+ "--AaB03x--\r\n";
Map<String, byte[]> parts = parse(data, Long.MAX_VALUE);
assertEquals(3, parts.size());
assertTrue(parts.containsKey("submit-name"));
@@ -53,22 +53,22 @@ public class MultipartParserTest {
}
@Test
- public void max_length() {
+ void max_length() {
String part1 = "Larry";
String part2 = "House 1";
String data =
"Content-Type: multipart/form-data; boundary=AaB03x\r\n" +
- "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
- "\r\n" +
- part1 + "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- part2 + "\r\n" +
- "--AaB03x--\r\n";
+ "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
+ "\r\n" +
+ part1 + "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ part2 + "\r\n" +
+ "--AaB03x--\r\n";
parse(data, part1.length() + part2.length());
try {
parse(data, part1.length() + part2.length() - 1);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview-2.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview-2.json
index 481997102d2..a7e2d1913cf 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview-2.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview-2.json
@@ -158,7 +158,6 @@
"jobName": "system-test",
"url": "https://some.url:43/instance/default/job/system-test",
"environment": "test",
- "region": "test.us-east-1",
"toRun": [ ],
"runs": [
{
@@ -348,7 +347,6 @@
"jobName": "staging-test",
"url": "https://some.url:43/instance/default/job/staging-test",
"environment": "staging",
- "region": "staging.us-east-3",
"toRun": [
{
"versions": {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview.json
index f39aab26d75..38e9d8c823e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/deployment-overview.json
@@ -62,7 +62,6 @@
"jobName": "system-test",
"url": "http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test",
"environment": "test",
- "region": "test.us-east-1",
"toRun": [ ],
"runs": [
{
@@ -191,7 +190,6 @@
"jobName": "staging-test",
"url": "http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test",
"environment": "staging",
- "region": "staging.us-east-3",
"toRun": [ ],
"runs": [
{
@@ -430,6 +428,7 @@
"url": "http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/run/1",
"start": 1600000000000,
"status": "running",
+ "reason": "triggered by user.myuser",
"versions": {
"targetPlatform": "6.1.0",
"targetApplication": {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-first-part.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-first-part.json
index 63869ecfba8..9b391196d55 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-first-part.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-first-part.json
@@ -11,6 +11,11 @@
{
"at": 0,
"type": "info",
+ "message": "Using CA signed certificate version 0"
+ },
+ {
+ "at": 0,
+ "type": "info",
"message": "Deployment successful."
},
{
@@ -49,7 +54,7 @@
}
]
},
- "lastId": 7,
+ "lastId": 8,
"steps": {
"deployReal": {
"status": "succeeded",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-second-part.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-second-part.json
index 175c45eb2cd..4ffac2bf738 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-second-part.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1-log-second-part.json
@@ -6,6 +6,11 @@
{
"at": 0,
"type": "info",
+ "message": "Found endpoints:"
+ },
+ {
+ "at": 0,
+ "type": "info",
"message": "- dev.us-east-1"
},
{
@@ -20,7 +25,7 @@
}
]
},
- "lastId": 11,
+ "lastId": 12,
"steps": {
"deployReal": {
"status": "succeeded",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1.json
deleted file mode 100644
index 2ca520c0122..00000000000
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/dev-us-east-1.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "tenant": "tenant1",
- "application": "application1",
- "instance": "instance1",
- "environment": "dev",
- "region": "us-east-1",
- "endpoints": [
- {
- "cluster": "default",
- "tls": true,
- "url": "https://instance1.application1.tenant1.us-east-1.dev.vespa.oath.cloud/",
- "scope": "zone",
- "routingMethod": "sharedLayer4",
- "legacy": false
- }
- ],
- "clusters":"http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/dev/region/us-east-1/clusters",
- "nodes": "http://localhost:8080/zone/v2/dev/us-east-1/nodes/v2/node/?recursive=true&application=tenant1.application1.instance1",
- "yamasUrl": "http://monitoring-system.test/?environment=dev&region=us-east-1&application=tenant1.application1.instance1",
- "version": "(ignore)",
- "revision": "(ignore)",
- "deployTimeEpochMs": "(ignore)",
- "screwdriverId": "123",
- "status": "complete",
- "quota": "(ignore)",
- "activity": {
- "lastQueried": 1527848130000,
- "lastWritten": 1527848130000,
- "lastQueriesPerSecond": 1.0,
- "lastWritesPerSecond": 2.0
- },
- "metrics": {
- "queriesPerSecond": 1.0,
- "writesPerSecond": 2.0,
- "documentCount": 3.0,
- "queryLatencyMillis": 4.0,
- "writeLatencyMillis": 5.0,
- "lastUpdated": 123123
- }
-}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/instance1-metering.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/instance1-metering.json
deleted file mode 100644
index 2e07a7e8a96..00000000000
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/instance1-metering.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "currentrate": {
- "cpu": 1.0,
- "mem": 2.0,
- "disk": 3.0
- },
- "thismonth": {
- "cpu": 12.0,
- "mem": 24.0,
- "disk": 1000.0
- },
- "lastmonth": {
- "cpu": 24.0,
- "mem": 48.0,
- "disk": 2000.0
- },
- "details": {
- "cpu": {
- "default": {
- "data": [
- {"unixms":123,"value":1.0},
- {"unixms":246,"value":1.0},
- {"unixms":492,"value":1.0}
- ]
- }
- },
- "mem": {
- "default": {
- "data": [
- {"unixms":123,"value":2.0},
- {"unixms":246,"value":2.0},
- {"unixms":492,"value":2.0}
- ]
- }
- },
- "disk": {
- "default": {
- "data": [
- {"unixms":123,"value":3.0},
- {"unixms":246,"value":3.0},
- {"unixms":492,"value":3.0}
- ]
- }
- }
- }
-} \ No newline at end of file
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/jobs.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/jobs.json
index 12430b67539..2477e8df56e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/jobs.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/jobs.json
@@ -9,6 +9,7 @@
"start": 1600000000000,
"end": 1600000000000,
"status": "success",
+ "reason": "triggered by user.myuser",
"versions": {
"targetPlatform": "6.1.0",
"targetApplication": {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/prod-us-central-1.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/prod-us-central-1.json
deleted file mode 100644
index 2daa7f54cf6..00000000000
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/prod-us-central-1.json
+++ /dev/null
@@ -1,74 +0,0 @@
-{
- "bcpStatus": {
- "rotationStatus": "UNKNOWN"
- },
- "tenant": "tenant1",
- "application": "application1",
- "instance": "instance1",
- "environment": "prod",
- "region": "us-central-1",
- "endpoints": [
- {
- "cluster": "default",
- "tls": true,
- "url": "https://instance1.application1.tenant1.us-central-1.vespa.oath.cloud/",
- "scope": "zone",
- "routingMethod": "sharedLayer4",
- "legacy": false
- },
- {
- "cluster": "foo",
- "tls": true,
- "url": "https://instance1.application1.tenant1.global.vespa.oath.cloud/",
- "scope": "global",
- "routingMethod": "sharedLayer4",
- "legacy": false
- },
- {
- "cluster": "foo",
- "tls": true,
- "url": "https://a0.application1.tenant1.us-central-1-r.vespa.oath.cloud/",
- "scope": "application",
- "routingMethod": "sharedLayer4",
- "legacy": false
- }
- ],
- "clusters": "http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/clusters",
- "nodes": "http://localhost:8080/zone/v2/prod/us-central-1/nodes/v2/node/?recursive=true&application=tenant1.application1.instance1",
- "yamasUrl": "http://monitoring-system.test/?environment=prod&region=us-central-1&application=tenant1.application1.instance1",
- "version": "(ignore)",
- "revision": "(ignore)",
- "deployTimeEpochMs": "(ignore)",
- "screwdriverId": "123",
- "endpointStatus": [
- {
- "endpointId": "default",
- "rotationId": "rotation-id-1",
- "clusterId": "foo",
- "status": "UNKNOWN",
- "lastUpdated": "(ignore)"
- }
- ],
- "applicationVersion": {
- "build": 1,
- "compileVersion": "6.1.0",
- "sourceUrl": "repository1/tree/commit1",
- "commit": "commit1"
- },
- "status": "complete",
- "quota": "(ignore)",
- "activity": {
- "lastQueried": 1527848130000,
- "lastWritten": 1527848130000,
- "lastQueriesPerSecond": 1.0,
- "lastWritesPerSecond": 2.0
- },
- "metrics": {
- "queriesPerSecond": 1.0,
- "writesPerSecond": 2.0,
- "documentCount": 3.0,
- "queryLatencyMillis": 4.0,
- "writeLatencyMillis": 5.0,
- "lastUpdated": 123123
- }
-}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/staging-test-log.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/staging-test-log.json
index ba65b962a73..a2f62621f5b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/staging-test-log.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/staging-test-log.json
@@ -85,6 +85,11 @@
{
"at": 14503000,
"type": "info",
+ "message": "Using CA signed certificate version 0"
+ },
+ {
+ "at": 14503000,
+ "type": "info",
"message": "Deployment successful."
},
{
@@ -160,7 +165,7 @@
}
]
},
- "lastId": 29,
+ "lastId": 30,
"steps": {
"deployTester": {
"status": "succeeded",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-details.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-details.json
index 3b505bc11fd..a691762c40b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-details.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-details.json
@@ -105,6 +105,11 @@
{
"at": 1600000000000,
"type": "info",
+ "message": "Using CA signed certificate version 1"
+ },
+ {
+ "at": 1600000000000,
+ "type": "info",
"message": "Deployment successful."
},
{
@@ -354,7 +359,7 @@
}
]
},
- "lastId": 66,
+ "lastId": 67,
"steps": {
"deployTester": {
"status": "succeeded",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-log.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-log.json
index 5bf6822baff..4e8737d5f67 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-log.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/system-test-log.json
@@ -100,6 +100,11 @@
{
"at": 0,
"type": "info",
+ "message": "Using CA signed certificate version 0"
+ },
+ {
+ "at": 0,
+ "type": "info",
"message": "Deployment successful."
},
{
@@ -349,7 +354,7 @@
}
]
},
- "lastId": 66,
+ "lastId": 67,
"steps": {
"deployTester": {
"status": "succeeded",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/tenant-with-application-with-metadata.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/tenant-with-application-with-metadata.json
deleted file mode 100644
index 194f2cdd494..00000000000
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/tenant-with-application-with-metadata.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "tenant": "tenant1",
- "type": "ATHENS",
- "athensDomain": "domain1",
- "property": "property1",
- "applications": [
- {
- "tenant": "tenant1",
- "application":"application1",
- "instance":"instance1",
- "url":"http://localhost:8080/application/v4/tenant/tenant1/application/application1/instance/instance1"
- }
- ],
- "metaData": {
- "createdAtMillis": "(ignore)",
- "lastDeploymentToDevMillis":"(ignore)",
- "lastSubmissionToProdMillis":1000
- }
-}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
index de3968727d6..3a539987443 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
@@ -19,7 +19,7 @@ public class AthenzApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/responses/";
@Test
- public void testAthenzApi() {
+ void testAthenzApi() {
ContainerTester tester = new ContainerTester(container, responseFiles);
ControllerTester controllerTester = new ControllerTester(tester);
@@ -38,19 +38,19 @@ public class AthenzApiTest extends ControllerContainerTest {
// GET root
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/"),
- new File("root.json"));
+ new File("root.json"));
// GET Athenz domains
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/domains"),
- new File("athensDomain-list.json"));
+ new File("athensDomain-list.json"));
// GET properties
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/properties/"),
- new File("property-list.json"));
+ new File("property-list.json"));
// POST user signup
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/user", "", Request.Method.POST),
- "{\"message\":\"User 'bob' added to admin role of 'vespa.vespa.tenants.sandbox'\"}");
+ "{\"message\":\"User 'bob' added to admin role of 'vespa.vespa.tenants.sandbox'\"}");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
index 38ebe030e8e..aa9cb57f541 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
@@ -12,9 +12,8 @@ import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.math.BigDecimal;
@@ -30,8 +29,8 @@ import static com.yahoo.application.container.handler.Request.Method.DELETE;
import static com.yahoo.application.container.handler.Request.Method.GET;
import static com.yahoo.application.container.handler.Request.Method.PATCH;
import static com.yahoo.application.container.handler.Request.Method.POST;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author olaa
@@ -47,7 +46,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void setup() {
tester = new ContainerTester(container, responseFiles);
billingController = (MockBillingController) tester.serviceRegistry().billingController();
@@ -79,32 +78,32 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void list_plans() {
+ void list_plans() {
var listPlansRequest = request("/billing/v1/plans", GET)
.roles(Role.hostedAccountant());
tester.assertResponse(listPlansRequest, "{\"plans\":[{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},{\"id\":\"paid\",\"name\":\"Paid Plan - for testing purposes\"},{\"id\":\"none\",\"name\":\"None Plan - for testing purposes\"}]}");
}
@Test
- public void setting_and_deleting_instrument() {
+ void setting_and_deleting_instrument() {
assertTrue(billingController.getDefaultInstrument(tenant).isEmpty());
var instrumentRequest = request("/billing/v1/tenant/tenant1/instrument", PATCH)
.data("{\"active\": \"id-1\"}")
.roles(tenantRole);
- tester.assertResponse(instrumentRequest,"OK");
+ tester.assertResponse(instrumentRequest, "OK");
assertEquals("id-1", billingController.getDefaultInstrument(tenant).get().getId());
var deleteInstrumentRequest = request("/billing/v1/tenant/tenant1/instrument/id-1", DELETE)
.roles(tenantRole);
- tester.assertResponse(deleteInstrumentRequest,"OK");
+ tester.assertResponse(deleteInstrumentRequest, "OK");
assertTrue(billingController.getDefaultInstrument(tenant).isEmpty());
}
@Test
- public void response_list_bills() {
+ void response_list_bills() {
var bill = createBill();
billingController.addBill(tenant, bill, true);
@@ -117,7 +116,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void test_bill_creation() {
+ void test_bill_creation() {
var bills = billingController.getBillsForTenant(tenant);
assertEquals(0, bills.size());
@@ -141,7 +140,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void adding_and_listing_line_item() {
+ void adding_and_listing_line_item() {
var requestBody = "{" +
"\"description\":\"some description\"," +
@@ -155,7 +154,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
tester.assertResponse(request, "{\"message\":\"Added line item for tenant tenant1\"}");
var lineItems = billingController.getUnusedLineItems(tenant);
- Assert.assertEquals(1, lineItems.size());
+ assertEquals(1, lineItems.size());
Bill.LineItem lineItem = lineItems.get(0);
assertEquals("some description", lineItem.description());
assertEquals(new BigDecimal("123.45"), lineItem.amount());
@@ -167,7 +166,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void adding_new_status() {
+ void adding_new_status() {
billingController.addBill(tenant, createBill(), true);
var requestBody = "{\"status\":\"DONE\"}";
@@ -181,7 +180,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void list_all_unbilled_items() {
+ void list_all_unbilled_items() {
tester.controller().tenants().create(new CloudTenantSpec(tenant, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
tester.controller().tenants().create(new CloudTenantSpec(tenant2, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
@@ -198,7 +197,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void setting_plans() {
+ void setting_plans() {
var planRequest = request("/billing/v1/tenant/tenant1/plan", PATCH)
.data("{\"plan\": \"new-plan\"}")
.roles(tenantRole);
@@ -207,7 +206,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void csv_export() {
+ void csv_export() {
var bill = createBill();
billingController.addBill(tenant, bill, true);
var csvRequest = request("/billing/v1/invoice/export", GET).roles(financeAdmin);
@@ -215,7 +214,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void patch_collection_method() {
+ void patch_collection_method() {
test_patch_collection_with_field_name("collectionMethod");
test_patch_collection_with_field_name("collection");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
index 58701732515..c62a9f1399f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
@@ -10,8 +10,8 @@ import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Set;
@@ -37,7 +37,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
private MockBillingController billingController;
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.controller().tenants().create(new CloudTenantSpec(tenant, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
@@ -68,13 +68,13 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_tenant_info() {
+ void require_tenant_info() {
var request = request("/billing/v2/tenant/" + tenant.value()).roles(tenantReader);
tester.assertResponse(request, "{\"tenant\":\"tenant1\",\"plan\":{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},\"collection\":\"AUTO\"}");
}
@Test
- public void require_admin_for_update_plan() {
+ void require_admin_for_update_plan() {
var request = request("/billing/v2/tenant/" + tenant.value(), Request.Method.PATCH)
.data("{\"plan\": \"paid\"}");
@@ -86,7 +86,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_accountant_for_update_collection() {
+ void require_accountant_for_update_collection() {
var request = request("/billing/v2/tenant/" + tenant.value(), Request.Method.PATCH)
.data("{\"collection\": \"INVOICE\"}");
@@ -99,13 +99,13 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_tenant_usage() {
+ void require_tenant_usage() {
var request = request("/billing/v2/tenant/" + tenant + "/usage").roles(tenantReader);
tester.assertResponse(request, "{\"from\":\"2021-04-13\",\"to\":\"2021-04-13\",\"total\":\"0.00\",\"items\":[]}");
}
@Test
- public void require_tenant_invoice() {
+ void require_tenant_invoice() {
var listRequest = request("/billing/v2/tenant/" + tenant + "/bill").roles(tenantReader);
tester.assertResponse(listRequest, "{\"invoices\":[{\"id\":\"id-1\",\"from\":\"2020-05-23\",\"to\":\"2020-05-28\",\"total\":\"123.00\",\"status\":\"OPEN\"}]}");
@@ -115,7 +115,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_accountant_summary() {
+ void require_accountant_summary() {
var tenantRequest = request("/billing/v2/accountant").roles(tenantReader);
tester.assertResponse(tenantRequest, "{\n" +
" \"code\" : 403,\n" +
@@ -124,17 +124,17 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
var accountantRequest = request("/billing/v2/accountant").roles(Role.hostedAccountant());
tester.assertResponse(accountantRequest, """
- {"tenants":[{"tenant":"tenant1","plan":{"id":"trial","name":"Free Trial - for testing purposes"},"collection":"AUTO","lastBill":null,"unbilled":"0.00"}]}""");
+ {"tenants":[{"tenant":"tenant1","plan":{"id":"trial","name":"Free Trial - for testing purposes"},"quota":{"budget":-1.0},"collection":"AUTO","lastBill":null,"unbilled":"0.00"}]}""");
}
@Test
- public void require_accountant_tenant_preview() {
+ void require_accountant_tenant_preview() {
var accountantRequest = request("/billing/v2/accountant/preview/tenant/tenant1").roles(Role.hostedAccountant());
tester.assertResponse(accountantRequest, "{\"id\":\"empty\",\"from\":\"2021-04-13\",\"to\":\"2021-04-12\",\"total\":\"0.00\",\"status\":\"OPEN\",\"statusHistory\":[{\"at\":\"2021-04-13T00:00:00Z\",\"status\":\"OPEN\"}],\"items\":[]}");
}
@Test
- public void require_accountant_tenant_bill() {
+ void require_accountant_tenant_bill() {
var accountantRequest = request("/billing/v2/accountant/preview/tenant/tenant1", Request.Method.POST)
.roles(Role.hostedAccountant())
.data("{\"from\": \"2020-05-01\",\"to\": \"2020-06-01\"}");
@@ -142,7 +142,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_list_of_all_plans() {
+ void require_list_of_all_plans() {
var accountantRequest = request("/billing/v2/accountant/plans")
.roles(Role.hostedAccountant());
tester.assertResponse(accountantRequest, "{\"plans\":[{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},{\"id\":\"paid\",\"name\":\"Paid Plan - for testing purposes\"},{\"id\":\"none\",\"name\":\"None Plan - for testing purposes\"}]}");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
index ea2c303d3f6..de2bf70997a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.HostAction;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Instant;
@@ -22,7 +22,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
@@ -32,7 +32,7 @@ public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responses);
addUserToHostedOperatorRole(operator);
@@ -42,26 +42,26 @@ public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_api() {
+ void test_api() {
assertFile(new Request("http://localhost:8080/changemanagement/v1/assessment", "{\"zone\":\"prod.us-east-3\", \"hosts\": [\"host1\"]}", Request.Method.POST), "initial.json");
assertFile(new Request("http://localhost:8080/changemanagement/v1/assessment", "{\"zone\":\"prod.us-east-3\", \"switches\": [\"switch1\"]}", Request.Method.POST), "initial.json");
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr"), "vcmrs.json");
}
@Test
- public void deletes_vcmr() {
+ void deletes_vcmr() {
assertEquals(1, tester.controller().curator().readChangeRequests().size());
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr/" + changeRequestId, "", Request.Method.DELETE), "vcmr.json");
assertEquals(0, tester.controller().curator().readChangeRequests().size());
}
@Test
- public void get_vcmr() {
+ void get_vcmr() {
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr/" + changeRequestId, "", Request.Method.GET), "vcmr.json");
}
@Test
- public void patch_vcmr() {
+ void patch_vcmr() {
var payload = "{" +
"\"approval\": \"REJECTED\"," +
"\"status\": \"COMPLETED\"," +
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
index ce6f713a13d..8bda8ba0d59 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
@@ -10,15 +10,15 @@ import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URI;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author freva
@@ -35,7 +35,7 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
private ConfigServerProxyMock proxy;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -45,14 +45,14 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /configserver/v1
tester.assertResponse(operatorRequest("http://localhost:8080/configserver/v1"),
new File("root.json"));
// GET /configserver/v1/nodes/v2
tester.assertResponse(operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2"),
- "ok");
+ "ok");
assertLastRequest("https://cfg.prod.us-north-1.test.vip:4443/", "GET");
// GET /configserver/v1/nodes/v2/node/?recursive=true
@@ -82,11 +82,11 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
assertLastRequest("https://cfg.dev.aws-us-north-2.test.vip:4443/", "PATCH");
assertEquals("{\"currentRestartGeneration\": 1}", proxy.lastRequestBody().get());
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void test_allowed_apis() {
+ void test_allowed_apis() {
// GET /configserver/v1/prod/us-north-1
tester.assertResponse(() -> operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-1/"),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Cannot access path '/' through /configserver/v1, following APIs are permitted: /flags/v1/, /nodes/v2/, /orchestrator/v1/\"}",
@@ -98,33 +98,33 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// POST /configserver/v1/prod/us-north-34/nodes/v2
tester.assertResponse(() -> operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-42/nodes/v2",
- "", Request.Method.POST),
+ "", Request.Method.POST),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-42\"}", 400);
assertFalse(proxy.lastReceived().isPresent());
}
@Test
- public void non_operators_are_forbidden() {
+ void non_operators_are_forbidden() {
// Read request
tester.assertResponse(() -> authenticatedRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node"),
"{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
// Write request
tester.assertResponse(() -> authenticatedRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node", "", Request.Method.POST),
"{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
}
@Test
- public void unauthenticated_request_are_unauthorized() {
+ void unauthenticated_request_are_unauthorized() {
{
// Read request
Request request = new Request("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node", "", Request.Method.GET);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
index 5936c135af9..fa652af18f3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
@@ -17,8 +17,8 @@ import com.yahoo.vespa.hosted.controller.auditlog.AuditLogger;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -27,7 +27,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author bratseth
@@ -38,42 +38,42 @@ public class ControllerApiTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
}
@Test
- public void testControllerApi() {
+ void testControllerApi() {
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/", "", Request.Method.GET), new File("root.json"));
((InMemoryFlagSource) tester.controller().flagSource()).withListFlag(PermanentFlags.INACTIVE_MAINTENANCE_JOBS.id(), List.of("DeploymentExpirer"), String.class);
// GET a list of all maintenance jobs
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/maintenance/", "", Request.Method.GET),
- new File("maintenance.json"));
+ new File("maintenance.json"));
}
@Test
- public void testStats() {
- var mock = (NodeRepositoryMock)tester.controller().serviceRegistry().configServer().nodeRepository();
+ void testStats() {
+ var mock = (NodeRepositoryMock) tester.controller().serviceRegistry().configServer().nodeRepository();
mock.putApplication(ZoneId.from("prod", "us-west-1"),
- new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
+ new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
mock.putApplication(ZoneId.from("prod", "us-west-1"),
- new Application(ApplicationId.fromFullString("t2.a2.i2"), List.of()));
+ new Application(ApplicationId.fromFullString("t2.a2.i2"), List.of()));
mock.putApplication(ZoneId.from("prod", "us-east-3"),
- new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
+ new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/stats", "", Request.Method.GET),
- new File("stats.json"));
+ new File("stats.json"));
}
@Test
- public void testUpgraderApi() {
+ void testUpgraderApi() {
// Get current configuration
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/jobs/upgrader", "", Request.Method.GET),
- "{\"upgradesPerMinute\":0.125,\"confidenceOverrides\":[]}",
- 200);
+ "{\"upgradesPerMinute\":0.125,\"confidenceOverrides\":[]}",
+ 200);
// Set invalid configuration
tester.assertResponse(
@@ -123,11 +123,11 @@ public class ControllerApiTest extends ControllerContainerTest {
"{\"upgradesPerMinute\":42.0,\"confidenceOverrides\":[{\"6.43\":\"broken\"}]}",
200);
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void testAuditLogApi() {
+ void testAuditLogApi() {
ManualClock clock = new ManualClock(Instant.parse("2019-03-01T12:13:14.00Z"));
AuditLogger logger = new AuditLogger(tester.controller().curator(), clock);
@@ -153,13 +153,13 @@ public class ControllerApiTest extends ControllerContainerTest {
}
@Test
- public void testMeteringApi() {
+ void testMeteringApi() {
ApplicationId applicationId = ApplicationId.from("tenant", "app", "instance");
Instant timestamp = Instant.ofEpochMilli(123456789);
ZoneId zoneId = ZoneId.defaultId();
List<ResourceSnapshot> snapshots = List.of(
- new ResourceSnapshot(applicationId, 12,48,1200, NodeResources.Architecture.arm64, timestamp, zoneId),
- new ResourceSnapshot(applicationId, 24, 96,2400, NodeResources.Architecture.x86_64, timestamp, zoneId)
+ new ResourceSnapshot(applicationId, 12, 48, 1200, NodeResources.Architecture.arm64, timestamp, zoneId),
+ new ResourceSnapshot(applicationId, 24, 96, 2400, NodeResources.Architecture.x86_64, timestamp, zoneId)
);
tester.controller().serviceRegistry().resourceDatabase().writeResourceSnapshots(snapshots);
tester.assertResponse(
@@ -169,24 +169,24 @@ public class ControllerApiTest extends ControllerContainerTest {
}
@Test
- public void testApproveMembership() {
+ void testApproveMembership() {
ApplicationId applicationId = ApplicationId.from("tenant", "app", "instance");
DeploymentId deployment = new DeploymentId(applicationId, ZoneId.defaultId());
String requestBody = "{\n" +
- " \"applicationId\": \"" + deployment.applicationId().serializedForm() + "\",\n" +
- " \"zone\": \"" + deployment.zoneId().value() + "\"\n" +
- "}";
+ " \"applicationId\": \"" + deployment.applicationId().serializedForm() + "\",\n" +
+ " \"zone\": \"" + deployment.zoneId().value() + "\"\n" +
+ "}";
MockAccessControlService accessControlService = (MockAccessControlService) tester.serviceRegistry().accessControlService();
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"message\":\"Unable to approve membership request\"}", 400);
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"message\":\"Unable to approve membership request\"}", 400);
accessControlService.addPendingMember(hostedOperator);
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"message\":\"Unable to approve membership request\"}", 400);
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"message\":\"Unable to approve membership request\"}", 400);
tester.controller().supportAccess().allow(deployment, tester.controller().clock().instant().plus(Duration.ofHours(1)), "tenantx");
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"members\":[\"user.alice\"]}");
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"members\":[\"user.alice\"]}");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/responses/stats.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/responses/stats.json
index 673767c13a0..44b52e5be2c 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/responses/stats.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/responses/stats.json
@@ -2,6 +2,8 @@
"zones": [
{
"id": "prod.us-east-3",
+ "totalCost": 0.0,
+ "totalAllocatedCost": 0.0,
"load": {
"cpu": 0.0,
"memory": 0.0,
@@ -27,6 +29,8 @@
},
{
"id": "prod.us-west-1",
+ "totalCost": 0.0,
+ "totalAllocatedCost": 0.0,
"load": {
"cpu": 0.0,
"memory": 0.0,
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
index d99239e8f23..5dd57b09af4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -24,30 +24,30 @@ public class BadgeApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/responses/";
@Test
- public void testBadgeApi() throws IOException {
+ void testBadgeApi() throws IOException {
ContainerTester tester = new ContainerTester(container, responseFiles);
DeploymentTester deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().upgradeSystem(Version.fromString("6.1"));
var application = deploymentTester.newDeploymentContext("tenant", "application", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().parallel("us-west-1", "aws-us-east-1a")
- .test("us-west-1")
- .region("ap-southeast-1")
- .test("ap-southeast-1")
- .region("eu-west-1")
- .test("eu-west-1")
- .build();
+ .test("us-west-1")
+ .region("ap-southeast-1")
+ .test("ap-southeast-1")
+ .region("eu-west-1")
+ .test("eu-west-1")
+ .build();
application.submit(applicationPackage).deploy();
application.submit(applicationPackage)
- .runJob(DeploymentContext.systemTest)
- .runJob(DeploymentContext.stagingTest)
- .runJob(DeploymentContext.productionUsWest1)
- .runJob(DeploymentContext.productionAwsUsEast1a)
- .runJob(DeploymentContext.testUsWest1)
- .runJob(DeploymentContext.productionApSoutheast1)
- .failDeployment(DeploymentContext.testApSoutheast1);
+ .runJob(DeploymentContext.systemTest)
+ .runJob(DeploymentContext.stagingTest)
+ .runJob(DeploymentContext.productionUsWest1)
+ .runJob(DeploymentContext.productionAwsUsEast1a)
+ .runJob(DeploymentContext.testUsWest1)
+ .runJob(DeploymentContext.productionApSoutheast1)
+ .failDeployment(DeploymentContext.testApSoutheast1);
application.submit(applicationPackage)
- .failTests(DeploymentContext.systemTest, true)
- .runJob(DeploymentContext.stagingTest);
+ .failTests(DeploymentContext.systemTest, true)
+ .runJob(DeploymentContext.stagingTest);
for (int i = 0; i < 31; i++)
if ((i & 1) == 0)
application.failDeployment(DeploymentContext.productionUsWest1);
@@ -58,27 +58,27 @@ public class BadgeApiTest extends ControllerContainerTest {
tester.controller().applications().deploymentTrigger().reTrigger(application.instanceId(), DeploymentContext.testEuWest1, "reason");
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default"),
- Files.readString(Paths.get(responseFiles + "overview.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "overview.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=0"),
- Files.readString(Paths.get(responseFiles + "single-running.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "single-running.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/system-test"),
- Files.readString(Paths.get(responseFiles + "running-test.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "running-test.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history.svg")), 200);
// New change not reflected before cache entry expires.
tester.serviceRegistry().clock().advance(Duration.ofSeconds(59));
application.runJob(DeploymentContext.productionUsWest1);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history.svg")), 200);
// Cached entry refreshed after a minute.
tester.serviceRegistry().clock().advance(Duration.ofSeconds(1));
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history2.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history2.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=0"),
- Files.readString(Paths.get(responseFiles + "single-done.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "single-done.svg")), 200);
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
index d837b9e8264..7ee5f6db9b9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.ArrayList;
@@ -30,7 +30,7 @@ public class DeploymentApiTest extends ControllerContainerTest {
private final static String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/responses/";
@Test
- public void testDeploymentApi() {
+ void testDeploymentApi() {
ContainerTester tester = new ContainerTester(container, responseFiles);
DeploymentTester deploymentTester = new DeploymentTester(new ControllerTester(tester));
Version version = Version.fromString("4.9");
@@ -43,8 +43,8 @@ public class DeploymentApiTest extends ControllerContainerTest {
.region("us-west-1")
.build();
ApplicationPackage emptyPackage = new ApplicationPackageBuilder().instances("default")
- .allow(ValidationId.deploymentRemoval)
- .build();
+ .allow(ValidationId.deploymentRemoval)
+ .build();
// Deploy application without any declared jobs on the oldest version.
var oldAppWithoutDeployment = deploymentTester.newDeploymentContext("tenant4", "application4", "default");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
index 577aab0ade6..877ca4a99d2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
@@ -15,13 +15,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFact
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzDbMock;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -48,7 +48,7 @@ public class AthenzRoleFilterTest {
private AthenzRoleFilter filter;
- @Before
+ @BeforeEach
public void setup() {
ControllerTester tester = new ControllerTester();
filter = new AthenzRoleFilter(new AthenzClientFactoryMock(tester.athenzDb()),
@@ -67,70 +67,70 @@ public class AthenzRoleFilterTest {
}
@Test
- public void testTranslations() throws Exception {
+ void testTranslations() throws Exception {
// Hosted operators are always members of the hostedOperator role.
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, NO_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, TENANT_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, APPLICATION_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, APPLICATION_CONTEXT_PATH));
// Tenant admins are members of the athenzTenantAdmin role within their tenant subtree.
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, TENANT2_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, TENANT2_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, APPLICATION2_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, APPLICATION2_CONTEXT_PATH));
// Build services are members of the buildService role within their application subtree.
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.buildService(TENANT, APPLICATION)),
- filter.roles(TENANT_PIPELINE, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, APPLICATION2_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, APPLICATION2_CONTEXT_PATH));
// Principals member of both tenantPipeline and tenantAdmin roles get correct roles
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN_AND_PIPELINE, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN_AND_PIPELINE, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT), Role.buildService(TENANT, APPLICATION)),
- filter.roles(TENANT_ADMIN_AND_PIPELINE, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN_AND_PIPELINE, APPLICATION_CONTEXT_PATH));
// Users have nothing special under their instance
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, INSTANCE_CONTEXT_PATH));
+ filter.roles(USER, INSTANCE_CONTEXT_PATH));
// Unprivileged users are just members of the everyone role.
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, NO_CONTEXT_PATH));
+ filter.roles(USER, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, TENANT_CONTEXT_PATH));
+ filter.roles(USER, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, APPLICATION_CONTEXT_PATH));
+ filter.roles(USER, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, INSTANCE2_CONTEXT_PATH));
+ filter.roles(USER, INSTANCE2_CONTEXT_PATH));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
index be3a50c38b0..64dce08e735 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.restapi.ApplicationRequestToDiscFilterRequestWrapper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -20,9 +20,9 @@ import java.util.Set;
import static com.yahoo.container.jdisc.RequestHandlerTestDriver.MockResponseHandler;
import static com.yahoo.jdisc.http.HttpResponse.Status.FORBIDDEN;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -33,7 +33,7 @@ public class ControllerAuthorizationFilterTest {
private static final ObjectMapper mapper = new ObjectMapper();
@Test
- public void operator() {
+ void operator() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "operator", Set.of(Role.hostedOperator()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -44,7 +44,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void supporter() {
+ void supporter() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "operator", Set.of(Role.hostedSupporter()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -54,7 +54,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void unprivileged() {
+ void unprivileged() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.everyone()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -65,7 +65,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void unprivilegedInPublic() {
+ void unprivilegedInPublic() {
ControllerTester tester = new ControllerTester(SystemName.Public);
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.everyone()));
@@ -76,7 +76,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void hostedDeveloper() {
+ void hostedDeveloper() {
ControllerTester tester = new ControllerTester();
TenantName tenantName = TenantName.defaultName();
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.hostedDeveloper(tenantName)));
@@ -88,14 +88,14 @@ public class ControllerAuthorizationFilterTest {
}
private static void assertIsAllowed(Optional<AuthorizationResponse> response) {
- assertFalse("Expected no response from filter, but got \"" +
- response.map(r -> r.message + "\" (" + r.statusCode + ")").orElse(""),
- response.isPresent());
+ assertFalse(response.isPresent(),
+ "Expected no response from filter, but got \"" +
+ response.map(r -> r.message + "\" (" + r.statusCode + ")").orElse(""));
}
private static void assertIsForbidden(Optional<AuthorizationResponse> response) {
- assertTrue("Expected a response from filter", response.isPresent());
- assertEquals("Invalid status code", FORBIDDEN, response.get().statusCode);
+ assertTrue(response.isPresent(), "Expected a response from filter");
+ assertEquals(FORBIDDEN, response.get().statusCode, "Invalid status code");
}
private static ControllerAuthorizationFilter createFilter(ControllerTester tester) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
index c7071cfb68c..b85c93a5d90 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.restapi.ApplicationRequestToDiscFilterRequestWrapper;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Set;
@@ -16,7 +16,7 @@ import java.util.Set;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.administrator;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.developer;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.user;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LastLoginUpdateFilterTest {
@@ -27,7 +27,7 @@ public class LastLoginUpdateFilterTest {
private final LastLoginUpdateFilter filter = new LastLoginUpdateFilter(tester.controller());
@Test
- public void updateLastLoginTimeTest() {
+ void updateLastLoginTimeTest() {
tester.createTenant(tenant1.value());
tester.createTenant(tenant2.value());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
index 9024d7c8e7e..ec9be1f04c3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
@@ -20,8 +20,8 @@ import com.yahoo.vespa.hosted.controller.tenant.ArchiveAccess;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class SignatureFilterTest {
@@ -63,7 +63,7 @@ public class SignatureFilterTest {
private SignatureFilter filter;
private RequestSigner signer;
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester();
applications = tester.controller().applications();
@@ -77,17 +77,18 @@ public class SignatureFilterTest {
ImmutableBiMap.of(),
TenantInfo.empty(),
List.of(),
- new ArchiveAccess()));
+ new ArchiveAccess(),
+ Optional.empty()));
tester.curator().writeApplication(new Application(appId, tester.clock().instant()));
}
@Test
- public void testFilter() {
+ void testFilter() {
// Unsigned request gets no role.
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://host:123/path/./..//..%2F?query=empty&%3F=%26"));
byte[] emptyBody = new byte[0];
verifySecurityContext(requestOf(request.copy().method("GET", HttpRequest.BodyPublishers.ofByteArray(emptyBody)).build(), emptyBody),
- null);
+ null);
// Signed request gets no role when no key is stored for the application.
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
@@ -97,42 +98,43 @@ public class SignatureFilterTest {
applications.lockApplicationOrThrow(appId, application -> applications.store(application.withDeployKey(otherPublicKey)));
// Signed request gets no role when no key is stored for the application.
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
- null);
+ null);
// Signed request gets a headless role when a matching key is stored for the application.
applications.lockApplicationOrThrow(appId, application -> applications.store(application.withDeployKey(publicKey)));
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
- new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
- Set.of(Role.reader(id.tenant()),
- Role.headless(id.tenant(), id.application())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
+ Set.of(Role.reader(id.tenant()),
+ Role.headless(id.tenant(), id.application())),
+ tester.clock().instant()));
// Signed POST request with X-Key header gets a headless role.
byte[] hiBytes = new byte[]{0x48, 0x69};
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.POST, () -> new ByteArrayInputStream(hiBytes)), hiBytes),
- new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
- Set.of(Role.reader(id.tenant()),
- Role.headless(id.tenant(), id.application())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
+ Set.of(Role.reader(id.tenant()),
+ Role.headless(id.tenant(), id.application())),
+ tester.clock().instant()));
// Signed request gets a developer role when a matching developer key is stored for the tenant.
tester.curator().writeTenant(new CloudTenant(appId.tenant(),
- Instant.EPOCH,
- LastLoginInfo.EMPTY,
- Optional.empty(),
- ImmutableBiMap.of(publicKey, () -> "user"),
- TenantInfo.empty(),
- List.of(),
- new ArchiveAccess()));
+ Instant.EPOCH,
+ LastLoginInfo.EMPTY,
+ Optional.empty(),
+ ImmutableBiMap.of(publicKey, () -> "user"),
+ TenantInfo.empty(),
+ List.of(),
+ new ArchiveAccess(),
+ Optional.empty()));
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.POST, () -> new ByteArrayInputStream(hiBytes)), hiBytes),
- new SecurityContext(new SimplePrincipal("user"),
- Set.of(Role.reader(id.tenant()),
- Role.developer(id.tenant())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("user"),
+ Set.of(Role.reader(id.tenant()),
+ Role.developer(id.tenant())),
+ tester.clock().instant()));
// Unsigned requests still get no roles.
verifySecurityContext(requestOf(request.copy().method("GET", HttpRequest.BodyPublishers.ofByteArray(emptyBody)).build(), emptyBody),
- null);
+ null);
}
private void verifySecurityContext(DiscFilterRequest request, SecurityContext securityContext) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
index 6d8826f6e48..ee89f506f17 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
@@ -7,10 +7,10 @@ import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -22,24 +22,24 @@ public class AuditedFlagsApiTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
addUserToHostedOperatorRole(operator);
tester = new ContainerTester(container, responses);
}
@Test
- public void test_audit_logging() {
+ void test_audit_logging() {
var body = "{\n" +
- " \"id\": \"id1\",\n" +
- " \"rules\": [\n" +
- " {\n" +
- " \"value\": true\n" +
- " }\n" +
- " ]\n" +
- "}";
+ " \"id\": \"id1\",\n" +
+ " \"rules\": [\n" +
+ " {\n" +
+ " \"value\": true\n" +
+ " }\n" +
+ " ]\n" +
+ "}";
assertResponse(new Request("http://localhost:8080/flags/v1/data/id1?force=true", body, Request.Method.PUT),
- "", 200);
+ "", 200);
var log = tester.controller().auditLogger().readLog();
assertEquals(1, log.entries().size());
var entry = log.entries().get(0);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
index 96b08006790..fabae508057 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
@@ -18,7 +18,7 @@ import java.util.Set;
public class HorizonApiTest extends ControllerContainerCloudTest {
@Test
- public void only_operators_and_flag_enabled_tenants_allowed() {
+ void only_operators_and_flag_enabled_tenants_allowed() {
ContainerTester tester = new ContainerTester(container, "");
TenantName tenantName = TenantName.defaultName();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
index 62ec8f4222c..d0d169720d0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.slime.JsonFormat;
import com.yahoo.slime.SlimeUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -16,7 +16,7 @@ import java.util.Set;
import static com.yahoo.slime.SlimeUtils.jsonToSlimeOrThrow;
import static com.yahoo.slime.SlimeUtils.toJsonBytes;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author valerijf
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class TsdbQueryRewriterTest {
@Test
- public void rewrites_query() throws IOException {
+ void rewrites_query() throws IOException {
assertRewrite("filters-complex.json", "filters-complex.expected.json", Set.of(TenantName.from("tenant2")), false);
assertRewrite("filter-in-execution-graph.json",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
index 15e7a804143..15f0100ade8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
@@ -2,6 +2,7 @@
package com.yahoo.vespa.hosted.controller.restapi.os;
import com.yahoo.application.container.handler.Request;
+import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.zone.UpgradePolicy;
@@ -11,25 +12,25 @@ import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
+import com.yahoo.vespa.hosted.controller.api.integration.deployment.OsRelease;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
import com.yahoo.vespa.hosted.controller.maintenance.ControllerMaintainer;
import com.yahoo.vespa.hosted.controller.maintenance.OsUpgrader;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
import org.intellij.lang.annotations.Language;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author mpolden
@@ -52,15 +53,18 @@ public class OsApiTest extends ControllerContainerTest {
return SystemName.cd;
}
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responses);
tester.serviceRegistry().clock().setInstant(Instant.ofEpochMilli(1234));
addUserToHostedOperatorRole(operator);
- zoneRegistryMock().setZones(zone1, zone2, zone3)
- .reprovisionToUpgradeOsIn(zone3)
- .setOsUpgradePolicy(cloud1, UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).build())
- .setOsUpgradePolicy(cloud2, UpgradePolicy.builder().upgrade(zone3).build());
+ tester.serviceRegistry().zoneRegistry().setZones(zone1, zone2, zone3)
+ .reprovisionToUpgradeOsIn(zone3)
+ .setOsUpgradePolicy(cloud1, UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).build())
+ .setOsUpgradePolicy(cloud2, UpgradePolicy.builder().upgrade(zone3).build());
+ tester.serviceRegistry().artifactRepository().addRelease(new OsRelease(Version.fromString("7.0"),
+ OsRelease.Tag.latest,
+ Instant.EPOCH));
osUpgraders = List.of(
new OsUpgrader(tester.controller(), Duration.ofDays(1),
cloud1),
@@ -69,7 +73,7 @@ public class OsApiTest extends ControllerContainerTest {
}
@Test
- public void test_api() {
+ void test_api() {
// No versions available yet
assertResponse(new Request("http://localhost:8080/os/v1/"), "{\"versions\":[]}", 200);
@@ -77,9 +81,9 @@ public class OsApiTest extends ControllerContainerTest {
upgradeAndUpdateStatus();
// Upgrade OS to a different version in each cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.5.2\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.2 with upgrade budget PT0S\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.2 with upgrade budget PT0S\"}", 200);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"8.2.1\", \"cloud\": \"cloud2\", \"upgradeBudget\": \"PT24H\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud2' to 8.2.1 with upgrade budget PT24H\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud2' to 8.2.1 with upgrade budget PT24H\"}", 200);
// Status is updated after some zones are upgraded
upgradeAndUpdateStatus();
@@ -93,49 +97,49 @@ public class OsApiTest extends ControllerContainerTest {
// Downgrade with force is permitted
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.5.1\", \"cloud\": \"cloud1\", \"force\": true, \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.1 with upgrade budget PT0S\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.1 with upgrade budget PT0S\"}", 200);
// Clear target for a given cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": null, \"cloud\": \"cloud2\"}", Request.Method.PATCH),
- "{\"message\":\"Cleared target OS version for cloud 'cloud2'\"}", 200);
+ "{\"message\":\"Cleared target OS version for cloud 'cloud2'\"}", 200);
// Error: Missing fields
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.6\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'cloud' is required\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'cloud' is required\"}", 400);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"cloud\": \"cloud1\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'version' is required\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'version' is required\"}", 400);
// Error: Invalid versions
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"0.0.0\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version '0.0.0'\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version '0.0.0'\"}", 400);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"foo\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version 'foo': For input string: \\\"foo\\\"\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version 'foo': For input string: \\\"foo\\\"\"}", 400);
// Error: Invalid cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.6\", \"cloud\": \"foo\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cloud 'foo' does not exist in this system\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cloud 'foo' does not exist in this system\"}", 400);
// Error: Downgrade OS
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.4.1\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade cloud 'cloud1' to version 7.4.1\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade cloud 'cloud1' to version 7.4.1\"}", 400);
// Request firmware checks in all zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/", "", Request.Method.POST),
- "{\"message\":\"Requested firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
+ "{\"message\":\"Requested firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
// Cancel firmware checks in all prod zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/prod/", "", Request.Method.DELETE),
- "{\"message\":\"Cancelled firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
+ "{\"message\":\"Cancelled firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
// Request firmware checks in prod.us-east-3.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/prod/us-east-3", "", Request.Method.POST),
- "{\"message\":\"Requested firmware checks in prod.us-east-3.\"}", 200);
+ "{\"message\":\"Requested firmware checks in prod.us-east-3.\"}", 200);
// Error: Cancel firmware checks in an empty set of zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/dev/", "", Request.Method.DELETE),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"No zones at path '/os/v1/firmware/dev/'\"}", 404);
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"No zones at path '/os/v1/firmware/dev/'\"}", 404);
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
private void upgradeAndUpdateStatus() {
@@ -160,10 +164,6 @@ public class OsApiTest extends ControllerContainerTest {
updateVersionStatus();
}
- private ZoneRegistryMock zoneRegistryMock() {
- return tester.serviceRegistry().zoneRegistry();
- }
-
private NodeRepositoryMock nodeRepository() {
return tester.serviceRegistry().configServerMock().nodeRepository();
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/responses/versions-all-upgraded.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/responses/versions-all-upgraded.json
index a5af4f45370..be94b85f113 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/responses/versions-all-upgraded.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/responses/versions-all-upgraded.json
@@ -104,6 +104,8 @@
"targetVersion": true,
"upgradeBudget": "PT24H",
"scheduledAt": 1234,
+ "nextVersion": "8.2.1.20211227",
+ "nextScheduledAt": 7200000,
"cloud": "cloud2",
"nodes": [
{
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
index ea7ec7c1589..cb402d700e2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
@@ -14,13 +14,13 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author mpolden
@@ -32,7 +32,7 @@ public class RoutingApiTest extends ControllerContainerTest {
private ContainerTester tester;
private DeploymentTester deploymentTester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
@@ -40,7 +40,7 @@ public class RoutingApiTest extends ControllerContainerTest {
}
@Test
- public void discovery() {
+ void discovery() {
// Deploy
var context = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
@@ -54,34 +54,34 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET root
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/", "",
- Request.Method.GET),
- new File("discovery/root.json"));
+ Request.Method.GET),
+ new File("discovery/root.json"));
// GET tenant
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1", "",
- Request.Method.GET),
- new File("discovery/tenant.json"));
+ Request.Method.GET),
+ new File("discovery/tenant.json"));
// GET application
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/",
- "",
- Request.Method.GET),
- new File("discovery/application.json"));
+ "",
+ Request.Method.GET),
+ new File("discovery/application.json"));
// GET instance
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/",
- "",
- Request.Method.GET),
- new File("discovery/instance.json"));
+ "",
+ Request.Method.GET),
+ new File("discovery/instance.json"));
// GET environment
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/", "",
- Request.Method.GET),
- new File("discovery/environment.json"));
+ Request.Method.GET),
+ new File("discovery/environment.json"));
}
@Test
- public void recursion() {
+ void recursion() {
var context1 = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
@@ -102,33 +102,33 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET tenant recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1?recursive=true", "",
- Request.Method.GET),
- new File("recursion/tenant.json"));
+ Request.Method.GET),
+ new File("recursion/tenant.json"));
// GET application recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1?recursive=true", "",
- Request.Method.GET),
- new File("recursion/application.json"));
+ Request.Method.GET),
+ new File("recursion/application.json"));
// GET instance recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default?recursive=true", "",
- Request.Method.GET),
- new File("recursion/application.json"));
+ Request.Method.GET),
+ new File("recursion/application.json"));
// GET environment recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment?recursive=true", "",
- Request.Method.GET),
- new File("recursion/environment.json"));
+ Request.Method.GET),
+ new File("recursion/environment.json"));
}
@Test
- public void exclusive_routing() {
+ void exclusive_routing() {
var context = deploymentTester.newDeploymentContext();
// Zones support direct routing
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
deploymentTester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(westZone),
- ZoneApiMock.from(eastZone));
+ ZoneApiMock.from(eastZone));
// Deploy application
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
@@ -140,45 +140,45 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET initial deployment status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-initial.json"));
// POST sets deployment out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-out.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-out.json"));
// DELETE sets deployment in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-in.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-in.json"));
// GET initial zone status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-initial.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-initial.json"));
// POST sets zone out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-out.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-out.json"));
// DELETE sets zone in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-in.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-in.json"));
// Endpoint is removed
applicationPackage = new ApplicationPackageBuilder()
@@ -191,12 +191,12 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET deployment status. Now empty as no routing policies have global endpoints
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"deployments\":[]}");
+ "", Request.Method.GET),
+ "{\"deployments\":[]}");
}
@Test
- public void shared_routing() {
+ void shared_routing() {
// Deploy application
var context = deploymentTester.newDeploymentContext();
var westZone = ZoneId.from("prod", "us-west-1");
@@ -208,61 +208,61 @@ public class RoutingApiTest extends ControllerContainerTest {
.build();
context.submit(applicationPackage).deploy();
- assertNotEquals("Rotation is assigned", List.of(), context.instance().rotations());
+ assertNotEquals(List.of(), context.instance().rotations(), "Rotation is assigned");
// GET initial deployment status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-initial.json"));
// POST sets deployment out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-out.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-out.json"));
// DELETE sets deployment in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-in.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-in.json"));
// GET initial zone status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-initial.json"));
// POST sets zone out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-out.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-out.json"));
// DELETE sets zone in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-in.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-in.json"));
}
@Test
- public void mixed_routing_multiple_zones() {
+ void mixed_routing_multiple_zones() {
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
// One shared and one exclusive zone
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(westZone),
- RoutingMethod.sharedLayer4);
+ RoutingMethod.sharedLayer4);
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(eastZone),
- RoutingMethod.exclusive);
+ RoutingMethod.exclusive);
// Deploy application
var context = deploymentTester.newDeploymentContext();
@@ -277,23 +277,23 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET status for zone using sharedLayer4 routing
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-initial.json"));
// GET status for zone using exclusive routing
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-east-3",
- "", Request.Method.GET),
- "{\"deployments\":[{\"routingMethod\":\"exclusive\",\"instance\":\"tenant:application:default\"," +
- "\"environment\":\"prod\",\"region\":\"us-east-3\",\"status\":\"in\",\"agent\":\"system\",\"changedAt\":0}]}");
+ "", Request.Method.GET),
+ "{\"deployments\":[{\"routingMethod\":\"exclusive\",\"instance\":\"tenant:application:default\"," +
+ "\"environment\":\"prod\",\"region\":\"us-east-3\",\"status\":\"in\",\"agent\":\"system\",\"changedAt\":0}]}");
}
@Test
- public void invalid_requests() {
+ void invalid_requests() {
// GET non-existent application
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"t1.a1 not found\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"t1.a1 not found\"}",
+ 400);
// GET, DELETE non-existent deployment
var context = deploymentTester.newDeploymentContext();
@@ -303,23 +303,23 @@ public class RoutingApiTest extends ControllerContainerTest {
.build();
context.submit(applicationPackage).deploy();
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
+ 400);
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
- 400);
+ "", Request.Method.DELETE),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
+ 400);
// GET non-existent zone
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-north-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-1\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-1\"}",
+ 400);
}
@Test
- public void endpoints_list() {
+ void endpoints_list() {
var context = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
@@ -331,7 +331,7 @@ public class RoutingApiTest extends ControllerContainerTest {
context.submit(applicationPackage).deploy();
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/endpoint", "", Request.Method.GET),
- new File("endpoint/endpoints.json"));
+ new File("endpoint/endpoints.json"));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
index c157cb3516f..36679e0dd91 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.hosted.controller.api.systemflags.v1.FlagsTarget;
import com.yahoo.vespa.hosted.controller.api.systemflags.v1.wire.WireSystemFlagsDeployResult;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class SystemFlagsDeployResultTest {
@Test
- public void changes_and_errors_are_present_in_wire_format() {
+ void changes_and_errors_are_present_in_wire_format() {
FlagsTarget controllerTarget = FlagsTarget.forController(SystemName.cd);
FlagId flagOne = new FlagId("flagone");
FlagId flagTwo = new FlagId("flagtwo");
@@ -40,7 +40,7 @@ public class SystemFlagsDeployResultTest {
}
@Test
- public void identical_errors_and_changes_from_multiple_targets_are_merged() {
+ void identical_errors_and_changes_from_multiple_targets_are_merged() {
ZoneApiMock prodUsWest1Zone = ZoneApiMock.fromId("prod.us-west-1");
ZoneRegistryMock registry = new ZoneRegistryMock(SystemName.cd).setZones(prodUsWest1Zone);
FlagsTarget prodUsWest1Target = FlagsTarget.forConfigServer(registry, prodUsWest1Zone.getId());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
index d92b0be0eb9..50354639f6f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.hosted.controller.api.systemflags.v1.FlagsTarget;
import com.yahoo.vespa.hosted.controller.api.systemflags.v1.SystemFlagsDataArchive;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -43,7 +43,7 @@ public class SystemFlagsDeployerTest {
private final FlagsTarget prodUsEast3Target = FlagsTarget.forConfigServer(registry, prodUsEast3Zone.getId());
@Test
- public void deploys_flag_data_to_targets() throws IOException {
+ void deploys_flag_data_to_targets() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(controllerTarget)).thenReturn(List.of());
when(flagsClient.listFlagData(prodUsWest1Target)).thenReturn(List.of(flagData("existing-prod.us-west-1.json")));
@@ -74,7 +74,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void dryrun_should_not_change_flags() throws IOException {
+ void dryrun_should_not_change_flags() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(controllerTarget)).thenReturn(List.of());
when(flagsClient.listDefinedFlags(controllerTarget)).thenReturn(List.of(new FlagId("my-flag")));
@@ -97,7 +97,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entries_in_result_if_flag_data_operations_fail() throws IOException {
+ void creates_error_entries_in_result_if_flag_data_operations_fail() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
UncheckedIOException exception = new UncheckedIOException(new IOException("I/O error message"));
when(flagsClient.listFlagData(prodUsWest1Target)).thenThrow(exception);
@@ -120,7 +120,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entry_for_invalid_flag_archive() throws IOException {
+ void creates_error_entry_for_invalid_flag_archive() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
FlagData defaultData = flagData("flags/my-flag/main.json");
SystemFlagsDataArchive archive = new SystemFlagsDataArchive.Builder()
@@ -135,7 +135,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entry_for_flag_data_of_undefined_flag() throws IOException {
+ void creates_error_entry_for_flag_data_of_undefined_flag() throws IOException {
FlagData prodUsEast3Data = flagData("flags/my-flag/main.prod.us-east-3.json");
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(prodUsEast3Target))
@@ -154,7 +154,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_warning_entry_for_existing_flag_data_for_undefined_flag() throws IOException {
+ void creates_warning_entry_for_existing_flag_data_for_undefined_flag() throws IOException {
FlagData prodUsEast3Data = flagData("flags/my-flag/main.prod.us-east-3.json");
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(prodUsEast3Target))
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
index 1cd4b5e5541..f7e270b3c68 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.jdisc.http.filter.security.misc.User;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.HashMap;
@@ -26,7 +26,7 @@ public class UserApiOnPremTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
@Test
- public void userMetadataOnPremTest() {
+ void userMetadataOnPremTest() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
ControllerTester controller = new ControllerTester(tester);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
index 1bb409b9906..1344b106bbe 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
@@ -14,7 +14,7 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Set;
@@ -22,7 +22,7 @@ import java.util.Set;
import static com.yahoo.application.container.handler.Request.Method.DELETE;
import static com.yahoo.application.container.handler.Request.Method.POST;
import static com.yahoo.application.container.handler.Request.Method.PUT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -42,7 +42,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
@Test
- public void testUserManagement() {
+ void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
@@ -51,25 +51,25 @@ public class UserApiTest extends ControllerContainerCloudTest {
// GET at application/v4 root fails as it's not public read.
tester.assertResponse(request("/application/v4/"),
- accessDenied, 403);
+ accessDenied, 403);
// GET at application/v4/tenant succeeds for operators.
tester.assertResponse(request("/application/v4/tenant")
- .roles(operator),
- "[]");
+ .roles(operator),
+ "[]");
// POST a tenant is not available to everyone.
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .data("{\"token\":\"hello\"}"),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"You are not currently permitted to create tenants. Please contact the Vespa team to request access.\"}", 403);
+ .data("{\"token\":\"hello\"}"),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"You are not currently permitted to create tenants. Please contact the Vespa team to request access.\"}", 403);
// POST a tenant is available to operators.
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .roles(operator)
- .principal("administrator@tenant")
- .user(new User("administrator@tenant", "administrator", "admin", "picture"))
- .data("{\"token\":\"hello\"}"),
- new File("tenant-without-applications.json"));
+ .roles(operator)
+ .principal("administrator@tenant")
+ .user(new User("administrator@tenant", "administrator", "admin", "picture"))
+ .data("{\"token\":\"hello\"}"),
+ new File("tenant-without-applications.json"));
// GET at tenant/info with contact information.
tester.assertResponse(request("/application/v4/tenant/my-tenant/info")
@@ -79,97 +79,80 @@ public class UserApiTest extends ControllerContainerCloudTest {
// GET at user/v1 root fails as no access control is defined there.
tester.assertResponse(request("/user/v1/"),
- accessDenied, 403);
+ accessDenied, 403);
// POST a hosted operator role is not allowed.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"evil@evil\",\"roles\":[\"hostedOperator\"]}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
// POST a tenant developer is available to the tenant owner.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
- "{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
+ "{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
// POST a tenant admin is not available to a tenant developer.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
- accessDenied, 403);
-
- // POST a headless for a non-existent application fails.
- tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
- .roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
- .data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"role 'headless' of 'my-app' owned by 'my-tenant' not found\"}", 400);
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roles\":[\"administrator\"]}"),
+ accessDenied, 403);
// POST an application is allowed for a tenant developer.
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
- .principal("developer@tenant")
- .roles(Set.of(Role.developer(id.tenant()))),
- new File("application-created.json"));
+ .principal("developer@tenant")
+ .roles(Set.of(Role.developer(id.tenant()))),
+ new File("application-created.json"));
// POST an application is not allowed under a different tenant.
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
- .roles(Set.of(Role.administrator(id.tenant()))),
- accessDenied, 403);
-
- // POST a tenant role is not allowed to an application.
- tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
- .roles(Set.of(Role.hostedOperator()))
- .data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
+ .roles(Set.of(Role.administrator(id.tenant()))),
+ accessDenied, 403);
// GET tenant role information is available to readers.
tester.assertResponse(request("/user/v1/tenant/my-tenant")
- .roles(Set.of(Role.reader(id.tenant()))),
- new File("tenant-roles.json"));
-
- // GET application role information is available to tenant administrators.
- tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
- .roles(Set.of(Role.administrator(id.tenant()))),
- new File("application-roles.json"));
+ .roles(Set.of(Role.reader(id.tenant()))),
+ new File("tenant-roles.json"));
// POST a pem deploy key
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("first-deploy-key.json"));
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("first-deploy-key.json"));
// POST a pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("joe@dev")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("first-developer-key.json"));
+ .principal("joe@dev")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("first-developer-key.json"));
// POST the same pem developer key for a different user is forbidden
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("operator@tenant")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
- 400);
+ .principal("operator@tenant")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key " + quotedPemPublicKey + " is already owned by joe@dev\"}",
+ 400);
// POST in a different pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("developer@tenant")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + otherPemPublicKey + "\"}"),
- new File("both-developer-keys.json"));
+ .principal("developer@tenant")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + otherPemPublicKey + "\"}"),
+ new File("both-developer-keys.json"));
// GET tenant information with keys
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
- .roles(Set.of(Role.reader(id.tenant()))),
- new File("tenant-with-keys.json"));
+ .roles(Set.of(Role.reader(id.tenant()))),
+ new File("tenant-with-keys.json"));
// DELETE a pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("second-developer-key.json"));
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("second-developer-key.json"));
// PUT in a new secret store for the tenant
tester.assertResponse(request("/application/v4/tenant/my-tenant/secret-store/secret-foo", PUT)
@@ -187,33 +170,33 @@ public class UserApiTest extends ControllerContainerCloudTest {
// DELETE an application is available to developers.
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
- .roles(Set.of(Role.developer(id.tenant()))),
- "{\"message\":\"Deleted application my-tenant.my-app\"}");
+ .roles(Set.of(Role.developer(id.tenant()))),
+ "{\"message\":\"Deleted application my-tenant.my-app\"}");
// DELETE a tenant role is available to tenant admins.
// DELETE the developer role clears any developer key.
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
- "{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
+ "{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
// DELETE the last tenant owner is not allowed.
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
- .roles(operator)
- .data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
+ .roles(operator)
+ .data("{\"user\":\"administrator@tenant\",\"roles\":[\"administrator\"]}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
// DELETE the tenant is not allowed
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
- .roles(Set.of(Role.developer(id.tenant()))),
- "{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ .roles(Set.of(Role.developer(id.tenant()))),
+ "{\n" +
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
}
@Test
- public void userMetadataTest() {
+ void userMetadataTest() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -262,7 +245,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
}
@Test
- public void maxTrialTenants() {
+ void maxTrialTenants() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -280,7 +263,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
}
@Test
- public void supportTenant() {
+ void supportTenant() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
index 8625628b74e..ed7d02d0047 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
@@ -14,7 +14,7 @@ import com.yahoo.vespa.flags.JsonNodeRawFlag;
import com.yahoo.vespa.flags.json.Condition;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -36,7 +36,7 @@ import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
public class UserFlagsSerializerTest {
@Test
- public void user_flag_test() throws IOException {
+ void user_flag_test() throws IOException {
String email1 = "alice@domain.tld";
String email2 = "bob@domain.tld";
@@ -56,33 +56,33 @@ public class UserFlagsSerializerTest {
rule("[\"value2\"]", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email2)),
rule("[\"value1\",\"value3\"]", condition(APPLICATION_ID, Condition.Type.BLACKLIST, "tenant1:video:default", "tenant1:video:default", "tenant2:music:default"))),
flagData("jackson-id", rule("{\"integer\":456,\"string\":\"xyz\"}", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email1), condition(TENANT_ID, Condition.Type.WHITELIST, "tenant1", "tenant3")))
- ).collect(Collectors.toMap(FlagData::id, fd -> fd));
+ ).collect(Collectors.toMap(FlagData::id, fd -> fd));
// double-id is not here as it does not have CONSOLE_USER_EMAIL dimension
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\"}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
- // Resolved for email, but conditions are empty since this user is not authorized for any tenants
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\"}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
+ // Resolved for email, but conditions are empty since this user is not authorized for any tenants
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
flagData, Set.of(), false, email1);
// Same as the first one, but user is authorized for tenant1
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\",\"values\":[\"tenant1\"]}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
- // Resolved for email, but conditions have filtered out tenant2
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\",\"values\":[\"tenant1\"]}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
+ // Resolved for email, but conditions have filtered out tenant2
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
flagData, Set.of("tenant1"), false, email1);
// As operator no conditions are filtered, but the email precondition is applied
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Default from code, no DB values match
- // Includes last value from DB which is not conditioned on email and the default from code
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\",\"tenant2:music:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"default value\"}]}]}", // Default from code
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Default from code, no DB values match
+ // Includes last value from DB which is not conditioned on email and the default from code
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\",\"tenant2:music:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"default value\"}]}]}", // Default from code
flagData, Set.of(), true, "operator@domain.tld");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/application-roles.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/application-roles.json
deleted file mode 100644
index 8497358fe40..00000000000
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/application-roles.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "tenant": "my-tenant",
- "application": "my-app",
- "roleNames": [ ],
- "users": [
- {
- "name": "administrator@tenant",
- "email": "administrator@tenant",
- "verified": false,
- "roles": { }
- },
- {
- "name": "developer@tenant",
- "email": "developer@tenant",
- "verified": false,
- "roles": { }
- }
- ]
-}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-keys.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-keys.json
index f980f9231f3..6b78bfda6c4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-keys.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-keys.json
@@ -20,9 +20,7 @@
}
},
"quota": {
- "budget": null,
- "budgetUsed": 0.0,
- "clusterSize": 5
+ "budgetUsed": 0.0
},
"archiveAccess": { },
"applications": [
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-secrets.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-secrets.json
index 1152033791b..8c3bcc041d6 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-secrets.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-with-secrets.json
@@ -28,9 +28,7 @@
}
},
"quota": {
- "budget": null,
- "budgetUsed": 0.0,
- "clusterSize": 5
+ "budgetUsed": 0.0
},
"archiveAccess": { },
"applications": [
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-without-applications.json b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-without-applications.json
index 631346181a1..694e886a876 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-without-applications.json
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/tenant-without-applications.json
@@ -11,9 +11,7 @@
}
},
"quota": {
- "budget": null,
- "budgetUsed": 0.0,
- "clusterSize": 5
+ "budgetUsed": 0.0
},
"archiveAccess": { },
"applications": [ ],
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
index fcf8402d23c..5d5e310503d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
@@ -8,8 +8,8 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
@@ -31,7 +31,7 @@ public class ZoneApiTest extends ControllerContainerCloudTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -40,30 +40,30 @@ public class ZoneApiTest extends ControllerContainerCloudTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /zone/v1
tester.assertResponse(request("/zone/v1")
- .roles(everyone),
- new File("root.json"));
+ .roles(everyone),
+ new File("root.json"));
// GET /zone/v1/environment/prod
tester.assertResponse(request("/zone/v1/environment/prod")
- .roles(everyone),
- new File("prod.json"));
+ .roles(everyone),
+ new File("prod.json"));
// GET /zone/v1/environment/dev/default
tester.assertResponse(request("/zone/v1/environment/dev/default")
- .roles(everyone),
- new File("default-for-region.json"));
+ .roles(everyone),
+ new File("default-for-region.json"));
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// GET /zone/v1/environment/prod/default: No default region
tester.assertResponse(request("/zone/v1/environment/prod/default")
- .roles(everyone),
- new File("no-default-region.json"),
- 400);
+ .roles(everyone),
+ new File("no-default-region.json"),
+ 400);
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
index fd39c13707b..81484f05d1e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
@@ -11,15 +11,15 @@ import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -36,7 +36,7 @@ public class ZoneApiTest extends ControllerContainerTest {
private ContainerTester tester;
private ConfigServerProxyMock proxy;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -46,53 +46,53 @@ public class ZoneApiTest extends ControllerContainerTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /zone/v2
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2"),
- new File("root.json"));
+ new File("root.json"));
// GET /zone/v2/prod/us-north-1
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1"),
- "ok");
+ "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET");
// GET /zone/v2/nodes/v2/node/?recursive=true
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/?recursive=true"),
- "ok");
+ "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET");
// POST /zone/v2/dev/us-north-2/nodes/v2/command/restart?hostname=node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/command/restart?hostname=node1",
- "", Method.POST),
- "ok");
+ "", Method.POST),
+ "ok");
// PUT /zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1",
- "", Method.PUT), "ok");
+ "", Method.PUT), "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "PUT");
// DELETE /zone/v2/prod/us-north-1/nodes/v2/node/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/node1",
- "", Method.DELETE), "ok");
+ "", Method.DELETE), "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "DELETE");
// PATCH /zone/v2/prod/us-north-1/nodes/v2/node/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/node/node1",
- "{\"currentRestartGeneration\": 1}",
- Method.PATCH), "ok");
+ "{\"currentRestartGeneration\": 1}",
+ Method.PATCH), "ok");
assertLastRequest(ZoneId.from("dev", "aws-us-north-2"), 1, "PATCH");
assertEquals("{\"currentRestartGeneration\": 1}", proxy.lastRequestBody().get());
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// POST /zone/v2/prod/us-north-34/nodes/v2
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-42/nodes/v2",
- "", Method.POST),
- new File("unknown-zone.json"), 400);
+ "", Method.POST),
+ new File("unknown-zone.json"), 400);
assertFalse(proxy.lastReceived().isPresent());
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
index c0fb9b3d8c7..c5d74e0b01d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
@@ -32,7 +32,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -47,9 +47,9 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mortent
@@ -67,7 +67,7 @@ public class RoutingPoliciesTest {
.build();
@Test
- public void global_routing_policies() {
+ void global_routing_policies() {
var tester = new RoutingPoliciesTester();
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
@@ -87,9 +87,9 @@ public class RoutingPoliciesTest {
tester.assertTargets(context1.instanceId(), EndpointId.of("r0"), 0, zone1, zone2);
tester.assertTargets(context1.instanceId(), EndpointId.of("r1"), 0, zone1);
tester.assertTargets(context1.instanceId(), EndpointId.of("r2"), 1, zone1, zone2);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context1.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context1.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
// Applications gains a new deployment
ApplicationPackage applicationPackage2 = applicationPackageBuilder()
@@ -144,13 +144,13 @@ public class RoutingPoliciesTest {
tester.assertTargets(context1.instanceId(), EndpointId.of("r2"), 0);
var policies = tester.policiesOf(context1.instanceId());
assertEquals(clustersPerZone * numberOfDeployments, policies.size());
- assertTrue("Rotation membership is removed from all policies",
- policies.asList().stream().allMatch(policy -> policy.instanceEndpoints().isEmpty()));
- assertEquals("Rotations for " + context2.application() + " are not removed", 1, tester.aliasDataOf(endpoint4).size());
+ assertTrue(policies.asList().stream().allMatch(policy -> policy.instanceEndpoints().isEmpty()),
+ "Rotation membership is removed from all policies");
+ assertEquals(1, tester.aliasDataOf(endpoint4).size(), "Rotations for " + context2.application() + " are not removed");
}
@Test
- public void global_routing_policies_with_duplicate_region() {
+ void global_routing_policies_with_duplicate_region() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
int clustersPerZone = 2;
@@ -168,40 +168,40 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1, zone3, zone4);
tester.assertTargets(context.instanceId(), EndpointId.of("r1"), 1, zone1, zone3, zone4);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
// A zone in shared region is set out
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone4), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
// Weight of inactive zone is set to zero
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L,
- zone3, 1L,
- zone4, 0L));
+ zone3, 1L,
+ zone4, 0L));
// Other zone in shared region is set out. Entire record group for the region is removed as all zones in the
// region are out (weight sum = 0)
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone3), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L));
// Everything is set back in
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone3), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone4), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L,
- zone3, 1L,
- zone4, 1L));
+ zone3, 1L,
+ zone4, 1L));
}
@Test
- public void global_routing_policies_legacy_global_service_id() {
+ void global_routing_policies_legacy_global_service_id() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
int clustersPerZone = 2;
@@ -216,13 +216,13 @@ public class RoutingPoliciesTest {
// Creates alias records
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.defaultId(), 0, zone1, zone2);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
}
@Test
- public void zone_routing_policies() {
+ void zone_routing_policies() {
zone_routing_policies(false);
zone_routing_policies(true);
}
@@ -313,12 +313,12 @@ public class RoutingPoliciesTest {
"c1.app1.tenant1.us-central-1.vespa.oath.cloud"
);
assertEquals(expectedRecords, tester.recordNames());
- assertTrue("Removes stale routing policies " + context2.application(), tester.routingPolicies().read(context2.instanceId()).isEmpty());
- assertEquals("Keeps routing policies for " + context1.application(), 4, tester.routingPolicies().read(context1.instanceId()).size());
+ assertTrue(tester.routingPolicies().read(context2.instanceId()).isEmpty(), "Removes stale routing policies " + context2.application());
+ assertEquals(4, tester.routingPolicies().read(context1.instanceId()).size(), "Keeps routing policies for " + context1.application());
}
@Test
- public void zone_routing_policies_without_dns_update() {
+ void zone_routing_policies_without_dns_update() {
var tester = new RoutingPoliciesTester(new DeploymentTester(), false);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
tester.provisionLoadBalancers(1, context.instanceId(), true, zone1, zone2);
@@ -329,7 +329,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void global_routing_policies_in_rotationless_system() {
+ void global_routing_policies_in_rotationless_system() {
var tester = new RoutingPoliciesTester(SystemName.Public);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
List<ZoneId> prodZones = tester.controllerTester().controller().zoneRegistry().zones().all().in(Environment.prod).ids();
@@ -345,13 +345,13 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1);
- assertTrue("No rotations assigned", context.application().instances().values().stream()
- .map(Instance::rotations)
- .allMatch(List::isEmpty));
+ assertTrue(context.application().instances().values().stream()
+ .map(Instance::rotations)
+ .allMatch(List::isEmpty), "No rotations assigned");
}
@Test
- public void global_routing_policies_in_public() {
+ void global_routing_policies_in_public() {
var tester = new RoutingPoliciesTester(SystemName.Public);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
List<ZoneId> prodZones = tester.controllerTester().controller().zoneRegistry().zones().all().in(Environment.prod).ids();
@@ -367,19 +367,19 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deploy();
tester.assertTargets(context.instanceId(), EndpointId.defaultId(),
- ClusterSpec.Id.from("default"), 0,
- Map.of(zone1, 1L, zone2, 1L));
- assertEquals("Registers expected DNS names",
- Set.of("app1.tenant1.aws-eu-west-1.w.vespa-app.cloud",
- "app1.tenant1.aws-eu-west-1a.z.vespa-app.cloud",
- "app1.tenant1.aws-us-east-1.w.vespa-app.cloud",
- "app1.tenant1.aws-us-east-1c.z.vespa-app.cloud",
- "app1.tenant1.g.vespa-app.cloud"),
- tester.recordNames());
+ ClusterSpec.Id.from("default"), 0,
+ Map.of(zone1, 1L, zone2, 1L));
+ assertEquals(Set.of("app1.tenant1.aws-eu-west-1.w.vespa-app.cloud",
+ "app1.tenant1.aws-eu-west-1a.z.vespa-app.cloud",
+ "app1.tenant1.aws-us-east-1.w.vespa-app.cloud",
+ "app1.tenant1.aws-us-east-1c.z.vespa-app.cloud",
+ "app1.tenant1.g.vespa-app.cloud"),
+ tester.recordNames(),
+ "Registers expected DNS names");
}
@Test
- public void manual_deployment_creates_routing_policy() {
+ void manual_deployment_creates_routing_policy() {
// Empty application package is valid in manually deployed environments
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -387,12 +387,12 @@ public class RoutingPoliciesTest {
var zone = ZoneId.from("dev", "us-east-1");
var zoneApi = ZoneApiMock.from(zone.environment(), zone.region());
tester.controllerTester().serviceRegistry().zoneRegistry()
- .setZones(zoneApi)
- .exclusiveRoutingIn(zoneApi);
+ .setZones(zoneApi)
+ .exclusiveRoutingIn(zoneApi);
// Deploy to dev
context.runJob(zone, emptyApplicationPackage);
- assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
+ assertEquals(DeploymentSpec.empty, context.application().deploymentSpec(), "DeploymentSpec is not persisted");
context.flushDnsUpdates();
// Routing policy is created and DNS is updated
@@ -401,7 +401,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void manual_deployment_creates_routing_policy_with_non_empty_spec() {
+ void manual_deployment_creates_routing_policy_with_non_empty_spec() {
// Initial deployment
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -415,7 +415,7 @@ public class RoutingPoliciesTest {
var devContext = tester.newDeploymentContext(context.application().id().instance("user"));
devContext.runJob(zone, applicationPackage);
- assertEquals("DeploymentSpec is persisted", applicationPackage.deploymentSpec(), context.application().deploymentSpec());
+ assertEquals(applicationPackage.deploymentSpec(), context.application().deploymentSpec(), "DeploymentSpec is persisted");
context.flushDnsUpdates();
// Routing policy is created and DNS is updated
@@ -424,7 +424,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void reprovisioning_load_balancer_preserves_cname_record() {
+ void reprovisioning_load_balancer_preserves_cname_record() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -449,23 +449,24 @@ public class RoutingPoliciesTest {
// Load balancer for the same application is provisioned again, but with a different hostname
var newHostname = HostName.of("new-hostname");
var loadBalancer = new LoadBalancer("LB-0-Z-" + zone1.value(),
- context.instanceId(),
- ClusterSpec.Id.from("c0"),
- Optional.of(newHostname),
- LoadBalancer.State.active,
- Optional.of("dns-zone-1"));
+ context.instanceId(),
+ ClusterSpec.Id.from("c0"),
+ Optional.of(newHostname),
+ LoadBalancer.State.active,
+ Optional.of("dns-zone-1"));
tester.controllerTester().configServer().putLoadBalancers(zone1, List.of(loadBalancer));
// Application redeployment preserves DNS record
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
assertEquals(expectedRecords, tester.recordNames());
assertEquals(1, tester.policiesOf(context.instanceId()).size());
- assertEquals("CNAME points to current load blancer", newHostname.value() + ".",
- tester.cnameDataOf(expectedRecords.iterator().next()).get(0));
+ assertEquals(newHostname.value() + ".",
+ tester.cnameDataOf(expectedRecords.iterator().next()).get(0),
+ "CNAME points to current load blancer");
}
@Test
- public void set_global_endpoint_status() {
+ void set_global_endpoint_status() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -486,7 +487,7 @@ public class RoutingPoliciesTest {
// Global routing status is overridden in one zone
var changedAt = tester.controllerTester().clock().instant();
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
// Inactive zone is removed from global DNS record
@@ -548,7 +549,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void set_zone_global_endpoint_status() {
+ void set_zone_global_endpoint_status() {
var tester = new RoutingPoliciesTester();
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var context2 = tester.newDeploymentContext("tenant2", "app2", "default");
@@ -573,12 +574,12 @@ public class RoutingPoliciesTest {
tester.assertTargets(context2.instanceId(), EndpointId.defaultId(), 0, zone1);
for (var context : contexts) {
var policies = tester.routingPolicies().read(context.instanceId());
- assertTrue("Global routing status for policy remains " + RoutingStatus.Value.in,
- policies.asList().stream()
- .map(RoutingPolicy::status)
- .map(RoutingPolicy.Status::routingStatus)
- .map(RoutingStatus::value)
- .allMatch(status -> status == RoutingStatus.Value.in));
+ assertTrue(policies.asList().stream()
+ .map(RoutingPolicy::status)
+ .map(RoutingPolicy.Status::routingStatus)
+ .map(RoutingStatus::value)
+ .allMatch(status -> status == RoutingStatus.Value.in),
+ "Global routing status for policy remains " + RoutingStatus.Value.in);
}
var changedAt = tester.controllerTester().clock().instant();
var zonePolicy = tester.controllerTester().controller().curator().readZoneRoutingPolicy(zone2);
@@ -604,7 +605,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void non_production_deployment_is_not_registered_in_global_endpoint() {
+ void non_production_deployment_is_not_registered_in_global_endpoint() {
var tester = new RoutingPoliciesTester(SystemName.Public);
// Configure the system to use the same region for test, staging and prod
@@ -634,7 +635,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void changing_global_routing_status_never_removes_all_members() {
+ void changing_global_routing_status_never_removes_all_members() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -652,20 +653,20 @@ public class RoutingPoliciesTest {
// Global routing status is overridden for one deployment
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone2);
// Setting other deployment out implicitly sets all deployments in. Weight is set to zero, but that has no
// impact on routing decisions when the weight sum is zero
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone2), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 0L, zone2, 0L));
// One inactive deployment is put back in. Global DNS record now points to the only active deployment
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1);
@@ -682,7 +683,7 @@ public class RoutingPoliciesTest {
// Inactive deployment is set in
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone2), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
for (var policy : tester.routingPolicies().read(context.instanceId())) {
assertSame(RoutingStatus.Value.in, policy.status().routingStatus().value());
@@ -691,7 +692,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void application_endpoint_routing_policy() {
+ void application_endpoint_routing_policy() {
RoutingPoliciesTester tester = new RoutingPoliciesTester();
TenantAndApplicationId application = TenantAndApplicationId.from("tenant1", "app1");
ApplicationId betaInstance = application.instance("beta");
@@ -704,11 +705,11 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 2,
- mainInstance.instance(), 8))
+ Map.of(betaInstance.instance(), 2,
+ mainInstance.instance(), 8))
.applicationEndpoint("a1", "c1", "us-central-1",
- Map.of(betaInstance.instance(), 4,
- mainInstance.instance(), 6))
+ Map.of(betaInstance.instance(), 4,
+ mainInstance.instance(), 6))
.build();
for (var zone : List.of(zone1, zone2)) {
tester.provisionLoadBalancers(2, betaInstance, zone);
@@ -724,11 +725,11 @@ public class RoutingPoliciesTest {
DeploymentId betaZone2 = betaContext.deploymentIdIn(zone2);
DeploymentId mainZone2 = mainContext.deploymentIdIn(zone2);
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
tester.assertTargets(application, EndpointId.of("a1"), ClusterSpec.Id.from("c1"), 1,
- Map.of(betaZone2, 4,
- mainZone2, 6));
+ Map.of(betaZone2, 4,
+ mainZone2, 6));
// Weights are updated
applicationPackage = applicationPackageBuilder()
@@ -736,19 +737,19 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 3,
- mainInstance.instance(), 7))
+ Map.of(betaInstance.instance(), 3,
+ mainInstance.instance(), 7))
.applicationEndpoint("a1", "c1", "us-central-1",
- Map.of(betaInstance.instance(), 1,
- mainInstance.instance(), 9))
+ Map.of(betaInstance.instance(), 1,
+ mainInstance.instance(), 9))
.build();
betaContext.submit(applicationPackage).deploy();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 3,
- mainZone1, 7));
+ Map.of(betaZone1, 3,
+ mainZone1, 7));
tester.assertTargets(application, EndpointId.of("a1"), ClusterSpec.Id.from("c1"), 1,
- Map.of(betaZone2, 1,
- mainZone2, 9));
+ Map.of(betaZone2, 1,
+ mainZone2, 9));
// An endpoint is removed
applicationPackage = applicationPackageBuilder()
@@ -756,21 +757,21 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 1))
+ Map.of(betaInstance.instance(), 1))
.build();
betaContext.submit(applicationPackage).deploy();
// Application endpoints now point to a single instance
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 1));
- assertTrue("Endpoint removed",
- tester.controllerTester().controller().routing()
- .readDeclaredEndpointsOf(application)
- .named(EndpointId.of("a1")).isEmpty());
+ Map.of(betaZone1, 1));
+ assertTrue(tester.controllerTester().controller().routing()
+ .readDeclaredEndpointsOf(application)
+ .named(EndpointId.of("a1")).isEmpty(),
+ "Endpoint removed");
}
@Test
- public void application_endpoint_routing_status() {
+ void application_endpoint_routing_status() {
RoutingPoliciesTester tester = new RoutingPoliciesTester();
TenantAndApplicationId application = TenantAndApplicationId.from("tenant1", "app1");
ApplicationId betaInstance = application.instance("beta");
@@ -782,8 +783,8 @@ public class RoutingPoliciesTest {
.instances("beta,main")
.region(zone1.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 2,
- mainInstance.instance(), 8))
+ Map.of(betaInstance.instance(), 2,
+ mainInstance.instance(), 8))
.build();
tester.provisionLoadBalancers(1, betaInstance, zone1);
tester.provisionLoadBalancers(1, mainInstance, zone1);
@@ -795,35 +796,35 @@ public class RoutingPoliciesTest {
DeploymentId betaZone1 = betaContext.deploymentIdIn(zone1);
DeploymentId mainZone1 = mainContext.deploymentIdIn(zone1);
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
// Changing routing status removes deployment from DNS
tester.routingPolicies().setRoutingStatus(mainZone1, RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2));
+ Map.of(betaZone1, 2));
// Changing routing status for remaining deployment adds back all deployments, because removing all deployments
// puts all IN
tester.routingPolicies().setRoutingStatus(betaZone1, RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
// Activating main deployment allows us to deactivate the beta deployment
tester.routingPolicies().setRoutingStatus(mainZone1, RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(mainZone1, 8));
+ Map.of(mainZone1, 8));
// Activate all deployments again
tester.routingPolicies().setRoutingStatus(betaZone1, RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
}
/** Returns an application package builder that satisfies requirements for a directly routed endpoint */
@@ -951,20 +952,21 @@ public class RoutingPoliciesTest {
.named(endpointId)
.targets(deployment)
.cluster(cluster);
- assertEquals("Expected a single endpoint with ID '" + endpointId + "'", 1,
- applicationEndpoints.size());
+ assertEquals(1,
+ applicationEndpoints.size(),
+ "Expected a single endpoint with ID '" + endpointId + "'");
String dnsName = applicationEndpoints.asList().get(0).dnsName();
deploymentsByDnsName.computeIfAbsent(dnsName, (k) -> new ArrayList<>())
.add(deployment);
}
- assertEquals("Found " + endpointId + " for " + application, 1, deploymentsByDnsName.size());
+ assertEquals(1, deploymentsByDnsName.size(), "Found " + endpointId + " for " + application);
deploymentsByDnsName.forEach((dnsName, deployments) -> {
Set<String> weightedTargets = deployments.stream()
.map(d -> "weighted/lb-" + loadBalancerId + "--" +
d.applicationId().toFullString() + "--" + d.zoneId().value() +
"/dns-zone-1/" + d.zoneId().value() + "/" + deploymentWeights.get(d))
.collect(Collectors.toSet());
- assertEquals(dnsName + " has expected targets", weightedTargets, aliasDataOf(dnsName));
+ assertEquals(weightedTargets, aliasDataOf(dnsName), dnsName + " has expected targets");
});
}
@@ -988,9 +990,9 @@ public class RoutingPoliciesTest {
instance.toFullString() + "--" + z.value() +
"/dns-zone-1/" + z.value() + "/" + zoneWeights.get(z))
.collect(Collectors.toSet());
- assertEquals("Region endpoint " + regionEndpoint + " points to load balancer",
- weightedTargets,
- aliasDataOf(regionEndpoint));
+ assertEquals(weightedTargets,
+ aliasDataOf(regionEndpoint),
+ "Region endpoint " + regionEndpoint + " points to load balancer");
ZoneId zone = zonesInRegion.get(0);
String latencyTarget = "latency/" + regionEndpoint + "/dns-zone-1/" + zone.value();
latencyTargets.add(latencyTarget);
@@ -1002,8 +1004,7 @@ public class RoutingPoliciesTest {
.primary()
.map(Endpoint::dnsName)
.orElse("<none>");
- assertEquals("Global endpoint " + globalEndpoint + " points to expected latency targets",
- latencyTargets, Set.copyOf(aliasDataOf(globalEndpoint)));
+ assertEquals(latencyTargets, Set.copyOf(aliasDataOf(globalEndpoint)), "Global endpoint " + globalEndpoint + " points to expected latency targets");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
index 277c8e1ef85..7477b94e3f4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
@@ -21,8 +21,8 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Oyvind Gronnesby
@@ -53,21 +53,21 @@ public class RotationRepositoryTest {
private final DeploymentContext application = tester.newDeploymentContext("tenant1", "app1", "default");
@Test
- public void assigns_and_reuses_rotation() {
+ void assigns_and_reuses_rotation() {
// Deploying assigns a rotation
application.submit(applicationPackage).deploy();
Rotation expected = new Rotation(new RotationId("foo-1"), "foo-1.com");
assertEquals(List.of(expected.id()), rotationIds(application.instance().rotations()));
assertEquals(URI.create("https://app1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(application.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(application.instanceId()).direct().first().get().url());
try (RotationLock lock = repository.lock()) {
List<AssignedRotation> rotations = repository.getOrAssignRotations(application.application().deploymentSpec(),
- application.instance(),
- lock);
+ application.instance(),
+ lock);
assertSingleRotation(expected, rotations, repository);
assertEquals(Set.of(RegionName.from("us-west-1"), RegionName.from("us-east-3")),
- application.instance().rotations().get(0).regions());
+ application.instance().rotations().get(0).regions());
}
// Submitting once more assigns same rotation
@@ -83,12 +83,12 @@ public class RotationRepositoryTest {
.build();
application.submit(applicationPackage).deploy();
assertEquals(Set.of(RegionName.from("us-west-1"), RegionName.from("us-east-3"),
- RegionName.from("us-central-1")),
- application.instance().rotations().get(0).regions());
+ RegionName.from("us-central-1")),
+ application.instance().rotations().get(0).regions());
}
-
+
@Test
- public void strips_whitespace_in_rotation_fqdn() {
+ void strips_whitespace_in_rotation_fqdn() {
var tester = new DeploymentTester(new ControllerTester(rotationsConfigWhitespaces, SystemName.main));
RotationRepository repository = tester.controller().routing().rotations();
var application2 = tester.newDeploymentContext("tenant1", "app2", "default");
@@ -103,7 +103,7 @@ public class RotationRepositoryTest {
}
@Test
- public void out_of_rotations() {
+ void out_of_rotations() {
// Assigns 1 rotation
application.submit(applicationPackage).deploy();
@@ -114,11 +114,11 @@ public class RotationRepositoryTest {
// We're now out of rotations and next deployment fails
var application3 = tester.newDeploymentContext("tenant3", "app3", "default");
application3.submit(applicationPackage)
- .runJobExpectingFailure(DeploymentContext.systemTest, Optional.of("out of rotations"));
+ .runJobExpectingFailure(DeploymentContext.systemTest, Optional.of("out of rotations"));
}
@Test
- public void too_few_zones() {
+ void too_few_zones() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
.region("us-east-3")
@@ -127,7 +127,7 @@ public class RotationRepositoryTest {
}
@Test
- public void no_rotation_assigned_for_application_without_service_id() {
+ void no_rotation_assigned_for_application_without_service_id() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.region("us-west-1")
@@ -137,7 +137,7 @@ public class RotationRepositoryTest {
}
@Test
- public void prefixes_system_when_not_main() {
+ void prefixes_system_when_not_main() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
.region("cd-us-east-1")
@@ -150,18 +150,18 @@ public class RotationRepositoryTest {
ZoneApiMock.fromId("prod.cd-us-west-1"));
DeploymentTester tester = new DeploymentTester(new ControllerTester(rotationsConfig, SystemName.cd));
tester.controllerTester().zoneRegistry()
- .setZones(zones)
- .setRoutingMethod(zones, RoutingMethod.sharedLayer4);
+ .setZones(zones)
+ .setRoutingMethod(zones, RoutingMethod.sharedLayer4);
tester.configServer().bootstrap(tester.controllerTester().zoneRegistry().zones().all().ids(), SystemApplication.notController());
var application2 = tester.newDeploymentContext("tenant2", "app2", "default");
application2.submit(applicationPackage).deploy();
assertEquals(List.of(new RotationId("foo-1")), rotationIds(application2.instance().rotations()));
assertEquals("https://cd.app2.tenant2.global.vespa.oath.cloud/",
- tester.controller().routing().readDeclaredEndpointsOf(application2.instanceId()).primary().get().url().toString());
+ tester.controller().routing().readDeclaredEndpointsOf(application2.instanceId()).primary().get().url().toString());
}
@Test
- public void multiple_instances_with_similar_global_service_id() {
+ void multiple_instances_with_similar_global_service_id() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-central-1")
@@ -169,19 +169,19 @@ public class RotationRepositoryTest {
.globalServiceId("global")
.build();
var instance1 = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
var instance2 = tester.newDeploymentContext("tenant1", "application1", "instance2");
assertEquals(List.of(new RotationId("foo-1")), rotationIds(instance1.instance().rotations()));
assertEquals(List.of(new RotationId("foo-2")), rotationIds(instance2.instance().rotations()));
assertEquals(URI.create("https://instance1.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
assertEquals(URI.create("https://instance2.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
}
@Test
- public void multiple_instances_with_similar_endpoints() {
+ void multiple_instances_with_similar_endpoints() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-central-1")
@@ -189,17 +189,17 @@ public class RotationRepositoryTest {
.endpoint("default", "foo", "us-central-1", "us-west-1")
.build();
var instance1 = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
var instance2 = tester.newDeploymentContext("tenant1", "application1", "instance2");
assertEquals(List.of(new RotationId("foo-1")), rotationIds(instance1.instance().rotations()));
assertEquals(List.of(new RotationId("foo-2")), rotationIds(instance2.instance().rotations()));
assertEquals(URI.create("https://instance1.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
assertEquals(URI.create("https://instance2.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
}
private void assertSingleRotation(Rotation expected, List<AssignedRotation> assignedRotations, RotationRepository repository) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManagerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManagerTest.java
new file mode 100644
index 00000000000..710e75fb235
--- /dev/null
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/security/CloudUserSessionManagerTest.java
@@ -0,0 +1,64 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.controller.security;
+
+import com.yahoo.config.provision.SystemName;
+import com.yahoo.config.provision.TenantName;
+import com.yahoo.vespa.flags.InMemoryFlagSource;
+import com.yahoo.vespa.flags.PermanentFlags;
+import com.yahoo.vespa.hosted.controller.ControllerTester;
+import com.yahoo.vespa.hosted.controller.LockedTenant;
+import com.yahoo.vespa.hosted.controller.api.role.Role;
+import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
+import com.yahoo.vespa.hosted.controller.api.role.SimplePrincipal;
+import com.yahoo.vespa.hosted.controller.api.role.TenantRole;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * @author freva
+ */
+class CloudUserSessionManagerTest {
+
+ private final ControllerTester tester = new ControllerTester(SystemName.Public);
+ private final CloudUserSessionManager userSessionManager = new CloudUserSessionManager(tester.controller());
+
+ @Test
+ void test() {
+ createTenant("tenant1", null);
+ createTenant("tenant2", 1234);
+ createTenant("tenant3", 1543);
+ createTenant("tenant4", 2313);
+
+ assertShouldExpire(false, 123);
+ assertShouldExpire(false, 123, "tenant1");
+ assertShouldExpire(true, 123, "tenant2");
+ assertShouldExpire(false, 2123, "tenant2");
+ assertShouldExpire(true, 123, "tenant1", "tenant2");
+
+ ((InMemoryFlagSource) tester.controller().flagSource()).withLongFlag(PermanentFlags.INVALIDATE_CONSOLE_SESSIONS.id(), 150);
+ assertShouldExpire(true, 123);
+ assertShouldExpire(true, 123, "tenant1");
+ }
+
+ private void assertShouldExpire(boolean expected, long issuedAtSeconds, String... tenantNames) {
+ Set<Role> roles = Stream.of(tenantNames).map(name -> TenantRole.developer(TenantName.from(name))).collect(Collectors.toSet());
+ SecurityContext context = new SecurityContext(new SimplePrincipal("dev"), roles, Instant.ofEpochSecond(issuedAtSeconds));
+ assertEquals(expected, userSessionManager.shouldExpireSessionFor(context));
+ }
+
+ private void createTenant(String tenantName, Integer invalidateAfterSeconds) {
+ tester.createTenant(tenantName);
+ Optional.ofNullable(invalidateAfterSeconds)
+ .map(Instant::ofEpochSecond)
+ .ifPresent(instant ->
+ tester.controller().tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
+ tester.controller().tenants().store(tenant.withInvalidateUserSessionsBefore(instant))));
+ }
+}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
index de268f34093..05a0aedb18b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
@@ -9,19 +9,19 @@ import com.yahoo.component.ComponentId;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyStoreUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.security.KeyStore;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author mpolden
@@ -30,28 +30,28 @@ public class SecureContainerTest {
private JDisc container;
- @Rule
- public TemporaryFolder folder = new TemporaryFolder();
+ @TempDir
+ public File folder;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(writeKeyStore()), Networking.enable);
}
- @After
+ @AfterEach
public void stopContainer() {
container.close();
}
@Test
- public void test_https_request() {
- assertNotNull("SslContextFactoryProvider is created", sslContextFactoryProvider());
+ void test_https_request() {
+ assertNotNull(sslContextFactoryProvider(), "SslContextFactoryProvider is created");
assertResponse(Request.Method.GET, "/", 200);
}
private void assertResponse(Request.Method method, String path, int expectedStatusCode) {
Response response = container.handleRequest(new Request("https://localhost:9999" + path, new byte[0], method));
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
private ControllerSslContextFactoryProvider sslContextFactoryProvider() {
@@ -83,7 +83,7 @@ public class SecureContainerTest {
Keys.keyPair.getPrivate(), new char[0], Keys.certificate)
.build();
try {
- Path path = folder.newFile().toPath();
+ Path path = File.createTempFile("junit", null, folder).toPath();
KeyStoreUtils.writeKeyStoreToFile(keyStore, path);
return path;
} catch (IOException e) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
index 25dd72ae622..33b1792accb 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.controller.versions;
import com.yahoo.vespa.hosted.controller.api.integration.maven.ArtifactId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -14,10 +14,10 @@ import static org.junit.Assert.assertEquals;
public class MavenRepositoryClientTest {
@Test
- public void testUri() {
+ void testUri() {
assertEquals(URI.create("https://domain:123/base/group/id/artifact-id/maven-metadata.xml"),
- MavenRepositoryClient.withArtifactPath(URI.create("https://domain:123/base/"),
- new ArtifactId("group.id", "artifact-id")));
+ MavenRepositoryClient.withArtifactPath(URI.create("https://domain:123/base/"),
+ new ArtifactId("group.id", "artifact-id")));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
index 7a137d4e410..18776be2dce 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
@@ -13,6 +13,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
+import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
@@ -21,12 +22,13 @@ import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import com.yahoo.vespa.hosted.controller.persistence.MockCuratorDb;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion.Confidence;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
+import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -35,11 +37,11 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.pro
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
import static java.util.stream.Collectors.toSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test computing of version status
@@ -98,8 +100,8 @@ public class VersionStatusTest {
writeControllerVersion(controller3, Version.fromString("6.2"), db);
VersionStatus versionStatus = VersionStatus.compute(tester.controller());
- assertEquals("Controller version is oldest version", Version.fromString("6.1"),
- versionStatus.controllerVersion().get().versionNumber());
+ assertEquals(Version.fromString("6.1"),
+ versionStatus.controllerVersion().get().versionNumber(), "Controller version is oldest version");
// Last controller upgrades
writeControllerVersion(controller2, Version.fromString("6.2"), db);
@@ -160,7 +162,7 @@ public class VersionStatusTest {
tester.triggerJobs();
tester.controllerTester().computeVersionStatus();
List<VespaVersion> versions = tester.controller().readVersionStatus().versions();
- assertEquals("The two versions above exist", 2, versions.size());
+ assertEquals(2, versions.size(), "The two versions above exist");
VespaVersion v1 = versions.get(0);
assertEquals(version1, v1.versionNumber());
@@ -176,9 +178,9 @@ public class VersionStatusTest {
context2.instanceId(), List.of(productionUsEast3),
context3.instanceId(), List.of(productionUsWest1, productionUsEast3)),
statistics1.productionSuccesses());
- assertEquals("No applications have active deployment jobs on version1.",
+ assertEquals(
List.of(),
- statistics1.runningUpgrade());
+ statistics1.runningUpgrade(), "No applications have active deployment jobs on version1.");
VespaVersion v2 = versions.get(1);
assertEquals(version2, v2.versionNumber());
@@ -201,13 +203,13 @@ public class VersionStatusTest {
}
private static void assertJobsRun(String assertion, Map<ApplicationId, List<JobType>> jobs, List<Run> runs) {
- assertEquals(assertion,
- jobs.entrySet().stream()
+ assertEquals(jobs.entrySet().stream()
.flatMap(entry -> entry.getValue().stream().map(type -> new JobId(entry.getKey(), type)))
.collect(toSet()),
runs.stream()
.map(run -> run.id().job())
- .collect(toSet()));
+ .collect(toSet()),
+ assertion);
}
@Test
@@ -218,7 +220,7 @@ public class VersionStatusTest {
tester.upgrader().maintain();
// Setup applications - all running on version0
- ApplicationPackage canaryPolicy = applicationPackage("canary");
+ ApplicationPackage canaryPolicy = applicationPackage("canary", 7);
var canary0 = tester.newDeploymentContext("tenant1", "canary0", "default")
.submit(canaryPolicy)
.deploy();
@@ -231,7 +233,7 @@ public class VersionStatusTest {
ApplicationPackage defaultPolicy = applicationPackage("default");
var default0 = tester.newDeploymentContext("tenant1", "default0", "default")
- .submit(defaultPolicy)
+ .submit(applicationPackage("default", 7))
.deploy();
var default1 = tester.newDeploymentContext("tenant1", "default1", "default")
.submit(defaultPolicy)
@@ -271,8 +273,8 @@ public class VersionStatusTest {
// Application without deployment
var ignored0 = tester.newDeploymentContext("tenant1", "ignored0", "default");
- assertEquals("All applications running on this version: High",
- Confidence.high, confidence(tester.controller(), version0));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "All applications running on this version: High");
// New version is released
Version version1 = new Version("6.3");
@@ -286,25 +288,25 @@ public class VersionStatusTest {
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "One canary failed: Broken");
// New version is released
Version version2 = new Version("6.4");
tester.controllerTester().upgradeSystem(version2);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Confidence defaults to low for version with no applications");
// All canaries upgrade successfully
canary0.deployPlatform(version2);
canary1.deployPlatform(version2);
- assertEquals("Confidence for remains unchanged for version1: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
- assertEquals("Nothing has failed but not all canaries have upgraded: Low",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "Confidence for remains unchanged for version1: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Nothing has failed but not all canaries have upgraded: Low");
// Remaining canary upgrades to version2 which raises confidence to normal and more apps upgrade
canary2.triggerJobs().jobAborted(systemTest).jobAborted(stagingTest);
@@ -313,8 +315,8 @@ public class VersionStatusTest {
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries have upgraded: Normal",
- Confidence.normal, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.normal, confidence(tester.controller(), version2), "Canaries have upgraded: Normal");
default0.deployPlatform(version2);
default1.deployPlatform(version2);
default2.deployPlatform(version2);
@@ -328,23 +330,23 @@ public class VersionStatusTest {
// Remember confidence across restart
tester.controllerTester().createNewController();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("All canaries deployed + < 90% of defaults: Normal",
- Confidence.normal, confidence(tester.controller(), version2));
- assertTrue("Status for version without applications is removed",
- tester.controller().readVersionStatus().versions().stream()
- .noneMatch(vespaVersion -> vespaVersion.versionNumber().equals(version1)));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ Confidence.normal, confidence(tester.controller(), version2), "All canaries deployed + < 90% of defaults: Normal");
+ assertTrue(tester.controller().readVersionStatus().versions().stream()
+ .noneMatch(vespaVersion -> vespaVersion.versionNumber().equals(version1)),
+ "Status for version without applications is removed");
// Another default application upgrades, raising confidence to high
default8.deployPlatform(version2);
default9.deployPlatform(version2);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("90% of defaults deployed successfully: High",
- VespaVersion.Confidence.high, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ VespaVersion.Confidence.high, confidence(tester.controller(), version2), "90% of defaults deployed successfully: High");
// A new version is released, all canaries upgrade successfully, but enough "default" apps fail to mark version
// as broken
@@ -364,12 +366,12 @@ public class VersionStatusTest {
default3.failDeployment(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("Confidence remains unchanged for version2: High",
- Confidence.high, confidence(tester.controller(), version2));
- assertEquals("40% of defaults failed: Broken",
- VespaVersion.Confidence.broken, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: High");
+ assertEquals(
+ VespaVersion.Confidence.broken, confidence(tester.controller(), version3), "40% of defaults failed: Broken");
// Test version order
List<VespaVersion> versions = tester.controller().readVersionStatus().versions();
@@ -379,6 +381,28 @@ public class VersionStatusTest {
assertTrue(versions.get(0).isReleased());
assertFalse(versions.get(1).isReleased()); // tesst quirk: maven repo lost during controller recreation; useful to test status though
assertTrue(versions.get(2).isReleased());
+
+ // A new major version is released and all canaries upgrade
+ Version version4 = new Version("7.1");
+ tester.controller().applications().setTargetMajorVersion(OptionalInt.of(version3.getMajor())); // Previous remains the default
+ tester.controllerTester().upgradeSystem(version4);
+ tester.upgrader().maintain();
+ tester.triggerJobs();
+ canary0.deployPlatform(version4);
+ canary1.deployPlatform(version4);
+ canary2.deployPlatform(version4);
+ tester.controllerTester().computeVersionStatus();
+ assertEquals(Confidence.normal, confidence(tester.controller(), version4));
+
+ // The single application allowing this major upgrades and confidence becomes 'high'
+ tester.upgrader().maintain();
+ tester.triggerJobs();
+ assertEquals(Change.of(version4), default0.instance().change());
+ default0.jobAborted(systemTest)
+ .jobAborted(stagingTest)
+ .deployPlatform(version4);
+ tester.controllerTester().computeVersionStatus();
+ assertEquals(Confidence.high, confidence(tester.controller(), version4));
}
@Test
@@ -393,8 +417,8 @@ public class VersionStatusTest {
.submit(appPackage)
.deploy();
- assertEquals("All applications running on this version: High",
- Confidence.high, confidence(tester.controller(), version0));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "All applications running on this version: High");
// New version is released
Version version1 = new Version("6.3");
@@ -406,59 +430,61 @@ public class VersionStatusTest {
canary0.failDeployment(systemTest);
canary0.abortJob(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "One canary failed: Broken");
// New version is released
Version version2 = new Version("6.4");
tester.controllerTester().upgradeSystem(version2);
tester.upgrader().maintain();
- assertEquals("Confidence remains unchanged for version1 until app overrides old tests: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "Confidence remains unchanged for version1 until app overrides old tests: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Confidence defaults to low for version with no applications");
assertEquals(version2, canary0.instance().change().platform().orElseThrow());
canary0.failDeployment(systemTest);
canary0.abortJob(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertFalse("Previous version should be forgotten, as canary only had test jobs run on it",
- tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version1)));
+ assertFalse(
+ tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version1)),
+ "Previous version should be forgotten, as canary only had test jobs run on it");
// App succeeds with tests, but fails production deployment
canary0.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "One canary failed: Broken");
// A new version is released, and the app again fails production deployment.
Version version3 = new Version("6.5");
tester.controllerTester().upgradeSystem(version3);
tester.upgrader().maintain();
- assertEquals("Confidence remains unchanged for version2: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version3), "Confidence defaults to low for version with no applications");
assertEquals(version3, canary0.instance().change().platform().orElseThrow());
canary0.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version2: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
- assertEquals("Canary broken, so confidence for version3: Broken",
- Confidence.broken, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: Broken");
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version3), "Canary broken, so confidence for version3: Broken");
// App succeeds production deployment, clearing failure on version2
canary0.runJob(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertFalse("Previous version should be forgotten, as canary only had test jobs run on it",
- tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version2)));
- assertEquals("Canary OK, but not done upgrading, so confidence for version3: Low",
- Confidence.low, confidence(tester.controller(), version3));
+ assertFalse(
+ tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version2)),
+ "Previous version should be forgotten, as canary only had test jobs run on it");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version3), "Canary OK, but not done upgrading, so confidence for version3: Low");
}
@Test
@@ -488,8 +514,9 @@ public class VersionStatusTest {
assertEquals(Confidence.high, confidence(tester.controller(), version1));
// Stale override was removed
- assertFalse("Stale override removed", tester.controller().curator().readConfidenceOverrides()
- .containsKey(version0));
+ assertFalse( tester.controller().curator().readConfidenceOverrides()
+ .containsKey(version0),
+ "Stale override removed");
}
@Test
@@ -668,11 +695,11 @@ public class VersionStatusTest {
private void assertOnVersion(Version version, ApplicationId instance, DeploymentTester tester) {
var vespaVersion = tester.controller().readVersionStatus().version(version);
- assertNotNull("Statistics for version " + version + " exist", vespaVersion);
+ assertNotNull(vespaVersion, "Statistics for version " + version + " exist");
var statistics = DeploymentStatistics.compute(List.of(version), tester.deploymentStatuses()).get(0);
- assertTrue("Application is on version " + version,
+ assertTrue(
Stream.of(statistics.productionSuccesses(), statistics.failingUpgrades(), statistics.runningUpgrade())
- .anyMatch(runs -> runs.stream().anyMatch(run -> run.id().application().equals(instance))));
+ .anyMatch(runs -> runs.stream().anyMatch(run -> run.id().application().equals(instance))), "Application is on version " + version);
}
private static void writeControllerVersion(HostName hostname, Version version, CuratorDb db) {
@@ -687,6 +714,14 @@ public class VersionStatusTest {
.orElseThrow(() -> new IllegalArgumentException("Expected to find version: " + version));
}
+ private static ApplicationPackage applicationPackage(String upgradePolicy, int majorVersion) {
+ return new ApplicationPackageBuilder().upgradePolicy(upgradePolicy)
+ .region("us-west-1")
+ .region("us-east-3")
+ .majorVersion(majorVersion)
+ .build();
+ }
+
private static final ApplicationPackage canaryApplicationPackage =
new ApplicationPackageBuilder().upgradePolicy("canary")
.region("us-west-1")
@@ -707,12 +742,12 @@ public class VersionStatusTest {
/** Returns empty prebuilt applications for efficiency */
private ApplicationPackage applicationPackage(String upgradePolicy) {
- switch (upgradePolicy) {
- case "canary" : return canaryApplicationPackage;
- case "default" : return defaultApplicationPackage;
- case "conservative" : return conservativeApplicationPackage;
- default : throw new IllegalArgumentException("No upgrade policy '" + upgradePolicy + "'");
- }
+ return switch (upgradePolicy) {
+ case "canary" -> canaryApplicationPackage;
+ case "default" -> defaultApplicationPackage;
+ case "conservative" -> conservativeApplicationPackage;
+ default -> throw new IllegalArgumentException("No upgrade policy '" + upgradePolicy + "'");
+ };
}
}
diff --git a/controller-server/src/test/resources/horizon/filters-complex.expected.json b/controller-server/src/test/resources/horizon/filters-complex.expected.json
index b3416f8a410..30ee6a28d7e 100644
--- a/controller-server/src/test/resources/horizon/filters-complex.expected.json
+++ b/controller-server/src/test/resources/horizon/filters-complex.expected.json
@@ -7,7 +7,7 @@
"type": "TimeSeriesDataSource",
"metric": {
"type": "MetricLiteral",
- "metric": "Vespa.vespa.qrserver.documents_covered.count"
+ "metric": "Vespa.vespa.container.documents_covered.count"
},
"sourceId": null,
"fetchLast": false,
diff --git a/controller-server/src/test/resources/horizon/filters-complex.json b/controller-server/src/test/resources/horizon/filters-complex.json
index 3acc7fe5044..e21fa61128a 100644
--- a/controller-server/src/test/resources/horizon/filters-complex.json
+++ b/controller-server/src/test/resources/horizon/filters-complex.json
@@ -7,7 +7,7 @@
"type": "TimeSeriesDataSource",
"metric": {
"type": "MetricLiteral",
- "metric": "Vespa.vespa.qrserver.documents_covered.count"
+ "metric": "Vespa.vespa.container.documents_covered.count"
},
"sourceId": null,
"fetchLast": false,
diff --git a/defaults/src/main/java/com/yahoo/vespa/defaults/Defaults.java b/defaults/src/main/java/com/yahoo/vespa/defaults/Defaults.java
index 3a169899ff1..e45ecbca57a 100644
--- a/defaults/src/main/java/com/yahoo/vespa/defaults/Defaults.java
+++ b/defaults/src/main/java/com/yahoo/vespa/defaults/Defaults.java
@@ -78,8 +78,7 @@ public class Defaults {
try {
return Integer.parseInt(port.get());
} catch (NumberFormatException e) {
- throw new IllegalArgumentException("must be an integer, was '" +
- port.get() + "'");
+ throw new IllegalArgumentException("must be an integer, was '" + port.get() + "'");
}
}
@@ -97,9 +96,10 @@ public class Defaults {
}
/**
- * Get the username to own directories, files and processes
+ * Get the username to own directories, files and processes.
+ *
* @return the vespa user name
- **/
+ */
public String vespaUser() { return vespaUser; }
@@ -108,8 +108,9 @@ public class Defaults {
* Detection of the hostname is now done before starting any Vespa
* programs and provided in the environment variable VESPA_HOSTNAME;
* if that variable isn't set a default of "localhost" is always returned.
+ *
* @return the vespa host name
- **/
+ */
public String vespaHostname() { return vespaHost; }
/**
@@ -159,13 +160,13 @@ public class Defaults {
*/
public int vespaPortBase() { return vespaPortBase; }
- /** @return port number used by cloud config server (for its RPC protocol) */
+ /** Returns port number used by cloud config server (for its RPC protocol) */
public int vespaConfigServerRpcPort() { return vespaPortConfigServerRpc; }
- /** @return port number used by cloud config server (REST api on HTTP) */
+ /** Returns port number used by cloud config server (REST api on HTTP) */
public int vespaConfigServerHttpPort() { return vespaPortConfigServerHttp; }
- /** @return port number used by config proxy server (RPC protocol) */
+ /** Returns port number used by config proxy server (RPC protocol) */
public int vespaConfigProxyRpcPort() { return vespaPortConfigProxyRpc; }
/** Returns the defaults of this runtime environment */
diff --git a/dist/vespa-engine.repo b/dist/vespa-engine.repo
index 33d439a9572..de436eb16ad 100644
--- a/dist/vespa-engine.repo
+++ b/dist/vespa-engine.repo
@@ -1,8 +1,10 @@
-[vespa-engine-stable]
-name=vespa-engine-stable
-baseurl=https://download.copr.fedorainfracloud.org/results/@vespa/vespa/epel-7-$basearch/
+[copr:copr.fedorainfracloud.org:group_vespa:vespa]
+name=Copr repo for vespa owned by @vespa
+baseurl=https://download.copr.fedorainfracloud.org/results/@vespa/vespa/centos-stream-8-$basearch/
type=rpm-md
+skip_if_unavailable=True
gpgcheck=1
gpgkey=https://download.copr.fedorainfracloud.org/results/@vespa/vespa/pubkey.gpg
repo_gpgcheck=0
enabled=1
+enabled_metadata=1
diff --git a/dist/vespa.spec b/dist/vespa.spec
index de1b5382040..b94a77491b8 100644
--- a/dist/vespa.spec
+++ b/dist/vespa.spec
@@ -282,13 +282,14 @@ Requires: vespa-xxhash = 0.8.0
Requires: xxhash
Requires: xxhash-libs >= 0.8.0
%endif
-Requires: zlib
-Requires: perf
Requires: gdb
+Requires: hostname
+Requires: perf
Requires: nc
Requires: nghttp2
Requires: net-tools
Requires: unzip
+Requires: zlib
Requires: zstd
%if 0%{?el7}
Requires: llvm7.0
diff --git a/docker/.gitignore b/docker/.gitignore
deleted file mode 100644
index 712576eb374..00000000000
--- a/docker/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.rpm
-logs/
-tmp/
diff --git a/docker/OWNERS b/docker/OWNERS
deleted file mode 100644
index 485a8c4be74..00000000000
--- a/docker/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-aressem
diff --git a/docker/README.md b/docker/README.md
deleted file mode 100644
index 18ab6648f3e..00000000000
--- a/docker/README.md
+++ /dev/null
@@ -1,26 +0,0 @@
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-
-# Building Vespa RPM on Docker (OS X and Linux)
-
-## Installing docker
-[Docker installation](https://docs.docker.com/engine/installation/)
-
-*On Linux, the default storage device is devicemapper with loopback device and max 10GB container size. This size is too small for a full build. Please see [here](http://www.projectatomic.io/blog/2016/03/daemon_option_basedevicesize/) and [here](http://www.projectatomic.io/blog/2015/06/notes-on-fedora-centos-and-docker-storage-drivers/) to overcome this limitation.*
-
-
-## Building Vespa RPM
-Execute ```./build-vespa.sh <Vespa version number>``` to build Vespa from this source code.
-
-The produced rpms will be available in this folder after compilation.
-The version number will be compiled into binaries and must be on the form x.y.z, like 7.1.2 -
-but has no other meaning than that.
-
-
-## Troubleshooting
-- Use ```docker logs CONTAINER``` for output - useful if the commands above fail.
-
-- If the build fails, start from scratch and build again. Clean local docker if docker image disk full:
- - ```docker rm -v $(docker ps -a -q -f status=exited)```
- - ```docker rmi $(docker images -f "dangling=true" -q)```
-
-- _Directory renamed before its status could be extracted_ can be caused by [1219](https://github.com/docker/for-mac/issues/1219) - workaround (from the issue): "It may be an overlay storage driver issue - you can add ```{"storage-driver":"aufs"}``` in the advanced daemon preferences pane and see if that makes a difference."
diff --git a/docker/build-vespa.sh b/docker/build-vespa.sh
deleted file mode 100755
index f7b106b7800..00000000000
--- a/docker/build-vespa.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/bash
-# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-set -e
-
-if [ $# -ne 1 ]; then
- echo "Usage: $0 <vespa version>"
- exit 1
-fi
-
-DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
-cd $DIR
-
-VESPA_VERSION=$1
-DOCKER_IMAGE="centos:7"
-
-docker pull ${DOCKER_IMAGE}
-
-docker run --rm -v $(pwd)/..:/vespa -w /vespa --entrypoint /vespa/docker/build/build-vespa-internal.sh "$DOCKER_IMAGE" "$VESPA_VERSION" "$(id -u)" "$(id -g)"
diff --git a/docker/build/build-vespa-internal.sh b/docker/build/build-vespa-internal.sh
deleted file mode 100755
index dada151a29f..00000000000
--- a/docker/build/build-vespa-internal.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/bin/bash
-# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-set -e
-
-if [ $# -ne 3 ]; then
- echo "Usage: $0 <vespa version> <caller uid> <caller gid>"
- echo "This script should not be called manually."
- exit 1
-fi
-VESPA_VERSION=$1
-CALLER_UID=$2
-CALLER_GID=$3
-
-if ! [ -x ./dist.sh ]; then
- echo ". is not a vespa-engine/vespa root directory"
- exit 1
-fi
-
-./dist.sh ${VESPA_VERSION}
-
-yum -y install epel-release
-yum -y install centos-release-scl
-
-if ! yum-config-manager --add-repo https://copr.fedorainfracloud.org/coprs/g/vespa/vespa/repo/epel-7/group_vespa-vespa-epel-7.repo; then
- cat << 'EOF' > /etc/yum.repos.d/vespa-release.repo
-[vespa-release]
-name=Vespa releases
-baseurl=https://verizonmedia.jfrog.io/artifactory/vespa/centos/$releasever/release/$basearch
-gpgcheck=0
-enabled=1
-EOF
-fi
-
-yum-builddep -y \
- --setopt="base-source.skip_if_unavailable=true" \
- --setopt="updates-source.skip_if_unavailable=true" \
- --setopt="extras-source.skip_if_unavailable=true" \
- --setopt="epel-source.skip_if_unavailable=true" \
- --setopt="centos-sclo-rh-source.skip_if_unavailable=true" \
- --setopt="centos-sclo-sclo-source.skip_if_unavailable=true" \
- ~/rpmbuild/SPECS/vespa-${VESPA_VERSION}.spec
-
-rpmbuild -bb ~/rpmbuild/SPECS/vespa-${VESPA_VERSION}.spec
-chown ${CALLER_UID}:${CALLER_GID} ~/rpmbuild/RPMS/x86_64/*.rpm
-mv ~/rpmbuild/RPMS/x86_64/*.rpm docker
diff --git a/docproc/pom.xml b/docproc/pom.xml
index e7d8d6e3a3e..325e198c59a 100644
--- a/docproc/pom.xml
+++ b/docproc/pom.xml
@@ -48,6 +48,12 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
+ <artifactId>container-disc</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
<artifactId>container-messagebus</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
@@ -82,12 +88,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
<!-- TEST scope -->
<dependency>
diff --git a/docproc/src/main/java/com/yahoo/docproc/jdisc/observability/DocprocsStatusExtension.java b/docproc/src/main/java/com/yahoo/docproc/jdisc/observability/DocprocsStatusExtension.java
new file mode 100644
index 00000000000..15f6c3a5cd9
--- /dev/null
+++ b/docproc/src/main/java/com/yahoo/docproc/jdisc/observability/DocprocsStatusExtension.java
@@ -0,0 +1,51 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.docproc.jdisc.observability;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.yahoo.component.provider.ComponentRegistry;
+import com.yahoo.container.handler.observability.ApplicationStatusHandler;
+import com.yahoo.docproc.Call;
+import com.yahoo.docproc.impl.DocprocService;
+import com.yahoo.docproc.jdisc.DocumentProcessingHandler;
+import com.yahoo.jdisc.handler.RequestHandler;
+
+import java.util.Iterator;
+import java.util.Map;
+
+
+/**
+ * @author bjorncs
+ */
+public class DocprocsStatusExtension implements ApplicationStatusHandler.Extension {
+
+ @Override
+ public Map<String, ? extends JsonNode> produceExtraFields(ApplicationStatusHandler statusHandler) {
+ return Map.of("docprocChains", renderDocprocChains(statusHandler));
+ }
+
+ private static JsonNode renderDocprocChains(ApplicationStatusHandler statusHandler) {
+ ObjectNode ret = statusHandler.jsonMapper().createObjectNode();
+ for (RequestHandler h : statusHandler.requestHandlers()) {
+ if (h instanceof DocumentProcessingHandler) {
+ ComponentRegistry<DocprocService> registry = ((DocumentProcessingHandler) h).getDocprocServiceRegistry();
+ for (DocprocService service : registry.allComponents()) {
+ ret.set(service.getId().stringValue(), renderCalls(statusHandler, service.getCallStack().iterator()));
+ }
+ }
+ }
+ return ret;
+ }
+
+ private static JsonNode renderCalls(ApplicationStatusHandler statusHandler, Iterator<Call> components) {
+ ArrayNode ret = statusHandler.jsonMapper().createArrayNode();
+ while (components.hasNext()) {
+ Call c = components.next();
+ JsonNode jc = ApplicationStatusHandler.renderComponent(c.getDocumentProcessor(), c.getDocumentProcessor().getId());
+ ret.add(jc);
+ }
+ return ret;
+ }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/package-info.java b/docproc/src/main/java/com/yahoo/docproc/jdisc/observability/package-info.java
index 61ce90654f8..0040acf1fdc 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/package-info.java
+++ b/docproc/src/main/java/com/yahoo/docproc/jdisc/observability/package-info.java
@@ -3,6 +3,6 @@
* @author bjorncs
*/
@ExportPackage
-package com.yahoo.security.tls.policy;
+package com.yahoo.docproc.jdisc.observability;
import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/docprocs/src/test/java/com/yahoo/docprocs/indexing/IndexingProcessorTestCase.java b/docprocs/src/test/java/com/yahoo/docprocs/indexing/IndexingProcessorTestCase.java
index 76f4578ac87..c6ba63b7924 100644
--- a/docprocs/src/test/java/com/yahoo/docprocs/indexing/IndexingProcessorTestCase.java
+++ b/docprocs/src/test/java/com/yahoo/docprocs/indexing/IndexingProcessorTestCase.java
@@ -125,6 +125,7 @@ public class IndexingProcessorTestCase {
return lst.get(0);
}
+ @SuppressWarnings("deprecation")
private static IndexingProcessor newProcessor(String configId) {
return new IndexingProcessor(new DocumentTypeManager(ConfigGetter.getConfig(DocumentmanagerConfig.class, configId)),
ConfigGetter.getConfig(IlscriptsConfig.class, configId),
diff --git a/document/abi-spec.json b/document/abi-spec.json
index 0ddc5dabc3c..443385bb0a0 100644
--- a/document/abi-spec.json
+++ b/document/abi-spec.json
@@ -208,7 +208,7 @@
"public bridge synthetic int compareTo(java.lang.Object)"
],
"fields": [
- "public static int classId",
+ "public static final int classId",
"public static final com.yahoo.document.NumericDataType NONE",
"public static final com.yahoo.document.NumericDataType INT",
"public static final com.yahoo.document.NumericDataType FLOAT",
@@ -485,6 +485,8 @@
"public void <init>()",
"public void <init>(com.yahoo.document.config.DocumentmanagerConfig)",
"public static com.yahoo.document.DocumentTypeManager fromFile(java.lang.String)",
+ "public boolean getIgnoreUndefinedFields()",
+ "public void setIgnoreUndefinedFields(boolean)",
"public void register(com.yahoo.document.DataType)",
"public com.yahoo.document.DocumentType registerDocumentType(com.yahoo.document.DocumentType)",
"public com.yahoo.document.DocumentType getDocumentType(com.yahoo.document.DataTypeName)",
diff --git a/document/src/main/java/com/yahoo/document/DataType.java b/document/src/main/java/com/yahoo/document/DataType.java
index b185ff53c87..e47c0c3a81e 100644
--- a/document/src/main/java/com/yahoo/document/DataType.java
+++ b/document/src/main/java/com/yahoo/document/DataType.java
@@ -34,7 +34,7 @@ import java.util.List;
public abstract class DataType extends Identifiable implements Comparable<DataType> {
// The global class identifier shared with C++.
- public static int classId = registerClass(Ids.document + 50, DataType.class);
+ public static final int classId = registerClass(Ids.document + 50, DataType.class);
// NOTE: These types are also defined in
// document/src/vespa/document/datatype/datatype.h
diff --git a/document/src/main/java/com/yahoo/document/DocumentTypeManager.java b/document/src/main/java/com/yahoo/document/DocumentTypeManager.java
index b5c9e54939e..379e0836a01 100644
--- a/document/src/main/java/com/yahoo/document/DocumentTypeManager.java
+++ b/document/src/main/java/com/yahoo/document/DocumentTypeManager.java
@@ -2,7 +2,6 @@
package com.yahoo.document;
import com.yahoo.component.annotation.Inject;
-import com.yahoo.config.subscription.ConfigSubscriber;
import com.yahoo.document.annotation.AnnotationType;
import com.yahoo.document.annotation.AnnotationTypeRegistry;
import com.yahoo.document.annotation.AnnotationTypes;
@@ -21,12 +20,11 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import java.util.logging.Logger;
/**
* The DocumentTypeManager keeps track of the document types registered in
* the Vespa common repository.
- * <p>
+ *
* The DocumentTypeManager is also responsible for registering a FieldValue
* factory for each data type a field can have. The Document object
* uses this factory to serialize and deserialize the various datatypes.
@@ -38,9 +36,6 @@ import java.util.logging.Logger;
*/
public class DocumentTypeManager {
- private final static Logger log = Logger.getLogger(DocumentTypeManager.class.getName());
-
-
// *Configured data types* (not built-in/primitive) indexed by their id
//
// *Primitive* data types are always available and have a single id.
@@ -54,6 +49,7 @@ public class DocumentTypeManager {
private Map<Integer, DataType> dataTypes = new LinkedHashMap<>();
private Map<DataTypeName, DocumentType> documentTypes = new LinkedHashMap<>();
private AnnotationTypeRegistry annotationTypeRegistry = new AnnotationTypeRegistry();
+ private boolean ignoreUndefinedFields = false;
public DocumentTypeManager() {
registerDefaultDataTypes();
@@ -103,22 +99,12 @@ public class DocumentTypeManager {
}
}
- boolean hasDataTypeInternal(String name) {
- if (name.startsWith("tensor(")) return true; // built-in dynamic: Always present
- for (DataType type : dataTypes.values()) {
- if (type.getName().equalsIgnoreCase(name)) {
- return true;
- }
- }
- return false;
- }
-
/**
* For internal use only, avoid whenever possible.
* Use constants and factories in DataType instead.
* For structs, use getStructType() in DocumentType.
* For annotation payloads, use getDataType() in AnnotationType.
- **/
+ */
DataType getDataTypeInternal(String name) {
if (name.startsWith("tensor(")) // built-in dynamic
return new TensorDataType(TensorType.fromSpec(name));
@@ -151,6 +137,13 @@ public class DocumentTypeManager {
}
/**
+ * Returns true if we should ignore attempts to set a field not defined in the document type,
+ * rather than (by default) throwing an exception.
+ */
+ public boolean getIgnoreUndefinedFields() { return ignoreUndefinedFields; }
+ public void setIgnoreUndefinedFields(boolean ignoreUndefinedFields) { this.ignoreUndefinedFields = ignoreUndefinedFields; }
+
+ /**
* Return a data type instance
*
* @param code the code of the data type to return, which must be either built in or present in this manager
diff --git a/document/src/main/java/com/yahoo/document/DocumentTypeManagerConfigurer.java b/document/src/main/java/com/yahoo/document/DocumentTypeManagerConfigurer.java
index d6833a482f1..518a80ca058 100644
--- a/document/src/main/java/com/yahoo/document/DocumentTypeManagerConfigurer.java
+++ b/document/src/main/java/com/yahoo/document/DocumentTypeManagerConfigurer.java
@@ -60,9 +60,8 @@ public class DocumentTypeManagerConfigurer implements ConfigSubscriber.SingleSub
/** One-shot configuration; should be called on a newly constructed manager */
static void configureNewManager(DocumentmanagerConfig config, DocumentTypeManager manager) {
- if (config == null) {
- return;
- }
+ if (config == null) return;
+ manager.setIgnoreUndefinedFields(config.ignoreundefinedfields());
new Apply(config, manager);
if (config.datatype().size() == 0 && config.annotationtype().size() == 0) {
new ApplyNewDoctypeConfig(config, manager);
@@ -328,6 +327,7 @@ public class DocumentTypeManagerConfigurer implements ConfigSubscriber.SingleSub
public ApplyNewDoctypeConfig(DocumentmanagerConfig config, DocumentTypeManager manager) {
this.manager = manager;
this.usev8geopositions = config.usev8geopositions();
+
apply(config);
}
diff --git a/document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java b/document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java
index 52f27046640..1f92bed5e75 100644
--- a/document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java
+++ b/document/src/main/java/com/yahoo/document/json/DocumentUpdateJsonSerializer.java
@@ -239,7 +239,7 @@ public class DocumentUpdateJsonSerializer {
operationKey = "decrement";
break;
default:
- throw new RuntimeException(String.format("Unrecognized arithmetic operator '%s'", operator.name));
+ throw new RuntimeException("Unrecognized arithmetic operator '%s'".formatted(operator.name));
}
wrapIOException(() -> generator.writeFieldName(operationKey));
diff --git a/document/src/main/java/com/yahoo/document/json/JsonReader.java b/document/src/main/java/com/yahoo/document/json/JsonReader.java
index 009fcb3de28..94ce986fc81 100644
--- a/document/src/main/java/com/yahoo/document/json/JsonReader.java
+++ b/document/src/main/java/com/yahoo/document/json/JsonReader.java
@@ -71,7 +71,7 @@ public class JsonReader {
throw new IllegalArgumentException(e);
}
documentParseInfo.operationType = operationType;
- VespaJsonDocumentReader vespaJsonDocumentReader = new VespaJsonDocumentReader();
+ VespaJsonDocumentReader vespaJsonDocumentReader = new VespaJsonDocumentReader(typeManager.getIgnoreUndefinedFields());
DocumentOperation operation = vespaJsonDocumentReader.createDocumentOperation(
getDocumentTypeFromString(documentParseInfo.documentId.getDocType(), typeManager), documentParseInfo);
operation.setCondition(TestAndSetCondition.fromConditionString(documentParseInfo.condition));
@@ -103,7 +103,7 @@ public class JsonReader {
state = END_OF_FEED;
return null;
}
- VespaJsonDocumentReader vespaJsonDocumentReader = new VespaJsonDocumentReader();
+ VespaJsonDocumentReader vespaJsonDocumentReader = new VespaJsonDocumentReader(typeManager.getIgnoreUndefinedFields());
DocumentOperation operation = vespaJsonDocumentReader.createDocumentOperation(
getDocumentTypeFromString(documentParseInfo.get().documentId.getDocType(), typeManager),
documentParseInfo.get());
diff --git a/document/src/main/java/com/yahoo/document/json/readers/AddRemoveCreator.java b/document/src/main/java/com/yahoo/document/json/readers/AddRemoveCreator.java
index b0882c3ab03..bc214f18776 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/AddRemoveCreator.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/AddRemoveCreator.java
@@ -21,22 +21,22 @@ public class AddRemoveCreator {
// yes, this suppresswarnings ugliness is by intention, the code relies on
// the contracts in the builders
- @SuppressWarnings({ "cast", "rawtypes", "unchecked" })
- public static void createAdds(TokenBuffer buffer, Field field, FieldUpdate update) {
- createAddsOrRemoves(buffer, field, update, false);
+ @SuppressWarnings("cast")
+ public static void createAdds(TokenBuffer buffer, Field field, FieldUpdate update, boolean ignoreUndefinedFields) {
+ createAddsOrRemoves(buffer, field, update, false, ignoreUndefinedFields);
}
// yes, this suppresswarnings ugliness is by intention, the code relies on
// the contracts in the builders
- @SuppressWarnings({ "cast", "rawtypes", "unchecked" })
- public static void createRemoves(TokenBuffer buffer, Field field, FieldUpdate update) {
- createAddsOrRemoves(buffer, field, update, true);
+ @SuppressWarnings("cast")
+ public static void createRemoves(TokenBuffer buffer, Field field, FieldUpdate update, boolean ignoreUndefinedFields) {
+ createAddsOrRemoves(buffer, field, update, true, ignoreUndefinedFields);
}
// yes, this suppresswarnings ugliness is by intention, the code relies on
// the contracts in the builders
@SuppressWarnings({ "cast", "rawtypes", "unchecked" })
- private static void createAddsOrRemoves(TokenBuffer buffer, Field field, FieldUpdate update, boolean isRemove) {
+ private static void createAddsOrRemoves(TokenBuffer buffer, Field field, FieldUpdate update, boolean isRemove, boolean ignoreUndefinedFields) {
FieldValue container = field.getDataType().createFieldValue();
FieldUpdate singleUpdate;
int initNesting = buffer.nesting();
@@ -45,10 +45,9 @@ public class AddRemoveCreator {
if (container instanceof CollectionFieldValue) {
buffer.next();
DataType valueType = ((CollectionFieldValue) container).getDataType().getNestedType();
- if (container instanceof WeightedSet) {
+ if (container instanceof WeightedSet weightedSet) {
// these are objects with string keys (which are the nested
// types) and values which are the weight
- WeightedSet weightedSet = (WeightedSet) container;
fillWeightedSetUpdate(buffer, initNesting, valueType, weightedSet);
if (isRemove) {
singleUpdate = FieldUpdate.createRemoveAll(field, weightedSet);
@@ -58,7 +57,7 @@ public class AddRemoveCreator {
}
} else {
List<FieldValue> arrayContents = new ArrayList<>();
- ArrayReader.fillArrayUpdate(buffer, initNesting, valueType, arrayContents);
+ ArrayReader.fillArrayUpdate(buffer, initNesting, valueType, arrayContents, ignoreUndefinedFields);
if (buffer.currentToken() != JsonToken.END_ARRAY) {
throw new IllegalArgumentException("Expected END_ARRAY. Got '" + buffer.currentToken() + "'.");
}
diff --git a/document/src/main/java/com/yahoo/document/json/readers/ArrayReader.java b/document/src/main/java/com/yahoo/document/json/readers/ArrayReader.java
index 9c27b1eb9d0..e8c4ae85356 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/ArrayReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/ArrayReader.java
@@ -15,22 +15,23 @@ import static com.yahoo.document.json.readers.SingleValueReader.readSingleValue;
public class ArrayReader {
- public static void fillArrayUpdate(TokenBuffer buffer, int initNesting, DataType valueType, List<FieldValue> arrayContents) {
+ public static void fillArrayUpdate(TokenBuffer buffer, int initNesting, DataType valueType,
+ List<FieldValue> arrayContents, boolean ignoreUndefinedFields) {
while (buffer.nesting() >= initNesting) {
Preconditions.checkArgument(buffer.currentToken() != JsonToken.VALUE_NULL, "Illegal null value for array entry");
- arrayContents.add(readSingleValue(buffer, valueType));
+ arrayContents.add(readSingleValue(buffer, valueType, ignoreUndefinedFields));
buffer.next();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
- public static void fillArray(TokenBuffer buffer, CollectionFieldValue parent, DataType valueType) {
+ public static void fillArray(TokenBuffer buffer, CollectionFieldValue parent, DataType valueType, boolean ignoreUndefinedFields) {
int initNesting = buffer.nesting();
expectArrayStart(buffer.currentToken());
buffer.next();
while (buffer.nesting() >= initNesting) {
Preconditions.checkArgument(buffer.currentToken() != JsonToken.VALUE_NULL, "Illegal null value for array entry");
- parent.add(readSingleValue(buffer, valueType));
+ parent.add(readSingleValue(buffer, valueType, ignoreUndefinedFields));
buffer.next();
}
}
diff --git a/document/src/main/java/com/yahoo/document/json/readers/CompositeReader.java b/document/src/main/java/com/yahoo/document/json/readers/CompositeReader.java
index 91274144710..a2dd91b90a0 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/CompositeReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/CompositeReader.java
@@ -19,10 +19,10 @@ import static com.yahoo.document.json.readers.WeightedSetReader.fillWeightedSet;
public class CompositeReader {
- // TODO createComposite is extremely similar to add/remove, refactor
+ // TODO: reateComposite is extremely similar to add/remove, refactor
// yes, this suppresswarnings ugliness is by intention, the code relies on the contracts in the builders
@SuppressWarnings({ "cast", "rawtypes" })
- public static void populateComposite(TokenBuffer buffer, FieldValue fieldValue) {
+ public static void populateComposite(TokenBuffer buffer, FieldValue fieldValue, boolean ignoreUndefinedFields) {
JsonToken token = buffer.currentToken();
if ((token != JsonToken.START_OBJECT) && (token != JsonToken.START_ARRAY)) {
throw new IllegalArgumentException("Expected '[' or '{'. Got '" + token + "'.");
@@ -32,14 +32,14 @@ public class CompositeReader {
if (fieldValue instanceof WeightedSet) {
fillWeightedSet(buffer, valueType, (WeightedSet) fieldValue);
} else {
- fillArray(buffer, (CollectionFieldValue) fieldValue, valueType);
+ fillArray(buffer, (CollectionFieldValue) fieldValue, valueType, ignoreUndefinedFields);
}
} else if (fieldValue instanceof MapFieldValue) {
- MapReader.fillMap(buffer, (MapFieldValue) fieldValue);
+ MapReader.fillMap(buffer, (MapFieldValue) fieldValue, ignoreUndefinedFields);
} else if (PositionDataType.INSTANCE.equals(fieldValue.getDataType())) {
GeoPositionReader.fillGeoPosition(buffer, fieldValue);
} else if (fieldValue instanceof StructuredFieldValue) {
- StructReader.fillStruct(buffer, (StructuredFieldValue) fieldValue);
+ StructReader.fillStruct(buffer, (StructuredFieldValue) fieldValue, ignoreUndefinedFields);
} else if (fieldValue instanceof TensorFieldValue) {
TensorReader.fillTensor(buffer, (TensorFieldValue) fieldValue);
} else {
diff --git a/document/src/main/java/com/yahoo/document/json/readers/MapReader.java b/document/src/main/java/com/yahoo/document/json/readers/MapReader.java
index fa8f9bfd6c5..1d4cb85d130 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/MapReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/MapReader.java
@@ -25,21 +25,22 @@ import static com.yahoo.document.json.readers.SingleValueReader.readSingleUpdate
import static com.yahoo.document.json.readers.SingleValueReader.readSingleValue;
public class MapReader {
+
public static final String MAP_KEY = "key";
public static final String MAP_VALUE = "value";
public static final String UPDATE_ELEMENT = "element";
public static final String UPDATE_MATCH = "match";
- public static void fillMap(TokenBuffer buffer, MapFieldValue parent) {
+ public static void fillMap(TokenBuffer buffer, MapFieldValue parent, boolean ignoreUndefinedFields) {
if (buffer.currentToken() == JsonToken.START_ARRAY) {
- MapReader.fillMapFromArray(buffer, parent);
+ MapReader.fillMapFromArray(buffer, parent, ignoreUndefinedFields);
} else {
- MapReader.fillMapFromObject(buffer, parent);
+ MapReader.fillMapFromObject(buffer, parent, ignoreUndefinedFields);
}
}
@SuppressWarnings({ "rawtypes", "cast", "unchecked" })
- public static void fillMapFromArray(TokenBuffer buffer, MapFieldValue parent) {
+ public static void fillMapFromArray(TokenBuffer buffer, MapFieldValue parent, boolean ignoreUndefinedFields) {
JsonToken token = buffer.currentToken();
int initNesting = buffer.nesting();
expectArrayStart(token);
@@ -53,9 +54,9 @@ public class MapReader {
token = buffer.next();
for (int i = 0; i < 2; ++i) {
if (MAP_KEY.equals(buffer.currentName())) {
- key = readSingleValue(buffer, keyType);
+ key = readSingleValue(buffer, keyType, ignoreUndefinedFields);
} else if (MAP_VALUE.equals(buffer.currentName())) {
- value = readSingleValue(buffer, valueType);
+ value = readSingleValue(buffer, valueType, ignoreUndefinedFields);
}
token = buffer.next();
}
@@ -68,7 +69,7 @@ public class MapReader {
}
@SuppressWarnings({ "rawtypes", "cast", "unchecked" })
- public static void fillMapFromObject(TokenBuffer buffer, MapFieldValue parent) {
+ public static void fillMapFromObject(TokenBuffer buffer, MapFieldValue parent, boolean ignoreUndefinedFields) {
JsonToken token = buffer.currentToken();
int initNesting = buffer.nesting();
expectObjectStart(token);
@@ -77,7 +78,7 @@ public class MapReader {
DataType valueType = parent.getDataType().getValueType();
while (buffer.nesting() >= initNesting) {
FieldValue key = readAtomic(buffer.currentName(), keyType);
- FieldValue value = readSingleValue(buffer, valueType);
+ FieldValue value = readSingleValue(buffer, valueType, ignoreUndefinedFields);
Preconditions.checkState(key != null && value != null, "Missing key or value for map entry.");
parent.put(key, value);
@@ -87,7 +88,11 @@ public class MapReader {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
- public static ValueUpdate createMapUpdate(TokenBuffer buffer, DataType currentLevel, FieldValue keyParent, FieldValue topLevelKey) {
+ public static ValueUpdate createMapUpdate(TokenBuffer buffer,
+ DataType currentLevel,
+ FieldValue keyParent,
+ FieldValue topLevelKey,
+ boolean ignoreUndefinedFields) {
TokenBuffer.Token element = buffer.prefetchScalar(UPDATE_ELEMENT);
if (UPDATE_ELEMENT.equals(buffer.currentName())) {
buffer.next();
@@ -102,24 +107,24 @@ public class MapReader {
if (!UPDATE_MATCH.equals(buffer.currentName())) {
// we have reached an action...
if (topLevelKey == null) {
- return ValueUpdate.createMap(key, readSingleUpdate(buffer, valueTypeForMapUpdate(currentLevel), buffer.currentName()));
+ return ValueUpdate.createMap(key, readSingleUpdate(buffer, valueTypeForMapUpdate(currentLevel), buffer.currentName(), ignoreUndefinedFields));
} else {
- return ValueUpdate.createMap(topLevelKey, readSingleUpdate(buffer, valueTypeForMapUpdate(currentLevel), buffer.currentName()));
+ return ValueUpdate.createMap(topLevelKey, readSingleUpdate(buffer, valueTypeForMapUpdate(currentLevel), buffer.currentName(), ignoreUndefinedFields));
}
} else {
// next level of matching
if (topLevelKey == null) {
- return createMapUpdate(buffer, valueTypeForMapUpdate(currentLevel), key, key);
+ return createMapUpdate(buffer, valueTypeForMapUpdate(currentLevel), key, key, ignoreUndefinedFields);
} else {
- return createMapUpdate(buffer, valueTypeForMapUpdate(currentLevel), key, topLevelKey);
+ return createMapUpdate(buffer, valueTypeForMapUpdate(currentLevel), key, topLevelKey, ignoreUndefinedFields);
}
}
}
@SuppressWarnings("rawtypes")
- public static ValueUpdate createMapUpdate(TokenBuffer buffer, Field field) {
+ public static ValueUpdate createMapUpdate(TokenBuffer buffer, Field field, boolean ignoreUndefinedFields) {
buffer.next();
- MapValueUpdate m = (MapValueUpdate) MapReader.createMapUpdate(buffer, field.getDataType(), null, null);
+ MapValueUpdate m = (MapValueUpdate) MapReader.createMapUpdate(buffer, field.getDataType(), null, null, ignoreUndefinedFields);
buffer.next();
// must generate the field value in parallell with the actual
return m;
diff --git a/document/src/main/java/com/yahoo/document/json/readers/SingleValueReader.java b/document/src/main/java/com/yahoo/document/json/readers/SingleValueReader.java
index 0ccdbdaa9d5..1747e739bbf 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/SingleValueReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/SingleValueReader.java
@@ -41,25 +41,25 @@ public class SingleValueReader {
arithmeticExpressionPattern = Pattern.compile("^\\$\\w+\\s*([" + validSigns + "])\\s*(\\d+(.\\d+)?)$");
}
- public static FieldValue readSingleValue(TokenBuffer buffer, DataType expectedType) {
+ public static FieldValue readSingleValue(TokenBuffer buffer, DataType expectedType, boolean ignoreUndefinedFields) {
if (buffer.currentToken().isScalarValue()) {
return readAtomic(buffer.currentText(), expectedType);
} else {
FieldValue fieldValue = expectedType.createFieldValue();
- CompositeReader.populateComposite(buffer, fieldValue);
+ CompositeReader.populateComposite(buffer, fieldValue, ignoreUndefinedFields);
return fieldValue;
}
}
@SuppressWarnings("rawtypes")
- public static ValueUpdate readSingleUpdate(TokenBuffer buffer, DataType expectedType, String action) {
+ public static ValueUpdate readSingleUpdate(TokenBuffer buffer, DataType expectedType, String action, boolean ignoreUndefinedFields) {
ValueUpdate update;
switch (action) {
case UPDATE_ASSIGN:
update = (buffer.currentToken() == JsonToken.VALUE_NULL)
? ValueUpdate.createClear()
- : ValueUpdate.createAssign(readSingleValue(buffer, expectedType));
+ : ValueUpdate.createAssign(readSingleValue(buffer, expectedType, ignoreUndefinedFields));
break;
// double is silly, but it's what is used internally anyway
case UPDATE_INCREMENT:
diff --git a/document/src/main/java/com/yahoo/document/json/readers/StructReader.java b/document/src/main/java/com/yahoo/document/json/readers/StructReader.java
index 54591134d4c..b9eaf0d8ec6 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/StructReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/StructReader.java
@@ -12,31 +12,31 @@ import static com.yahoo.document.json.readers.SingleValueReader.readSingleValue;
public class StructReader {
- public static void fillStruct(TokenBuffer buffer, StructuredFieldValue parent) {
+ public static void fillStruct(TokenBuffer buffer, StructuredFieldValue parent, boolean ignoreUndefinedFields) {
// do note the order of initializing initNesting and token is relevant for empty docs
int initNesting = buffer.nesting();
buffer.next();
while (buffer.nesting() >= initNesting) {
- Field f = getField(buffer, parent);
+ Field field = getField(buffer, parent, ignoreUndefinedFields);
try {
- // skip fields set to null
- if (buffer.currentToken() != JsonToken.VALUE_NULL) {
- FieldValue v = readSingleValue(buffer, f.getDataType());
- parent.setFieldValue(f, v);
+ if (field != null && buffer.currentToken() != JsonToken.VALUE_NULL) {
+ FieldValue v = readSingleValue(buffer, field.getDataType(), ignoreUndefinedFields);
+ parent.setFieldValue(field, v);
}
buffer.next();
} catch (IllegalArgumentException e) {
- throw new JsonReaderException(f, e);
+ throw new JsonReaderException(field, e);
}
}
}
- public static Field getField(TokenBuffer buffer, StructuredFieldValue parent) {
+ private static Field getField(TokenBuffer buffer, StructuredFieldValue parent, boolean ignoreUndefinedFields) {
Field field = parent.getField(buffer.currentName());
- if (field == null) {
+ if (field == null && ! ignoreUndefinedFields) {
throw new IllegalArgumentException("No field '" + buffer.currentName() + "' in the structure of type '" +
- parent.getDataType().getDataTypeName() + "', which has the fields:" + parent.getDataType().getFields());
+ parent.getDataType().getDataTypeName() +
+ "', which has the fields: " + parent.getDataType().getFields());
}
return field;
}
diff --git a/document/src/main/java/com/yahoo/document/json/readers/VespaJsonDocumentReader.java b/document/src/main/java/com/yahoo/document/json/readers/VespaJsonDocumentReader.java
index fb160a9bb44..7bc462ec73a 100644
--- a/document/src/main/java/com/yahoo/document/json/readers/VespaJsonDocumentReader.java
+++ b/document/src/main/java/com/yahoo/document/json/readers/VespaJsonDocumentReader.java
@@ -44,6 +44,12 @@ public class VespaJsonDocumentReader {
private static final String UPDATE_REMOVE = "remove";
private static final String UPDATE_ADD = "add";
+ private final boolean ignoreUndefinedFields;
+
+ public VespaJsonDocumentReader(boolean ignoreUndefinedFields) {
+ this.ignoreUndefinedFields = ignoreUndefinedFields;
+ }
+
public DocumentOperation createDocumentOperation(DocumentType documentType, DocumentParseInfo documentParseInfo) {
final DocumentOperation documentOperation;
try {
@@ -82,7 +88,7 @@ public class VespaJsonDocumentReader {
try {
if (buffer.isEmpty()) // no "fields" map
throw new IllegalArgumentException(put + " is missing a 'fields' map");
- populateComposite(buffer, put.getDocument());
+ populateComposite(buffer, put.getDocument(), ignoreUndefinedFields);
} catch (JsonReaderException e) {
throw JsonReaderException.addDocId(e, put.getId());
}
@@ -129,25 +135,25 @@ public class VespaJsonDocumentReader {
if (isTensorField(field)) {
fieldUpdate.addValueUpdate(createTensorRemoveUpdate(buffer, field));
} else {
- createRemoves(buffer, field, fieldUpdate);
+ createRemoves(buffer, field, fieldUpdate, ignoreUndefinedFields);
}
break;
case UPDATE_ADD:
if (isTensorField(field)) {
fieldUpdate.addValueUpdate(createTensorAddUpdate(buffer, field));
} else {
- createAdds(buffer, field, fieldUpdate);
+ createAdds(buffer, field, fieldUpdate, ignoreUndefinedFields);
}
break;
case UPDATE_MATCH:
- fieldUpdate.addValueUpdate(createMapUpdate(buffer, field));
+ fieldUpdate.addValueUpdate(createMapUpdate(buffer, field, ignoreUndefinedFields));
break;
case UPDATE_MODIFY:
fieldUpdate.addValueUpdate(createModifyUpdate(buffer, field));
break;
default:
String action = buffer.currentName();
- fieldUpdate.addValueUpdate(readSingleUpdate(buffer, field.getDataType(), action));
+ fieldUpdate.addValueUpdate(readSingleUpdate(buffer, field.getDataType(), action, ignoreUndefinedFields));
}
buffer.next();
}
@@ -183,14 +189,16 @@ public class VespaJsonDocumentReader {
private AssignFieldPathUpdate readAssignFieldPathUpdate(DocumentType documentType, String fieldPath, TokenBuffer buffer) {
AssignFieldPathUpdate fieldPathUpdate = new AssignFieldPathUpdate(documentType, fieldPath);
- FieldValue fv = SingleValueReader.readSingleValue(buffer, fieldPathUpdate.getFieldPath().getResultingDataType());
+ FieldValue fv = SingleValueReader.readSingleValue(buffer, fieldPathUpdate.getFieldPath().getResultingDataType(),
+ ignoreUndefinedFields);
fieldPathUpdate.setNewValue(fv);
return fieldPathUpdate;
}
private AddFieldPathUpdate readAddFieldPathUpdate(DocumentType documentType, String fieldPath, TokenBuffer buffer) {
AddFieldPathUpdate fieldPathUpdate = new AddFieldPathUpdate(documentType, fieldPath);
- FieldValue fv = SingleValueReader.readSingleValue(buffer, fieldPathUpdate.getFieldPath().getResultingDataType());
+ FieldValue fv = SingleValueReader.readSingleValue(buffer, fieldPathUpdate.getFieldPath().getResultingDataType(),
+ ignoreUndefinedFields);
fieldPathUpdate.setNewValues((Array) fv);
return fieldPathUpdate;
}
@@ -200,8 +208,8 @@ public class VespaJsonDocumentReader {
return new RemoveFieldPathUpdate(documentType, fieldPath);
}
- private AssignFieldPathUpdate readArithmeticFieldPathUpdate(
- DocumentType documentType, String fieldPath, TokenBuffer buffer, String fieldPathOperation) {
+ private AssignFieldPathUpdate readArithmeticFieldPathUpdate(DocumentType documentType, String fieldPath,
+ TokenBuffer buffer, String fieldPathOperation) {
AssignFieldPathUpdate fieldPathUpdate = new AssignFieldPathUpdate(documentType, fieldPath);
String arithmeticSign = SingleValueReader.UPDATE_OPERATION_TO_ARITHMETIC_SIGN.get(fieldPathOperation);
double value = Double.valueOf(buffer.currentText());
@@ -217,7 +225,7 @@ public class VespaJsonDocumentReader {
private static void verifyEndState(TokenBuffer buffer, JsonToken expectedFinalToken) {
Preconditions.checkState(buffer.currentToken() == expectedFinalToken,
- "Expected end of JSON struct (%s), got %s", expectedFinalToken, buffer.currentToken());
+ "Expected end of JSON struct (%s), got %s", expectedFinalToken, buffer.currentToken());
Preconditions.checkState(buffer.nesting() == 0, "Nesting not zero at end of operation");
Preconditions.checkState(buffer.next() == null, "Dangling data at end of operation");
Preconditions.checkState(buffer.size() == 0, "Dangling data at end of operation");
diff --git a/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java b/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
index 675ad502630..441f1fd28ea 100644
--- a/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
+++ b/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java
@@ -258,7 +258,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
smokeTestDoc(put.getDocument());
}
@@ -277,7 +277,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
smokeTestDoc(put.getDocument());
}
@@ -288,7 +288,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
assertEquals("id:unittest:smoke::whee", parseInfo.documentId.toString());
}
@@ -302,7 +302,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
Document doc = put.getDocument();
FieldValue f = doc.getFieldValue(doc.getField("skuggsjaa"));
assertSame(Struct.class, f.getClass());
@@ -316,7 +316,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentUpdate update = new DocumentUpdate(docType, parseInfo.documentId);
- new VespaJsonDocumentReader().readUpdate(parseInfo.fieldsBuffer, update);
+ new VespaJsonDocumentReader(false).readUpdate(parseInfo.fieldsBuffer, update);
return update;
}
@@ -505,7 +505,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
return put.getDocument();
}
@@ -684,7 +684,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
Document doc = put.getDocument();
FieldValue f = doc.getFieldValue(doc.getField("actualraw"));
assertSame(Raw.class, f.getClass());
@@ -701,7 +701,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
Document doc = put.getDocument();
FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt");
assertSame(MapFieldValue.class, f.getClass());
@@ -722,7 +722,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
Document doc = put.getDocument();
FieldValue f = doc.getFieldValue("actualMapStringToArrayOfInt");
assertSame(MapFieldValue.class, f.getClass());
@@ -987,7 +987,7 @@ public class JsonReaderTestCase {
}
@Test
- public void misspelledFieldTest() throws IOException{
+ public void nonExistingFieldCausesException() throws IOException{
JsonReader r = createReader(inputJson(
"{ 'put': 'id:unittest:smoke::whee',",
" 'fields': {",
@@ -996,8 +996,9 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
+
try {
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("No field 'smething' in the structure of type 'smoke'"));
@@ -1005,6 +1006,20 @@ public class JsonReaderTestCase {
}
@Test
+ public void nonExistingFieldCanBeIgnored() throws IOException{
+ JsonReader r = createReader(inputJson(
+ "{ 'put': 'id:unittest:smoke::whee',",
+ " 'fields': {",
+ " 'smething': 'smoketest',",
+ " 'nalle': 'bamse' }}"));
+ DocumentParseInfo parseInfo = r.parseDocument().get();
+ DocumentType docType = r.readDocumentType(parseInfo.documentId);
+ DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
+
+ new VespaJsonDocumentReader(true).readPut(parseInfo.fieldsBuffer, put);
+ }
+
+ @Test
public void feedWithBasicErrorTest() {
JsonReader r = createReader(inputJson("[",
" { 'put': 'id:test:smoke::0', 'fields': { 'something': 'foo' } },",
@@ -1029,7 +1044,7 @@ public class JsonReaderTestCase {
DocumentParseInfo parseInfo = r.parseDocument().get();
DocumentType docType = r.readDocumentType(parseInfo.documentId);
DocumentPut put = new DocumentPut(new Document(docType, parseInfo.documentId));
- new VespaJsonDocumentReader().readPut(parseInfo.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(parseInfo.fieldsBuffer, put);
smokeTestDoc(put.getDocument());
}
diff --git a/document/src/test/java/com/yahoo/document/json/JsonWriterTestCase.java b/document/src/test/java/com/yahoo/document/json/JsonWriterTestCase.java
index 92f28d8f219..e7368a691ab 100644
--- a/document/src/test/java/com/yahoo/document/json/JsonWriterTestCase.java
+++ b/document/src/test/java/com/yahoo/document/json/JsonWriterTestCase.java
@@ -349,7 +349,7 @@ public class JsonWriterTestCase {
DocumentParseInfo raw = r.parseDocument().get();
DocumentType docType = r.readDocumentType(raw.documentId);
DocumentPut put = new DocumentPut(new Document(docType, raw.documentId));
- new VespaJsonDocumentReader().readPut(raw.fieldsBuffer, put);
+ new VespaJsonDocumentReader(false).readPut(raw.fieldsBuffer, put);
return put.getDocument();
}
diff --git a/document/src/vespa/document/config/documentmanager.def b/document/src/vespa/document/config/documentmanager.def
index ec19ba8d802..0d0f3876f15 100644
--- a/document/src/vespa/document/config/documentmanager.def
+++ b/document/src/vespa/document/config/documentmanager.def
@@ -2,8 +2,8 @@
namespace=document.config
-## Whether to enable compression in this process.
-enablecompression bool default=false
+## Whether attempts to set an undefined field should be ignored rather than causing an error
+ignoreundefinedfields bool default=false
## Prefer "Vespa 8" format for the "position" type
usev8geopositions bool default=false
diff --git a/document/src/vespa/document/config/documenttypes.def b/document/src/vespa/document/config/documenttypes.def
index 202447295c3..0c135db7b0d 100644
--- a/document/src/vespa/document/config/documenttypes.def
+++ b/document/src/vespa/document/config/documenttypes.def
@@ -2,8 +2,8 @@
namespace=document.config
-## Whether to enable compression in this process.
-enablecompression bool default=false
+## Whether attempts to set an undefined field should be ignored rather than causing an error
+ignoreundefinedfields bool default=false
## Prefer "Vespa 8" format for the "position" type
usev8geopositions bool default=false
diff --git a/document/src/vespa/document/datatype/documenttype.cpp b/document/src/vespa/document/datatype/documenttype.cpp
index 21a4734af9b..0d38ce1f623 100644
--- a/document/src/vespa/document/datatype/documenttype.cpp
+++ b/document/src/vespa/document/datatype/documenttype.cpp
@@ -5,6 +5,7 @@
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
+#include <ostream>
LOG_SETUP(".document.datatype.document");
diff --git a/document/src/vespa/document/datatype/structdatatype.cpp b/document/src/vespa/document/datatype/structdatatype.cpp
index 6f0eff3b7ad..4d566ea1bfc 100644
--- a/document/src/vespa/document/datatype/structdatatype.cpp
+++ b/document/src/vespa/document/datatype/structdatatype.cpp
@@ -7,6 +7,7 @@
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <cassert>
+#include <ostream>
#include <vespa/log/log.h>
LOG_SETUP(".document.datatype.struct");
diff --git a/document/src/vespa/document/select/CMakeLists.txt b/document/src/vespa/document/select/CMakeLists.txt
index 7c5cf0747a7..11a62fbb9c8 100644
--- a/document/src/vespa/document/select/CMakeLists.txt
+++ b/document/src/vespa/document/select/CMakeLists.txt
@@ -46,3 +46,6 @@ vespa_add_library(document_select OBJECT
#TODO Remove once we have a recently new flex compiler. At least 2.5.38/39 or 2.6
set_source_files_properties(${FLEX_DocSelLexer_OUTPUTS} PROPERTIES COMPILE_FLAGS -Wno-register)
+if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ set_source_files_properties(${BISON_DocSelParser_OUTPUTS} PROPERTIES COMPILE_FLAGS -Wno-noexcept)
+endif()
diff --git a/documentapi-dependencies/pom.xml b/documentapi-dependencies/pom.xml
index 25552700528..cda469ab5f8 100644
--- a/documentapi-dependencies/pom.xml
+++ b/documentapi-dependencies/pom.xml
@@ -65,11 +65,6 @@
<artifactId>vespajlib</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
</dependencies>
</project>
diff --git a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java
index 3607f652a51..1c729008e2c 100755
--- a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java
+++ b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java
@@ -230,7 +230,6 @@ public class MessageBusVisitorSession implements VisitorSession {
@Override
public Sender createSender(ReplyHandler replyHandler, VisitorParameters visitorParameters) {
- messageBus.setMaxPendingCount(0);
SourceSessionParams sessionParams = createSourceSessionParams(visitorParameters);
return new MessageBusSender(messageBus.createSourceSession(replyHandler, sessionParams));
}
@@ -308,7 +307,7 @@ public class MessageBusVisitorSession implements VisitorSession {
private static final Logger log = Logger.getLogger(MessageBusVisitorSession.class.getName());
- private static AtomicLong sessionCounter = new AtomicLong(0);
+ private static final AtomicLong sessionCounter = new AtomicLong(0);
private static long getNextSessionId() {
return sessionCounter.incrementAndGet();
}
@@ -336,7 +335,7 @@ public class MessageBusVisitorSession implements VisitorSession {
private boolean done = false;
private boolean destroying = false; // For testing and sanity checking
private final Object completionMonitor = new Object();
- private Trace trace;
+ private final Trace trace;
/**
* We keep our own track of pending messages since the sender's pending
* count cannot be relied on in an async task execution context. This
diff --git a/documentapi/src/tests/policies/policies_test.cpp b/documentapi/src/tests/policies/policies_test.cpp
index dfa9cbb581e..19960d148df 100644
--- a/documentapi/src/tests/policies/policies_test.cpp
+++ b/documentapi/src/tests/policies/policies_test.cpp
@@ -746,8 +746,6 @@ void Test::testLoadBalancer() {
entries.push_back(IMirrorAPI::Spec("foo/1/default", "tcp/bar:2"));
entries.push_back(IMirrorAPI::Spec("foo/2/default", "tcp/bar:3"));
- const std::vector<LoadBalancer::NodeInfo>& nodeInfo = lb.getNodeInfo();
-
for (int i = 0; i < 99; i++) {
std::pair<string, int> recipient = lb.getRecipient(entries);
EXPECT_EQUAL((i % 3), recipient.second);
@@ -766,8 +764,8 @@ void Test::testLoadBalancer() {
lb.received(1, false);
}
- EXPECT_EQUAL(421, (int)(100 * nodeInfo[0].weight / nodeInfo[1].weight));
- EXPECT_EQUAL(421, (int)(100 * nodeInfo[2].weight / nodeInfo[1].weight));
+ EXPECT_EQUAL(421, (int)(100 * lb.getWeight(0) / lb.getWeight(1)));
+ EXPECT_EQUAL(421, (int)(100 * lb.getWeight(2) / lb.getWeight(1)));
EXPECT_EQUAL(0 , lb.getRecipient(entries).second);
EXPECT_EQUAL(0 , lb.getRecipient(entries).second);
diff --git a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.cpp b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.cpp
index 75a0e4d966c..d3ba72b54b5 100644
--- a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.cpp
+++ b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.cpp
@@ -5,12 +5,14 @@
namespace documentapi {
LoadBalancer::LoadBalancer(const string& cluster, const string& session)
- : _cluster(cluster),
+ : _mutex(),
+ _nodeInfo(),
+ _cluster(cluster),
_session(session),
_position(0)
{}
-LoadBalancer::~LoadBalancer() {}
+LoadBalancer::~LoadBalancer() = default;
uint32_t
LoadBalancer::getIndex(const string& name) const
@@ -20,9 +22,26 @@ LoadBalancer::getIndex(const string& name) const
return atoi(idx.c_str());
}
+string
+LoadBalancer::getLastSpec(size_t target) const {
+ lock_guard guard(_mutex);
+ return _nodeInfo[target].lastSpec;
+}
+
+double
+LoadBalancer::getWeight(size_t target) const {
+ lock_guard guard(_mutex);
+ return _nodeInfo[target].weight;
+}
+
std::pair<string, int>
-LoadBalancer::getRecipient(const slobrok::api::IMirrorAPI::SpecList& choices)
-{
+LoadBalancer::getRecipient(const slobrok::api::IMirrorAPI::SpecList& choices) {
+ lock_guard guard(_mutex);
+ return getRecipient(guard, choices);
+}
+
+std::pair<string, int>
+LoadBalancer::getRecipient(const lock_guard & guard, const slobrok::api::IMirrorAPI::SpecList& choices) {
std::pair<string, int> retVal("", -1);
if (choices.size() == 0) {
@@ -54,7 +73,7 @@ LoadBalancer::getRecipient(const slobrok::api::IMirrorAPI::SpecList& choices)
if (retVal.second == -1) {
_position -= weightSum;
- return getRecipient(choices);
+ return getRecipient(guard, choices);
} else {
_position += 1.0;
}
@@ -63,7 +82,7 @@ LoadBalancer::getRecipient(const slobrok::api::IMirrorAPI::SpecList& choices)
}
void
-LoadBalancer::normalizeWeights() {
+LoadBalancer::normalizeWeights(const lock_guard &) {
double lowest = -1.0;
for (uint32_t i = 0; i < _nodeInfo.size(); i++) {
@@ -88,10 +107,11 @@ LoadBalancer::normalizeWeights() {
void
LoadBalancer::received(uint32_t nodeIndex, bool busy) {
if (busy) {
+ lock_guard guard(_mutex);
NodeInfo& info = _nodeInfo[nodeIndex];
info.weight = info.weight - 0.01;
- normalizeWeights();
+ normalizeWeights(guard);
}
}
diff --git a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.h b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.h
index 6627fc57ef2..f401fc6fabe 100644
--- a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.h
+++ b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancer.h
@@ -3,33 +3,17 @@
#include <vespa/documentapi/common.h>
#include <vespa/slobrok/imirrorapi.h>
+#include <mutex>
namespace documentapi {
class LoadBalancer {
public:
- class NodeInfo {
- public:
- NodeInfo() noexcept : valid(false), sent(0), busy(0), weight(1.0) {};
-
- bool valid;
- uint32_t sent;
- uint32_t busy;
- double weight;
- string lastSpec;
- };
-
- std::vector<NodeInfo> _nodeInfo;
- string _cluster;
- string _session;
- double _position;
-
LoadBalancer(const string& cluster, const string& session);
~LoadBalancer();
- const std::vector<NodeInfo>& getNodeInfo() const { return _nodeInfo; }
-
- uint32_t getIndex(const string& name) const;
+ string getLastSpec(size_t target) const;
+ double getWeight(size_t target) const;
/**
Returns the spec and the node index of the node we should send to.
@@ -37,9 +21,28 @@ public:
*/
std::pair<string, int> getRecipient(const slobrok::api::IMirrorAPI::SpecList& choices);
- void normalizeWeights();
-
void received(uint32_t nodeIndex, bool busy);
+private:
+ using lock_guard = std::lock_guard<std::mutex>;
+ std::pair<string, int> getRecipient(const lock_guard & guard, const slobrok::api::IMirrorAPI::SpecList& choices);
+ void normalizeWeights(const lock_guard & guard);
+ uint32_t getIndex(const string& name) const;
+
+ class NodeInfo {
+ public:
+ NodeInfo() noexcept : weight(1.0), sent(0), busy(0), valid(false), lastSpec() {}
+
+ double weight;
+ uint32_t sent;
+ uint32_t busy;
+ bool valid;
+ string lastSpec;
+ };
+ mutable std::mutex _mutex;
+ std::vector<NodeInfo> _nodeInfo;
+ string _cluster;
+ string _session;
+ double _position;
};
}
diff --git a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancerpolicy.cpp b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancerpolicy.cpp
index 473d04ea7d9..160ee55adae 100644
--- a/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancerpolicy.cpp
+++ b/documentapi/src/vespa/documentapi/messagebus/policies/loadbalancerpolicy.cpp
@@ -60,7 +60,7 @@ LoadBalancerPolicy::merge(mbus::RoutingContext& context) {
bool busy = false;
for (uint32_t i = 0; i < reply->getNumErrors(); i++) {
if (reply->getError(i).getCode() == mbus::ErrorCode::SESSION_BUSY) {
- string lastSpec = _loadBalancer->getNodeInfo()[target].lastSpec;
+ string lastSpec = _loadBalancer->getLastSpec(target);
if (reply->getError(i).getMessage().find(lastSpec) == string::npos) {
LOG(debug, "Received busy with message %s, doesn't contain target %s so not updating weight.", reply->getError(i).getMessage().c_str(), lastSpec.c_str());
diff --git a/eval/src/vespa/eval/eval/interpreted_function.h b/eval/src/vespa/eval/eval/interpreted_function.h
index 98699c77842..99fb9a02082 100644
--- a/eval/src/vespa/eval/eval/interpreted_function.h
+++ b/eval/src/vespa/eval/eval/interpreted_function.h
@@ -14,7 +14,7 @@ namespace nodes { struct Node; }
struct TensorFunction;
class TensorSpec;
struct CTFMetaData;
-class ValueBuilderFactory;
+struct ValueBuilderFactory;
/**
* A Function that has been prepared for execution. This will
diff --git a/eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h b/eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h
index 3cdbe2f68a1..1183c2709c1 100644
--- a/eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h
+++ b/eval/src/vespa/eval/eval/value_cache/constant_tensor_loader.h
@@ -7,7 +7,7 @@
namespace vespalib::eval {
-class ValueBuilderFactory;
+struct ValueBuilderFactory;
/**
* A ConstantValueFactory that will load constant tensor values from
diff --git a/eval/src/vespa/eval/eval/value_codec.h b/eval/src/vespa/eval/eval/value_codec.h
index 80d955853c4..cda01cb3dcc 100644
--- a/eval/src/vespa/eval/eval/value_codec.h
+++ b/eval/src/vespa/eval/eval/value_codec.h
@@ -13,7 +13,7 @@ namespace vespalib::eval {
VESPA_DEFINE_EXCEPTION(DecodeValueException, Exception);
-class ValueBuilderFactory;
+struct ValueBuilderFactory;
/**
* encode a value (which must support the new APIs) to binary format
diff --git a/fat-model-dependencies/pom.xml b/fat-model-dependencies/pom.xml
index 180a39778a8..f3312bd5d89 100644
--- a/fat-model-dependencies/pom.xml
+++ b/fat-model-dependencies/pom.xml
@@ -91,11 +91,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>container-documentapi</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/fbench/src/fbench/fbench.cpp b/fbench/src/fbench/fbench.cpp
index c69d4f5af18..8c3ea7b1eed 100644
--- a/fbench/src/fbench/fbench.cpp
+++ b/fbench/src/fbench/fbench.cpp
@@ -372,13 +372,18 @@ FBench::Main(int argc, char *argv[])
bool optError;
optError = false;
+ std::string content_type = "Content-type:application/json";
while((opt = getopt(argc, argv, "H:A:T:C:K:Da:n:c:l:i:s:q:o:r:m:p:kdxyzP")) != -1) {
switch(opt) {
case 'A':
authority = optarg;
break;
case 'H':
- extraHeaders += std::string(optarg) + "\r\n";
+ if (strncmp(optarg, "Content-type:", 13) == 0) {
+ content_type = optarg;
+ } else {
+ extraHeaders += std::string(optarg) + "\r\n";
+ }
if (strncmp(optarg, "Host:", 5) == 0) {
fprintf(stderr, "Do not override 'Host:' header, use -A option instead\n");
return -1;
@@ -458,6 +463,9 @@ FBench::Main(int argc, char *argv[])
break;
}
}
+ if (usePostMode) {
+ extraHeaders += content_type + "\r\n";
+ }
if ( argc < (optind + 2) || optError) {
Usage();
@@ -477,8 +485,7 @@ FBench::Main(int argc, char *argv[])
short hosts = args / 2;
- for (int i=0; i<hosts; ++i)
- {
+ for (int i=0; i<hosts; ++i) {
_hostnames.push_back(std::string(argv[optind+2*i]));
int port = atoi(argv[optind+2*i+1]);
if (port == 0) {
@@ -490,9 +497,9 @@ FBench::Main(int argc, char *argv[])
// Find offset for each client if shared query file
_queryfileOffset.push_back(0);
+ char filename[1024];
if (singleQueryFile) {
// Open file to find offsets, with pattern as if client 0
- char filename[1024];
snprintf(filename, 1024, queryFilePattern, 0);
queryFilePattern = filename;
FileReader reader;
diff --git a/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/FileAcquirerImpl.java b/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/FileAcquirerImpl.java
index c85a24db9bb..122027d706b 100644
--- a/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/FileAcquirerImpl.java
+++ b/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/FileAcquirerImpl.java
@@ -5,6 +5,8 @@ import com.yahoo.cloud.config.filedistribution.FiledistributorrpcConfig;
import com.yahoo.config.subscription.ConfigSubscriber;
import com.yahoo.config.FileReference;
import com.yahoo.jrt.*;
+
+import java.time.Duration;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -56,7 +58,7 @@ class FileAcquirerImpl implements FileAcquirer {
target = supervisor.connect(spec);
// ping to check if connection is working
Request request = new Request("frt.rpc.ping");
- target.invokeSync(request, 5.0);
+ target.invokeSync(request, Duration.ofSeconds(5));
if (request.isError()) {
logWarning();
target.close();
diff --git a/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java b/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java
index b1ef519d901..e8c08edb621 100644
--- a/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java
+++ b/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.filedistribution.fileacquirer;
+import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
@@ -10,16 +11,16 @@ import java.util.concurrent.TimeUnit;
class Timer {
private final long endTime;
- private long timeLeft() {
- return endTime - System.currentTimeMillis();
+ private Duration timeLeft() {
+ return Duration.ofNanos(endTime - System.nanoTime());
}
public Timer(long timeout, TimeUnit timeUnit) {
- endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
+ endTime = System.nanoTime() + timeUnit.toNanos(timeout);
}
public long timeLeft(TimeUnit timeUnit) {
- long remaining = timeUnit.convert(timeLeft(), TimeUnit.MILLISECONDS);
+ long remaining = timeUnit.convert(timeLeft().toMillis(), TimeUnit.MILLISECONDS);
if (remaining > 0)
return remaining;
@@ -28,6 +29,6 @@ class Timer {
}
public boolean isTimeLeft() {
- return timeLeft() > 0;
+ return ! timeLeft().isNegative();
}
}
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/EmptyFileReferenceData.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/EmptyFileReferenceData.java
index 8b3bc32ff71..ea8461b42f3 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/EmptyFileReferenceData.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/EmptyFileReferenceData.java
@@ -12,7 +12,7 @@ public class EmptyFileReferenceData extends FileReferenceData {
private int contentRead = 0;
private EmptyFileReferenceData(FileReference fileReference, String filename, Type type, byte[] content, long xxhash) {
- super(fileReference, filename, type);
+ super(fileReference, filename, type, CompressionType.gzip);
this.content = content;
this.xxhash = xxhash;
}
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileDownloader.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileDownloader.java
index 5941ed536a8..63ae8faacfe 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileDownloader.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileDownloader.java
@@ -6,11 +6,11 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.vespa.config.Connection;
import com.yahoo.vespa.config.ConnectionPool;
import com.yahoo.vespa.defaults.Defaults;
-
import java.io.File;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -19,6 +19,8 @@ import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+
/**
* Handles downloads of files (file references only for now)
*
@@ -29,6 +31,7 @@ public class FileDownloader implements AutoCloseable {
private static final Logger log = Logger.getLogger(FileDownloader.class.getName());
private static final Duration defaultSleepBetweenRetries = Duration.ofSeconds(5);
public static final File defaultDownloadDirectory = new File(Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution"));
+ private static final boolean forceDownload = Boolean.parseBoolean(System.getenv("VESPA_CONFIG_PROXY_FORCE_DOWNLOAD_OF_FILE_REFERENCES"));
private final ConnectionPool connectionPool;
private final Supervisor supervisor;
@@ -37,19 +40,20 @@ public class FileDownloader implements AutoCloseable {
private final FileReferenceDownloader fileReferenceDownloader;
private final Downloads downloads = new Downloads();
- public FileDownloader(ConnectionPool connectionPool, Supervisor supervisor, Duration timeout) {
- this(connectionPool, supervisor, defaultDownloadDirectory, timeout, defaultSleepBetweenRetries);
+ public FileDownloader(ConnectionPool connectionPool, Supervisor supervisor, Duration timeout, Set<CompressionType> acceptedCompressionTypes) {
+ this(connectionPool, supervisor, defaultDownloadDirectory, timeout, defaultSleepBetweenRetries, acceptedCompressionTypes);
}
- public FileDownloader(ConnectionPool connectionPool, Supervisor supervisor, File downloadDirectory, Duration timeout) {
- this(connectionPool, supervisor, downloadDirectory, timeout, defaultSleepBetweenRetries);
+ public FileDownloader(ConnectionPool connectionPool, Supervisor supervisor, File downloadDirectory, Duration timeout, Set<CompressionType> acceptedCompressionTypes) {
+ this(connectionPool, supervisor, downloadDirectory, timeout, defaultSleepBetweenRetries, acceptedCompressionTypes);
}
public FileDownloader(ConnectionPool connectionPool,
Supervisor supervisor,
File downloadDirectory,
Duration timeout,
- Duration sleepBetweenRetries) {
+ Duration sleepBetweenRetries,
+ Set<CompressionType> acceptedCompressionTypes) {
this.connectionPool = connectionPool;
this.supervisor = supervisor;
this.downloadDirectory = downloadDirectory;
@@ -60,7 +64,10 @@ public class FileDownloader implements AutoCloseable {
downloads,
timeout,
sleepBetweenRetries,
- downloadDirectory);
+ downloadDirectory,
+ acceptedCompressionTypes);
+ if (forceDownload)
+ log.log(Level.INFO, "Force download of file references (download even if file reference exists on disk)");
}
public Optional<File> getFile(FileReferenceDownload fileReferenceDownload) {
@@ -99,6 +106,8 @@ public class FileDownloader implements AutoCloseable {
}
private static Optional<File> getFileFromFileSystem(FileReference fileReference, File downloadDirectory) {
+ if (forceDownload) return Optional.empty();
+
File[] files = new File(downloadDirectory, fileReference.value()).listFiles();
if (files == null) return Optional.empty();
if (files.length == 0) return Optional.empty();
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReceiver.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReceiver.java
index 81a8944149c..a285fbaafe2 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReceiver.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReceiver.java
@@ -23,6 +23,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static com.yahoo.vespa.filedistribution.FileReferenceData.Type;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
/**
* When asking for a file reference, this handles RPC callbacks from config server with file data and metadata.
@@ -48,7 +49,8 @@ public class FileReceiver {
private final StreamingXXHash64 hasher;
private final int sessionId;
private final FileReference reference;
- private final FileReferenceData.Type fileType;
+ private final Type fileType;
+ private final CompressionType compressionType;
private final String fileName;
private final long fileSize;
private long currentFileSize;
@@ -58,13 +60,18 @@ public class FileReceiver {
private final File tmpDir;
private final File inprogressFile;
- Session(File downloadDirectory, int sessionId, FileReference reference,
- FileReferenceData.Type fileType, String fileName, long fileSize)
- {
+ Session(File downloadDirectory,
+ int sessionId,
+ FileReference reference,
+ Type fileType,
+ FileReferenceData.CompressionType compressionType,
+ String fileName,
+ long fileSize) {
this.hasher = XXHashFactory.fastestInstance().newStreamingHash64(0);
this.sessionId = sessionId;
this.reference = reference;
this.fileType = fileType;
+ this.compressionType = compressionType;
this.fileName = fileName;
this.fileSize = fileSize;
currentFileSize = 0;
@@ -122,7 +129,8 @@ public class FileReceiver {
moveFileToDestination(inprogressFile, file);
} else {
decompressedDir = Files.createTempDirectory(tmpDir.toPath(), "archive").toFile();
- new FileReferenceCompressor(fileType).decompress(inprogressFile, decompressedDir);
+ log.log(Level.FINE, () -> "compression type to use=" + compressionType);
+ new FileReferenceCompressor(fileType, compressionType).decompress(inprogressFile, decompressedDir);
moveFileToDestination(decompressedDir, fileReferenceDir);
}
} catch (IOException e) {
@@ -161,11 +169,12 @@ public class FileReceiver {
// receiveFile after getting a serveFile method call). handler needs to implement receiveFile* methods
private List<Method> receiveFileMethod() {
List<Method> methods = new ArrayList<>();
- methods.add(new Method(RECEIVE_META_METHOD, "sssl", "ii", this::receiveFileMeta)
+ methods.add(new Method(RECEIVE_META_METHOD, "sssl*", "ii", this::receiveFileMeta)
.paramDesc(0, "filereference", "file reference to download")
.paramDesc(1, "filename", "filename")
.paramDesc(2, "type", "'file' or 'compressed'")
.paramDesc(3, "filelength", "length in bytes of file")
+ .paramDesc(3, "compressionType", "compression type: gzip, lz4, zstd")
.returnDesc(0, "ret", "0 if success, 1 otherwise")
.returnDesc(1, "session-id", "Session id to be used for this transfer"));
methods.add(new Method(RECEIVE_PART_METHOD, "siix", "i", this::receiveFilePart)
@@ -220,8 +229,11 @@ public class FileReceiver {
log.log(Level.FINE, () -> "Received method call '" + req.methodName() + "' with parameters : " + req.parameters());
FileReference reference = new FileReference(req.parameters().get(0).asString());
String fileName = req.parameters().get(1).asString();
- String type = req.parameters().get(2).asString();
+ Type type = FileReferenceData.Type.valueOf(req.parameters().get(2).asString());
long fileSize = req.parameters().get(3).asInt64();
+ CompressionType compressionType = (req.parameters().size() > 4)
+ ? CompressionType.valueOf(req.parameters().get(4).asString())
+ : CompressionType.gzip; // fallback/legacy compression type
int sessionId = nextSessionId.getAndIncrement();
int retval = 0;
synchronized (sessions) {
@@ -231,7 +243,7 @@ public class FileReceiver {
} else {
try {
sessions.put(sessionId, new Session(downloadDirectory, sessionId, reference,
- FileReferenceData.Type.valueOf(type),fileName, fileSize));
+ type, compressionType, fileName, fileSize));
} catch (Exception e) {
retval = 1;
}
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceCompressor.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceCompressor.java
index c36bcd22606..efb845bafe7 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceCompressor.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceCompressor.java
@@ -2,6 +2,8 @@
package com.yahoo.vespa.filedistribution;
import com.google.common.io.ByteStreams;
+import net.jpountz.lz4.LZ4BlockInputStream;
+import net.jpountz.lz4.LZ4BlockOutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
@@ -35,9 +37,11 @@ public class FileReferenceCompressor {
private static final int recurseDepth = 100;
private final FileReferenceData.Type type;
+ private final FileReferenceData.CompressionType compressionType;
- public FileReferenceCompressor(FileReferenceData.Type type) {
+ public FileReferenceCompressor(FileReferenceData.Type type, FileReferenceData.CompressionType compressionType) {
this.type = Objects.requireNonNull(type, "Type cannot be null");
+ this.compressionType = Objects.requireNonNull(compressionType, "Compression type cannot be null");
}
public File compress(File baseDir, List<File> inputFiles, File outputFile) throws IOException {
@@ -116,7 +120,15 @@ public class FileReferenceCompressor {
private OutputStream compressedOutputStream(File outputFile) throws IOException {
switch (type) {
case compressed:
- return new GZIPOutputStream(new FileOutputStream(outputFile));
+ log.log(Level.FINE, () -> "Compressing with compression type " + compressionType);
+ switch (compressionType) {
+ case gzip:
+ return new GZIPOutputStream(new FileOutputStream(outputFile));
+ case lz4:
+ return new LZ4BlockOutputStream(new FileOutputStream(outputFile));
+ default:
+ throw new RuntimeException("Unknown compression type " + compressionType);
+ }
case file:
return new FileOutputStream(outputFile);
default:
@@ -127,7 +139,15 @@ public class FileReferenceCompressor {
private InputStream decompressedInputStream(File inputFile) throws IOException {
switch (type) {
case compressed:
- return new GZIPInputStream(new FileInputStream(inputFile));
+ log.log(Level.FINE, () -> "Decompressing with compression type " + compressionType);
+ switch (compressionType) {
+ case gzip:
+ return new GZIPInputStream(new FileInputStream(inputFile));
+ case lz4:
+ return new LZ4BlockInputStream(new FileInputStream(inputFile));
+ default:
+ throw new RuntimeException("Unknown compression type " + compressionType);
+ }
case file:
return new FileInputStream(inputFile);
default:
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceData.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceData.java
index 03f8d184f94..3f83cbea506 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceData.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceData.java
@@ -13,15 +13,18 @@ import java.nio.ByteBuffer;
public abstract class FileReferenceData {
public enum Type { file, compressed }
+ public enum CompressionType { gzip, lz4, zstd }
private final FileReference fileReference;
private final String filename;
private final Type type;
+ private final CompressionType compressionType;
- public FileReferenceData(FileReference fileReference, String filename, Type type) {
+ public FileReferenceData(FileReference fileReference, String filename, Type type, CompressionType compressionType) {
this.fileReference = fileReference;
this.filename = filename;
this.type = type;
+ this.compressionType = compressionType;
}
public FileReference fileReference() {return fileReference;}
@@ -30,6 +33,8 @@ public abstract class FileReferenceData {
public Type type() {return type;}
+ public CompressionType compressionType() { return compressionType;}
+
public ByteBuffer content() {
ByteBuffer bb = ByteBuffer.allocate((int)size());
while (bb.remaining() > 0) {
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownload.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownload.java
index 8d6f428eaef..f3a8cf9299d 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownload.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownload.java
@@ -18,7 +18,7 @@ public class FileReferenceDownload {
private final boolean downloadFromOtherSourceIfNotFound;
private final String client;
- public FileReferenceDownload(FileReference fileReference, String client) {
+ public FileReferenceDownload(FileReference fileReference, String client) {
this(fileReference, client, true);
}
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownloader.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownloader.java
index 03448b5fa4a..f6ebfcc416c 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownloader.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/FileReferenceDownloader.java
@@ -5,14 +5,16 @@ import com.yahoo.concurrent.DaemonThreadFactory;
import com.yahoo.config.FileReference;
import com.yahoo.jrt.Int32Value;
import com.yahoo.jrt.Request;
+import com.yahoo.jrt.StringArray;
import com.yahoo.jrt.StringValue;
import com.yahoo.vespa.config.Connection;
import com.yahoo.vespa.config.ConnectionPool;
-
import java.io.File;
import java.time.Duration;
import java.time.Instant;
+import java.util.Objects;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -20,8 +22,10 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+
/**
- * Downloads file reference using rpc requests to config server and keeps track of files being downloaded
+ * Downloads file reference from config server and keeps track of files being downloaded
*
* @author hmusum
*/
@@ -38,12 +42,14 @@ public class FileReferenceDownloader {
private final Duration sleepBetweenRetries;
private final Duration rpcTimeout;
private final File downloadDirectory;
+ private final Set<CompressionType> acceptedCompressionTypes;
FileReferenceDownloader(ConnectionPool connectionPool,
Downloads downloads,
Duration timeout,
Duration sleepBetweenRetries,
- File downloadDirectory) {
+ File downloadDirectory,
+ Set<CompressionType> acceptedCompressionTypes) {
this.connectionPool = connectionPool;
this.downloads = downloads;
this.downloadTimeout = timeout;
@@ -51,6 +57,7 @@ public class FileReferenceDownloader {
this.downloadDirectory = downloadDirectory;
String timeoutString = System.getenv("VESPA_CONFIGPROXY_FILEDOWNLOAD_RPC_TIMEOUT");
this.rpcTimeout = Duration.ofSeconds(timeoutString == null ? 30 : Integer.parseInt(timeoutString));
+ this.acceptedCompressionTypes = requireNonEmpty(acceptedCompressionTypes);
}
private void waitUntilDownloadStarted(FileReferenceDownload fileReferenceDownload) {
@@ -106,17 +113,18 @@ public class FileReferenceDownloader {
private boolean startDownloadRpc(FileReferenceDownload fileReferenceDownload, int retryCount, Connection connection) {
Request request = createRequest(fileReferenceDownload);
Duration rpcTimeout = rpcTimeout(retryCount);
- connection.invokeSync(request, rpcTimeout.getSeconds());
+ connection.invokeSync(request, rpcTimeout);
Level logLevel = (retryCount > 3 ? Level.INFO : Level.FINE);
FileReference fileReference = fileReferenceDownload.fileReference();
if (validateResponse(request)) {
log.log(Level.FINE, () -> "Request callback, OK. Req: " + request + "\nSpec: " + connection);
- if (request.returnValues().get(0).asInt32() == 0) {
+ int errorCode = request.returnValues().get(0).asInt32();
+ if (errorCode == 0) {
log.log(Level.FINE, () -> "Found " + fileReference + " available at " + connection.getAddress());
return true;
} else {
- log.log(logLevel, fileReference + " not found at " + connection.getAddress());
+ log.log(logLevel, fileReference + " not found or timed out (error code " + errorCode + ") at " + connection.getAddress());
return false;
}
} else {
@@ -131,6 +139,9 @@ public class FileReferenceDownloader {
Request request = new Request("filedistribution.serveFile");
request.parameters().add(new StringValue(fileReferenceDownload.fileReference().value()));
request.parameters().add(new Int32Value(fileReferenceDownload.downloadFromOtherSourceIfNotFound() ? 0 : 1));
+ String[] temp = new String[acceptedCompressionTypes.size()];
+ acceptedCompressionTypes.stream().map(Enum::name).toList().toArray(temp);
+ request.parameters().add(new StringArray(temp));
return request;
}
@@ -159,4 +170,9 @@ public class FileReferenceDownloader {
}
}
+ private static Set<CompressionType> requireNonEmpty(Set<CompressionType> s) {
+ if (Objects.requireNonNull(s).isEmpty()) throw new IllegalArgumentException("set must be non-empty");
+ return s;
+ }
+
}
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyFileReferenceData.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyFileReferenceData.java
index 10de9c072b9..c8fbb639b35 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyFileReferenceData.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyFileReferenceData.java
@@ -17,8 +17,8 @@ public class LazyFileReferenceData extends FileReferenceData {
private final ReadableByteChannel channel;
private final StreamingXXHash64 hasher;
- public LazyFileReferenceData(FileReference fileReference, String filename, Type type, File file) throws IOException {
- super(fileReference, filename, type);
+ public LazyFileReferenceData(FileReference fileReference, String filename, Type type, File file, CompressionType compressionType) throws IOException {
+ super(fileReference, filename, type, compressionType);
this.file = file;
channel = Files.newByteChannel(file.toPath());
this.hasher = XXHashFactory.fastestInstance().newStreamingHash64(0);
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyTemporaryStorageFileReferenceData.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyTemporaryStorageFileReferenceData.java
index 974d5ff1489..a69370b28ff 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyTemporaryStorageFileReferenceData.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/LazyTemporaryStorageFileReferenceData.java
@@ -12,8 +12,8 @@ import java.nio.file.Files;
*/
public class LazyTemporaryStorageFileReferenceData extends LazyFileReferenceData {
- public LazyTemporaryStorageFileReferenceData(FileReference fileReference, String filename, Type type, File file) throws IOException {
- super(fileReference, filename, type, file);
+ public LazyTemporaryStorageFileReferenceData(FileReference fileReference, String filename, Type type, File file, CompressionType compressionType) throws IOException {
+ super(fileReference, filename, type, file, compressionType);
}
public void close() {
diff --git a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/RpcTester.java b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/RpcTester.java
index f3b166c60fe..571c1f3a81f 100644
--- a/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/RpcTester.java
+++ b/filedistribution/src/main/java/com/yahoo/vespa/filedistribution/RpcTester.java
@@ -13,6 +13,8 @@ import com.yahoo.jrt.StringValue;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.Transport;
+
+import java.time.Duration;
import java.util.logging.Level;
import net.jpountz.xxhash.XXHash64;
import net.jpountz.xxhash.XXHashFactory;
@@ -91,7 +93,7 @@ public class RpcTester {
fileBlob.parameters().add(new Int32Value(0));
fileBlob.parameters().add(new StringValue("OK"));
log.log(Level.INFO, "Doing invokeSync");
- target.invokeSync(fileBlob, 5);
+ target.invokeSync(fileBlob, Duration.ofSeconds(5));
log.log(Level.INFO, "Done with invokeSync");
}
}
diff --git a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java
index 637fbbbd0a7..ffef06e6367 100644
--- a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java
+++ b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java
@@ -17,7 +17,6 @@ import net.jpountz.xxhash.XXHashFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -26,12 +25,14 @@ import java.nio.file.Path;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static com.yahoo.jrt.ErrorCode.CONNECTION;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.compressed;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -40,6 +41,7 @@ import static org.junit.Assert.fail;
public class FileDownloaderTest {
private static final Duration sleepBetweenRetries = Duration.ofMillis(10);
+ private static final Set<FileReferenceData.CompressionType> acceptedCompressionTypes = Set.of(gzip);
private MockConnection connection;
private FileDownloader fileDownloader;
@@ -52,7 +54,7 @@ public class FileDownloaderTest {
downloadDir = Files.createTempDirectory("filedistribution").toFile();
connection = new MockConnection();
supervisor = new Supervisor(new Transport()).setDropEmptyBuffers(true);
- fileDownloader = new FileDownloader(connection, supervisor, downloadDir, Duration.ofSeconds(1), sleepBetweenRetries);
+ fileDownloader = createDownloader(connection, Duration.ofSeconds(1));
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
@@ -148,7 +150,7 @@ public class FileDownloaderTest {
File barFile = new File(subdir, "really-long-filename-over-100-bytes-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
IOUtils.writeFile(barFile, "bar", false);
- File tarFile = new FileReferenceCompressor(compressed).compress(tempPath.toFile(), Arrays.asList(fooFile, barFile), new File(tempPath.toFile(), filename));
+ File tarFile = new FileReferenceCompressor(compressed, gzip).compress(tempPath.toFile(), Arrays.asList(fooFile, barFile), new File(tempPath.toFile(), filename));
byte[] tarredContent = IOUtils.readFileBytes(tarFile);
receiveFile(fileReference, filename, compressed, tarredContent);
Optional<File> downloadedFile = getFile(fileReference);
@@ -166,7 +168,7 @@ public class FileDownloaderTest {
@Test
public void getFileWhenConnectionError() throws IOException {
- fileDownloader = new FileDownloader(connection, supervisor, downloadDir, Duration.ofSeconds(2), sleepBetweenRetries);
+ fileDownloader = createDownloader(connection, Duration.ofSeconds(2));
File downloadDir = fileDownloader.downloadDirectory();
int timesToFail = 2;
@@ -200,7 +202,7 @@ public class FileDownloaderTest {
public void getFileWhenDownloadInProgress() throws IOException, ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(2);
String filename = "abc.jar";
- fileDownloader = new FileDownloader(connection, supervisor, downloadDir, Duration.ofSeconds(3), sleepBetweenRetries);
+ fileDownloader = createDownloader(connection, Duration.ofSeconds(3));
File downloadDir = fileDownloader.downloadDirectory();
// Delay response so that we can make a second request while downloading the file from the first request
@@ -240,7 +242,7 @@ public class FileDownloaderTest {
Duration timeout = Duration.ofMillis(200);
MockConnection connectionPool = new MockConnection();
connectionPool.setResponseHandler(new MockConnection.WaitResponseHandler(timeout.plus(Duration.ofMillis(1000))));
- FileDownloader fileDownloader = new FileDownloader(connectionPool, supervisor, downloadDir, timeout, sleepBetweenRetries);
+ FileDownloader fileDownloader = createDownloader(connectionPool, timeout);
FileReference xyzzy = new FileReference("xyzzy");
// Should download since we do not have the file on disk
fileDownloader.downloadIfNeeded(new FileReferenceDownload(xyzzy, "test"));
@@ -263,6 +265,16 @@ public class FileDownloaderTest {
assertEquals("content", IOUtils.readFile(downloadedFile));
}
+ @Test
+ public void testCompressionTypes() {
+ try {
+ createDownloader(connection, Duration.ofSeconds(1), Set.of());
+ fail("expected to fail when set is empty");
+ } catch (IllegalArgumentException e) {
+ // ignore
+ }
+ }
+
private void writeFileReference(File dir, String fileReferenceString, String fileName) throws IOException {
File fileReferenceDir = new File(dir, fileReferenceString);
fileReferenceDir.mkdir();
@@ -291,7 +303,7 @@ public class FileDownloaderTest {
FileReferenceData.Type type, byte[] content) {
XXHash64 hasher = XXHashFactory.fastestInstance().hash64();
FileReceiver.Session session =
- new FileReceiver.Session(downloadDir, 1, fileReference, type, filename, content.length);
+ new FileReceiver.Session(downloadDir, 1, fileReference, type, gzip, filename, content.length);
session.addPart(0, content);
File file = session.close(hasher.hash(ByteBuffer.wrap(content), 0));
fileDownloader.downloads().completedDownloading(fileReference, file);
@@ -301,6 +313,14 @@ public class FileDownloaderTest {
return fileDownloader.getFile(new FileReferenceDownload(fileReference, "test"));
}
+ private FileDownloader createDownloader(MockConnection connection, Duration timeout) {
+ return createDownloader(connection, timeout, acceptedCompressionTypes);
+ }
+
+ private FileDownloader createDownloader(MockConnection connection, Duration timeout, Set<FileReferenceData.CompressionType> acceptedCompressionTypes) {
+ return new FileDownloader(connection, supervisor, downloadDir, timeout, sleepBetweenRetries, acceptedCompressionTypes);
+ }
+
private static class MockConnection implements ConnectionPool, com.yahoo.vespa.config.Connection {
private ResponseHandler responseHandler;
@@ -314,12 +334,12 @@ public class FileDownloaderTest {
}
@Override
- public void invokeAsync(Request request, double jrtTimeout, RequestWaiter requestWaiter) {
+ public void invokeAsync(Request request, Duration jrtTimeout, RequestWaiter requestWaiter) {
responseHandler.request(request);
}
@Override
- public void invokeSync(Request request, double jrtTimeout) {
+ public void invokeSync(Request request, Duration jrtTimeout) {
responseHandler.request(request);
}
diff --git a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReceiverTest.java b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReceiverTest.java
index 5c15f945ae3..84e7a07340e 100644
--- a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReceiverTest.java
+++ b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReceiverTest.java
@@ -16,7 +16,11 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.lz4;
import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.compressed;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.file;
import static org.junit.Assert.assertEquals;
public class FileReceiverTest {
@@ -58,18 +62,25 @@ public class FileReceiverTest {
writerB.close();
File tempFile = temporaryFolder.newFile();
- File file = new FileReferenceCompressor(compressed).compress(dirWithFiles, tempFile);
- transferCompressedData(new FileReference("ref"), "a", IOUtils.readFileBytes(file));
+ File file = new FileReferenceCompressor(compressed, gzip).compress(dirWithFiles, tempFile);
+ transferCompressedData(gzip, new FileReference("ref"), "a", IOUtils.readFileBytes(file));
File downloadDir = new File(root, "ref");
assertEquals("1", IOUtils.readFile(new File(downloadDir, "a")));
assertEquals("2", IOUtils.readFile(new File(downloadDir, "b")));
+
+ tempFile = temporaryFolder.newFile();
+ FileReferenceCompressor compressor = new FileReferenceCompressor(compressed, lz4);
+ file = compressor.compress(dirWithFiles, tempFile);
+ transferCompressedData(lz4, new FileReference("ref"), "a", IOUtils.readFileBytes(file));
+ downloadDir = new File(root, "ref");
+ assertEquals("1", IOUtils.readFile(new File(downloadDir, "a")));
+ assertEquals("2", IOUtils.readFile(new File(downloadDir, "b")));
}
private void transferPartsAndAssert(FileReference ref, String fileName, String all, int numParts) throws IOException {
byte [] allContent = Utf8.toBytes(all);
- FileReceiver.Session session = new FileReceiver.Session(root, 1, ref,
- FileReferenceData.Type.file, fileName, allContent.length);
+ FileReceiver.Session session = new FileReceiver.Session(root, 1, ref, file, gzip, fileName, allContent.length);
int partSize = (allContent.length+(numParts-1))/numParts;
ByteBuffer bb = ByteBuffer.wrap(allContent);
for (int i = 0, pos = 0; i < numParts; i++) {
@@ -87,8 +98,8 @@ public class FileReceiverTest {
assertEquals(all, Utf8.toString(allReadBytes));
}
- private void transferCompressedData(FileReference ref, String fileName, byte[] data) {
- FileReceiver.Session session = new FileReceiver.Session(root, 1, ref, compressed, fileName, data.length);
+ private void transferCompressedData(CompressionType compressionType, FileReference ref, String fileName, byte[] data) {
+ FileReceiver.Session session = new FileReceiver.Session(root, 1, ref, compressed, compressionType, fileName, data.length);
session.addPart(0, data);
session.close(hasher.hash(ByteBuffer.wrap(data), 0));
}
diff --git a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReferenceDataTest.java b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReferenceDataTest.java
index 66b731f204b..eda93331c73 100644
--- a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReferenceDataTest.java
+++ b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileReferenceDataTest.java
@@ -7,12 +7,15 @@ import com.yahoo.text.Utf8;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.CompressionType.gzip;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.Type;
+import static com.yahoo.vespa.filedistribution.FileReferenceData.Type.compressed;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -27,7 +30,7 @@ public class FileReferenceDataTest {
String content = "blob";
File tempFile = writeTempFile(content);
FileReferenceData fileReferenceData =
- new LazyTemporaryStorageFileReferenceData(new FileReference("ref"), "foo", FileReferenceData.Type.compressed, tempFile);
+ new LazyTemporaryStorageFileReferenceData(new FileReference("ref"), "foo", compressed, tempFile, gzip);
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
assertEquals(4, fileReferenceData.nextContent(byteBuffer));
assertEquals(content, Utf8.toString(Arrays.copyOfRange(byteBuffer.array(), 0, 4)));
@@ -44,7 +47,7 @@ public class FileReferenceDataTest {
String content = "blobbblubbblabb";
File file = writeTempFile(content);
FileReferenceData fileReferenceData =
- new LazyFileReferenceData(new FileReference("ref"), "foo", FileReferenceData.Type.compressed, file);
+ new LazyFileReferenceData(new FileReference("ref"), "foo", Type.compressed, file, CompressionType.gzip);
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
assertEquals(10, fileReferenceData.nextContent(byteBuffer));
assertEquals(content.substring(0,10), Utf8.toString(Arrays.copyOfRange(byteBuffer.array(), 0, 10)));
diff --git a/flags/pom.xml b/flags/pom.xml
index cf230c1b7a9..0c268fbd644 100644
--- a/flags/pom.xml
+++ b/flags/pom.xml
@@ -39,12 +39,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>vespajlib</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
@@ -62,19 +56,13 @@
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-junit</artifactId>
- <version>2.0.0.0</version>
+ <artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -82,17 +70,26 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
<plugins>
diff --git a/flags/src/main/java/com/yahoo/vespa/flags/Flags.java b/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
index 7894722ad85..1b1a5493cc5 100644
--- a/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
+++ b/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
@@ -15,6 +15,7 @@ import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
+import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
@@ -44,6 +45,15 @@ public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
+ public static final UnboundBooleanFlag MAIN_CHAIN_GRAPH = defineFeatureFlag(
+ "main-chain-graph", true,
+ List.of("hakonhall"), "2022-07-06", "2022-10-05",
+ "Whether to run all tasks in the main task chain up to the one failing to converge (false), or " +
+ "run all tasks in the main task chain whose dependencies have converged (true). And when suspending, " +
+ "whether to run the tasks in sequence (false) or in reverse sequence (true).",
+ "On first tick of the main chain after (re)start of host admin.",
+ ZONE_ID, NODE_TYPE, HOSTNAME);
+
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2023-01-01",
@@ -58,6 +68,12 @@ public class Flags {
"Takes effect at redeployment (requires restart)",
ZONE_ID, APPLICATION_ID);
+ public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag(
+ "keep-storage-node-up", true,
+ List.of("hakonhall"), "2022-07-07", "2022-09-07",
+ "Whether to leave the storage node (with wanted state) UP while the node is permanently down.",
+ "Takes effect immediately for nodes transitioning to permanently down.",
+ ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag(
"max-uncommitted-memory", 130000,
@@ -103,7 +119,7 @@ public class Flags {
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
- List.of("vekterli"), "2020-12-02", "2022-08-01",
+ List.of("vekterli"), "2020-12-02", "2022-08-15",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
@@ -129,6 +145,71 @@ public class Flags {
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
+ public static final UnboundBooleanFlag MBUS_DISPATCH_ON_ENCODE = defineFeatureFlag(
+ "mbus-dispatch-on-encode", true,
+ List.of("baldersheim"), "2022-07-01", "2023-01-01",
+ "Should we use mbus threadpool on encode",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+
+ public static final UnboundBooleanFlag MBUS_DISPATCH_ON_DECODE = defineFeatureFlag(
+ "mbus-dispatch-on-decode", true,
+ List.of("baldersheim"), "2022-07-01", "2023-01-01",
+ "Should we use mbus threadpool on decode",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+
+ public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag(
+ "mbus-java-num-targets", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number of rpc targets per service",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+ public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag(
+ "mbus-cpp-num-targets", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number of rpc targets per service",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+ public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag(
+ "rpc-num-targets", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number of rpc targets per content node",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+ public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag(
+ "mbus-java-events-before-wakeup", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number write events before waking up transport thread",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+ public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag(
+ "mbus-cpp-events-before-wakeup", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number write events before waking up transport thread",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+ public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag(
+ "rpc-events-before-wakeup", 1,
+ List.of("baldersheim"), "2022-07-05", "2023-01-01",
+ "Number write events before waking up transport thread",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+
+ public static final UnboundIntFlag MBUS_NUM_THREADS = defineIntFlag(
+ "mbus-num-threads", 4,
+ List.of("baldersheim"), "2022-07-01", "2023-01-01",
+ "Number of threads used for mbus threadpool",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+
+ public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag(
+ "mbus-num-network-threads", 1,
+ List.of("baldersheim"), "2022-07-01", "2023-01-01",
+ "Number of threads used for mbus network",
+ "Takes effect at redeployment",
+ ZONE_ID, APPLICATION_ID);
+
public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag(
"shared-string-repo-no-reclaim", false,
List.of("baldersheim"), "2022-06-14", "2023-01-01",
@@ -164,7 +245,7 @@ public class Flags {
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
- List.of("vekterli"), "2021-02-19", "2022-08-01",
+ List.of("vekterli"), "2021-02-19", "2022-08-15",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
@@ -172,14 +253,14 @@ public class Flags {
public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag(
"max-concurrent-merges-per-node", 16,
- List.of("balder", "vekterli"), "2021-06-06", "2022-08-01",
+ List.of("balder", "vekterli"), "2021-06-06", "2022-08-15",
"Specifies max concurrent merges per content node.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag(
"max-merge-queue-size", 100,
- List.of("balder", "vekterli"), "2021-06-06", "2022-08-01",
+ List.of("balder", "vekterli"), "2021-06-06", "2022-08-15",
"Specifies max size of merge queue.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
@@ -207,7 +288,7 @@ public class Flags {
public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag(
"enabled-horizon-dashboard", false,
- List.of("olaa"), "2021-09-13", "2022-07-01",
+ List.of("olaa"), "2021-09-13", "2022-10-01",
"Enable Horizon dashboard",
"Takes effect immediately",
TENANT_ID, CONSOLE_USER_EMAIL
@@ -242,13 +323,6 @@ public class Flags {
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
- public static final UnboundBooleanFlag FAIL_DEPLOYMENT_WITH_INVALID_JVM_OPTIONS = defineFeatureFlag(
- "fail-deployment-with-invalid-jvm-options", true,
- List.of("hmusum"), "2021-12-20", "2022-08-01",
- "Whether to fail deployments with invalid JVM options in services.xml",
- "Takes effect at redeployment",
- ZONE_ID, APPLICATION_ID);
-
public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag(
"enable-server-ocsp-stapling", false,
List.of("bjorncs"), "2021-12-17", "2022-09-01",
@@ -258,14 +332,14 @@ public class Flags {
public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag(
"enable-data-highway-in-aws", false,
- List.of("hmusum"), "2022-01-06", "2022-08-01",
+ List.of("hmusum"), "2022-01-06", "2022-09-01",
"Enable Data Highway in AWS",
"Takes effect on restart of Docker container",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag(
"merge-throttling-policy", "STATIC",
- List.of("vekterli"), "2022-01-25", "2022-08-01",
+ List.of("vekterli"), "2022-01-25", "2022-08-15",
"Sets the policy used for merge throttling on the content nodes. " +
"Valid values: STATIC, DYNAMIC",
"Takes effect at redeployment",
@@ -273,7 +347,7 @@ public class Flags {
public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag(
"persistence-throttling-ws-decrement-factor", 1.2,
- List.of("vekterli"), "2022-01-27", "2022-08-01",
+ List.of("vekterli"), "2022-01-27", "2022-08-15",
"Sets the dynamic throttle policy window size decrement factor for persistence " +
"async throttling. Only applies if DYNAMIC policy is used.",
"Takes effect on redeployment",
@@ -281,7 +355,7 @@ public class Flags {
public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag(
"persistence-throttling-ws-backoff", 0.95,
- List.of("vekterli"), "2022-01-27", "2022-08-01",
+ List.of("vekterli"), "2022-01-27", "2022-08-15",
"Sets the dynamic throttle policy window size backoff for persistence " +
"async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]",
"Takes effect on redeployment",
@@ -335,9 +409,9 @@ public class Flags {
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag APPLICATION_FILES_WITH_UNKNOWN_EXTENSION = defineStringFlag(
- "fail-deployment-for-files-with-unknown-extension", "NOOP",
- List.of("hmusum"), "2022-04-27", "2022-07-27",
- "Whether to log, fail or do nothing for deployments when app has a file with unknown extension (valid values LOG, FAIL, NOOP)",
+ "fail-deployment-for-files-with-unknown-extension", "FAIL",
+ List.of("hmusum"), "2022-04-27", "2022-09-01",
+ "Whether to log, fail or do nothing for deployments when app has a file with unknown extension (valid values: LOG, FAIL)",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
@@ -348,37 +422,30 @@ public class Flags {
"Takes effect immediately",
TENANT_ID);
- public static final UnboundStringFlag PROVISION_IN_EXTERNAL_ACCOUNT = defineStringFlag(
- "provision-in-external-account", "",
- List.of("mpolden"), "2022-05-02", "2022-09-01",
- "The 12-digit AWS account ID where resources belonging to an application should be provisioned",
- "Takes effect immediately",
- APPLICATION_ID);
-
public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag(
"enable-proxy-protocol-mixed-mode", true,
- List.of("tokle"), "2022-05-09", "2022-07-01",
+ List.of("tokle"), "2022-05-09", "2022-09-01",
"Enable or disable proxy protocol mixed mode",
"Takes effect on redeployment",
APPLICATION_ID);
- public static final UnboundStringFlag FILE_DISTRIBUTION_COMPRESSION_ALGORITHM = defineStringFlag(
- "file-distribution-compression-algorithm", "gzip",
- List.of("hmusum"), "2022-05-24", "2022-07-24",
- "Which algorithm to use for compressing file references when distributing files. Valid values: none, gzip",
- "Takes effect immediately",
+ public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag(
+ "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class,
+ List.of("hmusum"), "2022-07-05", "2022-09-05",
+ "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4",
+ "Takes effect on restart of service",
APPLICATION_ID);
- public static final UnboundBooleanFlag FILE_DISTRIBUTION_COMPRESS_SINGLE_FILES = defineFeatureFlag(
- "file-distribution-compress-single-files", false,
- List.of("hmusum"), "2022-05-24", "2022-07-24",
- "Whether to compress a file references that is a single file (directories are compressed by default).",
- "Takes effect immediately",
+ public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag(
+ "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class,
+ List.of("hmusum"), "2022-07-05", "2022-09-05",
+ "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4",
+ "Takes effect on restart of service",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag(
"use-yumproxy-v2", false,
- List.of("tokle"), "2022-05-05", "2022-07-01",
+ List.of("tokle"), "2022-05-05", "2022-09-01",
"Use yumproxy-v2",
"Takes effect on host admin restart",
HOSTNAME);
@@ -390,6 +457,28 @@ public class Flags {
"Takes effect immediately",
ZONE_ID, APPLICATION_ID);
+ public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag(
+ "separate-metric-check-config", false,
+ List.of("olaa"), "2022-07-04", "2022-09-01",
+ "Determines whether one metrics config check should be written per Vespa node",
+ "Takes effect on next tick",
+ HOSTNAME);
+
+ public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag(
+ "tls-capabilities-enforcement-mode", "disable",
+ List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01",
+ "Configure Vespa TLS capability enforcement mode",
+ "Takes effect on restart of Docker container",
+ APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION
+ );
+
+ public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag(
+ "cleanup-tenant-roles", false,
+ List.of("olaa"), "2022-08-10", "2022-10-01",
+ "Determines whether old tenant roles should be deleted",
+ "Takes effect next maintenance run"
+ );
+
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
diff --git a/flags/src/main/java/com/yahoo/vespa/flags/PermanentFlags.java b/flags/src/main/java/com/yahoo/vespa/flags/PermanentFlags.java
index adef0110858..b5a292a554d 100644
--- a/flags/src/main/java/com/yahoo/vespa/flags/PermanentFlags.java
+++ b/flags/src/main/java/com/yahoo/vespa/flags/PermanentFlags.java
@@ -114,7 +114,7 @@ public class PermanentFlags {
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag ZOOKEEPER_SERVER_VERSION = defineStringFlag(
- "zookeeper-server-version", "3.7.0",
+ "zookeeper-server-version", "3.7.1", // Note: Nodes running Vespa 7 have 3.7.1 as the only available version
"ZooKeeper server version, a jar file zookeeper-server-<ZOOKEEPER_SERVER_VERSION>-jar-with-dependencies.jar must exist",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java b/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
index 3c022c1ddd2..3edde140de8 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.flags;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.BooleanNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
@@ -12,11 +12,10 @@ import java.util.Objects;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -29,7 +28,7 @@ import static org.mockito.Mockito.when;
*/
public class FlagsTest {
@Test
- public void testBoolean() {
+ void testBoolean() {
final boolean defaultValue = false;
FlagSource source = mock(FlagSource.class);
BooleanFlag booleanFlag = Flags.defineFeatureFlag("id", defaultValue, List.of("owner"), "1970-01-01", "2100-01-01", "description",
@@ -45,8 +44,9 @@ public class FlagsTest {
ArgumentCaptor<FetchVector> vector = ArgumentCaptor.forClass(FetchVector.class);
verify(source).fetch(any(), vector.capture());
// hostname is set by default
- assertThat(vector.getValue().getValue(FetchVector.Dimension.HOSTNAME).isPresent(), is(true));
- assertThat(vector.getValue().getValue(FetchVector.Dimension.HOSTNAME).get(), is(not(emptyOrNullString())));
+ Optional<String> hostname = vector.getValue().getValue(FetchVector.Dimension.HOSTNAME);
+ assertTrue(hostname.isPresent());
+ assertFalse(hostname.get().isEmpty());
// zone is set because it was set on the unbound flag above
assertThat(vector.getValue().getValue(FetchVector.Dimension.ZONE_ID), is(Optional.of("a-zone")));
// application and node type are not set
@@ -66,41 +66,41 @@ public class FlagsTest {
}
@Test
- public void testString() {
+ void testString() {
testGeneric(Flags.defineStringFlag("string-id", "default value", List.of("owner"), "1970-01-01", "2100-01-01", "description",
- "modification effect", FetchVector.Dimension.ZONE_ID, FetchVector.Dimension.HOSTNAME),
- "other value");
+ "modification effect", FetchVector.Dimension.ZONE_ID, FetchVector.Dimension.HOSTNAME),
+ "other value");
}
@Test
- public void testInt() {
+ void testInt() {
testGeneric(Flags.defineIntFlag("int-id", 2, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 3);
}
@Test
- public void testLong() {
+ void testLong() {
testGeneric(Flags.defineLongFlag("long-id", 1L, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 2L);
}
@Test
- public void testDouble() {
+ void testDouble() {
testGeneric(Flags.defineDoubleFlag("double-id", 3.142, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 2.718);
}
@Test
- public void testList() {
+ void testList() {
testGeneric(Flags.defineListFlag("list-id", List.of("a"), String.class, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), List.of("a", "b", "c"));
}
@Test
- public void testJacksonClass() {
+ void testJacksonClass() {
ExampleJacksonClass defaultInstance = new ExampleJacksonClass();
ExampleJacksonClass instance = new ExampleJacksonClass();
instance.integer = -2;
instance.string = "foo";
testGeneric(Flags.defineJacksonFlag("jackson-id", defaultInstance, ExampleJacksonClass.class,
- List.of("owner"), "1970-01-01", "2100-01-01", "description", "modification effect", FetchVector.Dimension.HOSTNAME),
+ List.of("owner"), "1970-01-01", "2100-01-01", "description", "modification effect", FetchVector.Dimension.HOSTNAME),
instance);
testGeneric(Flags.defineListFlag("jackson-list-id", List.of(defaultInstance), ExampleJacksonClass.class, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"),
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java b/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
index dfd676b6472..6da994386a3 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.flags;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -18,7 +18,7 @@ import static org.mockito.Mockito.when;
*/
public class OrderedFlagSourceTest {
@Test
- public void test() {
+ void test() {
FlagSource source1 = mock(FlagSource.class);
FlagSource source2 = mock(FlagSource.class);
OrderedFlagSource orderedSource = new OrderedFlagSource(source1, source2);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java b/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
index 066955ee369..189e3fd79c9 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.flags.custom;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClusterCapacityTest {
@Test
- public void serialization() throws IOException {
+ void serialization() throws IOException {
ClusterCapacity clusterCapacity = new ClusterCapacity(7, 1.2, 3.4, 5.6, null);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(clusterCapacity);
@@ -25,7 +25,7 @@ public class ClusterCapacityTest {
}
@Test
- public void serialization2() throws IOException {
+ void serialization2() throws IOException {
ClusterCapacity clusterCapacity = new ClusterCapacity(7, 1.2, 3.4, 5.6, 2.3);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(clusterCapacity);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java b/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
index 852e1f9b7b1..1c8fbc41d35 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
@@ -2,22 +2,22 @@
package com.yahoo.vespa.flags.custom;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class SharedHostTest {
@Test
- public void serialization() throws IOException {
+ void serialization() throws IOException {
verifySerialization(new SharedHost(List.of(
new HostResources(1.0, 2.0, 3.0, 4.0, "fast", "remote",
- "container", 5, "x86_64")), 6));
+ "container", 5, "x86_64")), 6));
verifySerialization(new SharedHost(List.of(
new HostResources(1.0, 2.0, 3.0, 4.0, "fast", "remote",
- "admin", 5, "arm64")), null));
+ "admin", 5, "arm64")), null));
}
private void verifySerialization(SharedHost sharedHost) throws IOException {
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
index f2d389188f9..884d44e12b6 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
@@ -6,8 +6,7 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.test.file.TestFileSystem;
import org.hamcrest.collection.IsMapContaining;
-import org.hamcrest.collection.IsMapWithSize;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
@@ -19,6 +18,8 @@ import java.util.Map;
import static com.yahoo.yolean.Exceptions.uncheck;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
@@ -28,7 +29,7 @@ public class FlagDbFileTest {
private final FlagDbFile flagDb = new FlagDbFile(fileSystem);
@Test
- public void test() {
+ void test() {
Map<FlagId, FlagData> dataMap = new HashMap<>();
FlagId id1 = new FlagId("id1");
FlagData data1 = new FlagData(id1, new FetchVector());
@@ -38,12 +39,12 @@ public class FlagDbFileTest {
dataMap.put(id2, data2);
// Non-existing directory => empty map
- assertThat(flagDb.read(), IsMapWithSize.anEmptyMap());
+ assertTrue(flagDb.read().isEmpty());
// sync() will create directory with map content
assertThat(flagDb.sync(dataMap), equalTo(true));
Map<FlagId, FlagData> readDataMap = flagDb.read();
- assertThat(readDataMap, IsMapWithSize.aMapWithSize(2));
+ assertEquals(2, readDataMap.size());
assertThat(readDataMap, IsMapContaining.hasKey(id1));
assertThat(readDataMap, IsMapContaining.hasKey(id2));
@@ -61,7 +62,7 @@ public class FlagDbFileTest {
dataMap.put(id3, data3);
assertThat(flagDb.sync(dataMap), equalTo(true));
Map<FlagId, FlagData> anotherReadDataMap = flagDb.read();
- assertThat(anotherReadDataMap, IsMapWithSize.aMapWithSize(2));
+ assertEquals(2, anotherReadDataMap.size());
assertThat(anotherReadDataMap, IsMapContaining.hasKey(id1));
assertThat(anotherReadDataMap, IsMapContaining.hasKey(id3));
assertThat(anotherReadDataMap.get(id1).serializeToJson(), equalTo("{\"id\":\"id1\",\"attributes\":{\"hostname\":\"h1\"}}"));
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
index 677efd0fe1c..4da66bd5cc1 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
@@ -2,18 +2,18 @@
package com.yahoo.vespa.flags.json;
import com.yahoo.vespa.flags.FetchVector;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class ConditionTest {
@Test
- public void testWhitelist() {
+ void testWhitelist() {
String hostname1 = "host1";
var params = new Condition.CreateParams(FetchVector.Dimension.HOSTNAME).withValues(hostname1);
Condition condition = WhitelistCondition.create(params);
@@ -24,7 +24,7 @@ public class ConditionTest {
}
@Test
- public void testBlacklist() {
+ void testBlacklist() {
String hostname1 = "host1";
var params = new Condition.CreateParams(FetchVector.Dimension.HOSTNAME).withValues(hostname1);
Condition condition = BlacklistCondition.create(params);
@@ -35,7 +35,7 @@ public class ConditionTest {
}
@Test
- public void testRelational() {
+ void testRelational() {
verifyVespaVersionFor("<", true, false, false);
verifyVespaVersionFor("<=", true, true, false);
verifyVespaVersionFor(">", false, false, true);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
index 5856cf99558..c89b5883fd1 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.flags.json;
import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.RawFlag;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
@@ -52,7 +52,7 @@ public class FlagDataTest {
private final FetchVector vector = new FetchVector();
@Test
- public void test() {
+ void test() {
// Second rule matches with the default zone matching
verify(Optional.of("false"), vector);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
index 35478768924..2cc19917793 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
@@ -5,23 +5,23 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.yahoo.vespa.flags.json.wire.WireCondition;
import com.yahoo.vespa.flags.json.wire.WireFlagData;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class SerializationTest {
@Test
- public void emptyJson() throws IOException {
+ void emptyJson() throws IOException {
String json = "{\"id\":\"id1\"}";
WireFlagData wireData = WireFlagData.deserialize(json);
assertThat(wireData.id, equalTo("id1"));
@@ -33,7 +33,7 @@ public class SerializationTest {
}
@Test
- public void deserialization() throws IOException {
+ void deserialization() throws IOException {
String json = "{\n" +
" \"id\": \"id2\",\n" +
" \"rules\": [\n" +
@@ -107,7 +107,7 @@ public class SerializationTest {
}
@Test
- public void jsonWithStrayFields() {
+ void jsonWithStrayFields() {
String json = "{\n" +
" \"id\": \"id3\",\n" +
" \"foo\": true,\n" +
@@ -136,7 +136,7 @@ public class SerializationTest {
assertThat(whitelistCondition.dimension, equalTo("zone"));
assertThat(whitelistCondition.values, nullValue());
assertThat(wireData.rules.get(0).value, nullValue());
- assertThat(wireData.defaultFetchVector, anEmptyMap());
+ assertTrue(wireData.defaultFetchVector.isEmpty());
assertThat(wireData.serializeToJson(), equalTo("{\"id\":\"id3\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"zone\"}]}],\"attributes\":{}}"));
diff --git a/fnet/src/tests/frt/rpc/invoke.cpp b/fnet/src/tests/frt/rpc/invoke.cpp
index 1fbd356b239..e1912985379 100644
--- a/fnet/src/tests/frt/rpc/invoke.cpp
+++ b/fnet/src/tests/frt/rpc/invoke.cpp
@@ -7,8 +7,10 @@
#include <vespa/fnet/frt/target.h>
#include <vespa/fnet/frt/rpcrequest.h>
#include <vespa/fnet/frt/invoker.h>
+#include <vespa/fnet/frt/request_access_filter.h>
#include <mutex>
#include <condition_variable>
+#include <string_view>
using vespalib::SocketSpec;
using vespalib::BenchmarkTimer;
@@ -175,11 +177,25 @@ public:
//-------------------------------------------------------------
+struct MyAccessFilter : FRT_RequestAccessFilter {
+ ~MyAccessFilter() override = default;
+
+ constexpr static std::string_view WRONG_KEY = "...mellon!";
+ constexpr static std::string_view CORRECT_KEY = "let me in, I have cake";
+
+ bool allow(FRT_RPCRequest& req) const noexcept override {
+ const auto& req_param = req.GetParams()->GetValue(0)._string;
+ const auto magic_key = std::string_view(req_param._str, req_param._len);
+ return (magic_key == CORRECT_KEY);
+ }
+};
+
class TestRPC : public FRT_Invokable
{
private:
- uint32_t _intValue;
- RequestLatch _detached_req;
+ uint32_t _intValue;
+ RequestLatch _detached_req;
+ std::atomic<bool> _restricted_method_was_invoked;
TestRPC(const TestRPC &);
TestRPC &operator=(const TestRPC &);
@@ -187,7 +203,8 @@ private:
public:
TestRPC(FRT_Supervisor *supervisor)
: _intValue(0),
- _detached_req()
+ _detached_req(),
+ _restricted_method_was_invoked(false)
{
FRT_ReflectionBuilder rb(supervisor);
@@ -201,6 +218,9 @@ public:
FRT_METHOD(TestRPC::RPC_GetValue), this);
rb.DefineMethod("test", "iibb", "i",
FRT_METHOD(TestRPC::RPC_Test), this);
+ rb.DefineMethod("accessRestricted", "s", "",
+ FRT_METHOD(TestRPC::RPC_AccessRestricted), this);
+ rb.RequestAccessFilter(std::make_unique<MyAccessFilter>());
}
void RPC_Test(FRT_RPCRequest *req)
@@ -244,6 +264,16 @@ public:
req->GetReturn()->AddInt32(_intValue);
}
+ void RPC_AccessRestricted([[maybe_unused]] FRT_RPCRequest *req)
+ {
+ // We'll only get here if the access filter lets us in
+ _restricted_method_was_invoked.store(true);
+ }
+
+ bool restricted_method_was_invoked() const noexcept {
+ return _restricted_method_was_invoked.load();
+ }
+
RequestLatch &detached_req() { return _detached_req; }
};
@@ -264,6 +294,7 @@ public:
FRT_Target *make_bad_target() { return _client.supervisor().GetTarget("bogus address"); }
RequestLatch &detached_req() { return _testRPC.detached_req(); }
EchoTest &echo() { return _echoTest; }
+ const TestRPC& server_instance() const noexcept { return _testRPC; }
Fixture()
: _client(crypto),
@@ -421,6 +452,24 @@ TEST_F("require that parameters can be echoed as return values", Fixture()) {
EXPECT_TRUE(req.get().GetParams()->Equals(req.get().GetReturn()));
}
+TEST_F("request denied by access filter returns PERMISSION_DENIED and does not invoke server method", Fixture()) {
+ MyReq req("accessRestricted");
+ auto key = MyAccessFilter::WRONG_KEY;
+ req.get().GetParams()->AddString(key.data(), key.size());
+ f1.target().InvokeSync(req.borrow(), timeout);
+ EXPECT_EQUAL(req.get().GetErrorCode(), FRTE_RPC_PERMISSION_DENIED);
+ EXPECT_FALSE(f1.server_instance().restricted_method_was_invoked());
+}
+
+TEST_F("request allowed by access filter invokes server method as usual", Fixture()) {
+ MyReq req("accessRestricted");
+ auto key = MyAccessFilter::CORRECT_KEY;
+ req.get().GetParams()->AddString(key.data(), key.size());
+ f1.target().InvokeSync(req.borrow(), timeout);
+ ASSERT_FALSE(req.get().IsError());
+ EXPECT_TRUE(f1.server_instance().restricted_method_was_invoked());
+}
+
TEST_MAIN() {
crypto = my_crypto_engine();
TEST_RUN_ALL();
diff --git a/fnet/src/tests/info/info.cpp b/fnet/src/tests/info/info.cpp
index 0d4e0f90a09..4271546e647 100644
--- a/fnet/src/tests/info/info.cpp
+++ b/fnet/src/tests/info/info.cpp
@@ -80,7 +80,7 @@ TEST("size of important objects")
EXPECT_EQUAL(MUTEX_SIZE + sizeof(std::string) + 112u, sizeof(FNET_IOComponent));
EXPECT_EQUAL(32u, sizeof(FNET_Channel));
EXPECT_EQUAL(40u, sizeof(FNET_PacketQueue_NoLock));
- EXPECT_EQUAL(MUTEX_SIZE + sizeof(std::string) + 408u, sizeof(FNET_Connection));
+ EXPECT_EQUAL(MUTEX_SIZE + sizeof(std::string) + 416u, sizeof(FNET_Connection));
EXPECT_EQUAL(48u, sizeof(std::condition_variable));
EXPECT_EQUAL(56u, sizeof(FNET_DataBuffer));
EXPECT_EQUAL(8u, sizeof(FNET_Context));
diff --git a/fnet/src/vespa/fnet/connection.cpp b/fnet/src/vespa/fnet/connection.cpp
index 2677445e35d..26367c904b2 100644
--- a/fnet/src/vespa/fnet/connection.cpp
+++ b/fnet/src/vespa/fnet/connection.cpp
@@ -9,6 +9,7 @@
#include "config.h"
#include "transport_thread.h"
#include "transport.h"
+#include <vespa/vespalib/net/connection_auth_context.h>
#include <vespa/vespalib/net/socket_spec.h>
#include <vespa/log/log.h>
@@ -241,6 +242,8 @@ FNET_Connection::handshake()
break;
case vespalib::CryptoSocket::HandshakeResult::DONE: {
LOG(debug, "Connection(%s): handshake done with peer %s", GetSpec(), GetPeerSpec().c_str());
+ _auth_context = _socket->make_auth_context();
+ assert(_auth_context);
EnableReadEvent(true);
EnableWriteEvent(writePendingAfterConnect());
_flags._framed = (_socket->min_read_buffer_size() > 1);
@@ -764,3 +767,10 @@ FNET_Connection::GetPeerSpec() const
{
return vespalib::SocketAddress::peer_address(_socket->get_fd()).spec();
}
+
+const vespalib::net::ConnectionAuthContext&
+FNET_Connection::auth_context() const noexcept
+{
+ assert(_auth_context);
+ return *_auth_context;
+}
diff --git a/fnet/src/vespa/fnet/connection.h b/fnet/src/vespa/fnet/connection.h
index 15150ffbb07..10cf74e79de 100644
--- a/fnet/src/vespa/fnet/connection.h
+++ b/fnet/src/vespa/fnet/connection.h
@@ -18,6 +18,8 @@ class FNET_IPacketStreamer;
class FNET_IServerAdapter;
class FNET_IPacketHandler;
+namespace vespalib::net { class ConnectionAuthContext; }
+
/**
* Interface implemented by objects that want to perform connection
* cleanup. Use the SetCleanupHandler method to register with a
@@ -96,7 +98,7 @@ private:
using ResolveHandlerSP = std::shared_ptr<ResolveHandler>;
FNET_IPacketStreamer *_streamer; // custom packet streamer
FNET_IServerAdapter *_serverAdapter; // only on server side
- vespalib::CryptoSocket::UP _socket; // socket for this conn
+ vespalib::CryptoSocket::UP _socket; // socket for this conn
ResolveHandlerSP _resolve_handler; // async resolve callback
FNET_Context _context; // connection context
std::atomic<State> _state; // connection state. May be polled outside lock
@@ -115,6 +117,8 @@ private:
FNET_IConnectionCleanupHandler *_cleanup; // cleanup handler
+ std::unique_ptr<vespalib::net::ConnectionAuthContext> _auth_context;
+
static std::atomic<uint64_t> _num_connections; // total number of connections
@@ -236,10 +240,6 @@ private:
bool writePendingAfterConnect();
- /**
- * @return address spec of socket peer. Only makes sense to call on non-listening sockets.
- */
- vespalib::string GetPeerSpec() const;
public:
FNET_Connection(const FNET_Connection &) = delete;
FNET_Connection &operator=(const FNET_Connection &) = delete;
@@ -277,7 +277,7 @@ public:
/**
* Destructor.
**/
- ~FNET_Connection();
+ ~FNET_Connection() override;
/**
@@ -305,6 +305,10 @@ public:
return ((_currentID & 0x01) != (chid & 0x01));
}
+ /**
+ * @return address spec of socket peer. Only makes sense to call on non-listening sockets.
+ */
+ vespalib::string GetPeerSpec() const;
/**
* Does this connection have the ability to accept incoming channels ?
@@ -504,6 +508,12 @@ public:
uint32_t getInputBufferSize() const { return _input.GetBufSize(); }
/**
+ * Returns the connection's auth context. Must only be called _after_ the
+ * handshake phase has completed.
+ */
+ const vespalib::net::ConnectionAuthContext& auth_context() const noexcept;
+
+ /**
* @return the total number of connection objects
**/
static uint64_t get_num_connections() {
diff --git a/fnet/src/vespa/fnet/frt/CMakeLists.txt b/fnet/src/vespa/fnet/frt/CMakeLists.txt
index c7bcbe27041..329c6c8fa57 100644
--- a/fnet/src/vespa/fnet/frt/CMakeLists.txt
+++ b/fnet/src/vespa/fnet/frt/CMakeLists.txt
@@ -5,6 +5,7 @@ vespa_add_library(fnet_frt OBJECT
invoker.cpp
packets.cpp
reflection.cpp
+ require_capabilities.cpp
rpcrequest.cpp
supervisor.cpp
target.cpp
diff --git a/fnet/src/vespa/fnet/frt/error.cpp b/fnet/src/vespa/fnet/frt/error.cpp
index 6af9ea39757..fb91924bf35 100644
--- a/fnet/src/vespa/fnet/frt/error.cpp
+++ b/fnet/src/vespa/fnet/frt/error.cpp
@@ -12,19 +12,20 @@ FRT_GetErrorCodeName(uint32_t errorCode)
errorCode <= FRTE_RPC_LAST)
{
switch (errorCode) {
- case FRTE_RPC_GENERAL_ERROR: return "FRTE_RPC_GENERAL_ERROR";
- case FRTE_RPC_NOT_IMPLEMENTED: return "FRTE_RPC_NOT_IMPLEMENTED";
- case FRTE_RPC_ABORT: return "FRTE_RPC_ABORT";
- case FRTE_RPC_TIMEOUT: return "FRTE_RPC_TIMEOUT";
- case FRTE_RPC_CONNECTION: return "FRTE_RPC_CONNECTION";
- case FRTE_RPC_BAD_REQUEST: return "FRTE_RPC_BAD_REQUEST";
- case FRTE_RPC_NO_SUCH_METHOD: return "FRTE_RPC_NO_SUCH_METHOD";
- case FRTE_RPC_WRONG_PARAMS: return "FRTE_RPC_WRONG_PARAMS";
- case FRTE_RPC_OVERLOAD: return "FRTE_RPC_OVERLOAD";
- case FRTE_RPC_WRONG_RETURN: return "FRTE_RPC_WRONG_RETURN";
- case FRTE_RPC_BAD_REPLY: return "FRTE_RPC_BAD_REPLY";
- case FRTE_RPC_METHOD_FAILED: return "FRTE_RPC_METHOD_FAILED";
- default: return "[UNKNOWN RPC ERROR]";
+ case FRTE_RPC_GENERAL_ERROR: return "FRTE_RPC_GENERAL_ERROR";
+ case FRTE_RPC_NOT_IMPLEMENTED: return "FRTE_RPC_NOT_IMPLEMENTED";
+ case FRTE_RPC_ABORT: return "FRTE_RPC_ABORT";
+ case FRTE_RPC_TIMEOUT: return "FRTE_RPC_TIMEOUT";
+ case FRTE_RPC_CONNECTION: return "FRTE_RPC_CONNECTION";
+ case FRTE_RPC_BAD_REQUEST: return "FRTE_RPC_BAD_REQUEST";
+ case FRTE_RPC_NO_SUCH_METHOD: return "FRTE_RPC_NO_SUCH_METHOD";
+ case FRTE_RPC_WRONG_PARAMS: return "FRTE_RPC_WRONG_PARAMS";
+ case FRTE_RPC_OVERLOAD: return "FRTE_RPC_OVERLOAD";
+ case FRTE_RPC_WRONG_RETURN: return "FRTE_RPC_WRONG_RETURN";
+ case FRTE_RPC_BAD_REPLY: return "FRTE_RPC_BAD_REPLY";
+ case FRTE_RPC_METHOD_FAILED: return "FRTE_RPC_METHOD_FAILED";
+ case FRTE_RPC_PERMISSION_DENIED: return "FRTE_RPC_PERMISSION_DENIED";
+ default: return "[UNKNOWN RPC ERROR]";
}
}
return "[UNKNOWN ERROR]";
@@ -41,19 +42,20 @@ FRT_GetDefaultErrorMessage(uint32_t errorCode)
errorCode <= FRTE_RPC_LAST)
{
switch (errorCode) {
- case FRTE_RPC_GENERAL_ERROR: return "(RPC) General error";
- case FRTE_RPC_NOT_IMPLEMENTED: return "(RPC) Not implemented";
- case FRTE_RPC_ABORT: return "(RPC) Invocation aborted";
- case FRTE_RPC_TIMEOUT: return "(RPC) Invocation timed out";
- case FRTE_RPC_CONNECTION: return "(RPC) Connection error";
- case FRTE_RPC_BAD_REQUEST: return "(RPC) Bad request packet";
- case FRTE_RPC_NO_SUCH_METHOD: return "(RPC) No such method";
- case FRTE_RPC_WRONG_PARAMS: return "(RPC) Illegal parameters";
- case FRTE_RPC_OVERLOAD: return "(RPC) Request dropped due to server overload";
- case FRTE_RPC_WRONG_RETURN: return "(RPC) Illegal return values";
- case FRTE_RPC_BAD_REPLY: return "(RPC) Bad reply packet";
- case FRTE_RPC_METHOD_FAILED: return "(RPC) Method failed";
- default: return "[UNKNOWN RPC ERROR]";
+ case FRTE_RPC_GENERAL_ERROR: return "(RPC) General error";
+ case FRTE_RPC_NOT_IMPLEMENTED: return "(RPC) Not implemented";
+ case FRTE_RPC_ABORT: return "(RPC) Invocation aborted";
+ case FRTE_RPC_TIMEOUT: return "(RPC) Invocation timed out";
+ case FRTE_RPC_CONNECTION: return "(RPC) Connection error";
+ case FRTE_RPC_BAD_REQUEST: return "(RPC) Bad request packet";
+ case FRTE_RPC_NO_SUCH_METHOD: return "(RPC) No such method";
+ case FRTE_RPC_WRONG_PARAMS: return "(RPC) Illegal parameters";
+ case FRTE_RPC_OVERLOAD: return "(RPC) Request dropped due to server overload";
+ case FRTE_RPC_WRONG_RETURN: return "(RPC) Illegal return values";
+ case FRTE_RPC_BAD_REPLY: return "(RPC) Bad reply packet";
+ case FRTE_RPC_METHOD_FAILED: return "(RPC) Method failed";
+ case FRTE_RPC_PERMISSION_DENIED: return "(RPC) Permission denied";
+ default: return "[UNKNOWN RPC ERROR]";
}
}
return "[UNKNOWN ERROR]";
diff --git a/fnet/src/vespa/fnet/frt/error.h b/fnet/src/vespa/fnet/frt/error.h
index c5acfb744f6..7b3cdc7320b 100644
--- a/fnet/src/vespa/fnet/frt/error.h
+++ b/fnet/src/vespa/fnet/frt/error.h
@@ -4,21 +4,22 @@
#include <cstdint>
enum {
- FRTE_NO_ERROR = 0,
- FRTE_RPC_FIRST = 100,
- FRTE_RPC_GENERAL_ERROR = 100,
- FRTE_RPC_NOT_IMPLEMENTED = 101,
- FRTE_RPC_ABORT = 102,
- FRTE_RPC_TIMEOUT = 103,
- FRTE_RPC_CONNECTION = 104,
- FRTE_RPC_BAD_REQUEST = 105,
- FRTE_RPC_NO_SUCH_METHOD = 106,
- FRTE_RPC_WRONG_PARAMS = 107,
- FRTE_RPC_OVERLOAD = 108,
- FRTE_RPC_WRONG_RETURN = 109,
- FRTE_RPC_BAD_REPLY = 110,
- FRTE_RPC_METHOD_FAILED = 111,
- FRTE_RPC_LAST = 199
+ FRTE_NO_ERROR = 0,
+ FRTE_RPC_FIRST = 100,
+ FRTE_RPC_GENERAL_ERROR = 100,
+ FRTE_RPC_NOT_IMPLEMENTED = 101,
+ FRTE_RPC_ABORT = 102,
+ FRTE_RPC_TIMEOUT = 103,
+ FRTE_RPC_CONNECTION = 104,
+ FRTE_RPC_BAD_REQUEST = 105,
+ FRTE_RPC_NO_SUCH_METHOD = 106,
+ FRTE_RPC_WRONG_PARAMS = 107,
+ FRTE_RPC_OVERLOAD = 108,
+ FRTE_RPC_WRONG_RETURN = 109,
+ FRTE_RPC_BAD_REPLY = 110,
+ FRTE_RPC_METHOD_FAILED = 111,
+ FRTE_RPC_PERMISSION_DENIED = 112,
+ FRTE_RPC_LAST = 199
};
const char *FRT_GetErrorCodeName(uint32_t errorCode);
diff --git a/fnet/src/vespa/fnet/frt/invoker.cpp b/fnet/src/vespa/fnet/frt/invoker.cpp
index 85eae6cb41a..d4b35720a8d 100644
--- a/fnet/src/vespa/fnet/frt/invoker.cpp
+++ b/fnet/src/vespa/fnet/frt/invoker.cpp
@@ -52,6 +52,7 @@ FRT_RPCInvoker::FRT_RPCInvoker(FRT_Supervisor *supervisor,
std::string methodName(_req->GetMethodName(), _req->GetMethodNameLen());
LOG(debug, "invoke(server) init: '%s'", methodName.c_str());
}
+ req->SetReturnHandler(this); // RPC req -> FNET_Connection link is via this ptr; set prior to access filter invocation.
if (_method == nullptr) {
if (!req->IsError()) { // may be BAD_REQUEST
req->SetError(FRTE_RPC_NO_SUCH_METHOD);
@@ -60,8 +61,11 @@ FRT_RPCInvoker::FRT_RPCInvoker(FRT_Supervisor *supervisor,
req->GetParamSpec()))
{
req->SetError(FRTE_RPC_WRONG_PARAMS);
+ } else if (_method->GetRequestAccessFilter() &&
+ !_method->GetRequestAccessFilter()->allow(*req))
+ {
+ req->SetError(FRTE_RPC_PERMISSION_DENIED);
}
- req->SetReturnHandler(this);
}
bool FRT_RPCInvoker::Invoke()
diff --git a/fnet/src/vespa/fnet/frt/reflection.cpp b/fnet/src/vespa/fnet/frt/reflection.cpp
index 211e681df94..af7fa069eb9 100644
--- a/fnet/src/vespa/fnet/frt/reflection.cpp
+++ b/fnet/src/vespa/fnet/frt/reflection.cpp
@@ -14,7 +14,8 @@ FRT_Method::FRT_Method(const char * name, const char * paramSpec, const char * r
_returnSpec(returnSpec),
_method(method),
_handler(handler),
- _doc()
+ _doc(),
+ _access_filter()
{
}
@@ -124,6 +125,7 @@ FRT_ReflectionBuilder::Flush()
}
_method->SetDocumentation(_values);
+ _method->SetRequestAccessFilter(std::move(_access_filter)); // May be nullptr
_method = nullptr;
_req->Reset();
}
@@ -142,7 +144,8 @@ FRT_ReflectionBuilder::FRT_ReflectionBuilder(FRT_Supervisor *supervisor)
_arg_name(nullptr),
_arg_desc(nullptr),
_ret_name(nullptr),
- _ret_desc(nullptr)
+ _ret_desc(nullptr),
+ _access_filter()
{
}
@@ -183,6 +186,7 @@ FRT_ReflectionBuilder::DefineMethod(const char *name,
_arg_desc = _values->AddStringArray(_argCnt);
_ret_name = _values->AddStringArray(_retCnt);
_ret_desc = _values->AddStringArray(_retCnt);
+ _access_filter.reset();
}
@@ -224,3 +228,12 @@ FRT_ReflectionBuilder::ReturnDesc(const char *name, const char *desc)
_values->SetString(&_ret_desc[_curRet], desc);
_curRet++;
}
+
+void
+FRT_ReflectionBuilder::RequestAccessFilter(std::unique_ptr<FRT_RequestAccessFilter> access_filter)
+{
+ if (_method == nullptr) {
+ return;
+ }
+ _access_filter = std::move(access_filter);
+}
diff --git a/fnet/src/vespa/fnet/frt/reflection.h b/fnet/src/vespa/fnet/frt/reflection.h
index 6267cafeeb1..3f833d053f1 100644
--- a/fnet/src/vespa/fnet/frt/reflection.h
+++ b/fnet/src/vespa/fnet/frt/reflection.h
@@ -3,6 +3,8 @@
#pragma once
#include "invokable.h"
+#include "request_access_filter.h"
+#include <memory>
#include <string>
#include <vector>
@@ -23,6 +25,7 @@ private:
FRT_METHOD_PT _method; // method pointer
FRT_Invokable *_handler; // method handler
std::vector<char> _doc; // method documentation
+ std::unique_ptr<FRT_RequestAccessFilter> _access_filter; // (optional) access filter
public:
FRT_Method(const FRT_Method &) = delete;
@@ -41,6 +44,10 @@ public:
const char *GetReturnSpec() { return _returnSpec.c_str(); }
FRT_METHOD_PT GetMethod() { return _method; }
FRT_Invokable *GetHandler() { return _handler; }
+ const FRT_RequestAccessFilter* GetRequestAccessFilter() const noexcept { return _access_filter.get(); }
+ void SetRequestAccessFilter(std::unique_ptr<FRT_RequestAccessFilter> access_filter) noexcept {
+ _access_filter = std::move(access_filter);
+ }
void SetDocumentation(FRT_Values *values);
void GetDocumentation(FRT_Values *values);
};
@@ -104,6 +111,7 @@ private:
FRT_StringValue *_arg_desc;
FRT_StringValue *_ret_name;
FRT_StringValue *_ret_desc;
+ std::unique_ptr<FRT_RequestAccessFilter> _access_filter;
FRT_ReflectionBuilder(const FRT_ReflectionBuilder &);
FRT_ReflectionBuilder &operator=(const FRT_ReflectionBuilder &);
@@ -122,5 +130,6 @@ public:
void MethodDesc(const char *desc);
void ParamDesc(const char *name, const char *desc);
void ReturnDesc(const char *name, const char *desc);
+ void RequestAccessFilter(std::unique_ptr<FRT_RequestAccessFilter> access_filter);
};
diff --git a/fnet/src/vespa/fnet/frt/request_access_filter.h b/fnet/src/vespa/fnet/frt/request_access_filter.h
new file mode 100644
index 00000000000..a02dca646f3
--- /dev/null
+++ b/fnet/src/vespa/fnet/frt/request_access_filter.h
@@ -0,0 +1,24 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+class FRT_RPCRequest;
+
+/**
+ * An RPC request access filter will, if provided during method registration, be
+ * invoked _prior_ to any RPC handler callback invocation for that method. It allows
+ * for implementing method-specific authorization handling, logging etc.
+ *
+ * Must be thread safe.
+ */
+class FRT_RequestAccessFilter {
+public:
+ virtual ~FRT_RequestAccessFilter() = default;
+
+ /**
+ * Iff true is returned, the request is allowed through and the RPC callback
+ * will be invoked as usual. If false, the request is immediately failed back
+ * to the caller with an error code.
+ */
+ [[nodiscard]] virtual bool allow(FRT_RPCRequest&) const noexcept = 0;
+};
diff --git a/fnet/src/vespa/fnet/frt/require_capabilities.cpp b/fnet/src/vespa/fnet/frt/require_capabilities.cpp
new file mode 100644
index 00000000000..fc64621717f
--- /dev/null
+++ b/fnet/src/vespa/fnet/frt/require_capabilities.cpp
@@ -0,0 +1,29 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "require_capabilities.h"
+#include "rpcrequest.h"
+#include <vespa/fnet/connection.h>
+#include <vespa/vespalib/net/connection_auth_context.h>
+
+#include <vespa/log/bufferedlogger.h>
+LOG_SETUP(".fnet.frt.require_capabilities");
+
+using namespace vespalib::net::tls;
+
+bool
+FRT_RequireCapabilities::allow(FRT_RPCRequest& req) const noexcept
+{
+ const auto& auth_ctx = req.GetConnection()->auth_context();
+ const bool is_authorized = auth_ctx.capabilities().contains_all(_required_capabilities);
+ if (!is_authorized) {
+ auto peer_spec = req.GetConnection()->GetPeerSpec();
+ std::string method_name(req.GetMethodName(), req.GetMethodNameLen());
+ LOGBT(warning, peer_spec, "Permission denied for RPC method '%s'. "
+ "Peer at %s with %s. Call requires %s, but peer has %s",
+ method_name.c_str(), peer_spec.c_str(),
+ to_string(auth_ctx.peer_credentials()).c_str(),
+ _required_capabilities.to_string().c_str(),
+ auth_ctx.capabilities().to_string().c_str());
+ }
+ return is_authorized;
+}
diff --git a/fnet/src/vespa/fnet/frt/require_capabilities.h b/fnet/src/vespa/fnet/frt/require_capabilities.h
new file mode 100644
index 00000000000..7c80484783d
--- /dev/null
+++ b/fnet/src/vespa/fnet/frt/require_capabilities.h
@@ -0,0 +1,21 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
+#include "request_access_filter.h"
+#include <vespa/vespalib/net/tls/capability_set.h>
+
+/**
+ * An RPC access filter which verifies that a request is associated with an auth
+ * context that contains, at minimum, a given set of capabilities. If one or more
+ * required capabilities are missing, the request is denied.
+ */
+class FRT_RequireCapabilities final : public FRT_RequestAccessFilter {
+ vespalib::net::tls::CapabilitySet _required_capabilities;
+public:
+ explicit constexpr FRT_RequireCapabilities(vespalib::net::tls::CapabilitySet required_capabilities) noexcept
+ : _required_capabilities(required_capabilities)
+ {
+ }
+
+ bool allow(FRT_RPCRequest& req) const noexcept override;
+};
diff --git a/hosted-api/pom.xml b/hosted-api/pom.xml
index 6f7c6186ece..c016478c3f7 100644
--- a/hosted-api/pom.xml
+++ b/hosted-api/pom.xml
@@ -33,12 +33,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
diff --git a/hosted-api/src/main/java/ai/vespa/hosted/api/ControllerHttpClient.java b/hosted-api/src/main/java/ai/vespa/hosted/api/ControllerHttpClient.java
index 67cd7e1477e..3fdcf0e18d8 100644
--- a/hosted-api/src/main/java/ai/vespa/hosted/api/ControllerHttpClient.java
+++ b/hosted-api/src/main/java/ai/vespa/hosted/api/ControllerHttpClient.java
@@ -179,10 +179,21 @@ public abstract class ControllerHttpClient {
}
/** Returns the application package of the given id. */
+ // TODO(mpolden): Remove after all callers have switched to the method below
public HttpResponse<byte[]> applicationPackage(ApplicationId id) {
- return send(request(HttpRequest.newBuilder(applicationPackagePath(id))
- .timeout(Duration.ofMinutes(2)),
- GET));
+ return applicationPackage(id, false);
+ }
+
+ /**
+ * Returns the latest submitted application package of the given id. If latestDeployed is true, return the latest
+ * package that has been deployed to a production zone.
+ */
+ public HttpResponse<byte[]> applicationPackage(ApplicationId id, boolean latestDeployed) {
+ URI url = applicationPackagePath(id);
+ if (latestDeployed) {
+ url = withQuery(url, "build", "latestDeployed");
+ }
+ return send(request(HttpRequest.newBuilder(url).timeout(Duration.ofMinutes(2)), GET));
}
/** Returns the tenants in this system. */
diff --git a/hosted-tenant-base/pom.xml b/hosted-tenant-base/pom.xml
index 8bc98cf0733..6589e5bf1a3 100644
--- a/hosted-tenant-base/pom.xml
+++ b/hosted-tenant-base/pom.xml
@@ -99,6 +99,12 @@
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <version>${vespa.junit.version}</version>
+ </dependency>
+
+ <dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${vespa.junit.version}</version>
@@ -256,6 +262,9 @@
<!-- note: ordering affects how overrides are evaluated; put the most specific overrides first! -->
<testBundleScopeOverrides>
${extraTestBundleScopeOverrides},
+ org.junit.jupiter:junit-jupiter-engine:test, <!-- avoid embedding engine libraries, which are only used by the runner -->
+ org.junit.jupiter:junit-platform-engine:test, <!-- avoid embedding engine libraries, which are only used by the runner -->
+ org.junit.vintage:junit-vintage-engine:test, <!-- avoid embedding vintage engine, which isn't even supported -->
org.junit.jupiter:junit-jupiter-api:provided, <!-- ensure the api bundle provided by the tester container is used -->
com.yahoo.vespa:application:test, <!-- its transitive dependencies should be provided by the regular container -->
com.yahoo.vespa:container-test:test, <!-- its transitive dependencies should be provided by the regular container -->
@@ -340,6 +349,12 @@
<delete dir="target/application-test/src" />
<copy file="target/${project.artifactId}-tests.jar" todir="target/application-test/components/" />
+
+ <!-- Copy any additional application bundles to the test package -->
+ <copy todir="target/application-test/components">
+ <fileset dir="target/application/components" includes="*.jar" excludes="${project.artifactId}-deploy.jar" />
+ </copy>
+
<zip destfile="target/application-test.zip" basedir="target/application-test/" />
</tasks>
</configuration>
diff --git a/hosted-zone-api/abi-spec.json b/hosted-zone-api/abi-spec.json
index 826f731b4e0..0d9a6409759 100644
--- a/hosted-zone-api/abi-spec.json
+++ b/hosted-zone-api/abi-spec.json
@@ -16,6 +16,23 @@
],
"fields": []
},
+ "ai.vespa.cloud.Cloud": {
+ "superClass": "java.lang.Record",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "final",
+ "record"
+ ],
+ "methods": [
+ "public void <init>(java.lang.String)",
+ "public final java.lang.String toString()",
+ "public final int hashCode()",
+ "public final boolean equals(java.lang.Object)",
+ "public java.lang.String name()"
+ ],
+ "fields": []
+ },
"ai.vespa.cloud.Cluster": {
"superClass": "java.lang.Object",
"interfaces": [],
@@ -73,8 +90,10 @@
],
"methods": [
"public void <init>(ai.vespa.cloud.ApplicationId, ai.vespa.cloud.Zone, ai.vespa.cloud.Cluster, ai.vespa.cloud.Node)",
+ "public void <init>(ai.vespa.cloud.ApplicationId, ai.vespa.cloud.Zone, ai.vespa.cloud.Cloud, ai.vespa.cloud.Cluster, ai.vespa.cloud.Node)",
"public ai.vespa.cloud.ApplicationId application()",
"public ai.vespa.cloud.Zone zone()",
+ "public ai.vespa.cloud.Cloud cloud()",
"public ai.vespa.cloud.Cluster cluster()",
"public ai.vespa.cloud.Node node()"
],
diff --git a/hosted-zone-api/pom.xml b/hosted-zone-api/pom.xml
index 87012df8479..4227d457c4d 100644
--- a/hosted-zone-api/pom.xml
+++ b/hosted-zone-api/pom.xml
@@ -25,14 +25,25 @@
<artifactId>jdisc_core</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
-
- <!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- test -->
</dependencies>
<build>
<plugins>
diff --git a/hosted-zone-api/src/main/java/ai/vespa/cloud/Cloud.java b/hosted-zone-api/src/main/java/ai/vespa/cloud/Cloud.java
new file mode 100644
index 00000000000..1281ffe7038
--- /dev/null
+++ b/hosted-zone-api/src/main/java/ai/vespa/cloud/Cloud.java
@@ -0,0 +1,11 @@
+package ai.vespa.cloud;
+
+/**
+ * The cloud provider in which a cloud deployment may be running.
+ *
+ * This is "aws" when this runs in Amazon Web Services, and "gcp" when this runs in Google Cloud Platform.
+ *
+ * @author mpolden
+ */
+public record Cloud(String name) {
+}
diff --git a/hosted-zone-api/src/main/java/ai/vespa/cloud/SystemInfo.java b/hosted-zone-api/src/main/java/ai/vespa/cloud/SystemInfo.java
index 752e78b580f..325f62cd7f8 100644
--- a/hosted-zone-api/src/main/java/ai/vespa/cloud/SystemInfo.java
+++ b/hosted-zone-api/src/main/java/ai/vespa/cloud/SystemInfo.java
@@ -13,12 +13,20 @@ public class SystemInfo {
private final ApplicationId application;
private final Zone zone;
+ private final Cloud cloud;
private final Cluster cluster;
private final Node node;
+ // TODO: Remove on Vespa 9
+ @Deprecated(forRemoval = true)
public SystemInfo(ApplicationId application, Zone zone, Cluster cluster, Node node) {
+ this(application, zone, new Cloud(""), cluster, node);
+ }
+
+ public SystemInfo(ApplicationId application, Zone zone, Cloud cloud, Cluster cluster, Node node) {
this.application = Objects.requireNonNull(application, "Application cannot be null");
this.zone = Objects.requireNonNull(zone, "Zone cannot be null");
+ this.cloud = Objects.requireNonNull(cloud, "Cloud cannot be null");
this.cluster = Objects.requireNonNull(cluster, "Cluster cannot be null");
this.node = Objects.requireNonNull(node, "Node cannot be null");
}
@@ -29,6 +37,11 @@ public class SystemInfo {
/** Returns the zone this is running in */
public Zone zone() { return zone; }
+ /** Returns the cloud provider this is running in */
+ public Cloud cloud() {
+ return cloud;
+ }
+
/** Returns the cluster this is part of */
public Cluster cluster() { return cluster; }
diff --git a/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java b/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
index c14955d6614..2bae9f0c9e2 100644
--- a/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
+++ b/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.cloud;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -14,21 +14,23 @@ import static org.junit.Assert.fail;
public class SystemInfoTest {
@Test
- public void testSystemInfo() {
+ void testSystemInfo() {
ApplicationId application = new ApplicationId("tenant1", "application1", "instance1");
Zone zone = new Zone(Environment.dev, "us-west-1");
+ Cloud cloud = new Cloud("aws");
Cluster cluster = new Cluster(1, List.of());
Node node = new Node(0);
- SystemInfo info = new SystemInfo(application, zone, cluster, node);
+ SystemInfo info = new SystemInfo(application, zone, cloud, cluster, node);
assertEquals(application, info.application());
assertEquals(zone, info.zone());
+ assertEquals(cloud, info.cloud());
assertEquals(cluster, info.cluster());
assertEquals(node, info.node());
}
@Test
- public void testZone() {
+ void testZone() {
Zone zone = Zone.from("dev.us-west-1");
zone = Zone.from(zone.toString());
assertEquals(Environment.dev, zone.environment());
@@ -56,7 +58,7 @@ public class SystemInfoTest {
}
@Test
- public void testCluster() {
+ void testCluster() {
int size = 1;
var indices = List.of(1);
Cluster cluster = new Cluster(size, indices);
@@ -65,7 +67,7 @@ public class SystemInfoTest {
}
@Test
- public void testNode() {
+ void testNode() {
int index = 0;
Node node = new Node(index);
assertEquals(index, node.index());
diff --git a/http-client/pom.xml b/http-client/pom.xml
index 49512c09a72..26f76288c85 100644
--- a/http-client/pom.xml
+++ b/http-client/pom.xml
@@ -41,12 +41,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
diff --git a/http-utils/pom.xml b/http-utils/pom.xml
index 52dac0cfeea..6cb6cd018c8 100644
--- a/http-utils/pom.xml
+++ b/http-utils/pom.xml
@@ -50,8 +50,13 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -66,10 +71,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <release>${vespaClients.jdk.releaseVersion}</release>
- <showDeprecation>true</showDeprecation>
- </configuration>
</plugin>
</plugins>
</build>
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
index cf80375611f..27819ff0117 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
@@ -7,9 +7,9 @@ import org.apache.http.HttpRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -18,17 +18,17 @@ import static org.mockito.Mockito.mock;
public class VespaHttpClientBuilderTest {
@Test
- public void route_planner_modifies_scheme_of_requests() throws HttpException {
+ void route_planner_modifies_scheme_of_requests() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname:8080", "https://dummyhostname:8080");
}
@Test
- public void route_planer_handles_implicit_http_port() throws HttpException {
+ void route_planer_handles_implicit_http_port() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname", "https://dummyhostname:80");
}
@Test
- public void route_planer_handles_https_port() throws HttpException {
+ void route_planer_handles_https_port() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname:443", "https://dummyhostname:443");
}
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
index bd034ab9ef2..0b83227d538 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
@@ -2,7 +2,7 @@
package ai.vespa.util.http.hc4.retry;
import org.apache.http.client.protocol.HttpClientContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLException;
import java.io.IOException;
@@ -10,8 +10,8 @@ import java.net.ConnectException;
import java.time.Duration;
import java.util.Arrays;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -23,7 +23,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
@SuppressWarnings("unchecked")
@Test
- public void retry_consumers_are_invoked() {
+ void retry_consumers_are_invoked() {
RetryConsumer<IOException> retryConsumer = (RetryConsumer<IOException>) mock(RetryConsumer.class);
RetryFailedConsumer<IOException> retryFailedConsumer = (RetryFailedConsumer<IOException>) mock(RetryFailedConsumer.class);
@@ -51,7 +51,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_delay_sleeps_for_expected_duration() {
+ void retry_with_fixed_delay_sleeps_for_expected_duration() {
Sleeper sleeper = mock(Sleeper.class);
Duration delay = Duration.ofSeconds(2);
@@ -73,7 +73,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_backoff_sleeps_for_expected_durations() {
+ void retry_with_fixed_backoff_sleeps_for_expected_durations() {
Sleeper sleeper = mock(Sleeper.class);
Duration startDelay = Duration.ofMillis(500);
@@ -100,7 +100,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retries_for_listed_exceptions_until_max_retries_exceeded() {
+ void retries_for_listed_exceptions_until_max_retries_exceeded() {
int maxRetries = 2;
DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
@@ -119,7 +119,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void does_not_retry_for_non_listed_exception() {
+ void does_not_retry_for_non_listed_exception() {
DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
.withFixedDelay(Duration.ofSeconds(2), 2)
.retryForExceptions(Arrays.asList(SSLException.class, ConnectException.class))
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
index adbc445de1a..374dee63019 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
@@ -7,15 +7,15 @@ import org.apache.http.HttpVersion;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -26,7 +26,7 @@ public class DelayedResponseLevelRetryHandlerTest {
@Test
@SuppressWarnings("unchecked")
- public void retry_consumers_are_invoked() {
+ void retry_consumers_are_invoked() {
RetryConsumer<HttpResponse> retryConsumer = mock(RetryConsumer.class);
RetryFailedConsumer<HttpResponse> retryFailedConsumer = mock(RetryFailedConsumer.class);
@@ -53,7 +53,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_delay_sleeps_for_expected_duration() {
+ void retry_with_fixed_delay_sleeps_for_expected_duration() {
Duration delay = Duration.ofSeconds(2);
int maxRetries = 2;
@@ -71,7 +71,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_backoff_sleeps_for_expected_durations() {
+ void retry_with_fixed_backoff_sleeps_for_expected_durations() {
Duration startDelay = Duration.ofMillis(500);
Duration maxDelay = Duration.ofSeconds(5);
int maxRetries = 10;
@@ -90,12 +90,12 @@ public class DelayedResponseLevelRetryHandlerTest {
Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5));
for (int i = 1; i <= lastExecutionCount; i++) {
handler.retryRequest(response, i, ctx);
- assertEquals(expectedIntervals.get(i-1).toMillis(), handler.getRetryInterval());
+ assertEquals(expectedIntervals.get(i - 1).toMillis(), handler.getRetryInterval());
}
}
@Test
- public void retries_for_listed_exceptions_until_max_retries_exceeded() {
+ void retries_for_listed_exceptions_until_max_retries_exceeded() {
int maxRetries = 2;
DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder
@@ -113,7 +113,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void does_not_retry_for_non_listed_exception() {
+ void does_not_retry_for_non_listed_exception() {
DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder
.withFixedDelay(Duration.ofSeconds(2), 2)
.retryForStatusCodes(Arrays.asList(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY))
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
index 78c413fba56..b20d801e39c 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
@@ -6,9 +6,9 @@ import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -18,7 +18,7 @@ public class HttpToHttpsRoutePlannerTest {
final HttpToHttpsRoutePlanner planner = new HttpToHttpsRoutePlanner();
@Test
- public void verifySchemeMustBeHttp() throws HttpException {
+ void verifySchemeMustBeHttp() throws HttpException {
try {
planner.determineRoute(new HttpHost("https", "host", 1), new HttpClientContext());
}
@@ -28,7 +28,7 @@ public class HttpToHttpsRoutePlannerTest {
}
@Test
- public void verifyPortMustBeSet() throws HttpException {
+ void verifyPortMustBeSet() throws HttpException {
try {
planner.determineRoute(new HttpHost("http", "host", -1), new HttpClientContext());
}
@@ -39,7 +39,7 @@ public class HttpToHttpsRoutePlannerTest {
@Test
- public void verifyProxyIsDisallowed() throws HttpException {
+ void verifyProxyIsDisallowed() throws HttpException {
HttpClientContext context = new HttpClientContext();
context.setRequestConfig(RequestConfig.custom().setProxy(new HttpHost("proxy")).build());
try {
@@ -51,9 +51,9 @@ public class HttpToHttpsRoutePlannerTest {
}
@Test
- public void verifySchemeIsRewritten() throws HttpException {
+ void verifySchemeIsRewritten() throws HttpException {
assertEquals(new HttpRoute(new HttpHost("https", "host", 1)),
- planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext()));
+ planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext()));
}
}
diff --git a/jdisc-security-filters/pom.xml b/jdisc-security-filters/pom.xml
index 475a8b7e3e9..a452327f6ff 100644
--- a/jdisc-security-filters/pom.xml
+++ b/jdisc-security-filters/pom.xml
@@ -19,9 +19,21 @@
<!-- provided -->
<dependency>
<groupId>com.yahoo.vespa</groupId>
+ <artifactId>configdefinitions</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -32,11 +44,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -46,17 +53,6 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>testutil</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
index 24cd9245b61..520e22de136 100644
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
@@ -19,5 +19,6 @@ public class SecurityHeadersResponseFilter implements SecurityResponseFilter {
response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("X-Frame-Options", "DENY");
+ response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
}
}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
index dac4d3ee4d6..9fb709126bf 100644
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
@@ -6,7 +6,8 @@ import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.security.base.JsonSecurityRequestFilterBase;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Action;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Action;
import com.yahoo.restapi.Path;
import java.net.URI;
diff --git a/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def b/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
index 1d0dcddfc31..d619f5ff735 100644
--- a/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
+++ b/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
@@ -1,4 +1,6 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+# TODO: remove this def when oldest hosted model no longer uses it.
+
namespace=jdisc.http.filter.security.rule
dryrun bool default=false
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
index 63223f3c221..752f1026f3d 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
@@ -21,7 +21,7 @@ import com.yahoo.vespa.athenz.api.ZToken;
import com.yahoo.vespa.athenz.utils.AthenzIdentities;
import com.yahoo.vespa.athenz.zpe.AuthorizationResult;
import com.yahoo.vespa.athenz.zpe.Zpe;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -37,12 +37,12 @@ import static com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFil
import static com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter.MATCHED_ROLE_ATTRIBUTE;
import static com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter.RESULT_ATTRIBUTE;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
-import static com.yahoo.security.SubjectAlternativeName.Type.RFC822_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.EMAIL;
import static com.yahoo.vespa.athenz.zpe.AuthorizationResult.Type;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -72,7 +72,7 @@ public class AthenzAuthorizationFilterTest {
private static final String REJECTED_METRIC_NAME = "jdisc.http.filter.athenz.rejected_requests";
@Test
- public void accepts_request_with_access_token() {
+ void accepts_request_with_access_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -86,7 +86,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_role_certificate() {
+ void accepts_request_with_role_certificate() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -100,7 +100,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_role_token() {
+ void accepts_request_with_role_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -114,7 +114,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_proxied_access_token() {
+ void accepts_request_with_proxied_access_token() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
@@ -135,7 +135,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_access_token_and_matching_identity_certificate_with_proxy_support_enabled() {
+ void accepts_request_with_access_token_and_matching_identity_certificate_with_proxy_support_enabled() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
@@ -156,7 +156,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_forbidden_when_identity_certificate_has_unknown_proxy_identity() {
+ void returns_forbidden_when_identity_certificate_has_unknown_proxy_identity() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.DENY, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.DENY, ROLE));
@@ -174,7 +174,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_unauthorized_for_request_with_disabled_credential_type() {
+ void returns_unauthorized_for_request_with_disabled_credential_type() {
AthenzAuthorizationFilter filter =
createFilter(new AllowingZpe(), List.of(EnabledCredentials.ROLE_CERTIFICATE, EnabledCredentials.ACCESS_TOKEN));
@@ -188,7 +188,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_forbidden_for_credentials_rejected_by_zpe() {
+ void returns_forbidden_for_credentials_rejected_by_zpe() {
AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -200,7 +200,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void reports_metrics_for_rejected_requests() {
+ void reports_metrics_for_rejected_requests() {
MetricMock metric = new MetricMock();
AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of(), metric, null);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -211,7 +211,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void reports_metrics_for_accepted_requests() {
+ void reports_metrics_for_accepted_requests() {
MetricMock metric = new MetricMock();
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of(EnabledCredentials.ACCESS_TOKEN), metric, null);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -222,7 +222,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void ignores_access_token_if_client_has_role_certificate() {
+ void ignores_access_token_if_client_has_role_certificate() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -238,7 +238,7 @@ public class AthenzAuthorizationFilterTest {
private void assertMetrics(MetricMock metric, String metricName, Map<String, String> dimensions) {
assertTrue(metric.addInvocations.keySet().contains(metricName));
SimpleMetricContext metricContext = metric.addInvocations.get(metricName);
- assertNotNull("Metric not found " + metricName, metricName);
+ assertNotNull(metricName, "Metric not found " + metricName);
for (Map.Entry<String, String> entry : dimensions.entrySet()) {
String dimensionName = entry.getKey();
String expected = entry.getValue();
@@ -262,7 +262,7 @@ public class AthenzAuthorizationFilterTest {
Instant now = Instant.now();
return X509CertificateBuilder
.fromKeypair(keyPair, x500Name, now, now.plus(Duration.ofDays(30)), SHA256_WITH_ECDSA, BigInteger.ONE)
- .addSubjectAlternativeName(new SubjectAlternativeName(RFC822_NAME, identity.getFullName() + "@my.domain.my-identity-provider"))
+ .addSubjectAlternativeName(new SubjectAlternativeName(EMAIL, identity.getFullName() + "@my.domain.my-identity-provider"))
.build();
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
index d670c969e5c..0b04993a723 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
@@ -12,7 +12,7 @@ import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzPrincipal;
import com.yahoo.vespa.athenz.api.AthenzUser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.BufferedReader;
@@ -31,10 +31,10 @@ import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -48,7 +48,7 @@ public class AthenzPrincipalFilterTest {
private static final X509Certificate CERTIFICATE = createSelfSignedCertificate(IDENTITY);
@Test
- public void missing_certificate_is_unauthorized() {
+ void missing_certificate_is_unauthorized() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(emptyList());
@@ -61,7 +61,7 @@ public class AthenzPrincipalFilterTest {
}
@Test
- public void certificate_is_accepted() {
+ void certificate_is_accepted() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(singletonList(CERTIFICATE));
@@ -81,7 +81,7 @@ public class AthenzPrincipalFilterTest {
@Test
- public void no_response_produced_when_passthrough_mode_is_enabled() {
+ void no_response_produced_when_passthrough_mode_is_enabled() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(emptyList());
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
index 0f5512a6ec5..34db051aa28 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
@@ -6,13 +6,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
/**
@@ -23,7 +23,7 @@ public class JsonSecurityRequestFilterBaseTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
- public void filter_renders_errors_as_json() throws IOException {
+ void filter_renders_errors_as_json() throws IOException {
int statusCode = 403;
String message = "Forbidden";
DiscFilterRequest request = mock(DiscFilterRequest.class);
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
index ead816afdfd..b5b94d5a2c2 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
@@ -8,16 +8,16 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -29,28 +29,28 @@ import static org.mockito.Mockito.when;
public class CorsPreflightRequestFilterTest {
@Test
- public void any_options_request_yields_access_control_headers_in_response() {
+ void any_options_request_yields_access_control_headers_in_response() {
HeaderFields headers = doFilterRequest(newRequestFilter(), "http://any.origin");
ACCESS_CONTROL_HEADERS.keySet().forEach(
- header -> assertFalse("Empty header: " + header, headers.getFirst(header).isEmpty()));
+ header -> assertFalse(headers.getFirst(header).isEmpty(), "Empty header: " + header));
}
@Test
- public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ void allowed_request_origin_yields_allow_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
HeaderFields headers = doFilterRequest(newRequestFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.getFirst(ALLOW_ORIGIN_HEADER));
}
@Test
- public void allowed_wildcard_origin_yields_origin_header_in_response() {
+ void allowed_wildcard_origin_yields_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
HeaderFields headers = doFilterRequest(newRequestFilter("*"), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.getFirst(ALLOW_ORIGIN_HEADER));
}
@Test
- public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
HeaderFields headers = doFilterRequest(newRequestFilter("http://allowed.origin"), "http://disallowed.origin");
assertNull(headers.getFirst(ALLOW_ORIGIN_HEADER));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
index e3a3568700c..7762fde1a72 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.http.filter.DiscFilterResponse;
import com.yahoo.jdisc.http.filter.RequestView;
import com.yahoo.jdisc.http.filter.SecurityResponseFilter;
import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -16,9 +16,9 @@ import java.util.Optional;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -29,27 +29,27 @@ import static org.mockito.Mockito.when;
public class CorsResponseFilterTest {
@Test
- public void any_request_yields_access_control_headers_in_response() {
+ void any_request_yields_access_control_headers_in_response() {
Map<String, String> headers = doFilterRequest(newResponseFilter(), "http://any.origin");
ACCESS_CONTROL_HEADERS.keySet().forEach(
- header -> assertFalse("Empty header: " + header, headers.get(header).isEmpty()));
+ header -> assertFalse(headers.get(header).isEmpty(), "Empty header: " + header));
}
@Test
- public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ void allowed_request_origin_yields_allow_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
Map<String, String> headers = doFilterRequest(newResponseFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.get(ALLOW_ORIGIN_HEADER));
}
@Test
- public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
Map<String, String> headers = doFilterRequest(newResponseFilter("http://allowed.origin"), "http://disallowed.origin");
assertNull(headers.get(ALLOW_ORIGIN_HEADER));
}
@Test
- public void any_request_origin_yields_allow_origin_header_in_response_when_wildcard_is_allowed() {
+ void any_request_origin_yields_allow_origin_header_in_response_when_wildcard_is_allowed() {
Map<String, String> headers = doFilterRequest(newResponseFilter("*"), "http://any.origin");
assertEquals("http://any.origin", headers.get(ALLOW_ORIGIN_HEADER));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
index 676c3e23ad7..aaf6ebf1aee 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
@@ -4,13 +4,13 @@ package com.yahoo.jdisc.http.filter.security.misc;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.when;
/**
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
public class LocalhostFilterTest {
@Test
- public void filter() {
+ void filter() {
// Reject from non-loopback
assertUnauthorized(createRequest("1.2.3.4", null));
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
index d1d74d30572..95bc1f92572 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
@@ -9,7 +9,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.security.auth.x500.X500Principal;
@@ -21,14 +21,14 @@ import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.when;
public class VespaTlsFilterTest {
@Test
- public void testFilter() {
+ void testFilter() {
assertSuccess(createRequest(List.of(createCertificate())));
assertForbidden(createRequest(Collections.emptyList()));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
index cfd0e80968f..4ad593efe82 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
@@ -8,9 +8,9 @@ import com.yahoo.container.jdisc.RequestHandlerTestDriver.MockResponseHandler;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.DefaultRule;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule;
-import com.yahoo.test.json.JsonTestHelper;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.DefaultRule;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -237,7 +237,7 @@ class RuleBasedRequestFilterTest {
ObjectNode expectedJson = jsonMapper.createObjectNode();
expectedJson.put("message", expectedMessage).put("code", expectedCode);
JsonNode actualJson = jsonMapper.readTree(handler.readAll().getBytes());
- JsonTestHelper.assertJsonEquals(expectedJson, actualJson);
+ assertEquals(expectedJson, actualJson);
}
} \ No newline at end of file
diff --git a/jdisc_core/pom.xml b/jdisc_core/pom.xml
index 3ab469983c5..0e261f9dbef 100644
--- a/jdisc_core/pom.xml
+++ b/jdisc_core/pom.xml
@@ -51,11 +51,34 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -65,18 +88,15 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
- <scope>compile</scope>
<classifier>no_aop</classifier> <!-- Non-AOP version required for Java 8 compatibility -->
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.framework</artifactId>
- <scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.codehaus.mojo</groupId>
@@ -87,7 +107,6 @@
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.log</artifactId>
- <scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.osgi</groupId>
@@ -102,40 +121,28 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-lib</artifactId>
<version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>vespajlib</artifactId>
<version>${project.version}</version>
- <scope>compile</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -213,6 +220,8 @@
<classpath />
<argument>com.yahoo.jdisc.core.ExportPackages</argument>
<argument>${exportPackagesFile}</argument>
+ <!-- WARNING: Removing jars from the list below usually requires a new major Vespa version. -->
+ <!-- NOTE: This list must be kept in sync with ExportPackagesIT.java -->
<argument>__REPLACE_VERSION__${project.build.directory}/dependency/guava.jar</argument>
<argument>${project.build.directory}/dependency/guice-no_aop.jar</argument>
<argument>${project.build.directory}/dependency/slf4j-api.jar</argument>
@@ -224,7 +233,6 @@
<argument>${project.build.directory}/dependency/defaults.jar</argument>
<argument>${project.build.directory}/dependency/vespajlib.jar</argument>
<argument>${project.build.directory}/dependency/vespalog.jar</argument>
- <argument>${project.build.directory}/dependency/yolean.jar</argument>
<argument>${project.build.directory}/dependency/jaxb-api.jar</argument>
<argument>${project.build.directory}/dependency/jaxb-core.jar</argument>
<argument>${project.build.directory}/dependency/jaxb-impl.jar</argument>
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
index dc6ee180321..cdde43bb3c2 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
@@ -127,6 +127,7 @@ public class ApplicationLoader implements BootstrapLoader, ContainerActivator, C
@Override
public void start() throws Exception {
log.finer("Initializing application.");
+ watchdog.start();
Injector injector = guiceModules.activate();
Application app;
if (!appBundles.isEmpty()) {
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleCollisionHook.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleCollisionHook.java
index 75cca79f556..6b57b1e90e7 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleCollisionHook.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/BundleCollisionHook.java
@@ -18,6 +18,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
/**
* A bundle {@link CollisionHook} that contains a set of bundles that are allowed to collide with bundles
@@ -50,8 +51,10 @@ public class BundleCollisionHook implements CollisionHook, EventHook, FindHook {
/**
* Adds a collection of bundles to the allowed duplicates.
+ * Also clears any previous allowed duplicates of the new allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
+ allowedDuplicates.values().removeAll(bundles.stream().map(BsnVersion::new).collect(Collectors.toSet()));
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle));
}
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
index c010eac02b5..f28d5ea2b26 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
@@ -1,18 +1,29 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
+import com.yahoo.concurrent.Threads;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
+import com.yahoo.lang.MutableInteger;
+import org.apache.felix.framework.BundleWiringImpl;
+import org.osgi.framework.Bundle;
+import java.lang.reflect.Field;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -24,7 +35,7 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
static final Duration GRACE_PERIOD = Duration.ofMinutes(5);
static final Duration UPDATE_PERIOD = Duration.ofMinutes(5);
- static final Duration CHECK_PERIOD = Duration.ofSeconds(1);
+ static final Duration CONTAINER_CHECK_PERIOD = Duration.ofSeconds(1);
private static final Logger log = Logger.getLogger(ContainerWatchdog.class.getName());
@@ -37,6 +48,9 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
private Instant currentContainerActivationTime;
private int numStaleContainers;
private Instant lastLogTime;
+ private ScheduledFuture<?> threadMonitoringTask;
+ private ScheduledFuture<?> containerMontoringTask;
+
ContainerWatchdog() {
this(new ScheduledThreadPoolExecutor(
@@ -53,7 +67,11 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
this.scheduler = scheduler;
this.clock = clock;
this.lastLogTime = clock.instant();
- scheduler.scheduleAtFixedRate(this::monitorDeactivatedContainers, CHECK_PERIOD.getSeconds(), CHECK_PERIOD.getSeconds(), TimeUnit.SECONDS);
+ }
+
+ void start() {
+ this.containerMontoringTask = scheduler.scheduleAtFixedRate(this::monitorDeactivatedContainers,
+ CONTAINER_CHECK_PERIOD.getSeconds(), CONTAINER_CHECK_PERIOD.getSeconds(), TimeUnit.SECONDS);
}
@Override
@@ -67,8 +85,8 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
@Override
public void close() throws InterruptedException {
- scheduler.shutdownNow();
- scheduler.awaitTermination(1, TimeUnit.MINUTES);
+ if (containerMontoringTask != null) containerMontoringTask.cancel(false);
+ if (threadMonitoringTask != null) threadMonitoringTask.cancel(false);
synchronized (monitor) {
deactivatedContainers.clear();
currentContainer = null;
@@ -83,6 +101,8 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
}
currentContainer = nextContainer;
currentContainerActivationTime = clock.instant();
+ if (threadMonitoringTask != null) threadMonitoringTask.cancel(false);
+ threadMonitoringTask = scheduler.schedule(this::monitorThreads, 1, TimeUnit.MINUTES);
}
}
@@ -126,6 +146,68 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
return clock.instant().isAfter(container.timeDeactivated.plus(GRACE_PERIOD));
}
+ private void monitorThreads() {
+ Collection<Thread> threads = Threads.getAllThreads();
+ warnOnThreadsHavingClassloaderFromUninstalledBundles(threads);
+ }
+
+ /**
+ * Detect and warn on threads leaked by defunct application components.
+ * These are threads launched by components of application bundles and not stopped after subsequent component deconstruction.
+ * The below algorithm is a heuristic and will not detect all leaked threads.
+ */
+ private void warnOnThreadsHavingClassloaderFromUninstalledBundles(Collection<Thread> threads) {
+ record ThreadDetails(Thread thread, Bundle bundle) {}
+ List<ThreadDetails> staleThreads = new ArrayList<>();
+ for (Thread t : threads) {
+ // Find threads which are sub-classes of java.lang.Thread from an uninstalled bundle
+ Bundle b = hasClassloaderForUninstalledBundle(t).orElse(null);
+ if (b != null) {
+ staleThreads.add(new ThreadDetails(t, b));
+ continue;
+ }
+ // Find threads which Runnable is a class from an uninstalled bundle
+ // This may create false positives
+ b = getTargetFieldOfThread(t).flatMap(ContainerWatchdog::hasClassloaderForUninstalledBundle).orElse(null);
+ if (b != null) {
+ staleThreads.add(new ThreadDetails(t, b));
+ }
+ // Note: no reliable mechanism for detecting threads owned by leaked executors (e.g. ScheduledThreadPoolExecutor)
+ }
+ if (!staleThreads.isEmpty()) {
+ StringBuilder msg = new StringBuilder(
+ ("Found %d stale threads that should have been stopped during previous reconfiguration(s). " +
+ "These threads have a classloader for a bundle that has been uninstalled: \n")
+ .formatted(staleThreads.size()));
+ MutableInteger i = new MutableInteger(1);
+ Comparator<ThreadDetails> outputOrdering =
+ Comparator.<ThreadDetails, Long>comparing(td -> td.bundle().getBundleId())
+ .thenComparing(td -> td.thread().getName()).thenComparing(td -> td.thread().getId());
+ staleThreads.stream().sorted(outputOrdering).forEach(t ->
+ msg.append("%d) Thread '%s' using bundle '%s'. \n"
+ .formatted(i.next(), t.thread().getName(), t.bundle().toString())));
+ log.log(Level.INFO, msg::toString); // Level 'info' until deemed reliable enough as 'warning'
+ }
+ }
+
+ private static Optional<Runnable> getTargetFieldOfThread(Thread t) {
+ try {
+ Field f = Thread.class.getDeclaredField("target");
+ f.setAccessible(true);
+ return Optional.ofNullable((Runnable)f.get(t));
+ } catch (ReflectiveOperationException e) {
+ return Optional.empty();
+ }
+ }
+
+ private static Optional<Bundle> hasClassloaderForUninstalledBundle(Object o) {
+ if (o.getClass().getClassLoader() instanceof BundleWiringImpl.BundleClassLoader cl) {
+ Bundle b = cl.getBundle();
+ if (b.getState() == Bundle.UNINSTALLED) return Optional.of(b);
+ }
+ return Optional.empty();
+ }
+
private static class DeactivatedContainer {
final ActiveContainer instance;
final Instant timeActivated;
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/UnsafeContentInputStream.java b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/UnsafeContentInputStream.java
index 731e28b556c..4af40a22447 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/UnsafeContentInputStream.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/UnsafeContentInputStream.java
@@ -71,10 +71,9 @@ public class UnsafeContentInputStream extends InputStream {
read += toRead;
}
if (marked != null) {
- if (readSinceMarked + len < marked.length) {
- for (int i=0; i < len; i++) {
- marked[readSinceMarked++] = buf[off+i];
- }
+ if (readSinceMarked + read <= marked.length) {
+ System.arraycopy(buf, off, marked, readSinceMarked, read);
+ readSinceMarked += read;
} else {
marked = null;
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
index edde64c5e58..0de164ed693 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class AbstractResourceTestCase {
@Test
- public void requireThatDestroyIsCalledWhenReleased() {
+ void requireThatDestroyIsCalledWhenReleased() {
MyResource res = new MyResource();
assertFalse(res.destroyed);
res.release();
@@ -22,7 +22,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatDestroyIsCalledWhenRetainCountReachesZero() {
+ void requireThatDestroyIsCalledWhenRetainCountReachesZero() {
MyResource res = new MyResource();
assertEquals(1, res.retainCount());
assertFalse(res.destroyed);
@@ -37,7 +37,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatDestroyIsCalledWhenRetainCountReachesZeroOppositeOrder() {
+ void requireThatDestroyIsCalledWhenRetainCountReachesZeroOppositeOrder() {
MyResource res = new MyResource();
assertEquals(1, res.retainCount());
assertFalse(res.destroyed);
@@ -52,7 +52,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReleaseCanOnlyBeCalledOnceEvenWhenReferenceCountIsPositive() {
+ void requireThatReleaseCanOnlyBeCalledOnceEvenWhenReferenceCountIsPositive() {
MyResource res = new MyResource();
final ResourceReference secondReference = res.refer();
res.release();
@@ -66,7 +66,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatSecondaryReferenceCanOnlyBeClosedOnceEvenWhenReferenceCountIsPositive() {
+ void requireThatSecondaryReferenceCanOnlyBeClosedOnceEvenWhenReferenceCountIsPositive() {
MyResource res = new MyResource();
final ResourceReference secondReference = res.refer();
secondReference.close();
@@ -80,7 +80,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReleaseAfterDestroyThrows() {
+ void requireThatReleaseAfterDestroyThrows() {
MyResource res = new MyResource();
res.release();
assertTrue(res.destroyed);
@@ -101,7 +101,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReferAfterDestroyThrows() {
+ void requireThatReferAfterDestroyThrows() {
MyResource res = new MyResource();
res.release();
assertTrue(res.destroyed);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
index 184f7b4d77d..2a4360be0d7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.service.BindingSetNotFoundException;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertSame;
public class ContainerTestCase {
@Test
- public void requireThatNewRequestsReferenceSameSnapshot() throws Exception {
+ void requireThatNewRequestsReferenceSameSnapshot() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request foo = new Request(driver, URI.create("http://foo"));
@@ -31,7 +31,7 @@ public class ContainerTestCase {
}
@Test
- public void requireThatInjectionWorks() throws BindingSetNotFoundException {
+ void requireThatInjectionWorks() throws BindingSetNotFoundException {
final Object foo = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java
index 2fa5700f87b..70de99b191b 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
@@ -11,12 +11,13 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +26,7 @@ import static org.junit.Assert.fail;
public class HeaderFieldsTestCase {
@Test
- public void requireThatSizeWorksAsExpected() {
+ void requireThatSizeWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertEquals(0, headers.size());
headers.add("foo", "bar");
@@ -41,7 +42,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatIsEmptyWorksAsExpected() {
+ void requireThatIsEmptyWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.isEmpty());
headers.add("foo", "bar");
@@ -51,7 +52,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsKeyWorksAsExpected() {
+ void requireThatContainsKeyWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsKey("foo"));
assertFalse(headers.containsKey("FOO"));
@@ -61,7 +62,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsValueWorksAsExpected() {
+ void requireThatContainsValueWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsValue(Arrays.asList("bar")));
headers.add("foo", "bar");
@@ -69,7 +70,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsWorksAsExpected() {
+ void requireThatContainsWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.contains("foo", "bar"));
assertFalse(headers.contains("FOO", "bar"));
@@ -83,7 +84,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsIgnoreCaseWorksAsExpected() {
+ void requireThatContainsIgnoreCaseWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsIgnoreCase("foo", "bar"));
assertFalse(headers.containsIgnoreCase("FOO", "bar"));
@@ -97,7 +98,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddStringWorksAsExpected() {
+ void requireThatAddStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -107,7 +108,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddListWorksAsExpected() {
+ void requireThatAddListWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", Arrays.asList("bar"));
@@ -117,7 +118,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddAllWorksAsExpected() {
+ void requireThatAddAllWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -134,7 +135,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutStringWorksAsExpected() {
+ void requireThatPutStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.put("foo", "bar");
@@ -144,7 +145,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutListWorksAsExpected() {
+ void requireThatPutListWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.put("foo", Arrays.asList("bar"));
@@ -154,7 +155,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutAllWorksAsExpected() {
+ void requireThatPutAllWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -171,7 +172,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatRemoveWorksAsExpected() {
+ void requireThatRemoveWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -181,7 +182,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatRemoveStringWorksAsExpected() {
+ void requireThatRemoveStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -194,7 +195,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatClearWorksAsExpected() {
+ void requireThatClearWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -206,7 +207,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatGetWorksAsExpected() {
+ void requireThatGetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -214,7 +215,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatGetFirstWorksAsExpected() {
+ void requireThatGetFirstWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.getFirst("foo"));
headers.add("foo", Arrays.asList("bar", "baz"));
@@ -222,7 +223,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatIsTrueWorksAsExpected() {
+ void requireThatIsTrueWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.isTrue("foo"));
headers.put("foo", Arrays.asList("true"));
@@ -240,7 +241,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatKeySetWorksAsExpected() {
+ void requireThatKeySetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.keySet().isEmpty());
headers.add("foo", "bar");
@@ -250,7 +251,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatValuesWorksAsExpected() {
+ void requireThatValuesWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.values().isEmpty());
headers.add("foo", "bar");
@@ -266,7 +267,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntrySetWorksAsExpected() {
+ void requireThatEntrySetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.entrySet().isEmpty());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -280,7 +281,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntriesWorksAsExpected() {
+ void requireThatEntriesWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.entries().isEmpty());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -299,7 +300,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntryIsUnmodifiable() {
+ void requireThatEntryIsUnmodifiable() {
HeaderFields headers = new HeaderFields();
headers.put("foo", "bar");
Map.Entry<String, String> entry = headers.entries().get(0);
@@ -312,7 +313,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntriesAreUnmodifiable() {
+ void requireThatEntriesAreUnmodifiable() {
HeaderFields headers = new HeaderFields();
headers.put("foo", "bar");
List<Map.Entry<String, String>> entries = headers.entries();
@@ -331,25 +332,25 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEqualsWorksAsExpected() {
+ void requireThatEqualsWorksAsExpected() {
HeaderFields lhs = new HeaderFields();
HeaderFields rhs = new HeaderFields();
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
lhs.add("foo", "bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.add("foo", "bar");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatHashCodeWorksAsExpected() {
+ void requireThatHashCodeWorksAsExpected() {
HeaderFields lhs = new HeaderFields();
HeaderFields rhs = new HeaderFields();
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
lhs.add("foo", "bar");
assertTrue(lhs.hashCode() != rhs.hashCode());
rhs.add("foo", "bar");
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
}
private static class MyEntry implements Map.Entry<String, String> {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
index 017db9d39da..c6b959e1c37 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -16,13 +16,13 @@ import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -31,7 +31,7 @@ import static org.junit.Assert.fail;
public class ProxyRequestHandlerTestCase {
@Test
- public void requireThatRequestHandlerIsProxied() {
+ void requireThatRequestHandlerIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -54,7 +54,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentCompletedIsProxied() {
+ void requireThatRequestContentCompletedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -90,7 +90,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentFailedIsProxied() {
+ void requireThatRequestContentFailedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -128,7 +128,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatNullRequestContentIsProxied() {
+ void requireThatNullRequestContentIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newNullContent();
Request request = newRequest(driver, requestHandler);
@@ -140,7 +140,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestWriteCompletionCanOnlyBeCalledOnce() {
+ void requireThatRequestWriteCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -178,7 +178,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestCloseCompletionCanOnlyBeCalledOnce() {
+ void requireThatRequestCloseCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -214,7 +214,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseContentCompletedIsProxied() {
+ void requireThatResponseContentCompletedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -251,7 +251,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseContentFailedIsProxied() {
+ void requireThatResponseContentFailedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -290,7 +290,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatNullResponseContentIsProxied() {
+ void requireThatNullResponseContentIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -308,7 +308,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseWriteCompletionCanOnlyBeCalledOnce() {
+ void requireThatResponseWriteCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -347,7 +347,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseCloseCompletionCanOnlyBeCalledOnce() {
+ void requireThatResponseCloseCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -383,7 +383,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatUncaughtCompletionFailureIsLogged() {
+ void requireThatUncaughtCompletionFailureIsLogged() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
index 9b42ea19c81..42fc772f28b 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -13,7 +13,7 @@ import static org.mockito.Mockito.verify;
*/
public class ReferencedResourceTestCase {
@Test
- public void requireThatGettersMatchConstructor() {
+ void requireThatGettersMatchConstructor() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = mock(ResourceReference.class);
final ReferencedResource<SharedResource> referencedResource = new ReferencedResource<>(resource, reference);
@@ -22,7 +22,7 @@ public class ReferencedResourceTestCase {
}
@Test
- public void requireThatCloseCallsReferenceClose() {
+ void requireThatCloseCallsReferenceClose() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = mock(ResourceReference.class);
final ReferencedResource<SharedResource> referencedResource = new ReferencedResource<>(resource, reference);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java
index 7a561e7fc89..efe48e1e528 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -12,7 +12,7 @@ import static org.mockito.Mockito.verify;
*/
public class ReferencesTestCase {
@Test
- public void requireThatFromResourceCallsReleaseOnResource() {
+ void requireThatFromResourceCallsReleaseOnResource() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = References.fromResource(resource);
reference.close();
@@ -20,7 +20,7 @@ public class ReferencesTestCase {
}
@Test
- public void requireThatNoopReferenceCanBeCalledMultipleTimes() {
+ void requireThatNoopReferenceCanBeCalledMultipleTimes() {
References.NOOP_REFERENCE.close();
References.NOOP_REFERENCE.close();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
index 0d665e297da..4b2bb327442 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
@@ -12,19 +12,19 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.BindingSetNotFoundException;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -33,7 +33,7 @@ import static org.junit.Assert.fail;
public class RequestTestCase {
@Test
- public void requireThatAccessorsWork() throws BindingSetNotFoundException {
+ void requireThatAccessorsWork() throws BindingSetNotFoundException {
MyTimer timer = new MyTimer();
timer.currentTime = 69;
@@ -58,7 +58,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatCancelWorks() {
+ void requireThatCancelWorks() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -70,7 +70,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatDefaultTimeoutIsInfinite() {
+ void requireThatDefaultTimeoutIsInfinite() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -84,7 +84,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatTimeRemainingUsesTimer() {
+ void requireThatTimeRemainingUsesTimer() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -93,14 +93,14 @@ public class RequestTestCase {
++timer.currentTime)
{
assertEquals(request.getTimeout(TimeUnit.MILLISECONDS) - timer.currentTime,
- request.timeRemaining(TimeUnit.MILLISECONDS).longValue());
+ request.timeRemaining(TimeUnit.MILLISECONDS).longValue());
}
request.release();
assertTrue(driver.close());
}
@Test
- public void requireThatTimeoutCausesCancel() {
+ void requireThatTimeoutCausesCancel() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -113,7 +113,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatCancelIsTrueIfParentIsCancelled() {
+ void requireThatCancelIsTrueIfParentIsCancelled() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request parent = newRequest(driver);
Request child = new Request(parent, URI.create("http://localhost/"));
@@ -125,7 +125,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatDestroyReleasesContainer() {
+ void requireThatDestroyReleasesContainer() {
final MyContainer container = new MyContainer();
Request request = new Request(new CurrentContainer() {
@@ -140,7 +140,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatServerConnectResolvesToServerBinding() {
+ void requireThatServerConnectResolvesToServerBinding() {
MyContainer container = new MyContainer();
Request request = new Request(container, URI.create("http://localhost/"));
request.connect(new MyResponseHandler());
@@ -149,7 +149,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatClientConnectResolvesToClientBinding() {
+ void requireThatClientConnectResolvesToClientBinding() {
MyContainer container = new MyContainer();
Request serverReq = new Request(container, URI.create("http://localhost/"));
Request clientReq = new Request(serverReq, URI.create("http://localhost/"));
@@ -159,7 +159,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatNullTimeoutManagerThrowsException() {
+ void requireThatNullTimeoutManagerThrowsException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -175,7 +175,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatTimeoutManagerCanNotBeReplaced() {
+ void requireThatTimeoutManagerCanNotBeReplaced() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -193,7 +193,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatSetTimeoutCallsTimeoutManager() {
+ void requireThatSetTimeoutCallsTimeoutManager() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -207,7 +207,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatSetTimeoutManagerPropagatesCurrentTimeout() {
+ void requireThatSetTimeoutManagerPropagatesCurrentTimeout() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -221,7 +221,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatUriIsNormalized() {
+ void requireThatUriIsNormalized() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java
index b3fbbceb06a..ec5079a31ab 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class ResponseTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Response response = new Response(69);
assertEquals(69, response.getStatus());
response.setStatus(96);
@@ -27,7 +27,7 @@ public class ResponseTestCase {
}
@Test
- public void requireThatStatusCodesDoNotChange() {
+ void requireThatStatusCodesDoNotChange() {
assertEquals(100, Response.Status.CONTINUE);
assertEquals(101, Response.Status.SWITCHING_PROTOCOLS);
assertEquals(102, Response.Status.PROCESSING);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
index 3a6aa03ad45..03d5728679f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
@@ -4,15 +4,15 @@ package com.yahoo.jdisc.application;
import com.google.inject.Inject;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -21,27 +21,27 @@ import static org.junit.Assert.assertTrue;
public class AbstractApplicationTestCase {
@Test
- public void requireThatContainerApiIsAvailable() {
+ void requireThatContainerApiIsAvailable() {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- MyApplication app = (MyApplication)driver.application();
+ MyApplication app = (MyApplication) driver.application();
app.activateContainer(app.newContainerBuilder());
assertNotNull(app.container());
assertTrue(driver.close());
}
@Test
- public void requireThatDestroySignalsTermination() {
+ void requireThatDestroySignalsTermination() {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- MyApplication app = (MyApplication)driver.application();
+ MyApplication app = (MyApplication) driver.application();
assertFalse(app.isTerminated());
assertTrue(driver.close());
assertTrue(app.isTerminated());
}
@Test
- public void requireThatTerminationCanBeWaitedForWithTimeout() throws InterruptedException {
+ void requireThatTerminationCanBeWaitedForWithTimeout() throws InterruptedException {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- final MyApplication app = (MyApplication)driver.application();
+ final MyApplication app = (MyApplication) driver.application();
final CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(new Runnable() {
@@ -61,9 +61,9 @@ public class AbstractApplicationTestCase {
}
@Test
- public void requireThatTerminationCanBeWaitedForWithoutTimeout() throws InterruptedException {
+ void requireThatTerminationCanBeWaitedForWithoutTimeout() throws InterruptedException {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- final MyApplication app = (MyApplication)driver.application();
+ final MyApplication app = (MyApplication) driver.application();
final CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(new Runnable() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
index 63331d2014d..1ac091fcc68 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.jdisc.application;
import com.google.inject.Inject;
import com.google.inject.ProvisionException;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class ApplicationNotReadyTestCase {
@Test
- public void requireThatExceptionIsThrown() {
+ void requireThatExceptionIsThrown() {
try {
TestDriver.newInjectedApplicationInstanceWithoutOsgi(MyApplication.class);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
index 5c0942fbf37..7ea8e84228d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class BindingMatchTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Object obj = new Object();
UriPattern pattern = new UriPattern("http://*/*");
BindingMatch<Object> match = new BindingMatch<>(
@@ -31,7 +31,7 @@ public class BindingMatchTestCase {
}
@Test
- public void requireThatConstructorArgumentsCanNotBeNull() {
+ void requireThatConstructorArgumentsCanNotBeNull() {
try {
new BindingMatch<>(null, null, null);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
index 95ba6cde595..92a85cfdc4a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
@@ -7,19 +7,19 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.NonWorkingRequestHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.fail;
public class BindingRepositoryTestCase {
@Test
- public void requireThatRepositoryCanBeActivated() {
+ void requireThatRepositoryCanBeActivated() {
BindingRepository<Object> bindings = new BindingRepository<>();
bindings.bind("http://host/path", new Object());
@@ -41,7 +41,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatActivationIsSnapshotOfRepository() {
+ void requireThatActivationIsSnapshotOfRepository() {
BindingRepository<Object> bindings = new BindingRepository<>();
bindings.bind("http://host/path", new Object());
@@ -57,7 +57,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatObjectsCanBeBound() {
+ void requireThatObjectsCanBeBound() {
BindingRepository<Object> bindings = new BindingRepository<>();
Object foo = new Object();
Object bar = new Object();
@@ -79,7 +79,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPatternCannotBeStolen() {
+ void requireThatPatternCannotBeStolen() {
final String pattern = "http://host/path";
final RequestHandler originallyBoundHandler = new NonWorkingRequestHandler();
@@ -92,7 +92,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatBindAllMethodWorks() {
+ void requireThatBindAllMethodWorks() {
Object foo = new Object();
Object bar = new Object();
Object baz = new Object();
@@ -122,7 +122,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPutAllMethodWorks() {
+ void requireThatPutAllMethodWorks() {
Object foo = new Object();
Object bar = new Object();
Object baz = new Object();
@@ -153,7 +153,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPutNullThrowsException() {
+ void requireThatPutNullThrowsException() {
try {
new BindingRepository<>().put(null, new Object());
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
index 3b7d8aafcab..504810dc2ed 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.application;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.test.NonWorkingRequestHandler;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -14,12 +14,12 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertTrue;
public class BindingSetTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/foo"), foo);
@@ -51,7 +51,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatSimpleResolutionWorks() {
+ void requireThatSimpleResolutionWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/foo"), foo);
@@ -72,7 +72,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorks() {
+ void requireThatPatternResolutionWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/*"), foo);
@@ -94,7 +94,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorksForWildCards() {
+ void requireThatPatternResolutionWorksForWildCards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host:*/bar"), foo);
@@ -125,7 +125,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorksForFilters() {
+ void requireThatPatternResolutionWorksForFilters() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://*/filtered/*"), foo);
@@ -139,7 +139,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForSchemes() {
+ void requireThatTreeSplitCanBeBoundForSchemes() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler httpfoo = new NonWorkingRequestHandler();
RequestHandler httpsfoo = new NonWorkingRequestHandler();
@@ -152,7 +152,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForHosts() {
+ void requireThatTreeSplitCanBeBoundForHosts() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foobar = new NonWorkingRequestHandler();
@@ -165,7 +165,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForPorts() {
+ void requireThatTreeSplitCanBeBoundForPorts() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo8080 = new NonWorkingRequestHandler();
RequestHandler foo80 = new NonWorkingRequestHandler();
@@ -181,7 +181,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForPaths() {
+ void requireThatTreeSplitCanBeBoundForPaths() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foobar = new NonWorkingRequestHandler();
@@ -194,7 +194,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForWildcards() {
+ void requireThatTreeSplitCanBeBoundForWildcards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo8080 = new NonWorkingRequestHandler();
RequestHandler foo80 = new NonWorkingRequestHandler();
@@ -213,7 +213,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeWorksForURIWithQueryOrFragments() {
+ void requireThatTreeWorksForURIWithQueryOrFragments() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://*/application/v1/session"), foo);
@@ -226,7 +226,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeWorksForURIWithPathWildCards() {
+ void requireThatTreeWorksForURIWithPathWildCards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foo1 = new NonWorkingRequestHandler();
@@ -303,7 +303,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathOverPortWorks() {
+ void requireThatPathOverPortWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler applicationStatus = new NonWorkingRequestHandler();
RequestHandler search = new NonWorkingRequestHandler();
@@ -327,7 +327,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathOverPortsDoNotWorkOverStricterPatterns() {
+ void requireThatPathOverPortsDoNotWorkOverStricterPatterns() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -339,7 +339,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatSchemeOrderOverHost() {
+ void requireThatSchemeOrderOverHost() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -352,7 +352,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPortsAreOrdered() {
+ void requireThatPortsAreOrdered() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -370,7 +370,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathsAreOrdered() {
+ void requireThatPathsAreOrdered() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -388,7 +388,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatStrictPatternsOrderBeforeWildcards() {
+ void requireThatStrictPatternsOrderBeforeWildcards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler fooScheme = new NonWorkingRequestHandler();
@@ -436,7 +436,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatToStringMethodWorks() {
+ void requireThatToStringMethodWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -449,7 +449,7 @@ public class BindingSetTestCase {
@Test
- public void requireThatPatternsAreOrderedMoreSpecificToLess() {
+ void requireThatPatternsAreOrderedMoreSpecificToLess() {
assertOrder("3://host/path", "2://host/path", "1://host/path");
assertOrder("http://3/path", "http://2/path", "http://1/path");
assertOrder("http://host:3/path", "http://host:2/path", "http://host:1/path");
@@ -459,19 +459,19 @@ public class BindingSetTestCase {
assertOrder("http://host:*/3", "http://host:2/2", "http://host:1/1");
assertOrder("http://host/*/3/2/", "http://host/*/1/2", "http://host/*/2/*");
assertOrder("http://host:69/path",
- "http://host/*",
- "http://*:69/path",
- "http://*/path",
- "http://*:69/*",
- "http://*/*",
- "*://host/path",
- "*://*/path",
- "*://*/*");
+ "http://host/*",
+ "http://*:69/path",
+ "http://*/path",
+ "http://*:69/*",
+ "http://*/*",
+ "*://host/path",
+ "*://*/path",
+ "*://*/*");
assertOrder("http://*/HelloWorld",
- "http://*:4080/state/v1/*",
- "http://*:4083/*",
- "http://*:4081/*",
- "http://*:4080/*");
+ "http://*:4080/state/v1/*",
+ "http://*:4083/*",
+ "http://*:4081/*",
+ "http://*:4080/*");
}
private static void assertOrder(String... expected) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java
index 681ca4dea98..d16f13814c1 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.Bundle;
@@ -9,9 +9,9 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class BundleInstallationExceptionTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Throwable t = new Throwable("foo");
Collection<Bundle> bundles = new LinkedList<>();
bundles.add(Mockito.mock(Bundle.class));
@@ -31,7 +31,7 @@ public class BundleInstallationExceptionTestCase {
}
@Test
- public void requireThatBundlesCollectionIsDefensivelyCopied() {
+ void requireThatBundlesCollectionIsDefensivelyCopied() {
Collection<Bundle> bundles = new LinkedList<>();
bundles.add(Mockito.mock(Bundle.class));
BundleInstallationException e = new BundleInstallationException(bundles, new Throwable());
@@ -40,9 +40,9 @@ public class BundleInstallationExceptionTestCase {
}
@Test
- public void requireThatBundlesCollectionIsUnmodifiable() {
+ void requireThatBundlesCollectionIsUnmodifiable() {
BundleInstallationException e = new BundleInstallationException(Arrays.asList(Mockito.mock(Bundle.class)),
- new Throwable());
+ new Throwable());
try {
e.installedBundles().add(Mockito.mock(Bundle.class));
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
index 288b46c995f..a31c72584a5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
@@ -5,18 +5,18 @@ import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.fail;
public class ContainerBuilderTestCase {
@Test
- public void requireThatAccessorsWork() throws URISyntaxException {
+ void requireThatAccessorsWork() throws URISyntaxException {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -47,7 +47,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatContainerThreadFactoryIsBound() {
+ void requireThatContainerThreadFactoryIsBound() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
assertSame(ContainerThread.Factory.class, builder.getInstance(ThreadFactory.class).getClass());
@@ -55,7 +55,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatThreadFactoryCanBeReconfigured() {
+ void requireThatThreadFactoryCanBeReconfigured() {
final ThreadFactory factory = Executors.defaultThreadFactory();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -71,7 +71,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatBindingSetsAreCreatedOnDemand() {
+ void requireThatBindingSetsAreCreatedOnDemand() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
BindingRepository<?> repo = builder.serverBindings("foo");
@@ -87,12 +87,12 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatSafeClassCastWorks() {
+ void requireThatSafeClassCastWorks() {
ContainerBuilder.safeClassCast(Integer.class, Integer.class);
}
@Test
- public void requireThatSafeClassCastThrowsIllegalArgument() {
+ void requireThatSafeClassCastThrowsIllegalArgument() {
try {
ContainerBuilder.safeClassCast(Integer.class, Double.class);
fail();
@@ -102,7 +102,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatSafeStringSplitWorks() {
+ void requireThatSafeStringSplitWorks() {
assertTrue(ContainerBuilder.safeStringSplit(new Object(), ",").isEmpty());
assertTrue(ContainerBuilder.safeStringSplit("", ",").isEmpty());
assertTrue(ContainerBuilder.safeStringSplit(" \f\n\r\t", ",").isEmpty());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
index c7780808bf6..4d17b285926 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
@@ -2,13 +2,13 @@
package com.yahoo.jdisc.application;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -17,14 +17,14 @@ import static org.junit.Assert.assertSame;
public class ContainerThreadTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
MetricConsumer consumer = new MyConsumer();
ContainerThread thread = new ContainerThread(new MyTask(), consumer);
assertSame(consumer, thread.consumer());
}
@Test
- public void requireThatTaskIsRun() throws InterruptedException {
+ void requireThatTaskIsRun() throws InterruptedException {
MyTask task = new MyTask();
ContainerThread thread = new ContainerThread(task, null);
thread.start();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
index abe47662970..8a01406940f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
@@ -1,18 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertTrue;
public class GlobPatternTestCase {
@Test
- public void requireThatCompileCreatesExpectedParts() {
+ void requireThatCompileCreatesExpectedParts() {
assertToString("foo");
assertToString("*foo");
assertToString("*oo");
@@ -38,7 +38,7 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatGlobMatcherWorks() {
+ void requireThatGlobMatcherWorks() {
assertMatch("foo", "foo", Collections.<String>emptyList());
assertNotMatch("foo", "bar");
@@ -81,7 +81,7 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatGlobPatternOrdersMoreSpecificFirst() {
+ void requireThatGlobPatternOrdersMoreSpecificFirst() {
assertCompareEq("foo", "foo");
assertCompareLt("foo", "foo*");
assertCompareLt("foo", "*foo");
@@ -112,15 +112,15 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatEqualsIsImplemented() {
- assertTrue(GlobPattern.compile("foo").equals(GlobPattern.compile("foo")));
- assertFalse(GlobPattern.compile("foo").equals(GlobPattern.compile("bar")));
+ void requireThatEqualsIsImplemented() {
+ assertEquals(GlobPattern.compile("foo"), GlobPattern.compile("foo"));
+ assertNotEquals(GlobPattern.compile("foo"), GlobPattern.compile("bar"));
}
@Test
- public void requireThatHashCodeIsImplemented() {
- assertTrue(GlobPattern.compile("foo").hashCode() == GlobPattern.compile("foo").hashCode());
- assertFalse(GlobPattern.compile("foo").hashCode() == GlobPattern.compile("bar").hashCode());
+ void requireThatHashCodeIsImplemented() {
+ assertEquals(GlobPattern.compile("foo").hashCode(), GlobPattern.compile("foo").hashCode());
+ assertNotNull(GlobPattern.compile("bar").hashCode());
}
private static void assertCompareLt(String lhs, String rhs) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
index 11857163970..9e100e3346a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
@@ -10,18 +10,18 @@ import com.google.inject.Module;
import com.google.inject.PrivateModule;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -30,7 +30,7 @@ import static org.junit.Assert.fail;
public class GuiceRepositoryTestCase {
@Test
- public void requireThatInstallWorks() {
+ void requireThatInstallWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding module = new StringBinding("fooKey", "fooVal");
guice.install(module);
@@ -43,7 +43,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatInstallAllWorks() {
+ void requireThatInstallAllWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding foo = new StringBinding("fooKey", "fooVal");
StringBinding bar = new StringBinding("barKey", "barVal");
@@ -60,7 +60,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatUninstallWorks() {
+ void requireThatUninstallWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding module = new StringBinding("fooKey", "fooVal");
guice.install(module);
@@ -72,7 +72,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatUninstallAllWorks() {
+ void requireThatUninstallAllWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding foo = new StringBinding("fooKey", "fooVal");
StringBinding bar = new StringBinding("barKey", "barVal");
@@ -95,7 +95,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatBindingsCanBeOverridden() {
+ void requireThatBindingsCanBeOverridden() {
GuiceRepository guice = new GuiceRepository();
guice.install(new StringBinding("fooKey", "fooVal1"));
assertBinding(guice, "fooKey", "fooVal1");
@@ -104,7 +104,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatModulesAreOnlyEvaluatedOnce() {
+ void requireThatModulesAreOnlyEvaluatedOnce() {
GuiceRepository guice = new GuiceRepository();
EvalCounter foo = new EvalCounter();
EvalCounter bar = new EvalCounter();
@@ -119,18 +119,18 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatPrivateModulesWorks() {
+ void requireThatPrivateModulesWorks() {
GuiceRepository guice = new GuiceRepository();
List<Named> names = Arrays.asList(Names.named("A"), Names.named("B"));
- for (Named name: names) {
+ for (Named name : names) {
guice.install(createPrivateInjectNameModule(name));
}
Injector injector = guice.getInjector();
- for (Named name: names) {
+ for (Named name : names) {
NameHolder nameHolder = injector.getInstance(Key.get(NameHolder.class, name));
assertEquals(name, nameHolder.name);
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
index 29c51760347..33897d8eacc 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
@@ -5,7 +5,7 @@ import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -14,8 +14,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -24,13 +24,13 @@ import static org.junit.Assert.assertTrue;
public class MetricImplTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
Metric metric = Guice.createInjector().getInstance(Metric.class);
assertTrue(metric instanceof MetricImpl);
}
@Test
- public void requireThatConsumerIsOptional() {
+ void requireThatConsumerIsOptional() {
Injector injector = Guice.createInjector();
Metric metric = injector.getInstance(Metric.class);
metric.set("foo", 6, null);
@@ -38,7 +38,7 @@ public class MetricImplTestCase {
}
@Test
- public void requireThatConsumerIsCalled() throws InterruptedException {
+ void requireThatConsumerIsCalled() throws InterruptedException {
final MyConsumer consumer = new MyConsumer();
Injector injector = Guice.createInjector(new AbstractModule() {
@@ -57,7 +57,7 @@ public class MetricImplTestCase {
}
@Test
- public void requireThatWorkerMetricHasPrecedence() throws InterruptedException {
+ void requireThatWorkerMetricHasPrecedence() throws InterruptedException {
final MyConsumer globalConsumer = new MyConsumer();
Injector injector = Guice.createInjector(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
index da1ab024ede..111ae868e05 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class OsgiHeaderTestCase {
@Test
- public void requireThatOsgiHeadersDoNotChange() {
+ void requireThatOsgiHeadersDoNotChange() {
assertEquals("X-JDisc-Application", OsgiHeader.APPLICATION);
assertEquals("X-JDisc-Preinstall-Bundle", OsgiHeader.PREINSTALL_BUNDLE);
assertEquals("X-JDisc-Privileged-Activator", OsgiHeader.PRIVILEGED_ACTIVATOR);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
index b57fc5ae31f..49d76172c39 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class OsgiRepositoryTestCase {
@Test
- public void requireNothingSinceIntegrationModuleTestsThis() {
+ void requireNothingSinceIntegrationModuleTestsThis() {
assertTrue(true);
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
index b94ff063fc7..d422a6c45e5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
@@ -6,12 +6,12 @@ import com.google.inject.Key;
import com.yahoo.jdisc.AbstractResource;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class ResourcePoolTestCase {
@Test
- public void requireThatAddReturnsArgument() {
+ void requireThatAddReturnsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertSame(foo, new ResourcePool(driver.newContainerBuilder()).add(foo));
@@ -28,7 +28,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAddDoesNotRetainArgument() {
+ void requireThatAddDoesNotRetainArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
@@ -38,12 +38,12 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAddCanBeUsedWithoutContainerBuilder() {
+ void requireThatAddCanBeUsedWithoutContainerBuilder() {
new ResourcePool().add(new MyResource());
}
@Test
- public void requireThatRetainReturnsArgument() {
+ void requireThatRetainReturnsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertSame(foo, new ResourcePool(driver.newContainerBuilder()).retain(foo));
@@ -51,7 +51,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatRetainRetainsArgument() {
+ void requireThatRetainRetainsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
@@ -61,12 +61,12 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatRetainCanBeUsedWithoutContainerBuilder() {
+ void requireThatRetainCanBeUsedWithoutContainerBuilder() {
new ResourcePool().retain(new MyResource());
}
@Test
- public void requireThatGetReturnsBoundInstance() {
+ void requireThatGetReturnsBoundInstance() {
final MyResource foo = new MyResource();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -82,7 +82,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatGetDoesNotRetainArgument() {
+ void requireThatGetDoesNotRetainArgument() {
final MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -101,7 +101,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatGetCanNotBeUsedWithoutContainerBuilder() {
+ void requireThatGetCanNotBeUsedWithoutContainerBuilder() {
ResourcePool pool = new ResourcePool();
try {
pool.get(MyResource.class);
@@ -118,7 +118,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatResourcesAreReleasedOnDestroy() {
+ void requireThatResourcesAreReleasedOnDestroy() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ResourcePool pool = new ResourcePool(driver.newContainerBuilder());
@@ -152,7 +152,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAutoCloseCallsRelease() throws Exception {
+ void requireThatAutoCloseCallsRelease() throws Exception {
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
try (ResourcePool pool = new ResourcePool()) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
index a5d7184e31a..cb3a81277f3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.application;
import com.yahoo.jdisc.NoopSharedResource;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class ServerRepositoryTestCase {
@Test
- public void requireThatInstallWorks() {
+ void requireThatInstallWorks() {
ServerRepository servers = newServerRepository();
MyServer server = new MyServer();
servers.install(server);
@@ -31,7 +31,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatInstallAllWorks() {
+ void requireThatInstallAllWorks() {
ServerRepository servers = newServerRepository();
ServerProvider foo = new MyServer();
ServerProvider bar = new MyServer();
@@ -46,7 +46,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatUninstallWorks() {
+ void requireThatUninstallWorks() {
ServerRepository servers = newServerRepository();
ServerProvider server = new MyServer();
servers.install(server);
@@ -55,7 +55,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatUninstallAllWorks() {
+ void requireThatUninstallAllWorks() {
ServerRepository servers = newServerRepository();
ServerProvider foo = new MyServer();
ServerProvider bar = new MyServer();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java
index 32327ace4f4..7a67aeda5f8 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -9,11 +9,11 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ public class UriPatternTestCase {
private static final List<String> NO_GROUPS = Collections.emptyList();
@Test
- public void requireThatIllegalPatternsAreDetected() {
+ void requireThatIllegalPatternsAreDetected() {
assertIllegalPattern("scheme");
assertIllegalPattern("scheme://");
assertIllegalPattern("scheme://host");
@@ -36,13 +36,13 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatNoPortImpliesWildcard() {
+ void requireThatNoPortImpliesWildcard() {
assertEquals(new UriPattern("scheme://host/path"),
- new UriPattern("scheme://host:*/path"));
+ new UriPattern("scheme://host:*/path"));
}
@Test
- public void requireThatPatternMatches() {
+ void requireThatPatternMatches() {
// scheme matching
UriPattern pattern = new UriPattern("bar://host:69/path");
assertNotMatch(pattern, "foobar://host:69/path");
@@ -124,7 +124,7 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatUriWithoutPathDoesNotThrowException() {
+ void requireThatUriWithoutPathDoesNotThrowException() {
UriPattern pattern = new UriPattern("scheme://host/path");
assertNotMatch(pattern, "scheme://host");
@@ -133,123 +133,123 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatOnlySchemeHostPortAndPathIsMatched() {
+ void requireThatOnlySchemeHostPortAndPathIsMatched() {
UriPattern pattern = new UriPattern("scheme://host:69/path");
assertMatch(pattern, "scheme://host:69/path?foo", NO_GROUPS);
assertMatch(pattern, "scheme://host:69/path?foo#bar", NO_GROUPS);
}
@Test
- public void requireThatHostSupportsWildcard() {
+ void requireThatHostSupportsWildcard() {
UriPattern pattern = new UriPattern("scheme://*.host/path");
assertMatch(pattern, "scheme://a.host/path", Arrays.asList("a"));
assertMatch(pattern, "scheme://a.b.host/path", Arrays.asList("a.b"));
}
@Test
- public void requireThatSchemesAreOrdered() {
+ void requireThatSchemesAreOrdered() {
assertCompareLt("b://host:69/path",
- "a://host:69/path");
+ "a://host:69/path");
}
@Test
- public void requireThatSchemeOrdersBeforeHost() {
+ void requireThatSchemeOrdersBeforeHost() {
assertCompareLt("b://*:69/path",
- "a://host:69/path");
+ "a://host:69/path");
}
@Test
- public void requireThatHostsAreOrdered() {
+ void requireThatHostsAreOrdered() {
assertCompareLt("scheme://b:69/path",
- "scheme://a:69/path");
+ "scheme://a:69/path");
}
@Test
- public void requireThatHostOrdersBeforePath() {
+ void requireThatHostOrdersBeforePath() {
assertCompareLt("scheme://b:69/*",
- "scheme://a:69/path");
+ "scheme://a:69/path");
}
@Test
- public void requireThatPortsAreOrdered() {
+ void requireThatPortsAreOrdered() {
for (int i = 1; i < 69; ++i) {
assertCompareEq("scheme://host:" + i + "/path",
- "scheme://host:" + i + "/path");
+ "scheme://host:" + i + "/path");
assertCompareLt("scheme://host:" + (i + 1) + "/path",
- "scheme://host:" + i + "/path");
+ "scheme://host:" + i + "/path");
assertCompareLt("scheme://host:" + i + "/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
}
}
@Test
- public void requireThatPathsAreOrdered() {
+ void requireThatPathsAreOrdered() {
assertCompareLt("scheme://host:69/b",
- "scheme://host:69/a");
+ "scheme://host:69/a");
}
@Test
- public void requireThatPathOrdersBeforePort() {
+ void requireThatPathOrdersBeforePort() {
assertCompareLt("scheme://host:*/b",
- "scheme://host:69/a");
+ "scheme://host:69/a");
}
@Test
- public void requireThatEqualPatternsOrderEqual() {
+ void requireThatEqualPatternsOrderEqual() {
assertCompareEq("scheme://host:69/path",
- "scheme://host:69/path");
+ "scheme://host:69/path");
assertCompareEq("*://host:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareEq("scheme://*:69/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareEq("scheme://host:*/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
assertCompareEq("scheme://host:69/*",
- "scheme://host:69/*");
+ "scheme://host:69/*");
}
@Test
- public void requireThatStrictPatternsOrderBeforeWildcards() {
+ void requireThatStrictPatternsOrderBeforeWildcards() {
assertCompareLt("scheme://host:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareLt("scheme://a:69/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareLt("scheme://a:69/path",
- "scheme://*a:69/path");
+ "scheme://*a:69/path");
assertCompareLt("scheme://*aa:69/path",
- "scheme://*a:69/path");
+ "scheme://*a:69/path");
assertCompareLt("scheme://host:69/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
assertCompareLt("scheme://host:69/a",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/a",
- "scheme://host:69/a*");
+ "scheme://host:69/a*");
assertCompareLt("scheme://host:69/aa*",
- "scheme://host:69/a*");
+ "scheme://host:69/a*");
assertCompareLt("scheme://*:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareLt("scheme://host:*/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareLt("scheme://host:*/path",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/foo",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/foo/bar",
- "scheme://host:69/foo/*");
+ "scheme://host:69/foo/*");
assertCompareLt("scheme://host:69/foo/bar/baz",
- "scheme://host:69/foo/bar/*");
+ "scheme://host:69/foo/bar/*");
}
@Test
- public void requireThatLongPatternsOrderBeforeShort() {
+ void requireThatLongPatternsOrderBeforeShort() {
assertCompareLt("scheme://host:69/foo/bar",
- "scheme://host:69/foo");
+ "scheme://host:69/foo");
assertCompareLt("scheme://host:69/foo/bar/baz",
- "scheme://host:69/foo/bar");
+ "scheme://host:69/foo/bar");
}
@Test
- public void requireThatHttpsSchemeIsHandledAsHttp() {
+ void requireThatHttpsSchemeIsHandledAsHttp() {
UriPattern httpPattern = new UriPattern("http://host:80/path");
assertMatch(httpPattern, "https://host:80/path", NO_GROUPS);
@@ -258,7 +258,7 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatUrlEncodingIsNotDoneForPath() {
+ void requireThatUrlEncodingIsNotDoneForPath() {
UriPattern encodedSlashPattern = new UriPattern("http://host:80/one%2Fpath");
assertMatch(encodedSlashPattern, "http://host:80/one%2Fpath", NO_GROUPS);
assertNotMatch(encodedSlashPattern, "http://host:80/one/path");
@@ -304,7 +304,7 @@ public class UriPatternTestCase {
assertTrue(rhsCmp < 0);
return 1;
}
- assertTrue(rhsCmp == 0);
+ assertEquals(rhsCmp, 0);
return 0;
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
index d6f49c6a038..9dfe0ece0be 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.benchmark;
import com.yahoo.jdisc.application.BindingRepository;
import com.yahoo.jdisc.application.BindingSet;
import com.yahoo.jdisc.application.UriPattern;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -33,7 +33,7 @@ public class BindingMatchingTestCase {
private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
@Test
- public void runThroughtputMeasurements() throws Exception {
+ void runThroughtputMeasurements() throws Exception {
System.err.format("%15s%15s%15s%15s%15s%15s%15s%15s\n",
"No. of Bindings", "1 thread", "2 thread", "4 thread", "8 thread", "16 thread", "32 thread", "64 thread");
for (int numBindings : Arrays.asList(1, 10, 25, 50, 100, 250)) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
index 0ac453d2502..131b4187c2a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ public class LatencyTestCase {
private static final int NUM_REQUESTS = 100;
@Test
- public void runLatencyMeasurements() {
+ void runLatencyMeasurements() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
MyRequestHandler foo = new MyRequestHandler("foo");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
index 23d94114a38..8e369b0aba6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Iterator;
@@ -26,7 +26,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -45,7 +45,7 @@ public class ThroughputTestCase {
private static long preventOptimization = 0;
@Test
- public void runUnthreadedMeasurementsWithWorkload() throws Exception {
+ void runUnthreadedMeasurementsWithWorkload() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
runMeasurements(driver, new UnthreadedHandler(MAX_LOOPS)); // warmup
@@ -75,7 +75,7 @@ public class ThroughputTestCase {
}
@Test
- public void runThreadedMeasurements() throws Exception {
+ void runThreadedMeasurements() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
runMeasurements(driver, new ThreadedHandler()); // warmup
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
index e822bd20536..e20d2b6ff5e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.benchmark;
import com.yahoo.jdisc.application.UriPattern;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -19,7 +19,7 @@ public class UriMatchingTestCase {
private static long preventOptimization = 0;
@Test
- public void requireThatUriPatternMatchingIsFast() {
+ void requireThatUriPatternMatchingIsFast() {
List<String> inputs = Arrays.asList(
"other://host/",
"scheme://other/",
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
index 5534a97a10c..3362726ddc7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
@@ -6,7 +6,7 @@ import com.google.inject.Inject;
import com.yahoo.jdisc.application.BundleInstaller;
import com.yahoo.jdisc.application.ContainerActivator;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
@@ -16,8 +16,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class AbstractClientApplicationTestCase {
@Test
- public void requireThatApplicationCanBeShutdown() throws Exception {
+ void requireThatApplicationCanBeShutdown() throws Exception {
MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
@@ -35,7 +35,7 @@ public class AbstractClientApplicationTestCase {
}
@Test
- public void requireThatShutdownCanBeWaitedForWithTimeout() throws Exception {
+ void requireThatShutdownCanBeWaitedForWithTimeout() throws Exception {
final MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
@@ -57,7 +57,7 @@ public class AbstractClientApplicationTestCase {
}
@Test
- public void requireThatShutdownCanBeWaitedForWithoutTimeout() throws Exception {
+ void requireThatShutdownCanBeWaitedForWithoutTimeout() throws Exception {
final MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
index cd7d5552287..159d8ef8f44 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.jdisc.client;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class ClientDriverTestCase {
@Test
- public void requireThatApplicationInstanceInjectionWorks() throws Exception {
+ void requireThatApplicationInstanceInjectionWorks() throws Exception {
MyModule module = new MyModule();
ClientDriver.runApplication(new MyApplication(module));
assertEquals(5, module.state);
}
@Test
- public void requireThatApplicationClassInjectionWorks() throws Exception {
+ void requireThatApplicationClassInjectionWorks() throws Exception {
MyModule module = new MyModule();
ClientDriver.runApplication(MyApplication.class, module);
assertEquals(5, module.state);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
index cf1fa62b102..4232b6ed087 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
@@ -14,12 +14,13 @@ import com.yahoo.jdisc.test.TestDriver;
import java.util.Iterator;
import java.util.Map;
-import org.junit.Test;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -27,7 +28,7 @@ import static org.junit.Assert.assertSame;
public class ActiveContainerTestCase {
@Test
- public void requireThatGuiceAccessorWorks() {
+ void requireThatGuiceAccessorWorks() {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -42,7 +43,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatServerAccessorWorks() {
+ void requireThatServerAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ServerProvider foo = new NonWorkingServerProvider();
@@ -61,7 +62,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatServerBindingAccessorWorks() {
+ void requireThatServerBindingAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler foo = new NonWorkingRequestHandler();
@@ -103,7 +104,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatClientBindingAccessorWorks() {
+ void requireThatClientBindingAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler foo = new NonWorkingRequestHandler();
@@ -145,7 +146,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatDefaultBindingsAreAlwaysCreated() {
+ void requireThatDefaultBindingsAreAlwaysCreated() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ActiveContainer container = new ActiveContainer(builder);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
index d17c5b183d8..8a1d155df2c 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
@@ -15,9 +15,10 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import org.junit.Test;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -25,7 +26,7 @@ import static org.junit.Assert.assertEquals;
public class ApplicationConfigModuleTestCase {
@Test
- public void requireThatEntriesAreBoundWithLowerCaseKeys() {
+ void requireThatEntriesAreBoundWithLowerCaseKeys() {
Map<String, String> config = new HashMap<>();
config.put("foo_key", "foo");
config.put("BAR_key", "bar");
@@ -38,7 +39,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatEntriesAreBoundWithUnmodifiedValue() {
+ void requireThatEntriesAreBoundWithUnmodifiedValue() {
Map<String, String> config = new HashMap<>();
config.put("foo", "foo_val");
config.put("bar", "BAR_val");
@@ -51,7 +52,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatUpperCaseKeysPrecedeLowerCaseKeys() {
+ void requireThatUpperCaseKeysPrecedeLowerCaseKeys() {
Map<String, String> config = new HashMap<>();
config.put("foo", "lower-case");
assertBinding(config, "foo", "lower-case");
@@ -67,7 +68,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatNullFileNameThrowsException() throws IOException {
+ void requireThatNullFileNameThrowsException() throws IOException {
try {
ApplicationConfigModule.newInstanceFromFile(null);
fail();
@@ -77,7 +78,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatFileNotFoundThrowsException() throws IOException {
+ void requireThatFileNotFoundThrowsException() throws IOException {
try {
ApplicationConfigModule.newInstanceFromFile("/file/not/found");
fail();
@@ -87,7 +88,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatPropertieFilesCanBeRead() throws IOException {
+ void requireThatPropertieFilesCanBeRead() throws IOException {
Properties props = new Properties();
props.put("foo_key", "foo_val");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
index 3bd60832ca3..87a0d4d0e18 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
@@ -18,8 +18,8 @@ import java.util.Map;
import java.util.concurrent.ThreadFactory;
import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationEnvironmentModuleTestCase {
@Test
- public void requireThatBindingsExist() {
+ void requireThatBindingsExist() {
List<Class<?>> expected = new LinkedList<>();
expected.add(ContainerActivator.class);
expected.add(ContainerBuilder.class);
@@ -49,10 +49,10 @@ public class ApplicationEnvironmentModuleTestCase {
}
@Test
- public void requireThatContainerBuilderCanBeInjected() {
+ void requireThatContainerBuilderCanBeInjected() {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), emptyList());
assertNotNull(new ApplicationEnvironmentModule(loader).containerBuilder());
assertNotNull(Guice.createInjector(new ApplicationEnvironmentModule(loader))
- .getInstance(ContainerBuilder.class));
+ .getInstance(ContainerBuilder.class));
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
index e5d335beb38..301f0fc571e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
@@ -16,7 +16,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleContext;
import java.nio.ByteBuffer;
@@ -27,12 +27,12 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -41,9 +41,9 @@ import static org.junit.Assert.fail;
public class ApplicationLoaderTestCase {
@Test
- public void requireThatStartFailsWithoutApplication() throws Exception {
+ void requireThatStartFailsWithoutApplication() throws Exception {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Collections.<Module>emptyList());
+ Collections.<Module>emptyList());
try {
loader.init(null, false);
loader.start();
@@ -54,25 +54,25 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatStopDoesNotFailWithoutStart() throws Exception {
+ void requireThatStopDoesNotFailWithoutStart() throws Exception {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Collections.<Module>emptyList());
+ Collections.<Module>emptyList());
loader.stop();
loader.destroy();
}
@Test
- public void requireThatDestroyDoesNotFailWithActiveContainer() throws Exception {
+ void requireThatDestroyDoesNotFailWithActiveContainer() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertNull(driver.activateContainer(driver.newContainerBuilder()));
assertTrue(driver.close());
}
@Test
- public void requireThatApplicationStartExceptionUnsetsAndDestroysApplication() throws Exception {
+ void requireThatApplicationStartExceptionUnsetsAndDestroysApplication() throws Exception {
MyApplication app = MyApplication.newStartException();
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Arrays.asList(new MyApplicationModule(app)));
+ Arrays.asList(new MyApplicationModule(app)));
loader.init(null, false);
try {
loader.start();
@@ -94,10 +94,10 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatApplicationStopExceptionDestroysApplication() throws Exception {
+ void requireThatApplicationStopExceptionDestroysApplication() throws Exception {
MyApplication app = MyApplication.newStopException();
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Arrays.asList(new MyApplicationModule(app)));
+ Arrays.asList(new MyApplicationModule(app)));
loader.init(null, false);
loader.start();
try {
@@ -110,7 +110,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatApplicationDestroyIsCalledAfterContainerTermination() throws InterruptedException {
+ void requireThatApplicationDestroyIsCalledAfterContainerTermination() throws InterruptedException {
MyApplication app = MyApplication.newInstance();
TestDriver driver = TestDriver.newInjectedApplicationInstance(app);
ContainerBuilder builder = driver.newContainerBuilder();
@@ -125,7 +125,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatContainerActivatorReturnsPrev() throws Exception {
+ void requireThatContainerActivatorReturnsPrev() throws Exception {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.newInstance());
assertNull(driver.activateContainer(driver.newContainerBuilder()));
assertNotNull(driver.activateContainer(null));
@@ -133,7 +133,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatOsgiServicesAreRegistered() {
+ void requireThatOsgiServicesAreRegistered() {
TestDriver driver = TestDriver.newSimpleApplicationInstance();
BundleContext ctx = driver.osgiFramework().bundleContext();
Object service = ctx.getService(ctx.getServiceReference(CurrentContainer.class.getName()));
@@ -142,7 +142,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatThreadFactoryCanBeBound() {
+ void requireThatThreadFactoryCanBeBound() {
final ThreadFactory factory = Executors.defaultThreadFactory();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
index 941067ff27d..cf283fa3ae3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
@@ -11,7 +11,7 @@ import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -19,8 +19,8 @@ import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationRestartTestCase {
@Test
- public void requireThatStopStartDoesNotBreakShutdown() throws Exception {
+ void requireThatStopStartDoesNotBreakShutdown() throws Exception {
ApplicationLoader loader = newApplicationLoader();
loader.init(null, false);
loader.start();
@@ -40,7 +40,7 @@ public class ApplicationRestartTestCase {
}
@Test
- public void requireThatDestroyInitDoesNotBreakShutdown() throws Exception {
+ void requireThatDestroyInitDoesNotBreakShutdown() throws Exception {
ApplicationLoader loader = newApplicationLoader();
loader.init(null, false);
loader.start();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
index 3f906263867..fb88f5567e7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationShutdownTestCase {
@Test
- public void requireThatStopWaitsForPreviousContainer() throws Exception {
+ void requireThatStopWaitsForPreviousContainer() throws Exception {
Context ctx = new Context();
MyRequestHandler requestHandler = new MyRequestHandler();
ctx.activateContainer(requestHandler);
@@ -38,7 +38,7 @@ public class ApplicationShutdownTestCase {
}
@Test
- public void requireThatStopWaitsForAllPreviousContainers() {
+ void requireThatStopWaitsForAllPreviousContainers() {
Context ctx = new Context();
MyRequestHandler requestHandlerA = new MyRequestHandler();
ctx.activateContainer(requestHandlerA);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
index 86f7f5875a7..f65fb849836 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertEquals;
public class BundleLocationResolverTestCase {
@Test
- public void requireThatDollarsAreIncludedInLocation() {
+ void requireThatDollarsAreIncludedInLocation() {
assertLocation("scheme:$foo", "scheme:$foo");
assertLocation("scheme:foo$bar", "scheme:foo$bar");
}
@Test
- public void requireThatCurlyBracesAreIncludedInLocation() {
+ void requireThatCurlyBracesAreIncludedInLocation() {
assertLocation("scheme:{foo", "scheme:{foo");
assertLocation("scheme:foo{", "scheme:foo{");
assertLocation("scheme:foo{bar", "scheme:foo{bar");
@@ -32,14 +32,14 @@ public class BundleLocationResolverTestCase {
}
@Test
- public void requireThatUnterminatedPropertiesAreIncludedInLocation() {
+ void requireThatUnterminatedPropertiesAreIncludedInLocation() {
assertLocation("scheme:${foo", "scheme:${foo");
assertLocation("scheme:foo${", "scheme:foo${");
assertLocation("scheme:foo${bar", "scheme:foo${bar");
}
@Test
- public void requireThatAllSystemPropertiesAreExpanded() throws IOException {
+ void requireThatAllSystemPropertiesAreExpanded() throws IOException {
assertCanonicalPath("", "${foo}");
assertCanonicalPath("barcox", "${foo}bar${baz}cox");
assertCanonicalPath("foobaz", "foo${bar}baz${cox}");
@@ -50,18 +50,18 @@ public class BundleLocationResolverTestCase {
System.setProperty("requireThatAllSystemPropertiesAreExpanded.cox", "COX");
assertCanonicalPath("FOO", "${requireThatAllSystemPropertiesAreExpanded.foo}");
assertCanonicalPath("FOObarBAZcox", "${requireThatAllSystemPropertiesAreExpanded.foo}bar" +
- "${requireThatAllSystemPropertiesAreExpanded.baz}cox");
+ "${requireThatAllSystemPropertiesAreExpanded.baz}cox");
assertCanonicalPath("fooBARbazCOX", "foo${requireThatAllSystemPropertiesAreExpanded.bar}" +
- "baz${requireThatAllSystemPropertiesAreExpanded.cox}");
+ "baz${requireThatAllSystemPropertiesAreExpanded.cox}");
}
@Test
- public void requireThatUnschemedLocationsAreExpandedToBundleLocationProperty() throws IOException {
+ void requireThatUnschemedLocationsAreExpandedToBundleLocationProperty() throws IOException {
assertCanonicalPath(BundleLocationResolver.BUNDLE_PATH + "foo", "foo");
}
@Test
- public void requireThatFileSchemedLocationsAreCanonicalized() throws IOException {
+ void requireThatFileSchemedLocationsAreCanonicalized() throws IOException {
assertCanonicalPath("", "file:");
assertCanonicalPath("foo", "file:foo");
assertCanonicalPath("foo", "file:./foo");
@@ -71,7 +71,7 @@ public class BundleLocationResolverTestCase {
}
@Test
- public void requireThatOtherSchemedLocationsAreUntouched() {
+ void requireThatOtherSchemedLocationsAreUntouched() {
assertLocation("foo:", "foo:");
assertLocation("foo:bar", "foo:bar");
assertLocation("foo:bar/baz", "foo:bar/baz");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java
index f8a982d02cf..64130ddc125 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
@@ -13,7 +13,7 @@ import java.io.StringWriter;
import java.io.Writer;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -27,178 +27,178 @@ public class ConsoleLogFormatterTestCase {
// TODO: Should (at least) use ConsoleLogFormatter.ABSENCE_REPLACEMENT instead of literal '-'. See ticket 7128315.
@Test
- public void requireThatMillisecondsArePadded() {
+ void requireThatMillisecondsArePadded() {
for (int i = 0; i < 10000; ++i) {
LogEntry entry = new MyEntry(i, 0, null);
Instant instant = Instant.ofEpochMilli(i);
assertEquals(String.format("%d.%06d\t-\t-\t-\t-\tunknown\t", instant.getEpochSecond(), instant.getNano() / 1000),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
}
@Test
- public void requireThatHostNameIsIncluded() {
+ void requireThatHostNameIsIncluded() {
assertEquals("0.000000\thostName\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter("hostName", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter("hostName", null, null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatHostNameIsOptional() {
+ void requireThatHostNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter("", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter("", null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(" ", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(" ", null, null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIsIncluded() {
+ void requireThatProcessIdIsIncluded() {
assertEquals("0.000000\t-\tprocessId\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "processId", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, "processId", null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIsOptional() {
+ void requireThatProcessIdIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, "", null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, " ", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, " ", null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIncludesThreadIdWhenAvailable() {
+ void requireThatProcessIdIncludesThreadIdWhenAvailable() {
LogEntry entry = new MyEntry(0, 0, null).putProperty("THREAD_ID", "threadId");
assertEquals("0.000000\t-\tprocessId/threadId\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "processId", null).formatEntry(entry));
+ new ConsoleLogFormatter(null, "processId", null).formatEntry(entry));
}
@Test
- public void requireThatServiceNameIsIncluded() {
+ void requireThatServiceNameIsIncluded() {
assertEquals("0.000000\t-\t-\tserviceName\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, "serviceName").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, "serviceName").formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatServiceNameIsOptional() {
+ void requireThatServiceNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, "").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, "").formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, " ").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, " ").formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatBundleNameIsIncluded() {
+ void requireThatBundleNameIsIncluded() {
LogEntry entry = new MyEntry(0, 0, null).setBundleSymbolicName("bundleName");
assertEquals("0.000000\t-\t-\t-\tbundleName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatBundleNameIsOptional() {
+ void requireThatBundleNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
+ SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatLoggerNameIsIncluded() {
+ void requireThatLoggerNameIsIncluded() {
LogEntry entry = new MyEntry(0, 0, null).putProperty("LOGGER_NAME", "loggerName");
assertEquals("0.000000\t-\t-\t-\t/loggerName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatLoggerNameIsOptional() {
+ void requireThatLoggerNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
+ SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatBundleAndLoggerNameIsCombined() {
+ void requireThatBundleAndLoggerNameIsCombined() {
LogEntry entry = new MyEntry(0, 0, null).setBundleSymbolicName("bundleName")
- .putProperty("LOGGER_NAME", "loggerName");
+ .putProperty("LOGGER_NAME", "loggerName");
assertEquals("0.000000\t-\t-\t-\tbundleName/loggerName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatLevelNameIsIncluded() {
+ void requireThatLevelNameIsIncluded() {
ConsoleLogFormatter formatter = SIMPLE_FORMATTER;
assertEquals("0.000000\t-\t-\t-\t-\terror\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_ERROR, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_ERROR, null)));
assertEquals("0.000000\t-\t-\t-\t-\twarning\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_WARNING, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_WARNING, null)));
assertEquals("0.000000\t-\t-\t-\t-\tinfo\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_INFO, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_INFO, null)));
assertEquals("0.000000\t-\t-\t-\t-\tdebug\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_DEBUG, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_DEBUG, null)));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- formatter.formatEntry(new MyEntry(0, 69, null)));
+ formatter.formatEntry(new MyEntry(0, 69, null)));
}
@Test
- public void requireThatMessageIsIncluded() {
+ void requireThatMessageIsIncluded() {
LogEntry entry = new MyEntry(0, 0, "message");
assertEquals("0.000000\t-\t-\t-\t-\tunknown\tmessage",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatMessageIsOptional() {
+ void requireThatMessageIsOptional() {
LogEntry entry = new MyEntry(0, 0, null);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatMessageIsEscaped() {
+ void requireThatMessageIsEscaped() {
LogEntry entry = new MyEntry(0, 0, "\\\n\r\t");
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\\\\\n\\r\\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsIncluded() {
+ void requireThatExceptionIsIncluded() {
Throwable t = new Throwable();
LogEntry entry = new MyEntry(0, 0, null).setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\n" + formatThrowable(t),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsEscaped() {
+ void requireThatExceptionIsEscaped() {
Throwable t = new Throwable("\\\n\r\t");
LogEntry entry = new MyEntry(0, 0, null).setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\n" + formatThrowable(t),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsSimplifiedForInfoEntries() {
+ void requireThatExceptionIsSimplifiedForInfoEntries() {
Throwable t = new Throwable("exception");
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: exception",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatSimplifiedExceptionIsEscaped() {
+ void requireThatSimplifiedExceptionIsEscaped() {
Throwable t = new Throwable("\\\n\r\t");
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: \\\\\\n\\r\\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatSimplifiedExceptionMessageIsOptional() {
+ void requireThatSimplifiedExceptionMessageIsOptional() {
Throwable t = new Throwable();
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: java.lang.Throwable",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
private static String formatThrowable(Throwable t) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java
index 5f7f7e733fa..0efefc21a2f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogEntry;
@@ -11,7 +11,7 @@ import org.osgi.service.log.LogService;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vikas Panwar
@@ -22,7 +22,7 @@ public class ConsoleLogListenerTestCase {
private static final String PROCESS_ID = ConsoleLogListener.getProcessId();
@Test
- public void requireThatLogLevelParserKnowsOsgiLogLevels() {
+ void requireThatLogLevelParserKnowsOsgiLogLevels() {
assertEquals(LogService.LOG_ERROR, ConsoleLogListener.parseLogLevel("ERROR"));
assertEquals(LogService.LOG_WARNING, ConsoleLogListener.parseLogLevel("WARNING"));
assertEquals(LogService.LOG_INFO, ConsoleLogListener.parseLogLevel("INFO"));
@@ -30,31 +30,31 @@ public class ConsoleLogListenerTestCase {
}
@Test
- public void requireThatLogLevelParserKnowsOff() {
+ void requireThatLogLevelParserKnowsOff() {
assertEquals(Integer.MIN_VALUE, ConsoleLogListener.parseLogLevel("OFF"));
}
@Test
- public void requireThatLogLevelParserKnowsAll() {
+ void requireThatLogLevelParserKnowsAll() {
assertEquals(Integer.MAX_VALUE, ConsoleLogListener.parseLogLevel("ALL"));
}
@Test
- public void requireThatLogLevelParserKnowsIntegers() {
+ void requireThatLogLevelParserKnowsIntegers() {
for (int i = -69; i < 69; ++i) {
assertEquals(i, ConsoleLogListener.parseLogLevel(String.valueOf(i)));
}
}
@Test
- public void requireThatLogLevelParserErrorsReturnDefault() {
+ void requireThatLogLevelParserErrorsReturnDefault() {
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel(null));
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel(""));
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel("foo"));
}
@Test
- public void requireThatLogEntryWithLevelAboveThresholdIsNotOutput() {
+ void requireThatLogEntryWithLevelAboveThresholdIsNotOutput() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
LogListener listener = new ConsoleLogListener(new PrintStream(out), null, "5");
for (int i = 0; i < 10; ++i) {
@@ -62,12 +62,12 @@ public class ConsoleLogListenerTestCase {
}
// TODO: Should use ConsoleLogFormatter.ABSENCE_REPLACEMENT instead of literal '-'. See ticket 7128315.
assertEquals("0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\terror\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\twarning\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tinfo\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tdebug\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n",
- out.toString());
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\terror\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\twarning\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tinfo\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tdebug\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n",
+ out.toString());
}
private static class MyEntry implements LogEntry {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
index 4172d6d907a..fb5ee147bd8 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
@@ -2,17 +2,17 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogReaderService;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -21,7 +21,7 @@ import static org.junit.Assert.fail;
public class ConsoleLogManagerTestCase {
@Test
- public void requireThatManagerCanNotBeInstalledTwice() throws BundleException {
+ void requireThatManagerCanNotBeInstalledTwice() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -38,7 +38,7 @@ public class ConsoleLogManagerTestCase {
}
@Test
- public void requireThatManagerCanBeUninstalledTwice() throws BundleException {
+ void requireThatManagerCanBeUninstalledTwice() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -52,7 +52,7 @@ public class ConsoleLogManagerTestCase {
}
@Test
- public void requireThatLogReaderServicesAreTracked() throws BundleException {
+ void requireThatLogReaderServicesAreTracked() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
BundleContext ctx = felix.bundleContext();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
index a1610c81331..ca78bea85b4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
@@ -10,13 +10,13 @@ import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerResourceTestCase {
@Test
- public void requireThatBoundRequestHandlersAreRetainedOnActivate() {
+ void requireThatBoundRequestHandlersAreRetainedOnActivate() {
MyRequestHandler foo = new MyRequestHandler();
MyRequestHandler bar = new MyRequestHandler();
@@ -43,7 +43,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatBoundRequestHandlersAreReleasedOnTermination() {
+ void requireThatBoundRequestHandlersAreReleasedOnTermination() {
MyRequestHandler handler = new MyRequestHandler();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
@@ -62,7 +62,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatServerProvidersAreRetainedOnActivate() {
+ void requireThatServerProvidersAreRetainedOnActivate() {
MyServerProvider foo = new MyServerProvider();
MyServerProvider bar = new MyServerProvider();
@@ -80,7 +80,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatServerProvidersAreReleasedOnTermination() {
+ void requireThatServerProvidersAreReleasedOnTermination() {
MyServerProvider server = new MyServerProvider();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
index cf247040c41..458ce3200fc 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
@@ -11,14 +11,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -26,7 +26,7 @@ import static org.junit.Assert.fail;
public class ContainerShutdownTestCase {
@Test
- public void requireThatContainerBlocksTermination() {
+ void requireThatContainerBlocksTermination() {
Context ctx = Context.newInstance();
Container container = ctx.driver.newReference(URI.create("http://host/path"));
assertFalse(ctx.shutdown());
@@ -36,7 +36,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNewRequestBlocksTermination() {
+ void requireThatNewRequestBlocksTermination() {
Context ctx = Context.newPendingRequest(MyRequestHandler.newInstance());
assertFalse(ctx.shutdown());
ctx.request.release();
@@ -45,7 +45,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatOpenRequestBlocksTermination() {
+ void requireThatOpenRequestBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -58,7 +58,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponsePendingBlocksTermination() {
+ void requireThatResponsePendingBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -70,7 +70,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatOpenResponseBlocksTermination() {
+ void requireThatOpenResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -83,7 +83,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionDoesNotBlockTermination() {
+ void requireThatRequestExceptionDoesNotBlockTermination() {
Context ctx = Context.newPendingRequest(MyRequestHandler.newRequestException());
try {
ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -97,7 +97,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionWithEagerHandleResponseBlocksTermination() {
+ void requireThatRequestExceptionWithEagerHandleResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newRequestExceptionWithEagerHandleResponse();
Context ctx = Context.newPendingRequest(requestHandler);
try {
@@ -114,7 +114,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionWithEagerCloseResponseDoesNotBlockTermination() {
+ void requireThatRequestExceptionWithEagerCloseResponseDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newRequestExceptionWithEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
try {
@@ -129,7 +129,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentBlocksTermination() {
+ void requireThatNullRequestContentBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNullContent();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -142,7 +142,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentWithEagerHandleResponseBlocksTermination() {
+ void requireThatNullRequestContentWithEagerHandleResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNullContentWithEagerHandleResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -154,7 +154,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentWithEagerCloseResponseBlocksTermination() {
+ void requireThatNullRequestContentWithEagerCloseResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNulContentWithEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -166,7 +166,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteFailedDoesNotBlockTermination() {
+ void requireThatRequestContentWriteFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerFail();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -179,7 +179,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionDoesNotBlockTermination() {
+ void requireThatRequestContentWriteExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -197,7 +197,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionDoesNotForceTermination() {
+ void requireThatRequestContentWriteExceptionDoesNotForceTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -216,7 +216,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatRequestContentWriteExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -234,7 +234,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseFailedDoesNotBlockTermination() {
+ void requireThatRequestContentCloseFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerFail();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -246,7 +246,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseExceptionDoesNotBlockTermination() {
+ void requireThatRequestContentCloseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentCloseException();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -263,7 +263,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatRequestContentCloseExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentCloseException();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -280,7 +280,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestWriteCompletionBlocksTermination() {
+ void requireThatRequestWriteCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -295,7 +295,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestWriteCompletionExceptionDoesNotBlockTermination() {
+ void requireThatRequestWriteCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -315,7 +315,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestCloseCompletionBlocksTermination() {
+ void requireThatRequestCloseCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -328,7 +328,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestCloseCompletionExceptionDoesNotBlockTermination() {
+ void requireThatRequestCloseCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -346,7 +346,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullResponseContentBlocksTermination() {
+ void requireThatNullResponseContentBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newNullContent();
@@ -360,7 +360,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseExceptionDoesNotBlockTermination() {
+ void requireThatResponseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newResponseException()).close(null);
@@ -376,7 +376,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteFailedDoesNotBlockTermination() {
+ void requireThatResponseContentWriteFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newEagerFail();
@@ -390,7 +390,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseFailedDoesNotBlockTermination() {
+ void requireThatResponseContentCloseFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newEagerFail();
@@ -403,7 +403,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionDoesNotBlockTermination() {
+ void requireThatResponseContentWriteExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -423,7 +423,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionDoesNotForceTermination() {
+ void requireThatResponseContentWriteExceptionDoesNotForceTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -444,7 +444,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatResponseContentWriteExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -464,7 +464,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseExceptionDoesNotBlockTermination() {
+ void requireThatResponseContentCloseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newContentCloseException()).close(null);
@@ -480,7 +480,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatResponseContentCloseExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newContentCloseException()).close(null);
@@ -496,7 +496,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseWriteCompletionBlocksTermination() {
+ void requireThatResponseWriteCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -513,7 +513,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseWriteCompletionExceptionDoesNotBlockTermination() {
+ void requireThatResponseWriteCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -535,7 +535,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseCloseCompletionBlocksTermination() {
+ void requireThatResponseCloseCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -550,7 +550,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseCloseCompletionExceptionDoesNotBlockTermination() {
+ void requireThatResponseCloseCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
index dc1f3c7609e..2f93832b503 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
@@ -11,16 +11,16 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerSnapshotTestCase {
@Test
- public void requireThatServerHandlerCanBeResolved() {
+ void requireThatServerHandlerCanBeResolved() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://foo/*", MyRequestHandler.newInstance());
@@ -59,7 +59,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatClientHandlerCanBeResolved() {
+ void requireThatClientHandlerCanBeResolved() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.clientBindings().bind("http://foo/*", MyRequestHandler.newInstance());
@@ -89,7 +89,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatClientBindingsAreUsed() {
+ void requireThatClientBindingsAreUsed() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.clientBindings().bind("http://host/path", MyRequestHandler.newInstance());
@@ -101,7 +101,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatBindingMatchIsSetByResolveHandler() {
+ void requireThatBindingMatchIsSetByResolveHandler() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://*/*", MyRequestHandler.newInstance());
@@ -121,7 +121,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatNewRequestHasSameSnapshot() {
+ void requireThatNewRequestHasSameSnapshot() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request foo = new Request(driver, URI.create("http://host/foo"));
@@ -133,7 +133,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatActiveInjectorIsUsed() {
+ void requireThatActiveInjectorIsUsed() {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
index de22a49895f..110ea9745b6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.DeactivatedContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -16,14 +16,14 @@ import static org.junit.Assert.assertTrue;
public class ContainerTerminationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Object obj = new Object();
ContainerTermination termination = new ContainerTermination(obj);
assertSame(obj, termination.appContext());
}
@Test
- public void requireThatAppContextIsFromBuilder() {
+ void requireThatAppContextIsFromBuilder() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Object obj = new Object();
@@ -35,7 +35,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatEarlyTerminationIsNotified() {
+ void requireThatEarlyTerminationIsNotified() {
ContainerTermination termination = new ContainerTermination(null);
termination.run();
MyTask task = new MyTask();
@@ -44,7 +44,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatLaterTerminationIsNotified() {
+ void requireThatLaterTerminationIsNotified() {
ContainerTermination termination = new ContainerTermination(null);
MyTask task = new MyTask();
termination.notifyTermination(task);
@@ -54,7 +54,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatNotifyCanOnlyBeCalledOnce() {
+ void requireThatNotifyCanOnlyBeCalledOnce() {
ContainerTermination termination = new ContainerTermination(null);
termination.notifyTermination(new MyTask());
try {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
index e72b01d8b8f..d669961e728 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
@@ -4,14 +4,14 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock;
public class ContainerWatchdogTest {
@Test
- public void watchdog_counts_stale_container() {
+ void watchdog_counts_stale_container() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ManualClock clock = new ManualClock(Instant.EPOCH);
DummyMetric metric = new DummyMetric();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
index 66c92aa138a..50db994c4d3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.core;
import com.google.inject.Guice;
import com.yahoo.jdisc.application.BindingSet;
import com.yahoo.jdisc.application.BindingSetSelector;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -18,13 +18,13 @@ import static org.junit.Assert.assertTrue;
public class DefaultBindingSelectorTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
BindingSetSelector selector = Guice.createInjector().getInstance(BindingSetSelector.class);
assertTrue(selector instanceof DefaultBindingSelector);
}
@Test
- public void requireThatDefaultSetIsAlwaysSelected() {
+ void requireThatDefaultSetIsAlwaysSelected() {
DefaultBindingSelector selector = new DefaultBindingSelector();
assertEquals(BindingSet.DEFAULT, selector.select(null));
for (int i = 0; i < 69; ++i) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
index 395ddc889ae..e9aba0893f9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
@@ -1,15 +1,22 @@
package com.yahoo.jdisc.core;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.FileReader;
+import java.io.IOException;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for {@link ExportPackages}.
@@ -18,25 +25,102 @@ import static org.junit.Assert.assertTrue;
*/
public class ExportPackagesIT {
- @Rule
- public TemporaryFolder tempFolder= new TemporaryFolder();
+
+ private static final File expectedExportPackages = new File("src/test/resources" + ExportPackages.PROPERTIES_FILE);
+
+ private static final String JAR_PATH = "target/dependency/";
+
+ // This list must be kept in sync with the list in the export-packages execution in pom.xml.
+ private static final List<String> RE_EXPORTED_BUNDLES = Stream.of(
+ "guava.jar",
+ "guice-no_aop.jar",
+ "slf4j-api.jar",
+ "slf4j-jdk14.jar",
+ "jcl-over-slf4j.jar",
+ "log4j-over-slf4j.jar",
+ "annotations.jar",
+ "config-lib.jar",
+ "defaults.jar",
+ "vespajlib.jar",
+ "vespalog.jar",
+ "jaxb-api.jar",
+ "jaxb-core.jar",
+ "jaxb-impl.jar",
+ "javax.activation.jar"
+ ).map(f -> JAR_PATH + f).toList();
+
+ @TempDir
+ public static File tempFolder;
@Test
- public void export_packages_are_added_from_dependency_jars() throws Exception {
- File file = tempFolder.newFile(ExportPackages.PROPERTIES_FILE);
+ void exported_packages_are_not_changed_unintentionally() throws Exception {
+ Properties actualProperties = getPropertiesFromFile(createPropertiesFile());
+ String actualValue = actualProperties.getProperty(ExportPackages.EXPORT_PACKAGES);
+ assertNotNull(actualValue, "Missing exportPackages property in file.");
- ExportPackages.main(new String[] { file.getAbsolutePath(), "target/dependency/guice-no_aop.jar" });
- assertTrue(file.exists());
- Properties props = new Properties();
- String exportPackages;
- try (FileReader reader = new FileReader(file)) {
- props.load(reader);
- exportPackages = props.getProperty(ExportPackages.EXPORT_PACKAGES);
+ Properties expectedProperties = getPropertiesFromFile(expectedExportPackages);
+ String expectedValue = expectedProperties.getProperty(ExportPackages.EXPORT_PACKAGES);
+ assertNotNull(expectedValue, "Missing exportPackages property in file.");
+
+ Set<String> actualPackages = getPackages(actualValue);
+ Set<String> expectedPackages = getPackages(expectedValue);
+ if (!actualPackages.equals(expectedPackages)) {
+ StringBuilder message = getDiff(actualPackages, expectedPackages);
+ message.append("\n\nIf this test fails due to an intentional change in exported packages, run the following command:\n")
+ .append("$ cp jdisc_core/target/classes/exportPackages.properties jdisc_core/src/test/resources/")
+ .append("\n\nNote that removing exported packages usually requires a new major version of Vespa.\n");
+ fail(message.toString());
}
- assertNotNull(exportPackages);
+ }
- assertTrue(exportPackages.contains("com.google.inject"));
+ private static StringBuilder getDiff(Set<String> actual, Set<String> expected) {
+ StringBuilder sb = new StringBuilder();
+ Set<String> onlyInActual = onlyInSet1(actual, expected);
+ if (! onlyInActual.isEmpty()) {
+ sb.append("\nexportPackages.properties contained ")
+ .append(onlyInActual.size())
+ .append(" unexpected packages:\n")
+ .append(onlyInActual.stream().collect(Collectors.joining(",\n ", " [", "]")));
+ }
+
+ Set<String> onlyInExpected = onlyInSet1(expected, actual);
+ if (! onlyInExpected.isEmpty()) {
+ sb.append("\nexportPackages.properties did not contain ")
+ .append(onlyInExpected.size())
+ .append(" expected packages:\n")
+ .append(onlyInExpected.stream().collect(Collectors.joining(",\n ", " [", "]")));
+ }
+ return sb;
+ }
+
+ // Returns a sorted set for readability.
+ private static Set<String> onlyInSet1(Set<String> set1, Set<String> set2) {
+ return set1.stream()
+ .filter(s -> ! set2.contains(s))
+ .collect(Collectors.toCollection(TreeSet::new));
+ }
+
+ private static Set<String> getPackages(String propertyValue) {
+ return Arrays.stream(propertyValue.split(","))
+ .map(String::trim)
+ .filter(s -> ! s.isEmpty())
+ .collect(Collectors.toSet());
+ }
+
+ private static Properties getPropertiesFromFile(File file) throws IOException {
+ Properties properties = new Properties();
+ try (FileReader reader = new FileReader(file)) {
+ properties.load(reader);
+ }
+ return properties;
+ }
+ private static File createPropertiesFile() throws IOException {
+ File file = Paths.get(tempFolder.toString(), ExportPackages.PROPERTIES_FILE).toFile();
+ String[] args = Stream.concat(Stream.of(file.getAbsolutePath()),
+ RE_EXPORTED_BUNDLES.stream()).toArray(String[]::new);
+ ExportPackages.main(args);
+ return file;
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesTestCase.java
deleted file mode 100644
index 225ecd4a242..00000000000
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesTestCase.java
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.jdisc.core;
-
-import org.junit.Test;
-
-import java.io.File;
-import java.io.FileReader;
-import java.util.Properties;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Simon Thoresen Hult
- */
-public class ExportPackagesTestCase {
-
- @Test
- public void requireThatPropertiesAreWritten() throws Exception {
- File file = new File("target", ExportPackages.PROPERTIES_FILE);
- file.deleteOnExit();
- ExportPackages.main(new String[] { file.getAbsolutePath() });
- assertTrue(file.exists());
- Properties props = new Properties();
- try (FileReader reader = new FileReader(file)) {
- props.load(reader);
- assertNotNull(props.getProperty(ExportPackages.EXPORT_PACKAGES));
- }
- }
-}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
index fb663afa23f..d1cb59dbc30 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleException;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -14,20 +14,20 @@ import static org.junit.Assert.fail;
public class FelixFrameworkTestCase {
@Test
- public void requireThatLifecycleWorks() throws BundleException {
+ void requireThatLifecycleWorks() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
felix.stop();
}
@Test
- public void requireThatStopWithoutStartDoesNotThrowException() throws BundleException {
+ void requireThatStopWithoutStartDoesNotThrowException() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.stop();
}
@Test
- public void requireThatInstallCanThrowException() throws BundleException {
+ void requireThatInstallCanThrowException() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
try {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java
index 490470b4fdf..6c488f8b735 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Constants;
import java.util.Arrays;
@@ -9,9 +9,9 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class FelixParamsTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FelixParams params = new FelixParams();
params.setCachePath("foo");
assertEquals("foo", params.getCachePath());
@@ -28,7 +28,7 @@ public class FelixParamsTestCase {
}
@Test
- public void requireThatSystemPackagesAreNotReplaced() {
+ void requireThatSystemPackagesAreNotReplaced() {
String systemPackages = ExportPackages.getSystemPackages();
FelixParams params = new FelixParams(systemPackages);
@@ -46,7 +46,7 @@ public class FelixParamsTestCase {
}
@Test
- public void requireThatExportsAreIncludedInConfig() {
+ void requireThatExportsAreIncludedInConfig() {
FelixParams params = new FelixParams();
Map<String, String> config = params.toConfig();
assertNotNull(config);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
index 7c07623814e..626cae67c41 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
@@ -1,12 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import java.time.Instant;
-import java.util.Arrays;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.logging.Handler;
@@ -14,11 +13,11 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -26,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class OsgiLogHandlerTestCase {
@Test
- public void requireThatLogRecordsArePublishedToLogService() {
+ void requireThatLogRecordsArePublishedToLogService() {
MyLogService logService = new MyLogService();
Logger log = newLogger(logService);
@@ -43,7 +42,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatStadardLogLevelsAreConverted() {
+ void requireThatStadardLogLevelsAreConverted() {
assertLogLevel(LogService.LOG_ERROR, Level.SEVERE);
assertLogLevel(LogService.LOG_WARNING, Level.WARNING);
assertLogLevel(LogService.LOG_INFO, Level.INFO);
@@ -54,7 +53,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatCustomLogLevelsAreConverted() {
+ void requireThatCustomLogLevelsAreConverted() {
for (int i = Level.ALL.intValue() - 69; i < Level.OFF.intValue() + 69; ++i) {
int expectedLevel;
if (i >= Level.SEVERE.intValue()) {
@@ -71,7 +70,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatJdk14PropertiesAreAvailableThroughServiceReference() {
+ void requireThatJdk14PropertiesAreAvailableThroughServiceReference() {
MyLogService logService = new MyLogService();
Logger log = newLogger(logService);
@@ -93,19 +92,19 @@ public class OsgiLogHandlerTestCase {
ServiceReference<?> ref = logService.lastServiceReference;
assertNotNull(ref);
- assertTrue(Arrays.equals(new String[] { "LEVEL",
- "LOGGER_NAME",
- "MESSAGE",
- "MILLIS",
- "PARAMETERS",
- "RESOURCE_BUNDLE",
- "RESOURCE_BUNDLE_NAME",
- "SEQUENCE_NUMBER",
- "SOURCE_CLASS_NAME",
- "SOURCE_METHOD_NAME",
- "THREAD_ID",
- "THROWN" },
- ref.getPropertyKeys()));
+ assertArrayEquals(new String[]{"LEVEL",
+ "LOGGER_NAME",
+ "MESSAGE",
+ "MILLIS",
+ "PARAMETERS",
+ "RESOURCE_BUNDLE",
+ "RESOURCE_BUNDLE_NAME",
+ "SEQUENCE_NUMBER",
+ "SOURCE_CLASS_NAME",
+ "SOURCE_METHOD_NAME",
+ "THREAD_ID",
+ "THROWN"},
+ ref.getPropertyKeys());
assertEquals(Level.INFO, ref.getProperty("LEVEL"));
assertEquals("loggerName", ref.getProperty("LOGGER_NAME"));
assertEquals("message", ref.getProperty("MESSAGE"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
index be4c0ada514..7b5af97ca13 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
@@ -13,9 +13,9 @@ import org.osgi.service.log.LogService;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertSame;
public class OsgiLogManagerTestCase {
@Test
- public void requireThatAllLogMethodsAreImplemented() throws BundleException {
+ void requireThatAllLogMethodsAreImplemented() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -55,7 +55,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatLogManagerWritesToAllRegisteredLogServices() throws BundleException {
+ void requireThatLogManagerWritesToAllRegisteredLogServices() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -122,7 +122,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatRootLoggerModificationCanBeDisabled() throws BundleException {
+ void requireThatRootLoggerModificationCanBeDisabled() throws BundleException {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.WARNING);
@@ -134,7 +134,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatRootLoggerLevelIsModifiedIfNoLoggerConfigIsGiven() {
+ void requireThatRootLoggerLevelIsModifiedIfNoLoggerConfigIsGiven() {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.WARNING);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
index 15377d7ae37..bfdaad9450f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -20,12 +20,12 @@ import static org.junit.Assert.fail;
public class OsgiLogServiceTestCase {
@Test
- public void requireThatLogServiceIsRegistered() throws BundleException, InterruptedException {
+ void requireThatLogServiceIsRegistered() throws BundleException, InterruptedException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
- ServiceTracker<?,?> logs = newTracker(osgi, LogService.class);
- ServiceTracker<?,?> logReaders = newTracker(osgi, LogReaderService.class);
+ ServiceTracker<?, ?> logs = newTracker(osgi, LogService.class);
+ ServiceTracker<?, ?> logReaders = newTracker(osgi, LogReaderService.class);
assertEquals(1, logs.getTrackingCount());
assertEquals(1, logReaders.getTrackingCount());
@@ -38,7 +38,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotBeStartedTwice() throws BundleException {
+ void requireThatLogServiceCanNotBeStartedTwice() throws BundleException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
@@ -57,7 +57,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotBeStoppedTwice() throws BundleException {
+ void requireThatLogServiceCanNotBeStoppedTwice() throws BundleException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
@@ -77,7 +77,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatUnstartedLogServiceCanNotBeStopped() throws BundleException {
+ void requireThatUnstartedLogServiceCanNotBeStopped() throws BundleException {
try {
new OsgiLogService().stop();
fail();
@@ -87,7 +87,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotStartWithoutBundleContext() throws BundleException {
+ void requireThatLogServiceCanNotStartWithoutBundleContext() throws BundleException {
try {
new OsgiLogService().start(null);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java
index 163111c641d..cd963caa8d2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedList;
@@ -11,9 +11,9 @@ import java.util.Queue;
import static com.yahoo.jdisc.core.ScheduledQueue.MILLIS_PER_SLOT;
import static com.yahoo.jdisc.core.ScheduledQueue.NUM_SLOTS;
import static com.yahoo.jdisc.core.ScheduledQueue.NUM_SLOTS_UNDILATED;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,21 +21,21 @@ import static org.junit.Assert.fail;
public class ScheduledQueueTestCase {
@Test
- public void requireThatSlotMaskPreventsOverflow() {
+ void requireThatSlotMaskPreventsOverflow() {
for (int slot = 0; slot < NUM_SLOTS * 2; ++slot) {
assertTrue((slot & ScheduledQueue.SLOT_MASK) < NUM_SLOTS);
}
}
@Test
- public void requireThatIterShiftDiscardsSlotBits() {
+ void requireThatIterShiftDiscardsSlotBits() {
for (int slot = 0; slot < NUM_SLOTS * 2; ++slot) {
assertEquals(slot / NUM_SLOTS, slot >> ScheduledQueue.ITER_SHIFT);
}
}
@Test
- public void requireThatNewEntryDoesNotAcceptNull() {
+ void requireThatNewEntryDoesNotAcceptNull() {
ScheduledQueue queue = new ScheduledQueue(0);
try {
queue.newEntry(null);
@@ -46,7 +46,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeScheduled() {
+ void requireThatEntriesCanBeScheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -57,7 +57,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeRescheduled() {
+ void requireThatEntriesCanBeRescheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -69,7 +69,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeUnscheduled() {
+ void requireThatEntriesCanBeUnscheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -80,7 +80,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatDrainToOnlyDrainsExpiredEntries() {
+ void requireThatDrainToOnlyDrainsExpiredEntries() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, 100);
Object bar = scheduleAt(queue, 300);
@@ -93,7 +93,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesDoNotExpireMoreThanOnce() {
+ void requireThatEntriesDoNotExpireMoreThanOnce() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, NUM_SLOTS * MILLIS_PER_SLOT + 50);
@@ -108,7 +108,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatNegativeScheduleTranslatesToNow() {
+ void requireThatNegativeScheduleTranslatesToNow() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, -100);
@@ -116,7 +116,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatDrainToPerformsTimeDilationWhenOverloaded() {
+ void requireThatDrainToPerformsTimeDilationWhenOverloaded() {
ScheduledQueue queue = new ScheduledQueue(0);
List<Object> payloads = new LinkedList<>();
for (int i = 1; i <= NUM_SLOTS_UNDILATED + 1; ++i) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
index 52e25877402..dc6d3b30cb2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.jdisc.core;
import com.google.inject.Guice;
import com.yahoo.jdisc.Timer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertTrue;
public class SystemTimerTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
Timer timer = Guice.createInjector().getInstance(Timer.class);
assertTrue(timer instanceof SystemTimer);
}
@Test
- public void requireThatSystemTimerIsSane() {
+ void requireThatSystemTimerIsSane() {
long before = System.currentTimeMillis();
long millis = new SystemTimer().currentTimeMillis();
long after = System.currentTimeMillis();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
index 75ebad12158..0308abebd8a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
@@ -19,7 +19,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -28,13 +28,13 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -44,35 +44,35 @@ public class TimeoutManagerImplTestCase {
private static final String REQUEST_URI = "http://host/path";
@Test
- public void requireThatDefaultIsNoTimeout() {
+ void requireThatDefaultIsNoTimeout() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertNull(ctx.dispatchRequest(null, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutCanBeSetByServerProvider() {
+ void requireThatTimeoutCanBeSetByServerProvider() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertEquals(Long.valueOf(69), ctx.dispatchRequest(69L, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutCanBeSetByRequestHandler() {
+ void requireThatTimeoutCanBeSetByRequestHandler() {
Context ctx = new Context(MyRequestHandler.newTimeoutWithEagerResponse(69));
assertEquals(Long.valueOf(69), ctx.dispatchRequest(null, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutRequestHandlerTimeoutHasPrecedence() {
+ void requireThatTimeoutRequestHandlerTimeoutHasPrecedence() {
Context ctx = new Context(MyRequestHandler.newTimeoutWithEagerResponse(6));
assertEquals(Long.valueOf(6), ctx.dispatchRequest(9L, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatResponseCancelsTimeout() throws InterruptedException {
+ void requireThatResponseCancelsTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertEquals(Response.Status.OK, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
assertEquals(Response.Status.OK, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -80,7 +80,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNullRequestContentCanTimeout() throws InterruptedException {
+ void requireThatNullRequestContentCanTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newNullContent());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -88,7 +88,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterRequestDenied() throws InterruptedException {
+ void requireThatTimeoutWorksAfterRequestDenied() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newFirstRequestDenied());
try {
ctx.dispatchRequest(null, MyResponseHandler.newInstance());
@@ -101,7 +101,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseDenied() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseDenied() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newResponseDenied()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -109,7 +109,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseThrowsException() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseThrowsException() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newThrowException()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -117,7 +117,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseInterruptsThread() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseInterruptsThread() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInterruptThread()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -125,7 +125,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutOccursInOrder() throws InterruptedException {
+ void requireThatTimeoutOccursInOrder() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
MyResponseHandler foo = MyResponseHandler.newInstance();
ctx.dispatchRequest(300L, foo);
@@ -152,7 +152,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatResponseHandlerIsWellBehavedAfterTimeout() throws InterruptedException {
+ void requireThatResponseHandlerIsWellBehavedAfterTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -172,11 +172,11 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatManagedHandlerForwardsAllCalls() throws InterruptedException {
+ void requireThatManagedHandlerForwardsAllCalls() throws InterruptedException {
Request request = NonWorkingRequest.newInstance(REQUEST_URI);
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
TimeoutManagerImpl timeoutManager = new TimeoutManagerImpl(Executors.defaultThreadFactory(),
- new SystemTimer());
+ new SystemTimer());
RequestHandler managedHandler = timeoutManager.manageHandler(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -219,7 +219,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutOccursAtExpectedTime() throws InterruptedException {
+ void requireThatTimeoutOccursAtExpectedTime() throws InterruptedException {
final Context ctx = new Context(MyRequestHandler.newInstance());
final MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -251,7 +251,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatQueueEntryIsRemovedWhenResponseHandlerIsCalledBeforeTimeout() {
+ void requireThatQueueEntryIsRemovedWhenResponseHandlerIsCalledBeforeTimeout() {
Context ctx = new Context(MyRequestHandler.newInstance());
ctx.dispatchRequest(69L, MyResponseHandler.newInstance());
assertTrue(ctx.awaitQueueSize(1, 600, TimeUnit.SECONDS));
@@ -261,7 +261,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfTimeoutIsNull() {
+ void requireThatNoEntryIsMadeIfTimeoutIsNull() {
Context ctx = new Context(MyRequestHandler.newInstance());
ctx.dispatchRequest(null, MyResponseHandler.newInstance());
assertFalse(ctx.awaitQueueSize(1, 100, TimeUnit.MILLISECONDS));
@@ -271,7 +271,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfHandleRequestCallsHandleResponse() {
+ void requireThatNoEntryIsMadeIfHandleRequestCallsHandleResponse() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
ctx.dispatchRequest(69L, MyResponseHandler.newInstance());
assertFalse(ctx.awaitQueueSize(1, 100, TimeUnit.MILLISECONDS));
@@ -280,7 +280,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfTimeoutHandlerHasBeenSet() {
+ void requireThatNoEntryIsMadeIfTimeoutHandlerHasBeenSet() {
final Context ctx = new Context(MyRequestHandler.newInstance());
new RequestDispatch() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java
index 4951ff72ffd..7578e3213dd 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -11,8 +11,8 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -21,15 +21,15 @@ import static org.junit.Assert.assertTrue;
public class AbstractContentOutputStreamTestCase {
@Test
- public void requireThatStreamCanBeWrittenTo() throws IOException {
+ void requireThatStreamCanBeWrittenTo() throws IOException {
MyOutputStream out = new MyOutputStream();
int len = 2 * AbstractContentOutputStream.BUFFERSIZE;
for (int i = 0; i < len; ++i) {
out.write(69);
- out.write(new byte[] { });
- out.write(new byte[] { 6, 9 });
- out.write(new byte[] { 6, 69, 9 }, 1, 0); // zero length
- out.write(new byte[] { 6, 69, 9 }, 1, 1);
+ out.write(new byte[]{});
+ out.write(new byte[]{6, 9});
+ out.write(new byte[]{6, 69, 9}, 1, 0); // zero length
+ out.write(new byte[]{6, 69, 9}, 1, 1);
}
out.close();
@@ -45,7 +45,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatBigBuffersAreWrittenInOrder() throws IOException {
+ void requireThatBigBuffersAreWrittenInOrder() throws IOException {
MyOutputStream out = new MyOutputStream();
out.write(6);
out.write(new byte[2 * AbstractContentOutputStream.BUFFERSIZE]);
@@ -62,7 +62,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatEmptyBuffersAreNotFlushed() throws Exception {
+ void requireThatEmptyBuffersAreNotFlushed() throws Exception {
MyOutputStream out = new MyOutputStream();
out.close();
assertTrue(out.writes.isEmpty());
@@ -70,9 +70,9 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatNoExcessiveBytesAreWritten() throws Exception {
+ void requireThatNoExcessiveBytesAreWritten() throws Exception {
MyOutputStream out = new MyOutputStream();
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
out.close();
InputStream in = out.toInputStream();
@@ -85,7 +85,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatWrittenArraysAreCopied() throws Exception {
+ void requireThatWrittenArraysAreCopied() throws Exception {
MyOutputStream out = new MyOutputStream();
byte[] buf = new byte[1];
for (byte b = 0; b < 127; ++b) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
index 6b5382b8bba..14ff6d87555 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
@@ -6,18 +6,18 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.NonWorkingRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -28,7 +28,7 @@ public class AbstractRequestHandlerTestCase {
private static final int NUM_REQUESTS = 666;
@Test
- public void requireThatHandleTimeoutIsImplemented() throws Exception {
+ void requireThatHandleTimeoutIsImplemented() throws Exception {
FutureResponse handler = new FutureResponse();
new AbstractRequestHandler() {
@@ -43,7 +43,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatHelloWorldWorks() throws InterruptedException {
+ void requireThatHelloWorldWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new HelloWorldHandler());
@@ -62,7 +62,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatEchoWorks() throws InterruptedException {
+ void requireThatEchoWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new EchoHandler());
@@ -83,7 +83,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatForwardWorks() throws InterruptedException {
+ void requireThatForwardWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new ForwardHandler());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
index 7d76e9de7e2..03fd4368be9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -18,14 +18,14 @@ import static org.junit.Assert.fail;
public class BindingNotFoundTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://host/path");
BindingNotFoundException e = new BindingNotFoundException(uri);
assertEquals(uri, e.uri());
}
@Test
- public void requireThatBindingNotFoundIsThrown() {
+ void requireThatBindingNotFoundIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java
index 651c24648a1..96c6edbdcf5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertTrue;
public class BlockingContentWriterTestCase {
@Test
- public void requireThatContentChannelIsNotNull() {
+ void requireThatContentChannelIsNotNull() {
try {
new BlockingContentWriter(null);
fail();
@@ -27,7 +27,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteDeliversBuffer() throws InterruptedException {
+ void requireThatWriteDeliversBuffer() throws InterruptedException {
MyContent content = MyContent.newNonBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
ByteBuffer buf = ByteBuffer.allocate(69);
@@ -36,7 +36,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteIsBlocking() throws Exception {
+ void requireThatWriteIsBlocking() throws Exception {
MyContent content = MyContent.newBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
FutureTask<Boolean> task = new FutureTask<>(new WriteTask(writer, ByteBuffer.allocate(69)));
@@ -53,7 +53,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteExceptionIsThrown() throws Exception {
+ void requireThatWriteExceptionIsThrown() throws Exception {
Throwable throwMe = new RuntimeException();
try {
new BlockingContentWriter(MyContent.newFailedContent(throwMe)).write(ByteBuffer.allocate(69));
@@ -76,7 +76,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatCloseIsBlocking() throws Exception {
+ void requireThatCloseIsBlocking() throws Exception {
MyContent content = MyContent.newBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
FutureTask<Boolean> task = new FutureTask<>(new CloseTask(writer));
@@ -93,7 +93,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatCloseExceptionIsThrown() throws Exception {
+ void requireThatCloseExceptionIsThrown() throws Exception {
Throwable throwMe = new RuntimeException();
try {
new BlockingContentWriter(MyContent.newFailedContent(throwMe)).close();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java
index 705d6d008b0..3824c0eb928 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.LinkedList;
@@ -9,11 +9,11 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class BufferedContentChannelTestCase {
@Test
- public void requireThatIsConnectedWorks() {
+ void requireThatIsConnectedWorks() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
@@ -30,7 +30,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatConnectToNullThrowsException() {
+ void requireThatConnectToNullThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
try {
content.connectTo(null);
@@ -41,7 +41,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterCloseThrowsException() {
+ void requireThatWriteAfterCloseThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.close(null);
try {
@@ -53,7 +53,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterCloseThrowsException() {
+ void requireThatCloseAfterCloseThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.close(null);
try {
@@ -65,7 +65,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatConnecToAfterConnecToThrowsException() {
+ void requireThatConnecToAfterConnecToThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(new MyContent());
try {
@@ -77,7 +77,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteBeforeConnectToWritesToTarget() {
+ void requireThatWriteBeforeConnectToWritesToTarget() {
BufferedContentChannel content = new BufferedContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
MyCompletion completion = new MyCompletion();
@@ -89,7 +89,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterConnectToWritesToTarget() {
+ void requireThatWriteAfterConnectToWritesToTarget() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(target);
@@ -101,7 +101,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseBeforeConnectToClosesTarget() {
+ void requireThatCloseBeforeConnectToClosesTarget() {
BufferedContentChannel content = new BufferedContentChannel();
MyCompletion completion = new MyCompletion();
content.close(completion);
@@ -112,7 +112,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterConnectToClosesTarget() {
+ void requireThatCloseAfterConnectToClosesTarget() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(target);
@@ -123,7 +123,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatIsConnectedIsTrueWhenConnectedBeforeClose() {
+ void requireThatIsConnectedIsTrueWhenConnectedBeforeClose() {
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
content.connectTo(new MyContent());
@@ -133,7 +133,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatIsConnectedIsTrueWhenClosedBeforeConnected() {
+ void requireThatIsConnectedIsTrueWhenClosedBeforeConnected() {
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
content.close(null);
@@ -143,7 +143,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatContentIsThreadSafe() throws Exception {
+ void requireThatContentIsThreadSafe() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(101);
for (int run = 0; run < 69; ++run) {
List<ByteBuffer> bufs = new LinkedList<>();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
index b11afacb518..6e5ad50f447 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
@@ -5,12 +5,12 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class CallableRequestDispatchTestCase {
@Test
- public void requireThatDispatchIsCalled() throws Exception {
+ void requireThatDispatchIsCalled() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
index bb17bb9bc41..ff953fe0384 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertSame;
public class CallableResponseDispatchTestCase {
@Test
- public void requireThatDispatchIsCalled() throws Exception {
+ void requireThatDispatchIsCalled() throws Exception {
final Response response = new Response(Response.Status.OK);
FutureResponse handler = new FutureResponse();
new CallableResponseDispatch(handler) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java
index f90251bc16e..30169699077 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Future;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertTrue;
public class ContentInputStreamTestCase {
@Test
- public void requireThatContentInputStreamExtendsUnsafeContentInputStream() {
+ void requireThatContentInputStreamExtendsUnsafeContentInputStream() {
assertTrue(UnsafeContentInputStream.class.isAssignableFrom(ContentInputStream.class));
}
@Test
@SuppressWarnings("FinalizeCalledExplicitly")
- public void requireThatFinalizerClosesStream() throws Throwable {
+ void requireThatFinalizerClosesStream() throws Throwable {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java
index 2cdc0e1256f..3f97fe014e6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -18,15 +18,15 @@ import static org.junit.Assert.fail;
public class FastContentOutputStreamTestCase {
@Test
- public void requireThatNullConstructorArgumentThrows() {
+ void requireThatNullConstructorArgumentThrows() {
try {
- new FastContentOutputStream((ContentChannel)null);
+ new FastContentOutputStream((ContentChannel) null);
fail();
} catch (NullPointerException e) {
assertEquals("out", e.getMessage());
}
try {
- new FastContentOutputStream((FastContentWriter)null);
+ new FastContentOutputStream((FastContentWriter) null);
fail();
} catch (NullPointerException e) {
assertEquals("out", e.getMessage());
@@ -34,11 +34,11 @@ public class FastContentOutputStreamTestCase {
}
@Test
- public void requireThatAllMethodsDelegateToWriter() throws Exception {
+ void requireThatAllMethodsDelegateToWriter() throws Exception {
FastContentWriter writer = Mockito.mock(FastContentWriter.class);
FastContentOutputStream out = new FastContentOutputStream(writer);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
out.flush();
Mockito.verify(writer).write(Mockito.any(ByteBuffer.class));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java
index 45bc230896f..4e0b989db74 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
@@ -15,14 +15,14 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -30,7 +30,7 @@ import static org.junit.Assert.assertArrayEquals;
public class FastContentWriterTestCase {
@Test
- public void requireThatContentCanBeWritten() throws ExecutionException, InterruptedException {
+ void requireThatContentCanBeWritten() throws ExecutionException, InterruptedException {
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -50,7 +50,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatStringsAreUtf8Encoded() {
+ void requireThatStringsAreUtf8Encoded() {
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -65,7 +65,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatCancelThrowsUnsupportedOperation() {
+ void requireThatCancelThrowsUnsupportedOperation() {
try {
new FastContentWriter(Mockito.mock(ContentChannel.class)).cancel(true);
fail();
@@ -75,7 +75,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatCancelIsAlwaysFalse() {
+ void requireThatCancelIsAlwaysFalse() {
FastContentWriter writer = new FastContentWriter(Mockito.mock(ContentChannel.class));
assertFalse(writer.isCancelled());
try {
@@ -88,11 +88,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatGetThrowsTimeoutUntilCloseCompletionHandlerIsCalled() throws Exception {
+ void requireThatGetThrowsTimeoutUntilCloseCompletionHandlerIsCalled() throws Exception {
ReadableContentChannel buf = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(buf);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
assertFalse(out.isDone());
try {
out.get(100, TimeUnit.MILLISECONDS);
@@ -126,11 +126,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatSyncWriteExceptionFailsFuture() throws InterruptedException {
+ void requireThatSyncWriteExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ContentChannel content = Mockito.mock(ContentChannel.class);
Mockito.doThrow(expected)
- .when(content).write(Mockito.any(ByteBuffer.class), Mockito.any(CompletionHandler.class));
+ .when(content).write(Mockito.any(ByteBuffer.class), Mockito.any(CompletionHandler.class));
FastContentWriter out = new FastContentWriter(content);
try {
out.write("foo");
@@ -147,11 +147,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatSyncCloseExceptionFailsFuture() throws InterruptedException {
+ void requireThatSyncCloseExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ContentChannel content = Mockito.mock(ContentChannel.class);
Mockito.doThrow(expected)
- .when(content).close(Mockito.any(CompletionHandler.class));
+ .when(content).close(Mockito.any(CompletionHandler.class));
FastContentWriter out = new FastContentWriter(content);
try {
out.close();
@@ -168,7 +168,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatAsyncExceptionFailsFuture() throws InterruptedException {
+ void requireThatAsyncExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -183,13 +183,13 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatWriterCanBeListenedTo() throws InterruptedException {
+ void requireThatWriterCanBeListenedTo() throws InterruptedException {
ReadableContentChannel buf = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(buf);
RunnableLatch listener = new RunnableLatch();
out.addListener(listener, Runnable::run);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNotNull(buf.read());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
@@ -200,7 +200,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatWriterIsThreadSafe() throws Exception {
+ void requireThatWriterIsThreadSafe() throws Exception {
final CountDownLatch latch = new CountDownLatch(2);
final ReadableContentChannel content = new ReadableContentChannel();
Future<Integer> read = Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
@@ -235,6 +235,6 @@ public class FastContentWriterTestCase {
}
});
assertEquals(read.get(600, TimeUnit.SECONDS),
- write.get(600, TimeUnit.SECONDS));
+ write.get(600, TimeUnit.SECONDS));
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
index ef63b200b5f..fe4b329ba9d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertSame;
public class FutureCompletionTestCase {
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isCancelled());
try {
@@ -38,7 +38,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletedReturnsTrue() throws Exception {
+ void requireThatCompletedReturnsTrue() throws Exception {
FutureCompletion future = new FutureCompletion();
try {
future.get(0, TimeUnit.MILLISECONDS);
@@ -52,7 +52,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenCompleted() {
+ void requireThatCompletionIsDoneWhenCompleted() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isDone());
future.completed();
@@ -60,7 +60,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenFailed() {
+ void requireThatCompletionIsDoneWhenFailed() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isDone());
future.failed(new Throwable());
@@ -68,7 +68,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatFailedCauseIsRethrown() throws Exception {
+ void requireThatFailedCauseIsRethrown() throws Exception {
FutureCompletion future = new FutureCompletion();
Throwable t = new Throwable();
future.failed(t);
@@ -87,7 +87,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionCanBeListenedTo() throws InterruptedException {
+ void requireThatCompletionCanBeListenedTo() throws InterruptedException {
FutureCompletion completion = new FutureCompletion();
RunnableLatch listener = new RunnableLatch();
completion.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java
index 1aa78a16dfc..16c6b394426 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
@@ -10,10 +10,10 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -23,13 +23,17 @@ public class FutureConjunctionTestCase {
private final ExecutorService executor = Executors.newCachedThreadPool();
@Test
- public void requireThatAllFuturesAreWaitedFor() throws Exception {
+ void requireThatAllFuturesAreWaitedFor() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
FutureConjunction future = new FutureConjunction();
CompletableFuture<Boolean> cf = new CompletableFuture<>();
cf.completeAsync(() -> {
- try { return latch.await(600, TimeUnit.SECONDS); }
- catch (InterruptedException e) { return false; }
+ try {
+ return latch.await(600, TimeUnit.SECONDS);
+ }
+ catch (InterruptedException e) {
+ return false;
+ }
}, executor);
future.addOperand(cf);
try {
@@ -43,7 +47,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatGetReturnValueIsAConjunction() throws Exception {
+ void requireThatGetReturnValueIsAConjunction() throws Exception {
assertTrue(tryGet(true));
assertTrue(tryGet(true, true));
assertTrue(tryGet(true, true, true));
@@ -60,7 +64,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatIsDoneReturnValueIsAConjunction() {
+ void requireThatIsDoneReturnValueIsAConjunction() {
assertTrue(tryIsDone(true));
assertTrue(tryIsDone(true, true));
assertTrue(tryIsDone(true, true, true));
@@ -77,7 +81,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatCancelReturnValueIsAConjuction() {
+ void requireThatCancelReturnValueIsAConjuction() {
assertTrue(tryCancel(true));
assertTrue(tryCancel(true, true));
assertTrue(tryCancel(true, true, true));
@@ -94,7 +98,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatIsCancelledReturnValueIsAConjuction() {
+ void requireThatIsCancelledReturnValueIsAConjuction() {
assertTrue(tryIsCancelled(true));
assertTrue(tryIsCancelled(true, true));
assertTrue(tryIsCancelled(true, true, true));
@@ -111,7 +115,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatConjunctionCanBeListenedTo() throws InterruptedException {
+ void requireThatConjunctionCanBeListenedTo() throws InterruptedException {
FutureConjunction conjunction = new FutureConjunction();
RunnableLatch listener = new RunnableLatch();
conjunction.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
index 398f288e307..09f6db882fb 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.test.NonWorkingContentChannel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertSame;
public class FutureResponseTestCase {
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
FutureResponse future = new FutureResponse();
assertFalse(future.isCancelled());
try {
@@ -39,7 +39,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenHandlerIsCalled() {
+ void requireThatCompletionIsDoneWhenHandlerIsCalled() {
FutureResponse future = new FutureResponse();
assertFalse(future.isDone());
future.handleResponse(new Response(69));
@@ -47,7 +47,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseBecomesAvailable() throws Exception {
+ void requireThatResponseBecomesAvailable() throws Exception {
FutureResponse future = new FutureResponse();
try {
future.get(0, TimeUnit.MILLISECONDS);
@@ -61,7 +61,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseContentIsReturnedToCaller() throws Exception {
+ void requireThatResponseContentIsReturnedToCaller() throws Exception {
ContentChannel content = new NonWorkingContentChannel();
FutureResponse future = new FutureResponse(content);
Response response = new Response(Response.Status.OK);
@@ -69,7 +69,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseCanBeListenedTo() throws InterruptedException {
+ void requireThatResponseCanBeListenedTo() throws InterruptedException {
FutureResponse response = new FutureResponse();
RunnableLatch listener = new RunnableLatch();
response.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
index 598d21b94ea..8e18ab01ae3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class NullContentTestCase {
@Test
- public void requireThatWriteThrowsException() {
+ void requireThatWriteThrowsException() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
try {
NullContent.INSTANCE.write(ByteBuffer.allocate(69), completion);
@@ -26,7 +26,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatWriteEmptyDoesNotThrowException() {
+ void requireThatWriteEmptyDoesNotThrowException() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
NullContent.INSTANCE.write(ByteBuffer.allocate(0), completion);
Mockito.verify(completion).completed();
@@ -34,7 +34,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatCloseCallsCompletion() {
+ void requireThatCloseCallsCompletion() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
NullContent.INSTANCE.close(completion);
Mockito.verify(completion).completed();
@@ -42,7 +42,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatCloseWithoutCompletionDoesNotThrow() {
+ void requireThatCloseWithoutCompletionDoesNotThrow() {
NullContent.INSTANCE.close(null);
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java
index 385cd4015b9..77da00bfa89 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Iterator;
@@ -10,12 +10,12 @@ import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertSame;
public class ReadableContentChannelTestCase {
@Test
- public void requireThatWriteNullThrowsException() {
+ void requireThatWriteNullThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
try {
content.write(null, new MyCompletion());
@@ -34,7 +34,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterCloseThrowsException() {
+ void requireThatWriteAfterCloseThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
try {
@@ -46,7 +46,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterFailedThrowsException() {
+ void requireThatWriteAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -58,7 +58,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterCloseThrowsException() {
+ void requireThatCloseAfterCloseThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
try {
@@ -70,7 +70,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterFailedThrowsException() {
+ void requireThatCloseAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -82,7 +82,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedAfterFailedThrowsException() {
+ void requireThatFailedAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -94,7 +94,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatIteratorDoesNotSupportRemove() {
+ void requireThatIteratorDoesNotSupportRemove() {
try {
new ReadableContentChannel().iterator().remove();
fail();
@@ -104,7 +104,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBufferCanBeRead() {
+ void requireThatWrittenBufferCanBeRead() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
content.write(buf, null);
@@ -112,7 +112,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBuffersAreReadInOrder() {
+ void requireThatWrittenBuffersAreReadInOrder() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer foo = ByteBuffer.allocate(69);
content.write(foo, null);
@@ -124,7 +124,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadAfterCloseIsNull() {
+ void requireThatReadAfterCloseIsNull() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
assertNull(content.read());
@@ -132,7 +132,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBufferCanBeReadByIterator() {
+ void requireThatWrittenBufferCanBeReadByIterator() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer foo = ByteBuffer.allocate(69);
content.write(foo, null);
@@ -155,7 +155,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadAfterFailedIsNull() {
+ void requireThatReadAfterFailedIsNull() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
assertNull(content.read());
@@ -163,7 +163,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadCallsCompletion() {
+ void requireThatReadCallsCompletion() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
MyCompletion completion = new MyCompletion();
@@ -180,7 +180,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadWaitsForWrite() throws Exception {
+ void requireThatReadWaitsForWrite() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> readBuf = executor.submit(new ReadTask(content));
@@ -196,7 +196,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseNotifiesRead() throws Exception {
+ void requireThatCloseNotifiesRead() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> buf = executor.submit(new ReadTask(content));
@@ -211,7 +211,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedNotifiesRead() throws Exception {
+ void requireThatFailedNotifiesRead() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> buf = executor.submit(new ReadTask(content));
@@ -226,7 +226,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedCallsPendingCompletions() {
+ void requireThatFailedCallsPendingCompletions() {
MyCompletion foo = new MyCompletion();
MyCompletion bar = new MyCompletion();
ReadableContentChannel content = new ReadableContentChannel();
@@ -239,10 +239,10 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatAvailableIsNotBlocking() {
+ void requireThatAvailableIsNotBlocking() {
ReadableContentChannel content = new ReadableContentChannel();
assertEquals(0, content.available());
- ByteBuffer buf = ByteBuffer.wrap(new byte[] { 6, 9 });
+ ByteBuffer buf = ByteBuffer.wrap(new byte[]{6, 9});
content.write(buf, null);
assertTrue(content.available() > 0);
assertSame(buf, content.read());
@@ -253,7 +253,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatContentIsThreadSafe() {
+ void requireThatContentIsThreadSafe() {
ExecutorService executor = Executors.newFixedThreadPool(100);
for (int run = 0; run < 69; ++run) {
List<ByteBuffer> bufs = new LinkedList<>();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
index 01634498bf3..724125e9c5e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertSame;
public class RequestDeniedTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
@@ -30,7 +30,7 @@ public class RequestDeniedTestCase {
}
@Test
- public void requireThatRequestDeniedIsThrown() {
+ void requireThatRequestDeniedIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler requestHandler = new MyRequestHandler();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
index 6ec78f01733..fdae7e8e701 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -16,12 +16,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -29,7 +29,7 @@ import static org.junit.Assert.fail;
public class RequestDispatchTestCase {
@Test
- public void requireThatRequestCanBeDispatched() throws Exception {
+ void requireThatRequestCanBeDispatched() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9));
ReadableContentChannel receivedContent = new ReadableContentChannel();
@@ -62,7 +62,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatStreamCanBeConnected() throws IOException {
+ void requireThatStreamCanBeConnected() throws IOException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ReadableContentChannel content = new ReadableContentChannel();
@@ -84,7 +84,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
RequestDispatch dispatch = driver.newRequestDispatch("http://localhost/", new FutureResponse());
assertFalse(dispatch.isCancelled());
@@ -106,7 +106,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesConnectException() {
+ void requireThatDispatchHandlesConnectException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new AbstractRequestHandler() {
@@ -127,7 +127,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesWriteException() {
+ void requireThatDispatchHandlesWriteException() {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
@@ -165,7 +165,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesCloseException() {
+ void requireThatDispatchHandlesCloseException() {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
@@ -203,7 +203,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchCanBeListenedTo() throws InterruptedException {
+ void requireThatDispatchCanBeListenedTo() throws InterruptedException {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ReadableContentChannel requestContent = new ReadableContentChannel();
@@ -220,7 +220,7 @@ public class RequestDispatchTestCase {
}.dispatch().whenComplete((__, ___) -> listener.run());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
ContentChannel responseContent = ResponseDispatch.newInstance(Response.Status.OK)
- .connect(requestHandler.responseHandler);
+ .connect(requestHandler.responseHandler);
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNull(requestContent.read());
assertTrue(listener.await(600, TimeUnit.SECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
index 4006ab072cb..2c00689c3f4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -13,13 +13,13 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.fail;
public class ResponseDispatchTestCase {
@Test
- public void requireThatFactoryMethodsWork() throws Exception {
+ void requireThatFactoryMethodsWork() throws Exception {
{
FutureResponse handler = new FutureResponse();
ResponseDispatch.newInstance(69).dispatch(handler);
@@ -78,7 +78,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatResponseCanBeDispatched() throws Exception {
+ void requireThatResponseCanBeDispatched() throws Exception {
final Response response = new Response(Response.Status.OK);
final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9));
ResponseDispatch dispatch = new ResponseDispatch() {
@@ -109,7 +109,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatStreamCanBeConnected() throws IOException {
+ void requireThatStreamCanBeConnected() throws IOException {
ReadableContentChannel responseContent = new ReadableContentChannel();
OutputStream out = new FastContentOutputStream(new ResponseDispatch() {
@@ -129,7 +129,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
ResponseDispatch dispatch = ResponseDispatch.newInstance(69);
assertFalse(dispatch.isCancelled());
try {
@@ -149,7 +149,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatDispatchClosesContentIfWriteThrowsException() {
+ void requireThatDispatchClosesContentIfWriteThrowsException() {
final AtomicBoolean closed = new AtomicBoolean(false);
try {
ResponseDispatch.newInstance(6, ByteBuffer.allocate(9)).dispatch(
@@ -173,12 +173,12 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatDispatchCanBeListenedTo() throws InterruptedException {
+ void requireThatDispatchCanBeListenedTo() throws InterruptedException {
RunnableLatch listener = new RunnableLatch();
ReadableContentChannel responseContent = new ReadableContentChannel();
ResponseDispatch.newInstance(6, ByteBuffer.allocate(9))
- .dispatch(new MyResponseHandler(responseContent))
- .whenComplete((__, ___) -> listener.run());
+ .dispatch(new MyResponseHandler(responseContent))
+ .whenComplete((__, ___) -> listener.run());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNotNull(responseContent.read());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
index f639877b87b..63a6d310208 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -18,12 +18,12 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -31,7 +31,7 @@ import static org.junit.Assert.fail;
public class ThreadedRequestHandlerTestCase {
@Test
- public void requireThatNullExecutorThrowsException() {
+ void requireThatNullExecutorThrowsException() {
try {
new ThreadedRequestHandler(null) {
@@ -47,7 +47,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatAccessorWork() {
+ void requireThatAccessorWork() {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
requestHandler.setTimeout(1000, TimeUnit.MILLISECONDS);
assertEquals(1000, requestHandler.getTimeout(TimeUnit.MILLISECONDS));
@@ -55,7 +55,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
+ void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
requestHandler.setTimeout(600, TimeUnit.SECONDS);
TestDriver driver = newTestDriver("http://localhost/", requestHandler);
@@ -74,7 +74,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
+ void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
TestDriver driver = newTestDriver("http://localhost/", requestHandler);
@@ -99,18 +99,18 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatNotImplementedHandlerDoesNotPreventShutdown() throws Exception {
+ void requireThatNotImplementedHandlerDoesNotPreventShutdown() throws Exception {
TestDriver driver = newTestDriver("http://localhost/", new ThreadedRequestHandler(newExecutor()) {
});
assertEquals(Response.Status.NOT_IMPLEMENTED,
- dispatchRequest(driver, "http://localhost/", ByteBuffer.wrap(new byte[] { 69 }))
- .get(600, TimeUnit.SECONDS).getStatus());
+ dispatchRequest(driver, "http://localhost/", ByteBuffer.wrap(new byte[]{69}))
+ .get(600, TimeUnit.SECONDS).getStatus());
assertTrue(driver.close());
}
@Test
- public void requireThatThreadedRequestHandlerRetainsTheRequestUntilHandlerIsRun() throws Exception {
+ void requireThatThreadedRequestHandlerRetainsTheRequestUntilHandlerIsRun() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
final AtomicInteger baseRetainCount = new AtomicInteger();
@@ -130,7 +130,7 @@ public class ThreadedRequestHandlerTestCase {
@Override
public void handleRequest(Request request, ReadableContentChannel requestContent,
- ResponseHandler responseHandler) {
+ ResponseHandler responseHandler) {
try {
entryLatch.await(600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
index 864604d76d6..50d695dbb27 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.handler;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
@@ -10,10 +10,11 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,7 +22,7 @@ import static org.junit.Assert.fail;
public class UnsafeContentInputStreamTestCase {
@Test
- public void requireThatBytesCanBeRead() throws IOException {
+ void requireThatBytesCanBeRead() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("Hello ");
@@ -34,7 +35,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void testMark() throws IOException {
+ void testMark() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("Hello ");
@@ -50,6 +51,11 @@ public class UnsafeContentInputStreamTestCase {
stream.read(buf);
assertEquals("ello Wor", Utf8.toString(buf));
stream.reset();
+ stream.mark(8);
+ buf = new byte[8];
+ stream.read(buf);
+ assertEquals("ello Wor", Utf8.toString(buf));
+ stream.reset();
stream.mark(5);
buf = new byte [9];
stream.read(buf);
@@ -65,7 +71,22 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCompletionsAreCalledWithDeprecatedContentWriter() throws IOException {
+ void requireThatReadAfterResetIncludesDataAfterMark() throws IOException {
+ ReadableContentChannel content = new ReadableContentChannel();
+ UnsafeContentInputStream in = new UnsafeContentInputStream(content);
+ byte[] outBuf = new byte[]{1, 2, 3};
+ content.write(ByteBuffer.wrap(outBuf), null);
+ in.mark(4);
+ assertEquals(3, in.read(new byte[]{101, 102, 103, 104}));
+ in.reset();
+ byte[] inBuf = new byte[4];
+ int read = in.read(inBuf);
+ assertEquals(3, read);
+ assertArrayEquals(new byte[]{1, 2, 3, 0}, inBuf);
+ }
+
+ @Test
+ void requireThatCompletionsAreCalledWithDeprecatedContentWriter() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -80,7 +101,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCompletionsAreCalled() throws IOException {
+ void requireThatCompletionsAreCalled() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -95,7 +116,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCloseDrainsStreamWithDeprecatedContentWriter() {
+ void requireThatCloseDrainsStreamWithDeprecatedContentWriter() {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -106,7 +127,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCloseDrainsStream() {
+ void requireThatCloseDrainsStream() {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -117,11 +138,11 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatAvailableIsNotBlocking() throws IOException {
+ void requireThatAvailableIsNotBlocking() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
InputStream stream = asInputStream(channel);
assertEquals(0, stream.available());
- channel.write(ByteBuffer.wrap(new byte[] { 6, 9 }), null);
+ channel.write(ByteBuffer.wrap(new byte[]{6, 9}), null);
assertTrue(stream.available() > 0);
assertEquals(6, stream.read());
assertTrue(stream.available() > 0);
@@ -133,11 +154,11 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatReadLargeArrayIsNotBlocking() throws IOException {
+ void requireThatReadLargeArrayIsNotBlocking() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
InputStream stream = asInputStream(channel);
assertEquals(0, stream.available());
- channel.write(ByteBuffer.wrap(new byte[] { 6, 9 }), null);
+ channel.write(ByteBuffer.wrap(new byte[]{6, 9}), null);
assertTrue(stream.available() > 0);
byte[] buf = new byte[69];
assertEquals(2, stream.read(buf));
@@ -150,12 +171,12 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatAllByteValuesCanBeRead() throws IOException {
+ void requireThatAllByteValuesCanBeRead() throws IOException {
ReadableContentChannel content = new ReadableContentChannel();
InputStream in = new UnsafeContentInputStream(content);
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; ++i) {
- content.write(ByteBuffer.wrap(new byte[] { (byte)i }), null);
- assertEquals(i, (byte)in.read());
+ content.write(ByteBuffer.wrap(new byte[]{(byte) i}), null);
+ assertEquals(i, (byte) in.read());
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
index bd205fd777e..9fe0b91cb39 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.jdisc.service;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -15,12 +15,12 @@ import static org.junit.Assert.assertTrue;
public class AbstractClientProviderTestCase {
@Test
- public void requireThatAbstractClassIsAClientProvider() {
+ void requireThatAbstractClassIsAClientProvider() {
assertTrue(ClientProvider.class.isInstance(new MyClientProvider()));
}
@Test
- public void requireThatStartDoesNotThrowAnException() {
+ void requireThatStartDoesNotThrowAnException() {
new MyClientProvider().start();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
index 7f4d9f72980..d46c5067dd9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.jdisc.service;
import com.google.inject.Inject;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -16,14 +16,14 @@ import static org.junit.Assert.assertTrue;
public class AbstractServerProviderTestCase {
@Test
- public void requireThatAbstractClassIsAServerProvider() {
+ void requireThatAbstractClassIsAServerProvider() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertTrue(ServerProvider.class.isInstance(new MyServerProvider(driver)));
assertTrue(driver.close());
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
MyServerProvider server = builder.getInstance(MyServerProvider.class);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
index 880641fe0f0..ad09c9d745e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.service;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.application.BindingSetSelector;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -18,13 +18,13 @@ import static org.junit.Assert.fail;
public class BindingSetNotFoundTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
BindingSetNotFoundException e = new BindingSetNotFoundException("foo");
assertEquals("foo", e.bindingSet());
}
@Test
- public void requireThatBindingSetNotFoundIsThrown() {
+ void requireThatBindingSetNotFoundIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@Override
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
index 7182379dc85..3de43874129 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
@@ -9,14 +9,14 @@ import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.fail;
public class ConnectToHandlerTestCase {
@Test
- public void requireThatNullResponseHandlerThrowsException() {
+ void requireThatNullResponseHandlerThrowsException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
@@ -40,7 +40,7 @@ public class ConnectToHandlerTestCase {
}
@Test
- public void requireThatConnectToHandlerWorks() {
+ void requireThatConnectToHandlerWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContent());
ContainerBuilder builder = driver.newContainerBuilder();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
index 6fcc7601339..70a0b55f75a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.jdisc.service;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.fail;
public class ContainerNotReadyTestCase {
@Test
- public void requireThatExceptionIsThrown() throws BindingSetNotFoundException {
+ void requireThatExceptionIsThrown() throws BindingSetNotFoundException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
try {
driver.newReference(URI.create("http://host"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
index 6aa8b891480..99622f2f3d2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.jdisc.service;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull;
public class CurrentContainerTestCase {
@Test
- public void requireThatNewRequestsCreateSnapshot() throws Exception {
+ void requireThatNewRequestsCreateSnapshot() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
index cd59f676d62..68733b35adb 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.service;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.application.BindingSetSelector;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -18,14 +18,14 @@ import static org.junit.Assert.fail;
public class NoBindingSetSelectedTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://host/path");
NoBindingSetSelectedException e = new NoBindingSetSelectedException(uri);
assertEquals(uri, e.uri());
}
@Test
- public void requireThatNoBindingSetSelectedIsThrown() {
+ void requireThatNoBindingSetSelectedIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@Override
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
index 82cf4953010..862acfa1ce4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.service.ClientProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingClientTestCase {
@Test
- public void requireThatHandleRequestThrowsException() {
+ void requireThatHandleRequestThrowsException() {
ClientProvider client = new NonWorkingClientProvider();
try {
client.handleRequest(null, null);
@@ -24,7 +24,7 @@ public class NonWorkingClientTestCase {
}
@Test
- public void requireThatHandleTimeoutThrowsException() {
+ void requireThatHandleTimeoutThrowsException() {
ClientProvider client = new NonWorkingClientProvider();
try {
client.handleTimeout(null, null);
@@ -35,19 +35,19 @@ public class NonWorkingClientTestCase {
}
@Test
- public void requireThatStartDoesNotThrow() {
+ void requireThatStartDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.start();
}
@Test
- public void requireThatRetainDoesNotThrow() {
+ void requireThatRetainDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.release();
}
@Test
- public void requireThatReleaseDoesNotThrow() {
+ void requireThatReleaseDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
index 7aff45e195f..edd4447cbe6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.CompletionHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingCompletionHandlerTestCase {
@Test
- public void requireThatCompletedThrowsException() {
+ void requireThatCompletedThrowsException() {
CompletionHandler completion = new NonWorkingCompletionHandler();
try {
completion.completed();
@@ -24,7 +24,7 @@ public class NonWorkingCompletionHandlerTestCase {
}
@Test
- public void requireThatFailedThrowsException() {
+ void requireThatFailedThrowsException() {
CompletionHandler completion = new NonWorkingCompletionHandler();
try {
completion.failed(null);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
index 4b26a53442d..46bbbad95ca 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class NonWorkingContentChannelTestCase {
@Test
- public void requireThatWriteThrowsException() {
+ void requireThatWriteThrowsException() {
ContentChannel content = new NonWorkingContentChannel();
try {
content.write(null, null);
@@ -48,7 +48,7 @@ public class NonWorkingContentChannelTestCase {
}
@Test
- public void requireThatCloseThrowsException() {
+ void requireThatCloseThrowsException() {
ContentChannel content = new NonWorkingContentChannel();
try {
content.close(null);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
index 64d670b3efe..96c4e66987d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
@@ -2,15 +2,15 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.application.OsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import java.util.Collections;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -19,26 +19,26 @@ import static org.junit.Assert.fail;
public class NonWorkingOsgiFrameworkTestCase {
@Test
- public void requireThatFrameworkCanStartAndStop() throws BundleException {
+ void requireThatFrameworkCanStartAndStop() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
osgi.start();
osgi.stop();
}
@Test
- public void requireThatFrameworkHasNoBundles() throws BundleException {
+ void requireThatFrameworkHasNoBundles() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
assertTrue(osgi.bundles().isEmpty());
}
@Test
- public void requireThatFrameworkHasNoBundleContext() {
+ void requireThatFrameworkHasNoBundleContext() {
OsgiFramework osgi = new NonWorkingOsgiFramework();
assertNull(osgi.bundleContext());
}
@Test
- public void requireThatFrameworkThrowsOnInstallBundle() throws BundleException {
+ void requireThatFrameworkThrowsOnInstallBundle() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.installBundle("file:bundle.jar");
@@ -49,7 +49,7 @@ public class NonWorkingOsgiFrameworkTestCase {
}
@Test
- public void requireThatFrameworkThrowsOnStartBundles() throws BundleException {
+ void requireThatFrameworkThrowsOnStartBundles() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.startBundles(Collections.<Bundle>emptyList(), false);
@@ -60,7 +60,7 @@ public class NonWorkingOsgiFrameworkTestCase {
}
@Test
- public void requireThatFrameworkThrowsOnRefreshPackages() throws BundleException, InterruptedException {
+ void requireThatFrameworkThrowsOnRefreshPackages() throws BundleException, InterruptedException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.refreshPackages();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
index 4d7e911907f..26713d78ca2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.RequestHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingRequestHandlerTestCase {
@Test
- public void requireThatHandleRequestThrowsException() {
+ void requireThatHandleRequestThrowsException() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
try {
requestHandler.handleRequest(null, null);
@@ -24,7 +24,7 @@ public class NonWorkingRequestHandlerTestCase {
}
@Test
- public void requireThatHandleTimeoutThrowsException() {
+ void requireThatHandleTimeoutThrowsException() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
try {
requestHandler.handleTimeout(null, null);
@@ -35,7 +35,7 @@ public class NonWorkingRequestHandlerTestCase {
}
@Test
- public void requireThatDestroyDoesNotThrow() {
+ void requireThatDestroyDoesNotThrow() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
requestHandler.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
index b0d67102a12..31c08057c87 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.jdisc.test;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.Request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -15,12 +15,12 @@ import static org.junit.Assert.assertSame;
public class NonWorkingRequestTestCase {
@Test
- public void requireThatFactoryMethodWorks() {
+ void requireThatFactoryMethodWorks() {
assertNotNull(NonWorkingRequest.newInstance("scheme://host/path"));
}
@Test
- public void requireThatGuiceModulesAreInjected() {
+ void requireThatGuiceModulesAreInjected() {
Object obj = new Object();
Request request = NonWorkingRequest.newInstance("scheme://host/path", new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
index 6b7af12c763..08b0a58b75c 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingResponseHandlerTestCase {
@Test
- public void requireThatHandleResponseThrowsException() {
+ void requireThatHandleResponseThrowsException() {
NonWorkingResponseHandler handler = new NonWorkingResponseHandler();
try {
handler.handleResponse(new Response(Response.Status.OK));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
index 1666f737459..54fbb29afec 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author Simon Thoresen Hult
@@ -10,25 +10,25 @@ import org.junit.Test;
public class NonWorkingServerTestCase {
@Test
- public void requireThatStartDoesNotThrow() {
+ void requireThatStartDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.start();
}
@Test
- public void requireThatCloseDoesNotThrow() {
+ void requireThatCloseDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.close();
}
@Test
- public void requireThatReferDoesNotThrow() {
+ void requireThatReferDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.refer();
}
@Test
- public void requireThatReleaseDoesNotThrow() {
+ void requireThatReleaseDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
index c9c7ec1db48..89befa40367 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
@@ -12,7 +12,7 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
index 70ee85861e6..961e2998d8f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
@@ -11,13 +11,13 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestDeniedException;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.ContainerNotReadyException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -26,7 +26,7 @@ import static org.junit.Assert.fail;
public class TestDriverTestCase {
@Test
- public void requireThatFactoryMethodsWork() {
+ void requireThatFactoryMethodsWork() {
TestDriver.newInjectedApplicationInstance(MyApplication.class).close();
TestDriver.newInjectedApplicationInstanceWithoutOsgi(MyApplication.class).close();
TestDriver.newInjectedApplicationInstance(new MyApplication()).close();
@@ -36,14 +36,14 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertNotNull(driver.bootstrapLoader());
assertTrue(driver.close());
}
@Test
- public void requireThatConnectRequestWorks() {
+ void requireThatConnectRequestWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContentChannel());
ContainerBuilder builder = driver.newContainerBuilder();
@@ -58,7 +58,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatDispatchRequestWorks() {
+ void requireThatDispatchRequestWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContentChannel());
ContainerBuilder builder = driver.newContainerBuilder();
@@ -72,7 +72,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatFailedRequestCreateDoesNotBlockClose() {
+ void requireThatFailedRequestCreateDoesNotBlockClose() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
try {
driver.connectRequest("scheme://host/path", new MyResponseHandler());
@@ -84,7 +84,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatFailedRequestConnectDoesNotBlockClose() {
+ void requireThatFailedRequestConnectDoesNotBlockClose() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("scheme://host/path", new MyRequestHandler(null));
diff --git a/jdisc_core/src/test/resources/exportPackages.properties b/jdisc_core/src/test/resources/exportPackages.properties
new file mode 100644
index 00000000000..82242b1644b
--- /dev/null
+++ b/jdisc_core/src/test/resources/exportPackages.properties
@@ -0,0 +1,3 @@
+#generated by com.yahoo.jdisc.core.ExportPackages
+#Wed Jul 20 02:55:26 CEST 2022
+exportPackages=org.osgi.framework; version\="1.10.0", org.osgi.framework.connect; version\="1.0.0", org.osgi.framework.dto; uses\:\="org.osgi.dto"; version\="1.8.0", org.osgi.framework.hooks.bundle; uses\:\="org.osgi.framework"; version\="1.1.0", org.osgi.framework.hooks.resolver; uses\:\="org.osgi.framework.wiring"; version\="1.0.0", org.osgi.framework.hooks.service; uses\:\="org.osgi.framework"; version\="1.1.0", org.osgi.framework.hooks.weaving; uses\:\="org.osgi.framework.wiring"; version\="1.1.0", org.osgi.framework.launch; uses\:\="org.osgi.framework"; version\="1.2.0", org.osgi.framework.namespace; uses\:\="org.osgi.resource"; version\="1.2.0", org.osgi.framework.startlevel; uses\:\="org.osgi.framework"; version\="1.0.0", org.osgi.framework.startlevel.dto; uses\:\="org.osgi.dto"; version\="1.0.0", org.osgi.framework.wiring; uses\:\="org.osgi.framework,org.osgi.resource"; version\="1.2.0", org.osgi.framework.wiring.dto; uses\:\="org.osgi.dto,org.osgi.resource.dto"; version\="1.3.0", org.osgi.resource; version\="1.0.1", org.osgi.resource.dto; uses\:\="org.osgi.dto"; version\="1.0.1", org.osgi.service.packageadmin; uses\:\="org.osgi.framework"; version\="1.2.1", org.osgi.service.startlevel; uses\:\="org.osgi.framework"; version\="1.1.1", org.osgi.service.url; version\="1.0.1", org.osgi.service.resolver; uses\:\="org.osgi.resource"; version\="1.1.1", org.osgi.util.tracker; uses\:\="org.osgi.framework"; version\="1.5.3", org.osgi.dto; version\="1.1.1", org.osgi.service.condition; version\="1.0.0", javax.security.auth.callback; version\="0.0.0.JavaSE_017", javax.security.auth.login; version\="0.0.0.JavaSE_017", javax.net.ssl; version\="0.0.0.JavaSE_017", java.lang.constant; version\="0.0.0.JavaSE_017", java.security.interfaces; version\="0.0.0.JavaSE_017", java.text.spi; version\="0.0.0.JavaSE_017", java.nio.channels.spi; version\="0.0.0.JavaSE_017", java.math; version\="0.0.0.JavaSE_017", java.nio.file; version\="0.0.0.JavaSE_017", java.util.concurrent.atomic; version\="0.0.0.JavaSE_017", java.security.cert; version\="0.0.0.JavaSE_017", java.security.spec; version\="0.0.0.JavaSE_017", java.nio.channels; version\="0.0.0.JavaSE_017", java.time.chrono; version\="0.0.0.JavaSE_017", javax.crypto; version\="0.0.0.JavaSE_017", java.time.zone; version\="0.0.0.JavaSE_017", java.nio.charset; version\="0.0.0.JavaSE_017", java.io; version\="0.0.0.JavaSE_017", java.util.spi; version\="0.0.0.JavaSE_017", java.net; version\="0.0.0.JavaSE_017", javax.security.cert; version\="0.0.0.JavaSE_017", java.lang.annotation; version\="0.0.0.JavaSE_017", javax.security.auth.spi; version\="0.0.0.JavaSE_017", java.util.concurrent; version\="0.0.0.JavaSE_017", java.nio.charset.spi; version\="0.0.0.JavaSE_017", javax.crypto.interfaces; version\="0.0.0.JavaSE_017", java.util; version\="0.0.0.JavaSE_017", java.security; version\="0.0.0.JavaSE_017", java.nio.file.spi; version\="0.0.0.JavaSE_017", java.nio; version\="0.0.0.JavaSE_017", java.util.jar; version\="0.0.0.JavaSE_017", javax.security.auth; version\="0.0.0.JavaSE_017", java.lang.ref; version\="0.0.0.JavaSE_017", java.util.regex; version\="0.0.0.JavaSE_017", java.net.spi; version\="0.0.0.JavaSE_017", java.lang.module; version\="0.0.0.JavaSE_017", java.lang.invoke; version\="0.0.0.JavaSE_017", java.time.format; version\="0.0.0.JavaSE_017", java.util.concurrent.locks; version\="0.0.0.JavaSE_017", java.time.temporal; version\="0.0.0.JavaSE_017", java.util.zip; version\="0.0.0.JavaSE_017", java.nio.file.attribute; version\="0.0.0.JavaSE_017", java.util.random; version\="0.0.0.JavaSE_017", java.text; version\="0.0.0.JavaSE_017", javax.crypto.spec; version\="0.0.0.JavaSE_017", java.util.stream; version\="0.0.0.JavaSE_017", java.time; version\="0.0.0.JavaSE_017", java.lang; version\="0.0.0.JavaSE_017", java.lang.runtime; version\="0.0.0.JavaSE_017", java.util.function; version\="0.0.0.JavaSE_017", javax.net; version\="0.0.0.JavaSE_017", javax.security.auth.x500; version\="0.0.0.JavaSE_017", java.lang.reflect; version\="0.0.0.JavaSE_017", javax.lang.model; version\="0.0.0.JavaSE_017", javax.annotation.processing; version\="0.0.0.JavaSE_017", javax.lang.model.element; version\="0.0.0.JavaSE_017", javax.tools; version\="0.0.0.JavaSE_017", javax.lang.model.type; version\="0.0.0.JavaSE_017", javax.lang.model.util; version\="0.0.0.JavaSE_017", java.awt.datatransfer; version\="0.0.0.JavaSE_017", java.awt.desktop; version\="0.0.0.JavaSE_017", javax.swing.plaf.synth; version\="0.0.0.JavaSE_017", java.beans; version\="0.0.0.JavaSE_017", javax.swing.text.html.parser; version\="0.0.0.JavaSE_017", javax.swing.text.rtf; version\="0.0.0.JavaSE_017", java.awt.font; version\="0.0.0.JavaSE_017", javax.imageio; version\="0.0.0.JavaSE_017", java.awt.im.spi; version\="0.0.0.JavaSE_017", java.applet; version\="0.0.0.JavaSE_017", javax.sound.midi; version\="0.0.0.JavaSE_017", java.awt.dnd; version\="0.0.0.JavaSE_017", javax.swing.text; version\="0.0.0.JavaSE_017", javax.swing.plaf.basic; version\="0.0.0.JavaSE_017", javax.swing.undo; version\="0.0.0.JavaSE_017", javax.swing.plaf; version\="0.0.0.JavaSE_017", javax.swing.filechooser; version\="0.0.0.JavaSE_017", javax.imageio.event; version\="0.0.0.JavaSE_017", javax.sound.sampled; version\="0.0.0.JavaSE_017", javax.print.attribute; version\="0.0.0.JavaSE_017", javax.print; version\="0.0.0.JavaSE_017", javax.swing.plaf.nimbus; version\="0.0.0.JavaSE_017", javax.accessibility; version\="0.0.0.JavaSE_017", java.awt.event; version\="0.0.0.JavaSE_017", javax.swing.text.html; version\="0.0.0.JavaSE_017", javax.imageio.spi; version\="0.0.0.JavaSE_017", javax.swing.border; version\="0.0.0.JavaSE_017", javax.sound.sampled.spi; version\="0.0.0.JavaSE_017", javax.imageio.plugins.bmp; version\="0.0.0.JavaSE_017", java.awt.color; version\="0.0.0.JavaSE_017", java.awt.geom; version\="0.0.0.JavaSE_017", javax.imageio.plugins.jpeg; version\="0.0.0.JavaSE_017", javax.swing.tree; version\="0.0.0.JavaSE_017", javax.imageio.plugins.tiff; version\="0.0.0.JavaSE_017", java.awt.print; version\="0.0.0.JavaSE_017", java.awt.image; version\="0.0.0.JavaSE_017", javax.imageio.metadata; version\="0.0.0.JavaSE_017", javax.swing.table; version\="0.0.0.JavaSE_017", javax.sound.midi.spi; version\="0.0.0.JavaSE_017", javax.print.attribute.standard; version\="0.0.0.JavaSE_017", javax.swing.colorchooser; version\="0.0.0.JavaSE_017", javax.swing; version\="0.0.0.JavaSE_017", java.awt.image.renderable; version\="0.0.0.JavaSE_017", javax.swing.plaf.multi; version\="0.0.0.JavaSE_017", java.awt.im; version\="0.0.0.JavaSE_017", javax.print.event; version\="0.0.0.JavaSE_017", javax.swing.plaf.metal; version\="0.0.0.JavaSE_017", java.beans.beancontext; version\="0.0.0.JavaSE_017", java.awt; version\="0.0.0.JavaSE_017", javax.imageio.stream; version\="0.0.0.JavaSE_017", javax.swing.event; version\="0.0.0.JavaSE_017", java.lang.instrument; version\="0.0.0.JavaSE_017", java.util.logging; version\="0.0.0.JavaSE_017", javax.management.timer; version\="0.0.0.JavaSE_017", javax.management; version\="0.0.0.JavaSE_017", javax.management.relation; version\="0.0.0.JavaSE_017", javax.management.loading; version\="0.0.0.JavaSE_017", javax.management.openmbean; version\="0.0.0.JavaSE_017", java.lang.management; version\="0.0.0.JavaSE_017", javax.management.remote; version\="0.0.0.JavaSE_017", javax.management.monitor; version\="0.0.0.JavaSE_017", javax.management.modelmbean; version\="0.0.0.JavaSE_017", javax.management.remote.rmi; version\="0.0.0.JavaSE_017", javax.naming.event; version\="0.0.0.JavaSE_017", javax.naming.ldap.spi; version\="0.0.0.JavaSE_017", javax.naming; version\="0.0.0.JavaSE_017", javax.naming.spi; version\="0.0.0.JavaSE_017", javax.naming.ldap; version\="0.0.0.JavaSE_017", javax.naming.directory; version\="0.0.0.JavaSE_017", java.net.http; version\="0.0.0.JavaSE_017", java.util.prefs; version\="0.0.0.JavaSE_017", java.rmi.registry; version\="0.0.0.JavaSE_017", javax.rmi.ssl; version\="0.0.0.JavaSE_017", java.rmi.dgc; version\="0.0.0.JavaSE_017", java.rmi; version\="0.0.0.JavaSE_017", java.rmi.server; version\="0.0.0.JavaSE_017", javax.script; version\="0.0.0.JavaSE_017", org.ietf.jgss; version\="0.0.0.JavaSE_017", javax.security.auth.kerberos; version\="0.0.0.JavaSE_017", javax.security.sasl; version\="0.0.0.JavaSE_017", javax.smartcardio; version\="0.0.0.JavaSE_017", java.sql; version\="0.0.0.JavaSE_017", javax.sql; version\="0.0.0.JavaSE_017", javax.sql.rowset.spi; version\="0.0.0.JavaSE_017", javax.sql.rowset.serial; version\="0.0.0.JavaSE_017", javax.sql.rowset; version\="0.0.0.JavaSE_017", javax.transaction.xa; version\="0.0.0.JavaSE_017", javax.xml; version\="0.0.0.JavaSE_017", javax.xml.transform.sax; version\="0.0.0.JavaSE_017", javax.xml.datatype; version\="0.0.0.JavaSE_017", javax.xml.catalog; version\="0.0.0.JavaSE_017", org.w3c.dom.traversal; version\="0.0.0.JavaSE_017", javax.xml.stream.events; version\="0.0.0.JavaSE_017", javax.xml.stream; version\="0.0.0.JavaSE_017", org.xml.sax; version\="0.0.0.JavaSE_017", javax.xml.transform; version\="0.0.0.JavaSE_017", javax.xml.xpath; version\="0.0.0.JavaSE_017", org.w3c.dom.events; version\="0.0.0.JavaSE_017", org.w3c.dom.ranges; version\="0.0.0.JavaSE_017", org.w3c.dom.ls; version\="0.0.0.JavaSE_017", javax.xml.stream.util; version\="0.0.0.JavaSE_017", javax.xml.namespace; version\="0.0.0.JavaSE_017", javax.xml.transform.stax; version\="0.0.0.JavaSE_017", org.xml.sax.helpers; version\="0.0.0.JavaSE_017", org.w3c.dom.views; version\="0.0.0.JavaSE_017", org.w3c.dom.bootstrap; version\="0.0.0.JavaSE_017", org.w3c.dom; version\="0.0.0.JavaSE_017", javax.xml.transform.stream; version\="0.0.0.JavaSE_017", javax.xml.transform.dom; version\="0.0.0.JavaSE_017", javax.xml.validation; version\="0.0.0.JavaSE_017", javax.xml.parsers; version\="0.0.0.JavaSE_017", org.xml.sax.ext; version\="0.0.0.JavaSE_017", javax.xml.crypto.dsig.spec; version\="0.0.0.JavaSE_017", javax.xml.crypto.dsig.keyinfo; version\="0.0.0.JavaSE_017", javax.xml.crypto.dsig.dom; version\="0.0.0.JavaSE_017", javax.xml.crypto.dom; version\="0.0.0.JavaSE_017", javax.xml.crypto; version\="0.0.0.JavaSE_017", javax.xml.crypto.dsig; version\="0.0.0.JavaSE_017", com.sun.java.accessibility.util; version\="0.0.0.JavaSE_017", com.sun.tools.attach.spi; version\="0.0.0.JavaSE_017", com.sun.tools.attach; version\="0.0.0.JavaSE_017", com.sun.source.doctree; version\="0.0.0.JavaSE_017", com.sun.source.tree; version\="0.0.0.JavaSE_017", com.sun.source.util; version\="0.0.0.JavaSE_017", com.sun.tools.javac; version\="0.0.0.JavaSE_017", jdk.dynalink.beans; version\="0.0.0.JavaSE_017", jdk.dynalink.linker.support; version\="0.0.0.JavaSE_017", jdk.dynalink.support; version\="0.0.0.JavaSE_017", jdk.dynalink; version\="0.0.0.JavaSE_017", jdk.dynalink.linker; version\="0.0.0.JavaSE_017", com.sun.net.httpserver; version\="0.0.0.JavaSE_017", com.sun.net.httpserver.spi; version\="0.0.0.JavaSE_017", com.sun.jarsigner; version\="0.0.0.JavaSE_017", jdk.security.jarsigner; version\="0.0.0.JavaSE_017", jdk.javadoc.doclet; version\="0.0.0.JavaSE_017", com.sun.tools.jconsole; version\="0.0.0.JavaSE_017", com.sun.jdi.connect; version\="0.0.0.JavaSE_017", com.sun.jdi.event; version\="0.0.0.JavaSE_017", com.sun.jdi.connect.spi; version\="0.0.0.JavaSE_017", com.sun.jdi; version\="0.0.0.JavaSE_017", com.sun.jdi.request; version\="0.0.0.JavaSE_017", jdk.jfr.consumer; version\="0.0.0.JavaSE_017", jdk.jfr; version\="0.0.0.JavaSE_017", jdk.jshell; version\="0.0.0.JavaSE_017", jdk.jshell.execution; version\="0.0.0.JavaSE_017", jdk.jshell.spi; version\="0.0.0.JavaSE_017", jdk.jshell.tool; version\="0.0.0.JavaSE_017", netscape.javascript; version\="0.0.0.JavaSE_017", com.sun.management; version\="0.0.0.JavaSE_017", jdk.management.jfr; version\="0.0.0.JavaSE_017", jdk.net; version\="0.0.0.JavaSE_017", jdk.nio; version\="0.0.0.JavaSE_017", jdk.nio.mapmode; version\="0.0.0.JavaSE_017", com.sun.nio.sctp; version\="0.0.0.JavaSE_017", com.sun.security.auth.module; version\="0.0.0.JavaSE_017", com.sun.security.auth.login; version\="0.0.0.JavaSE_017", com.sun.security.auth; version\="0.0.0.JavaSE_017", com.sun.security.auth.callback; version\="0.0.0.JavaSE_017", com.sun.security.jgss; version\="0.0.0.JavaSE_017", sun.reflect; version\="0.0.0.JavaSE_017", sun.misc; version\="0.0.0.JavaSE_017", com.sun.nio.file; version\="0.0.0.JavaSE_017", jdk.swing.interop; version\="0.0.0.JavaSE_017", org.w3c.dom.stylesheets; version\="0.0.0.JavaSE_017", org.w3c.dom.html; version\="0.0.0.JavaSE_017", org.w3c.dom.xpath; version\="0.0.0.JavaSE_017", org.w3c.dom.css; version\="0.0.0.JavaSE_017", com.yahoo.jdisc, com.yahoo.jdisc.application, com.yahoo.jdisc.handler, com.yahoo.jdisc.service, com.yahoo.jdisc.statistics, javax.inject;version\=1.0.0, org.aopalliance.intercept, org.aopalliance.aop, com.google.common.annotations;version\="27.1.0",com.google.common.base;version\="27.1.0",com.google.common.cache;version\="27.1.0";uses\:\="com.google.common.base,com.google.common.collect,com.google.common.util.concurrent",com.google.common.collect;version\="27.1.0";uses\:\="com.google.common.base",com.google.common.escape;version\="27.1.0";uses\:\="com.google.common.base",com.google.common.eventbus;version\="27.1.0",com.google.common.graph;version\="27.1.0";uses\:\="com.google.common.collect",com.google.common.hash;version\="27.1.0";uses\:\="com.google.common.base",com.google.common.html;version\="27.1.0";uses\:\="com.google.common.escape",com.google.common.io;version\="27.1.0";uses\:\="com.google.common.base,com.google.common.collect,com.google.common.graph,com.google.common.hash",com.google.common.math;version\="27.1.0",com.google.common.net;version\="27.1.0";uses\:\="com.google.common.base,com.google.common.collect,com.google.common.escape",com.google.common.primitives;version\="27.1.0";uses\:\="com.google.common.base",com.google.common.reflect;version\="27.1.0";uses\:\="com.google.common.collect,com.google.common.io",com.google.common.util.concurrent;version\="27.1.0";uses\:\="com.google.common.base,com.google.common.collect,com.google.common.util.concurrent.internal",com.google.common.xml;version\="27.1.0";uses\:\="com.google.common.escape", com.google.inject;version\="1.4",com.google.inject.binder;version\="1.4",com.google.inject.matcher;version\="1.4",com.google.inject.multibindings;version\="1.4",com.google.inject.name;version\="1.4",com.google.inject.spi;version\="1.4",com.google.inject.util;version\="1.4", org.slf4j;version\=1.7.32, org.slf4j.spi;version\=1.7.32, org.slf4j.helpers;version\=1.7.32, org.slf4j.event;version\=1.7.32, org.slf4j.impl;version\=1.7.32, org.apache.commons.logging;version\=1.2, org.apache.commons.logging.impl;version\=1.2, org.apache.log4j;version\=1.2.17,org.apache.log4j.helpers;version\=1.2.17,org.apache.log4j.spi;version\=1.2.17,org.apache.log4j.xml;version\=1.2.17, com.yahoo.component.annotation;version\="1.0.0", com.yahoo.config;version\=1.0.0, com.yahoo.vespa.defaults;version\=1.0.0, ai.vespa.http;version\=1.0.0,ai.vespa.validation;version\=1.0.0,com.yahoo.binaryprefix;version\=1.0.0,com.yahoo.collections;version\=1.0.0,com.yahoo.compress;version\=1.0.0,com.yahoo.concurrent.classlock;version\=1.0.0,com.yahoo.concurrent.maintenance;version\=1.0.0,com.yahoo.concurrent;version\=1.0.0,com.yahoo.data.access.simple;version\=1.0.0,com.yahoo.data.access.slime;version\=1.0.0,com.yahoo.data.access;version\=1.0.0,com.yahoo.errorhandling;version\=1.0.0,com.yahoo.exception;version\=1.0.0,com.yahoo.geo;version\=1.0.0,com.yahoo.io.reader;version\=1.0.0,com.yahoo.io;version\=1.0.0,com.yahoo.javacc;version\=1.0.0,com.yahoo.lang;version\=1.0.0,com.yahoo.nativec;version\=1.0.0,com.yahoo.net;version\=1.0.0,com.yahoo.path;version\=1.0.0,com.yahoo.protect;version\=1.0.0,com.yahoo.reflection;version\=1.0.0,com.yahoo.slime;version\=1.0.0,com.yahoo.stream;version\=1.0.0,com.yahoo.system.execution;version\=1.0.0,com.yahoo.system;version\=1.0.0,com.yahoo.tensor.evaluation;version\=1.0.0,com.yahoo.tensor.functions;version\=1.0.0,com.yahoo.tensor.serialization;version\=1.0.0,com.yahoo.tensor;version\=1.0.0,com.yahoo.text.internal;version\=1.0.0,com.yahoo.text;version\=1.0.0,com.yahoo.time;version\=1.0.0,com.yahoo.transaction;version\=1.0.0,com.yahoo.vespa.objects;version\=1.0.0,com.yahoo.yolean.chain;version\=1.0.0,com.yahoo.yolean.concurrent;version\=1.0.0,com.yahoo.yolean.function;version\=1.0.0,com.yahoo.yolean.system;version\=1.0.0,com.yahoo.yolean.trace;version\=1.0.0,com.yahoo.yolean;version\=1.0.0, com.yahoo.log.event;version\=1.0.0,com.yahoo.log.impl;version\=1.0.0,com.yahoo.log;version\=1.0.0, javax.xml.bind;version\="2.3";uses\:\="javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.namespace,javax.xml.stream,javax.xml.transform,javax.xml.validation,org.w3c.dom,org.xml.sax",javax.xml.bind.annotation;version\="2.3";uses\:\="javax.xml.bind,javax.xml.parsers,javax.xml.transform,javax.xml.transform.dom,org.w3c.dom",javax.xml.bind.annotation.adapters;version\="2.3",javax.xml.bind.attachment;version\="2.3";uses\:\="javax.activation",javax.xml.bind.helpers;version\="2.3";uses\:\="javax.xml.bind,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.stream,javax.xml.transform,javax.xml.validation,org.w3c.dom,org.xml.sax",javax.xml.bind.util;version\="2.3";uses\:\="javax.xml.bind,javax.xml.transform.sax", com.sun.istack;version\="3.0.5";uses\:\="javax.activation,javax.xml.stream,org.xml.sax,org.xml.sax.helpers",com.sun.istack.localization;version\="3.0.5",com.sun.istack.logging;version\="3.0.5",com.sun.xml.bind;uses\:\="org.xml.sax";version\="2.3.0",com.sun.xml.bind.annotation;version\="2.3.0",com.sun.xml.bind.api;uses\:\="org.xml.sax";version\="2.3.0",com.sun.xml.bind.api.impl;version\="2.3.0",com.sun.xml.bind.marshaller;uses\:\="javax.xml.parsers,org.w3c.dom,org.xml.sax,org.xml.sax.helpers";version\="2.3.0",com.sun.xml.bind.unmarshaller;uses\:\="com.sun.xml.bind.v2.runtime.unmarshaller,javax.xml.bind,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.util;version\="2.3.0",com.sun.xml.bind.v2;version\="2.3.0",com.sun.xml.bind.v2.model.annotation;uses\:\="com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.runtime";version\="2.3.0",com.sun.xml.bind.v2.model.core;uses\:\="com.sun.xml.bind.v2.model.annotation,com.sun.xml.bind.v2.model.impl,com.sun.xml.bind.v2.model.nav,com.sun.xml.bind.v2.runtime,javax.activation,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.namespace,javax.xml.transform";version\="2.3.0",com.sun.xml.bind.v2.model.impl;uses\:\="com.sun.xml.bind.v2.model.annotation,com.sun.xml.bind.v2.model.nav";version\="2.3.0",com.sun.xml.bind.v2.model.nav;uses\:\="com.sun.xml.bind.v2.runtime";version\="2.3.0",com.sun.xml.bind.v2.model.util;uses\:\="javax.xml.namespace";version\="2.3.0",com.sun.xml.bind.v2.runtime;uses\:\="com.sun.xml.bind.v2.model.annotation,javax.activation,javax.xml.bind,javax.xml.bind.annotation.adapters";version\="2.3.0",com.sun.xml.bind.v2.runtime.unmarshaller;uses\:\="javax.xml.bind,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.schemagen.episode;uses\:\="com.sun.xml.txw2,com.sun.xml.txw2.annotation";version\="2.3.0",com.sun.xml.bind.v2.util;uses\:\="javax.xml.parsers,javax.xml.transform,javax.xml.validation,javax.xml.xpath";version\="2.3.0",com.sun.xml.txw2;uses\:\="com.sun.xml.txw2.output,javax.xml.namespace";version\="2.3.0",com.sun.xml.txw2.annotation;version\="2.3.0",com.sun.xml.txw2.output;uses\:\="com.sun.xml.txw2,javax.xml.namespace,javax.xml.stream,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stream,org.w3c.dom,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers";version\="2.3.0", com.sun.xml.bind;uses\:\="com.sun.xml.bind.v2.runtime.reflect,javax.xml.bind,javax.xml.bind.annotation.adapters,javax.xml.datatype,javax.xml.namespace,javax.xml.stream,org.xml.sax";version\="2.3.0",com.sun.xml.bind.api;uses\:\="com.sun.xml.bind.v2.model.annotation,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime,javax.xml.bind,javax.xml.bind.attachment,javax.xml.namespace,javax.xml.stream,javax.xml.transform,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.marshaller;version\="2.3.0",com.sun.xml.bind.unmarshaller;uses\:\="org.xml.sax";version\="2.3.0",com.sun.xml.bind.util;uses\:\="com.sun.xml.bind,javax.xml.bind.helpers,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.annotation,javax.xml.bind";version\="2.3.0",com.sun.xml.bind.v2.bytecode;version\="2.3.0",com.sun.xml.bind.v2.model.annotation;uses\:\="com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.nav,com.sun.xml.bind.v2.runtime";version\="2.3.0",com.sun.xml.bind.v2.model.impl;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.annotation,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.nav,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime,javax.activation,javax.xml.namespace";version\="2.3.0",com.sun.xml.bind.v2.model.runtime;uses\:\="com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.reflect,javax.xml.bind,javax.xml.namespace,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime;uses\:\="com.sun.istack,com.sun.xml.bind.api,com.sun.xml.bind.marshaller,com.sun.xml.bind.v2.model.annotation,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime.output,com.sun.xml.bind.v2.runtime.property,com.sun.xml.bind.v2.runtime.unmarshaller,javax.activation,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.namespace,javax.xml.stream,javax.xml.transform,javax.xml.transform.sax,javax.xml.validation,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime.output;uses\:\="com.sun.xml.bind.marshaller,com.sun.xml.bind.v2.runtime,com.sun.xml.fastinfoset.stax,javax.xml.stream,org.jvnet.staxex,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime.property;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.reflect,com.sun.xml.bind.v2.runtime.unmarshaller,com.sun.xml.bind.v2.util,javax.xml.namespace,javax.xml.stream,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime.reflect;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.unmarshaller,javax.xml.bind,javax.xml.bind.annotation.adapters,javax.xml.stream,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime.reflect.opt;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.runtime,com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.reflect,javax.xml.stream,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.runtime.unmarshaller;uses\:\="com.sun.xml.bind,com.sun.xml.bind.api,com.sun.xml.bind.unmarshaller,com.sun.xml.bind.util,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.output,com.sun.xml.bind.v2.runtime.reflect,javax.activation,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.namespace,javax.xml.stream,javax.xml.transform,javax.xml.transform.sax,javax.xml.validation,org.w3c.dom,org.xml.sax";version\="2.3.0",com.sun.xml.bind.v2.schemagen;uses\:\="com.sun.xml.bind.api,com.sun.xml.bind.v2.model.core,com.sun.xml.bind.v2.model.nav,com.sun.xml.txw2.output,javax.xml.bind,javax.xml.namespace";version\="2.3.0",com.sun.xml.bind.v2.schemagen.xmlschema;uses\:\="com.sun.xml.txw2,com.sun.xml.txw2.annotation,javax.xml.namespace";version\="2.3.0",com.sun.xml.bind.v2.util;uses\:\="com.sun.xml.bind.v2.runtime,com.sun.xml.bind.v2.runtime.unmarshaller,javax.activation,javax.xml.namespace,javax.xml.transform.stream,org.xml.sax";version\="2.3.0", javax.activation;uses\:\="com.sun.activation.registries";version\="1.2",com.sun.activation.viewers;uses\:\="javax.activation";version\="1.2.0",com.sun.activation.registries;version\="1.2.0"
diff --git a/jrt/src/com/yahoo/jrt/Connection.java b/jrt/src/com/yahoo/jrt/Connection.java
index 00aceb7e352..8a185907aae 100644
--- a/jrt/src/com/yahoo/jrt/Connection.java
+++ b/jrt/src/com/yahoo/jrt/Connection.java
@@ -1,7 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
+import com.yahoo.security.tls.ConnectionAuthContext;
+
import java.io.IOException;
+import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
@@ -9,7 +12,6 @@ import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
-import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -436,9 +438,16 @@ class Connection extends Target {
}
@Override
- public Optional<SecurityContext> getSecurityContext() {
- return Optional.ofNullable(socket)
- .flatMap(CryptoSocket::getSecurityContext);
+ public ConnectionAuthContext connectionAuthContext() {
+ if (socket == null) throw new IllegalStateException("Not connected");
+ return socket.connectionAuthContext();
+ }
+
+ @Override
+ public Spec peerSpec() {
+ if (socket == null) throw new IllegalStateException("Not connected");
+ InetSocketAddress addr = (InetSocketAddress) socket.channel().socket().getRemoteSocketAddress();
+ return new Spec(addr.getHostString(), addr.getPort());
}
public boolean isClient() {
@@ -455,8 +464,7 @@ class Connection extends Target {
waiter.waitDone();
}
- public void invokeAsync(Request req, double timeout,
- RequestWaiter waiter) {
+ public void invokeAsync(Request req, double timeout, RequestWaiter waiter) {
if (timeout < 0.0) {
timeout = 0.0;
}
diff --git a/jrt/src/com/yahoo/jrt/CryptoSocket.java b/jrt/src/com/yahoo/jrt/CryptoSocket.java
index 78308b76624..e30579d2bdc 100644
--- a/jrt/src/com/yahoo/jrt/CryptoSocket.java
+++ b/jrt/src/com/yahoo/jrt/CryptoSocket.java
@@ -2,10 +2,11 @@
package com.yahoo.jrt;
+import com.yahoo.security.tls.ConnectionAuthContext;
+
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
-import java.util.Optional;
/**
@@ -102,11 +103,6 @@ public interface CryptoSocket {
**/
public void dropEmptyBuffers();
- /**
- * Returns the security context for the current connection (given handshake completed),
- * or empty if the current connection is not secure.
- */
- default public Optional<SecurityContext> getSecurityContext() {
- return Optional.empty();
- }
+ /** Returns the auth context for the current connection (given handshake completed) */
+ default ConnectionAuthContext connectionAuthContext() { return ConnectionAuthContext.defaultAllCapabilities(); }
}
diff --git a/jrt/src/com/yahoo/jrt/ErrorCode.java b/jrt/src/com/yahoo/jrt/ErrorCode.java
index beaabcea316..8e129cfef98 100644
--- a/jrt/src/com/yahoo/jrt/ErrorCode.java
+++ b/jrt/src/com/yahoo/jrt/ErrorCode.java
@@ -49,4 +49,7 @@ public class ErrorCode
/** Method failed (111) **/
public static final int METHOD_FAILED = 111;
+
+ /** Permission denied (112) **/
+ public static final int PERMISSION_DENIED = 112;
}
diff --git a/jrt/src/com/yahoo/jrt/InvocationServer.java b/jrt/src/com/yahoo/jrt/InvocationServer.java
index 9df92eb20a6..7704c0019ed 100644
--- a/jrt/src/com/yahoo/jrt/InvocationServer.java
+++ b/jrt/src/com/yahoo/jrt/InvocationServer.java
@@ -31,7 +31,11 @@ class InvocationServer {
public void invoke() {
if (method != null) {
if (method.checkParameters(request)) {
- method.invoke(request);
+ if (method.requestAccessFilter().allow(request)) {
+ method.invoke(request);
+ } else {
+ request.setError(ErrorCode.PERMISSION_DENIED, "Permission denied");
+ }
} else {
request.setError(ErrorCode.WRONG_PARAMS, "Parameters in " + request + " does not match " + method);
}
diff --git a/jrt/src/com/yahoo/jrt/MaybeTlsCryptoSocket.java b/jrt/src/com/yahoo/jrt/MaybeTlsCryptoSocket.java
index df01f4f2fa7..ab9d78d2676 100644
--- a/jrt/src/com/yahoo/jrt/MaybeTlsCryptoSocket.java
+++ b/jrt/src/com/yahoo/jrt/MaybeTlsCryptoSocket.java
@@ -1,10 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
+import com.yahoo.security.tls.ConnectionAuthContext;
+
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
-import java.util.Optional;
/**
* A crypto socket for the server side of a connection that
@@ -130,5 +131,5 @@ public class MaybeTlsCryptoSocket implements CryptoSocket {
@Override public int write(ByteBuffer src) throws IOException { return socket.write(src); }
@Override public FlushResult flush() throws IOException { return socket.flush(); }
@Override public void dropEmptyBuffers() { socket.dropEmptyBuffers(); }
- @Override public Optional<SecurityContext> getSecurityContext() { return Optional.ofNullable(socket).flatMap(CryptoSocket::getSecurityContext); }
+ @Override public ConnectionAuthContext connectionAuthContext() { return socket.connectionAuthContext(); }
}
diff --git a/jrt/src/com/yahoo/jrt/Method.java b/jrt/src/com/yahoo/jrt/Method.java
index 4fc9f0714da..89c66747e0b 100644
--- a/jrt/src/com/yahoo/jrt/Method.java
+++ b/jrt/src/com/yahoo/jrt/Method.java
@@ -40,6 +40,8 @@ public class Method {
private String[] returnName;
private String[] returnDesc;
+ private RequestAccessFilter filter = RequestAccessFilter.ALLOW_ALL;
+
private static final String undocumented = "???";
@@ -147,6 +149,10 @@ public class Method {
return this;
}
+ public Method requestAccessFilter(RequestAccessFilter filter) { this.filter = filter; return this; }
+
+ public RequestAccessFilter requestAccessFilter() { return filter; }
+
/**
* Obtain the name of a parameter
*
diff --git a/jrt/src/com/yahoo/jrt/RequestAccessFilter.java b/jrt/src/com/yahoo/jrt/RequestAccessFilter.java
new file mode 100644
index 00000000000..6701436d6ce
--- /dev/null
+++ b/jrt/src/com/yahoo/jrt/RequestAccessFilter.java
@@ -0,0 +1,17 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jrt;
+
+/**
+ * Request access filter is invoked before any call to {@link Method#invoke(Request)}.
+ * If {@link #allow(Request)} returns false, the method is not invoked, and the request is failed with error
+ * {@link ErrorCode#PERMISSION_DENIED}.
+ *
+ * @author bjorncs
+ */
+public interface RequestAccessFilter {
+
+ RequestAccessFilter ALLOW_ALL = __ -> true;
+
+ boolean allow(Request r);
+
+}
diff --git a/jrt/src/com/yahoo/jrt/RequireCapabilitiesFilter.java b/jrt/src/com/yahoo/jrt/RequireCapabilitiesFilter.java
new file mode 100644
index 00000000000..9bb497e96ed
--- /dev/null
+++ b/jrt/src/com/yahoo/jrt/RequireCapabilitiesFilter.java
@@ -0,0 +1,34 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jrt;
+
+import com.yahoo.security.tls.Capability;
+import com.yahoo.security.tls.CapabilitySet;
+import com.yahoo.security.tls.MissingCapabilitiesException;
+
+/**
+ * @author bjorncs
+ */
+public class RequireCapabilitiesFilter implements RequestAccessFilter {
+
+ private final CapabilitySet requiredCapabilities;
+
+ public RequireCapabilitiesFilter(CapabilitySet requiredCapabilities) {
+ this.requiredCapabilities = requiredCapabilities;
+ }
+
+ public RequireCapabilitiesFilter(Capability... requiredCapabilities) {
+ this(CapabilitySet.from(requiredCapabilities));
+ }
+
+ @Override
+ public boolean allow(Request r) {
+ try {
+ r.target().connectionAuthContext()
+ .verifyCapabilities(requiredCapabilities, "RPC", r.methodName(), r.target().peerSpec().toString());
+ return true;
+ } catch (MissingCapabilitiesException e) {
+ return false;
+ }
+ }
+
+}
diff --git a/jrt/src/com/yahoo/jrt/SecurityContext.java b/jrt/src/com/yahoo/jrt/SecurityContext.java
deleted file mode 100644
index 4eef99cb93f..00000000000
--- a/jrt/src/com/yahoo/jrt/SecurityContext.java
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.jrt;
-
-import java.security.cert.X509Certificate;
-import java.util.List;
-
-/**
- * @author bjorncs
- */
-public class SecurityContext {
-
- private final List<X509Certificate> peerCertificateChain;
-
- public SecurityContext(List<X509Certificate> peerCertificateChain) {
- this.peerCertificateChain = peerCertificateChain;
- }
-
- /**
- * @return the peer certificate chain if the peer was authenticated, empty list if not.
- */
- public List<X509Certificate> peerCertificateChain() {
- return peerCertificateChain;
- }
-}
diff --git a/jrt/src/com/yahoo/jrt/Target.java b/jrt/src/com/yahoo/jrt/Target.java
index a59aa341fe0..6cb9d432e03 100644
--- a/jrt/src/com/yahoo/jrt/Target.java
+++ b/jrt/src/com/yahoo/jrt/Target.java
@@ -1,7 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
-import java.util.Optional;
+import com.yahoo.security.tls.ConnectionAuthContext;
+
+import java.time.Duration;
/**
* A Target represents a connection endpoint with RPC
@@ -69,9 +71,13 @@ public abstract class Target {
public Exception getConnectionLostReason() { return null; }
/**
- * Returns the security context associated with this target, or empty if no connection or is insecure.
+ * Returns the connection auth context associated with this target.
*/
- public abstract Optional<SecurityContext> getSecurityContext();
+ public abstract ConnectionAuthContext connectionAuthContext();
+
+
+ /** @return address spec of socket peer */
+ public abstract Spec peerSpec();
/**
* Check if this target represents the client side of a
@@ -97,6 +103,10 @@ public abstract class Target {
*/
public abstract void invokeSync(Request req, double timeout);
+ public void invokeSync(Request req, Duration timeout) {
+ invokeSync(req, toSeconds(timeout));
+ }
+
/**
* Invoke a request on this target and let the completion be
* signalled with a callback.
@@ -105,8 +115,15 @@ public abstract class Target {
* @param timeout timeout in seconds
* @param waiter callback handler
*/
- public abstract void invokeAsync(Request req, double timeout,
- RequestWaiter waiter);
+ public abstract void invokeAsync(Request req, double timeout, RequestWaiter waiter);
+
+ public void invokeAsync(Request req, Duration timeout, RequestWaiter waiter) {
+ invokeAsync(req, toSeconds(timeout), waiter);
+ }
+
+ private static double toSeconds(Duration duration) {
+ return ((double)duration.toMillis())/1000.0;
+ }
/**
* Invoke a request on this target, but ignore the return
diff --git a/jrt/src/com/yahoo/jrt/TlsCryptoSocket.java b/jrt/src/com/yahoo/jrt/TlsCryptoSocket.java
index a899938dd45..d83c1ee8baa 100644
--- a/jrt/src/com/yahoo/jrt/TlsCryptoSocket.java
+++ b/jrt/src/com/yahoo/jrt/TlsCryptoSocket.java
@@ -1,27 +1,23 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
-import com.yahoo.security.tls.authz.AuthorizationResult;
-import com.yahoo.security.tls.authz.PeerAuthorizerTrustManager;
+import com.yahoo.security.tls.ConnectionAuthContext;
+import com.yahoo.security.tls.PeerAuthorizationFailedException;
+import com.yahoo.security.tls.TransportSecurityUtils;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
+import java.util.Objects;
import java.util.logging.Logger;
-import static java.util.stream.Collectors.toList;
import static javax.net.ssl.SSLEngineResult.Status;
/**
@@ -46,7 +42,7 @@ public class TlsCryptoSocket implements CryptoSocket {
private int sessionApplicationBufferSize;
private ByteBuffer handshakeDummyBuffer;
private HandshakeState handshakeState;
- private AuthorizationResult authorizationResult;
+ private ConnectionAuthContext authContext;
public TlsCryptoSocket(SocketChannel channel, SSLEngine sslEngine) {
this.channel = channel;
@@ -102,15 +98,6 @@ public class TlsCryptoSocket implements CryptoSocket {
channelRead();
break;
case NEED_WORK:
- if (authorizationResult == null) {
- PeerAuthorizerTrustManager.getAuthorizationResult(sslEngine) // only available during handshake
- .ifPresent(result -> {
- if (!result.succeeded()) {
- metrics.incrementPeerAuthorizationFailures();
- }
- authorizationResult = result;
- });
- }
break;
case COMPLETED:
return HandshakeState.COMPLETED;
@@ -127,6 +114,10 @@ public class TlsCryptoSocket implements CryptoSocket {
SSLSession session = sslEngine.getSession();
sessionApplicationBufferSize = session.getApplicationBufferSize();
sessionPacketBufferSize = session.getPacketBufferSize();
+ authContext = TransportSecurityUtils.getConnectionAuthContext(session).orElseThrow();
+ if (!authContext.authorized()) {
+ metrics.incrementPeerAuthorizationFailures();
+ }
log.fine(() -> String.format("Handshake complete: protocol=%s, cipherSuite=%s", session.getProtocol(), session.getCipherSuite()));
if (sslEngine.getUseClientMode()) {
metrics.incrementClientTlsConnectionsEstablished();
@@ -148,8 +139,7 @@ public class TlsCryptoSocket implements CryptoSocket {
}
}
} catch (SSLHandshakeException e) {
- // sslEngine.getDelegatedTask().run() and handshakeWrap() may throw SSLHandshakeException, potentially handshakeUnwrap() and sslEngine.beginHandshake() as well.
- if (authorizationResult == null || authorizationResult.succeeded()) { // don't include handshake failures due from PeerAuthorizerTrustManager
+ if (!(e.getCause() instanceof PeerAuthorizationFailedException)) {
metrics.incrementTlsCertificateVerificationFailures();
}
throw e;
@@ -224,19 +214,9 @@ public class TlsCryptoSocket implements CryptoSocket {
}
@Override
- public Optional<SecurityContext> getSecurityContext() {
- try {
- if (handshakeState != HandshakeState.COMPLETED) {
- return Optional.empty();
- }
- List<X509Certificate> peerCertificateChain =
- Arrays.stream(sslEngine.getSession().getPeerCertificates())
- .map(X509Certificate.class::cast)
- .collect(toList());
- return Optional.of(new SecurityContext(peerCertificateChain));
- } catch (SSLPeerUnverifiedException e) { // unverified peer: non-certificate based ciphers or peer did not provide a certificate
- return Optional.of(new SecurityContext(List.of())); // secure connection, but peer does not have a certificate chain.
- }
+ public ConnectionAuthContext connectionAuthContext() {
+ if (handshakeState != HandshakeState.COMPLETED) throw new IllegalStateException("Handshake not complete");
+ return Objects.requireNonNull(authContext);
}
private boolean handshakeWrap() throws IOException {
diff --git a/jrt/src/com/yahoo/jrt/slobrok/api/Mirror.java b/jrt/src/com/yahoo/jrt/slobrok/api/Mirror.java
index 7963cd51c75..778cb0455e8 100644
--- a/jrt/src/com/yahoo/jrt/slobrok/api/Mirror.java
+++ b/jrt/src/com/yahoo/jrt/slobrok/api/Mirror.java
@@ -13,6 +13,7 @@ import com.yahoo.jrt.Task;
import com.yahoo.jrt.TransportThread;
import com.yahoo.jrt.Values;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -206,7 +207,7 @@ public class Mirror implements IMirror {
req = new Request("slobrok.incremental.fetch");
req.parameters().add(new Int32Value(specsGeneration)); // gencnt
req.parameters().add(new Int32Value(5000)); // mstimeout
- target.invokeAsync(req, 40.0, reqWait);
+ target.invokeAsync(req, Duration.ofSeconds(40), reqWait);
}
private void handleUpdate() {
diff --git a/jrt/src/com/yahoo/jrt/slobrok/api/Register.java b/jrt/src/com/yahoo/jrt/slobrok/api/Register.java
index 14afea396bf..e529dea2eff 100644
--- a/jrt/src/com/yahoo/jrt/slobrok/api/Register.java
+++ b/jrt/src/com/yahoo/jrt/slobrok/api/Register.java
@@ -15,6 +15,7 @@ import com.yahoo.jrt.Task;
import com.yahoo.jrt.TransportThread;
import com.yahoo.jrt.Values;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -279,7 +280,7 @@ public class Register {
req.parameters().add(new StringValue(name));
req.parameters().add(new StringValue(mySpec));
log.log(Level.FINE, logMessagePrefix() + " now");
- target.invokeAsync(req, 35.0, reqWait);
+ target.invokeAsync(req, Duration.ofSeconds(35), reqWait);
}
private String logMessagePrefix() {
diff --git a/jrt/src/com/yahoo/jrt/slobrok/server/Slobrok.java b/jrt/src/com/yahoo/jrt/slobrok/server/Slobrok.java
index 24ab63c1d2f..5fd8beb3cc7 100644
--- a/jrt/src/com/yahoo/jrt/slobrok/server/Slobrok.java
+++ b/jrt/src/com/yahoo/jrt/slobrok/server/Slobrok.java
@@ -17,6 +17,7 @@ import com.yahoo.jrt.TargetWatcher;
import com.yahoo.jrt.Task;
import com.yahoo.jrt.Transport;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -225,7 +226,7 @@ public class Slobrok {
this.spec = spec;
target = orb.connect(new Spec(spec));
Request cbReq = new Request("slobrok.callback.listNamesServed");
- target.invokeAsync(cbReq, 5.0, this);
+ target.invokeAsync(cbReq, Duration.ofSeconds(5), this);
}
@Override
diff --git a/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java b/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java
index 71049673d90..67933cfafde 100644
--- a/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java
+++ b/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java
@@ -16,6 +16,7 @@ import com.yahoo.jrt.Transport;
import com.yahoo.jrt.Value;
import com.yahoo.jrt.Values;
+import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
@@ -80,7 +81,7 @@ public class RpcInvoker {
supervisor = new Supervisor(new Transport("invoker"));
target = supervisor.connect(new Spec(connectspec));
Request request = createRequest(method,arguments);
- target.invokeSync(request,10.0);
+ target.invokeSync(request, Duration.ofSeconds(10));
if (request.isError()) {
System.err.println("error(" + request.errorCode() + "): " + request.errorMessage());
return;
diff --git a/jrt/tests/com/yahoo/jrt/AbortTest.java b/jrt/tests/com/yahoo/jrt/AbortTest.java
index 2f31b3a52f6..df1f207458e 100644
--- a/jrt/tests/com/yahoo/jrt/AbortTest.java
+++ b/jrt/tests/com/yahoo/jrt/AbortTest.java
@@ -4,6 +4,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -44,7 +46,7 @@ public class AbortTest {
Test.Waiter w = new Test.Waiter();
Request req = new Request("test");
req.parameters().add(new Int32Value(20));
- target.invokeAsync(req, 5.0, w);
+ target.invokeAsync(req, Duration.ofSeconds(5), w);
req.abort();
barrier.breakIt();
w.waitDone();
@@ -54,7 +56,7 @@ public class AbortTest {
Request req2 = new Request("test");
req2.parameters().add(new Int32Value(30));
- target.invokeSync(req2, 5.0);
+ target.invokeSync(req2, Duration.ofSeconds(5));
assertTrue(!req2.isError());
assertEquals(1, req2.returnValues().size());
assertEquals(30, req2.returnValues().get(0).asInt32());
diff --git a/jrt/tests/com/yahoo/jrt/BackTargetTest.java b/jrt/tests/com/yahoo/jrt/BackTargetTest.java
index a55a6d7f474..5b9e7ccb157 100644
--- a/jrt/tests/com/yahoo/jrt/BackTargetTest.java
+++ b/jrt/tests/com/yahoo/jrt/BackTargetTest.java
@@ -4,6 +4,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -81,24 +83,24 @@ public class BackTargetTest {
@org.junit.Test
public void testBackTarget() {
checkTargets(false, false);
- target.invokeSync(new Request("sample_target"), 5.0);
+ target.invokeSync(new Request("sample_target"), Duration.ofSeconds(5));
checkTargets(true, false);
- serverBackTarget.invokeSync(new Request("sample_target"), 5.0);
+ serverBackTarget.invokeSync(new Request("sample_target"), Duration.ofSeconds(5));
checkTargets(true, true);
checkValues(0, 0);
- target.invokeSync(new Request("inc"), 5.0);
+ target.invokeSync(new Request("inc"), Duration.ofSeconds(5));
checkValues(1, 0);
- serverBackTarget.invokeSync(new Request("inc"), 5.0);
+ serverBackTarget.invokeSync(new Request("inc"), Duration.ofSeconds(5));
checkValues(1, 1);
- clientBackTarget.invokeSync(new Request("inc"), 5.0);
+ clientBackTarget.invokeSync(new Request("inc"), Duration.ofSeconds(5));
checkValues(2, 1);
- target.invokeSync(new Request("back_inc"), 5.0);
+ target.invokeSync(new Request("back_inc"), Duration.ofSeconds(5));
checkValues(2, 2);
- serverBackTarget.invokeSync(new Request("back_inc"), 5.0);
+ serverBackTarget.invokeSync(new Request("back_inc"), Duration.ofSeconds(5));
checkValues(3, 2);
- clientBackTarget.invokeSync(new Request("back_inc"), 5.0);
+ clientBackTarget.invokeSync(new Request("back_inc"), Duration.ofSeconds(5));
checkValues(3, 3);
}
diff --git a/jrt/tests/com/yahoo/jrt/CryptoUtils.java b/jrt/tests/com/yahoo/jrt/CryptoUtils.java
index f1672f86e9b..cef138ffba1 100644
--- a/jrt/tests/com/yahoo/jrt/CryptoUtils.java
+++ b/jrt/tests/com/yahoo/jrt/CryptoUtils.java
@@ -4,15 +4,14 @@ package com.yahoo.jrt;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.tls.AuthorizationMode;
+import com.yahoo.security.tls.AuthorizedPeers;
import com.yahoo.security.tls.DefaultTlsContext;
import com.yahoo.security.tls.HostnameVerification;
import com.yahoo.security.tls.PeerAuthentication;
+import com.yahoo.security.tls.PeerPolicy;
+import com.yahoo.security.tls.RequiredPeerCredential;
+import com.yahoo.security.tls.RequiredPeerCredential.Field;
import com.yahoo.security.tls.TlsContext;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.RequiredPeerCredential.Field;
-import com.yahoo.security.tls.policy.Role;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
@@ -42,8 +41,6 @@ class CryptoUtils {
singleton(
new PeerPolicy(
"localhost-policy",
- singleton(
- new Role("localhost-role")),
singletonList(
RequiredPeerCredential.of(Field.CN, "localhost")))));
diff --git a/jrt/tests/com/yahoo/jrt/DetachTest.java b/jrt/tests/com/yahoo/jrt/DetachTest.java
index 3c3356b53e2..4c3ee085913 100644
--- a/jrt/tests/com/yahoo/jrt/DetachTest.java
+++ b/jrt/tests/com/yahoo/jrt/DetachTest.java
@@ -4,6 +4,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -66,11 +68,11 @@ public class DetachTest {
Test.Waiter w1 = new Test.Waiter();
Request req1 = new Request("d_inc");
req1.parameters().add(new Int32Value(50));
- target.invokeAsync(req1, 5.0, w1);
+ target.invokeAsync(req1, Duration.ofSeconds(5), w1);
Request req2 = new Request("d_inc_r");
req2.parameters().add(new Int32Value(60));
- target.invokeSync(req2, 5.0);
+ target.invokeSync(req2, Duration.ofSeconds(5));
assertTrue(!req2.isError());
assertEquals(1, req2.returnValues().size());
@@ -123,7 +125,7 @@ public class DetachTest {
Test.Waiter w = new Test.Waiter();
Request req3 = new Request("inc_b");
req3.parameters().add(new Int32Value(100));
- target.invokeAsync(req3, 5.0, w);
+ target.invokeAsync(req3, Duration.ofSeconds(5), w);
Request blocked = (Request) receptor.get();
try {
blocked.returnRequest();
diff --git a/jrt/tests/com/yahoo/jrt/EchoTest.java b/jrt/tests/com/yahoo/jrt/EchoTest.java
index 26d4315fad6..11742fa42e2 100644
--- a/jrt/tests/com/yahoo/jrt/EchoTest.java
+++ b/jrt/tests/com/yahoo/jrt/EchoTest.java
@@ -2,6 +2,7 @@
package com.yahoo.jrt;
+import com.yahoo.security.tls.ConnectionAuthContext;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
@@ -10,12 +11,12 @@ import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.security.cert.X509Certificate;
+import java.time.Duration;
import java.util.List;
import static com.yahoo.jrt.CryptoUtils.createTestTlsContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
@@ -28,19 +29,19 @@ public class EchoTest {
Supervisor client;
Target target;
Values refValues;
- SecurityContext securityContext;
+ ConnectionAuthContext connAuthCtx;
private interface MetricsAssertions {
void assertMetrics(TransportMetrics.Snapshot snapshot) throws AssertionError;
}
- private interface SecurityContextAssertion {
- void assertSecurityContext(SecurityContext securityContext) throws AssertionError;
+ private interface ConnectionAuthContextAssertion {
+ void assertConnectionAuthContext(ConnectionAuthContext authContext) throws AssertionError;
}
@Parameter(value = 0) public CryptoEngine crypto;
@Parameter(value = 1) public MetricsAssertions metricsAssertions;
- @Parameter(value = 2) public SecurityContextAssertion securityContextAssertion;
+ @Parameter(value = 2) public ConnectionAuthContextAssertion connAuthCtxAssertion;
@Parameters(name = "{0}") public static Object[] engines() {
@@ -62,7 +63,7 @@ public class EchoTest {
assertEquals(1, metrics.serverTlsConnectionsEstablished());
assertEquals(1, metrics.clientTlsConnectionsEstablished());
},
- (SecurityContextAssertion) context -> {
+ (ConnectionAuthContextAssertion) context -> {
List<X509Certificate> chain = context.peerCertificateChain();
assertEquals(1, chain.size());
assertEquals(CryptoUtils.certificate, chain.get(0));
@@ -80,7 +81,7 @@ public class EchoTest {
assertEquals(1, metrics.serverTlsConnectionsEstablished());
assertEquals(1, metrics.clientTlsConnectionsEstablished());
},
- (SecurityContextAssertion) context -> {
+ (ConnectionAuthContextAssertion) context -> {
List<X509Certificate> chain = context.peerCertificateChain();
assertEquals(1, chain.size());
assertEquals(CryptoUtils.certificate, chain.get(0));
@@ -146,7 +147,7 @@ public class EchoTest {
for (int i = 0; i < p.size(); i++) {
r.add(p.get(i));
}
- securityContext = req.target().getSecurityContext().orElse(null);
+ connAuthCtx = req.target().connectionAuthContext();
}
@org.junit.Test
@@ -156,7 +157,7 @@ public class EchoTest {
for (int i = 0; i < refValues.size(); i++) {
p.add(refValues.get(i));
}
- target.invokeSync(req, 60.0);
+ target.invokeSync(req, Duration.ofSeconds(60));
assertTrue(req.checkReturnTypes("bBhHiIlLfFdDxXsS"));
assertTrue(Test.equals(req.returnValues(), req.parameters()));
assertTrue(Test.equals(req.returnValues(), refValues));
@@ -164,11 +165,9 @@ public class EchoTest {
if (metricsAssertions != null) {
metricsAssertions.assertMetrics(metrics.snapshot().changesSince(startSnapshot));
}
- if (securityContextAssertion != null) {
- assertNotNull(securityContext);
- securityContextAssertion.assertSecurityContext(securityContext);
- } else {
- assertNull(securityContext);
+ if (connAuthCtxAssertion != null) {
+ assertNotNull(connAuthCtx);
+ connAuthCtxAssertion.assertConnectionAuthContext(connAuthCtx);
}
}
}
diff --git a/jrt/tests/com/yahoo/jrt/InvokeAsyncTest.java b/jrt/tests/com/yahoo/jrt/InvokeAsyncTest.java
index 5e9f426bb17..e17b6c0cfdd 100644
--- a/jrt/tests/com/yahoo/jrt/InvokeAsyncTest.java
+++ b/jrt/tests/com/yahoo/jrt/InvokeAsyncTest.java
@@ -5,6 +5,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -16,6 +18,7 @@ public class InvokeAsyncTest {
Supervisor client;
Target target;
Test.Barrier barrier;
+ SimpleRequestAccessFilter filter;
@Before
public void setUp() throws ListenFailedException {
@@ -23,11 +26,13 @@ public class InvokeAsyncTest {
client = new Supervisor(new Transport());
acceptor = server.listen(new Spec(0));
target = client.connect(new Spec("localhost", acceptor.port()));
+ filter = new SimpleRequestAccessFilter();
server.addMethod(new Method("concat", "ss", "s", this::rpc_concat)
.methodDesc("Concatenate 2 strings")
.paramDesc(0, "str1", "a string")
.paramDesc(1, "str2", "another string")
- .returnDesc(0, "ret", "str1 followed by str2"));
+ .returnDesc(0, "ret", "str1 followed by str2")
+ .requestAccessFilter(filter));
barrier = new Test.Barrier();
}
@@ -54,7 +59,7 @@ public class InvokeAsyncTest {
req.parameters().add(new StringValue("def"));
Test.Waiter w = new Test.Waiter();
- target.invokeAsync(req, 5.0, w);
+ target.invokeAsync(req, Duration.ofSeconds(5), w);
assertFalse(w.isDone());
barrier.breakIt();
w.waitDone();
@@ -65,4 +70,21 @@ public class InvokeAsyncTest {
assertEquals("abcdef", req.returnValues().get(0).asString());
}
+ @org.junit.Test
+ public void testFilterIsInvoked() {
+ Request req = new Request("concat");
+ req.parameters().add(new StringValue("abc"));
+ req.parameters().add(new StringValue("def"));
+ assertFalse(filter.invoked);
+ Test.Waiter w = new Test.Waiter();
+ target.invokeAsync(req, Duration.ofSeconds(10), w);
+ assertFalse(w.isDone());
+ barrier.breakIt();
+ w.waitDone();
+ assertTrue(w.isDone());
+ assertFalse(req.isError());
+ assertEquals("abcdef", req.returnValues().get(0).asString());
+ assertTrue(filter.invoked);
+ }
+
}
diff --git a/jrt/tests/com/yahoo/jrt/InvokeErrorTest.java b/jrt/tests/com/yahoo/jrt/InvokeErrorTest.java
index a9a0b18b5a1..0b75fe713c2 100644
--- a/jrt/tests/com/yahoo/jrt/InvokeErrorTest.java
+++ b/jrt/tests/com/yahoo/jrt/InvokeErrorTest.java
@@ -5,17 +5,22 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class InvokeErrorTest {
- final double timeout=60.0;
+ final Duration timeout = Duration.ofSeconds(60);
Supervisor server;
Acceptor acceptor;
Supervisor client;
Target target;
Test.Barrier barrier;
+ SimpleRequestAccessFilter filter;
+ RpcTestMethod testMethod;
@Before
public void setUp() throws ListenFailedException {
@@ -23,7 +28,9 @@ public class InvokeErrorTest {
client = new Supervisor(new Transport());
acceptor = server.listen(new Spec(0));
target = client.connect(new Spec("localhost", acceptor.port()));
- server.addMethod(new Method("test", "iib", "i", this::rpc_test));
+ filter = new SimpleRequestAccessFilter();
+ testMethod = new RpcTestMethod();
+ server.addMethod(new Method("test", "iib", "i", testMethod).requestAccessFilter(filter));
server.addMethod(new Method("test_barrier", "iib", "i", this::rpc_test_barrier));
barrier = new Test.Barrier();
}
@@ -36,22 +43,8 @@ public class InvokeErrorTest {
server.transport().shutdown().join();
}
- private void rpc_test(Request req) {
- int value = req.parameters().get(0).asInt32();
- int error = req.parameters().get(1).asInt32();
- int extra = req.parameters().get(2).asInt8();
-
- req.returnValues().add(new Int32Value(value));
- if (extra != 0) {
- req.returnValues().add(new Int32Value(value));
- }
- if (error != 0) {
- req.setError(error, "Custom error");
- }
- }
-
private void rpc_test_barrier(Request req) {
- rpc_test(req);
+ testMethod.invoke(req);
barrier.waitFor();
}
@@ -157,4 +150,40 @@ public class InvokeErrorTest {
assertEquals(ErrorCode.CONNECTION, req1.errorCode());
}
+ @org.junit.Test
+ public void testFilterFailsRequest() {
+ Request r = new Request("test");
+ r.parameters().add(new Int32Value(42));
+ r.parameters().add(new Int32Value(0));
+ r.parameters().add(new Int8Value((byte)0));
+ filter.allowed = false;
+ assertFalse(filter.invoked);
+ target.invokeSync(r, timeout);
+ assertTrue(r.isError());
+ assertTrue(filter.invoked);
+ assertFalse(testMethod.invoked);
+ assertEquals(ErrorCode.PERMISSION_DENIED, r.errorCode());
+ assertEquals("Permission denied", r.errorMessage());
+ }
+
+ private static class RpcTestMethod implements MethodHandler {
+ boolean invoked = false;
+
+ @Override public void invoke(Request req) { invoked = true; rpc_test(req); }
+
+ void rpc_test(Request req) {
+ int value = req.parameters().get(0).asInt32();
+ int error = req.parameters().get(1).asInt32();
+ int extra = req.parameters().get(2).asInt8();
+
+ req.returnValues().add(new Int32Value(value));
+ if (extra != 0) {
+ req.returnValues().add(new Int32Value(value));
+ }
+ if (error != 0) {
+ req.setError(error, "Custom error");
+ }
+ }
+ }
+
}
diff --git a/jrt/tests/com/yahoo/jrt/InvokeSyncTest.java b/jrt/tests/com/yahoo/jrt/InvokeSyncTest.java
index ca7d0db129d..ff44017e1bc 100644
--- a/jrt/tests/com/yahoo/jrt/InvokeSyncTest.java
+++ b/jrt/tests/com/yahoo/jrt/InvokeSyncTest.java
@@ -10,8 +10,10 @@ import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
+import java.time.Duration;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -21,6 +23,7 @@ public class InvokeSyncTest {
Acceptor acceptor;
Supervisor client;
Target target;
+ SimpleRequestAccessFilter filter;
@Before
public void setUp() throws ListenFailedException {
@@ -28,11 +31,13 @@ public class InvokeSyncTest {
client = new Supervisor(new Transport());
acceptor = server.listen(new Spec(0));
target = client.connect(new Spec("localhost", acceptor.port()));
+ filter = new SimpleRequestAccessFilter();
server.addMethod(new Method("concat", "ss", "s", this::rpc_concat)
.methodDesc("Concatenate 2 strings")
.paramDesc(0, "str1", "a string")
.paramDesc(1, "str2", "another string")
- .returnDesc(0, "ret", "str1 followed by str2"));
+ .returnDesc(0, "ret", "str1 followed by str2")
+ .requestAccessFilter(filter));
server.addMethod(new Method("alltypes", "bhilfds", "s", this::rpc_alltypes)
.methodDesc("Method taking all types of params"));
}
@@ -63,7 +68,7 @@ public class InvokeSyncTest {
req.parameters().add(new StringValue("abc"));
req.parameters().add(new StringValue("def"));
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertTrue(!req.isError());
assertEquals(1, req.returnValues().size());
@@ -84,4 +89,17 @@ public class InvokeSyncTest {
assertEquals(baos.toString(), "This was alltypes. The string param was: baz\n");
}
+ @org.junit.Test
+ public void testFilterIsInvoked() {
+ Request req = new Request("concat");
+ req.parameters().add(new StringValue("abc"));
+ req.parameters().add(new StringValue("def"));
+ assertFalse(filter.invoked);
+ target.invokeSync(req, Duration.ofSeconds(10));
+ assertFalse(req.isError());
+ assertEquals("abcdef", req.returnValues().get(0).asString());
+ assertTrue(filter.invoked);
+ }
+
+
}
diff --git a/jrt/tests/com/yahoo/jrt/InvokeVoidTest.java b/jrt/tests/com/yahoo/jrt/InvokeVoidTest.java
index 8b674136fe2..64c3bc91371 100644
--- a/jrt/tests/com/yahoo/jrt/InvokeVoidTest.java
+++ b/jrt/tests/com/yahoo/jrt/InvokeVoidTest.java
@@ -5,6 +5,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -56,7 +58,7 @@ public class InvokeVoidTest {
public void testInvokeVoid() {
Request req = new Request("set");
req.parameters().add(new Int32Value(40));
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertTrue(!req.isError());
assertEquals(0, req.returnValues().size());
@@ -64,7 +66,7 @@ public class InvokeVoidTest {
target.invokeVoid(new Request("inc"));
req = new Request("get");
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertTrue(!req.isError());
assertEquals(42, req.returnValues().get(0).asInt32());
diff --git a/jrt/tests/com/yahoo/jrt/LatencyTest.java b/jrt/tests/com/yahoo/jrt/LatencyTest.java
index 0df15ed400b..945833e51a8 100644
--- a/jrt/tests/com/yahoo/jrt/LatencyTest.java
+++ b/jrt/tests/com/yahoo/jrt/LatencyTest.java
@@ -2,6 +2,7 @@
package com.yahoo.jrt;
+import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Logger;
@@ -116,7 +117,7 @@ public class LatencyTest {
}
Request req = new Request("inc");
req.parameters().add(new Int32Value(value));
- target.invokeSync(req, 60.0);
+ target.invokeSync(req, Duration.ofSeconds(60));
long duration = System.nanoTime() - t;
assertTrue(req.checkReturnTypes("i"));
assertEquals(value + 1, req.returnValues().get(0).asInt32());
diff --git a/jrt/tests/com/yahoo/jrt/MandatoryMethodsTest.java b/jrt/tests/com/yahoo/jrt/MandatoryMethodsTest.java
index 212447dd6da..c0ef9606b1f 100644
--- a/jrt/tests/com/yahoo/jrt/MandatoryMethodsTest.java
+++ b/jrt/tests/com/yahoo/jrt/MandatoryMethodsTest.java
@@ -5,6 +5,7 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
@@ -38,7 +39,7 @@ public class MandatoryMethodsTest {
@org.junit.Test
public void testPing() {
Request req = new Request("frt.rpc.ping");
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertFalse(req.isError());
assertEquals(0, req.returnValues().size());
@@ -47,7 +48,7 @@ public class MandatoryMethodsTest {
@org.junit.Test
public void testGetMethodList() {
Request req = new Request("frt.rpc.getMethodList");
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertFalse(req.isError());
assertTrue(req.checkReturnTypes("SSS"));
@@ -81,7 +82,7 @@ public class MandatoryMethodsTest {
public void testGetMethodInfo() {
Request req = new Request("frt.rpc.getMethodInfo");
req.parameters().add(new StringValue("frt.rpc.getMethodInfo"));
- target.invokeSync(req, 5.0);
+ target.invokeSync(req, Duration.ofSeconds(5));
assertFalse(req.isError());
assertTrue(req.checkReturnTypes("sssSSSS"));
diff --git a/jrt/tests/com/yahoo/jrt/SimpleRequestAccessFilter.java b/jrt/tests/com/yahoo/jrt/SimpleRequestAccessFilter.java
new file mode 100644
index 00000000000..38d59720848
--- /dev/null
+++ b/jrt/tests/com/yahoo/jrt/SimpleRequestAccessFilter.java
@@ -0,0 +1,9 @@
+package com.yahoo.jrt;// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+/**
+ * @author bjorncs
+ */
+class SimpleRequestAccessFilter implements RequestAccessFilter {
+ volatile boolean invoked = false, allowed = true;
+ @Override public boolean allow(Request r) { invoked = true; return allowed; }
+}
diff --git a/jrt/tests/com/yahoo/jrt/TimeoutTest.java b/jrt/tests/com/yahoo/jrt/TimeoutTest.java
index 0366020b221..1a802758e60 100644
--- a/jrt/tests/com/yahoo/jrt/TimeoutTest.java
+++ b/jrt/tests/com/yahoo/jrt/TimeoutTest.java
@@ -5,6 +5,8 @@ package com.yahoo.jrt;
import org.junit.After;
import org.junit.Before;
+import java.time.Duration;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -52,11 +54,11 @@ public class TimeoutTest {
req.parameters().add(new StringValue("abc"));
req.parameters().add(new StringValue("def"));
- target.invokeSync(req, 0.1);
+ target.invokeSync(req, Duration.ofMillis(100));
barrier.breakIt();
Request flush = new Request("frt.rpc.ping");
- target.invokeSync(flush, 5.0);
+ target.invokeSync(flush, Duration.ofSeconds(5));
assertTrue(!flush.isError());
assertTrue(req.isError());
@@ -72,7 +74,7 @@ public class TimeoutTest {
req.parameters().add(new StringValue("def"));
Test.Waiter w = new Test.Waiter();
- target.invokeAsync(req, 30.0, w);
+ target.invokeAsync(req, Duration.ofSeconds(30), w);
try { Thread.sleep(2500); } catch (InterruptedException e) {}
barrier.breakIt();
w.waitDone();
diff --git a/logserver/pom.xml b/logserver/pom.xml
index 61b777ad86b..68ed459f315 100644
--- a/logserver/pom.xml
+++ b/logserver/pom.xml
@@ -27,11 +27,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>vespalog</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/logserver/src/main/java/com/yahoo/logserver/testutils/VerifyLogfile.java b/logserver/src/main/java/com/yahoo/logserver/testutils/VerifyLogfile.java
deleted file mode 100644
index ec99f99b930..00000000000
--- a/logserver/src/main/java/com/yahoo/logserver/testutils/VerifyLogfile.java
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.logserver.testutils;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-
-import com.yahoo.log.LogLevel;
-import com.yahoo.log.event.MalformedEventException;
-import com.yahoo.log.InvalidLogFormatException;
-import com.yahoo.log.LogMessage;
-
-/**
- * This utility is used to check that the log messages contained
- * in a log file are correct. Any incorrectly formatted log
- * message is output to stdout.
- *
- * @author Bjorn Borud
- */
-@SuppressWarnings("deprecation")
-public class VerifyLogfile {
-
- public static void main (String[] args) throws IOException {
- int messages = 0;
- int events = 0;
- int invalidLogMessages = 0;
- int invalidEvents = 0;
- int numFiles = 0;
-
- if (args.length < 1) {
- System.err.println("\nPlease provide name of log file(s)\n");
- }
-
- for (int i = 0; i < args.length; i++) {
- BufferedReader br = new BufferedReader(new FileReader(args[i]));
- numFiles++;
- for (String line = br.readLine();
- line != null;
- line = br.readLine())
- {
- messages++;
- LogMessage m;
- try {
- m = LogMessage.parseNativeFormat(line);
- if (m.getLevel() == LogLevel.EVENT) {
- events++;
- m.getEvent();
- }
- } catch (MalformedEventException e) {
- System.out.println("EVENT\t" + line);
- invalidEvents++;
- } catch (InvalidLogFormatException e) {
- System.out.println("MESSAGE\t" + line);
- invalidLogMessages++;
- }
- }
- br.close();
- }
-
- System.err.println("numFiles: " + numFiles);
- System.err.println("messages: " + messages);
- System.err.println("events: " + events);
- System.err.println("invalidLogMessages: " + invalidLogMessages);
- System.err.println("invalidEvents: " + invalidEvents);
- }
-}
diff --git a/logserver/src/test/java/ai/vespa/logserver/protocol/ArchiveLogMessagesMethodTest.java b/logserver/src/test/java/ai/vespa/logserver/protocol/ArchiveLogMessagesMethodTest.java
index d60587d1642..1a95909c8a4 100644
--- a/logserver/src/test/java/ai/vespa/logserver/protocol/ArchiveLogMessagesMethodTest.java
+++ b/logserver/src/test/java/ai/vespa/logserver/protocol/ArchiveLogMessagesMethodTest.java
@@ -15,6 +15,7 @@ import com.yahoo.log.LogMessage;
import com.yahoo.logserver.LogDispatcher;
import org.junit.Test;
+import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
@@ -68,7 +69,7 @@ public class ArchiveLogMessagesMethodTest {
request.parameters().add(new Int8Value((byte)0));
request.parameters().add(new Int32Value(requestPayload.length));
request.parameters().add(new DataValue(requestPayload));
- target.invokeSync(request, 30/*seconds*/);
+ target.invokeSync(request, Duration.ofSeconds(30));
Values returnValues = request.returnValues();
assertEquals(3, returnValues.size());
assertEquals(0, returnValues.get(0).asInt8());
diff --git a/messagebus/pom.xml b/messagebus/pom.xml
index 512c001e3ff..10ce87a429b 100644
--- a/messagebus/pom.xml
+++ b/messagebus/pom.xml
@@ -15,11 +15,6 @@
<packaging>jar</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>vespajlib</artifactId>
<version>${project.version}</version>
@@ -37,6 +32,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config</artifactId>
<version>${project.version}</version>
diff --git a/messagebus/src/main/java/com/yahoo/messagebus/MessageBus.java b/messagebus/src/main/java/com/yahoo/messagebus/MessageBus.java
index c3279d994c9..19d3b5b3e43 100644
--- a/messagebus/src/main/java/com/yahoo/messagebus/MessageBus.java
+++ b/messagebus/src/main/java/com/yahoo/messagebus/MessageBus.java
@@ -14,6 +14,7 @@ import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.routing.RoutingSpec;
import com.yahoo.messagebus.routing.RoutingTable;
import com.yahoo.messagebus.routing.RoutingTableSpec;
+import com.yahoo.protect.Process;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
@@ -148,8 +149,10 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
// Attach and start network.
this.net = net;
net.attach(this);
- if ( ! net.net().waitUntilReady(120))
+ if ( ! net.net().waitUntilReady(120)) {
+ Process.dumpThreads();
throw new IllegalStateException("Network failed to become ready in time.");
+ }
// Start messenger.
msn = new Messenger();
@@ -467,6 +470,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
*
* @return The resender.
*/
+ @Deprecated // Remove on 9
public Resender getResender() {
return resender;
}
@@ -477,6 +481,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
*
* @return The pending count.
*/
+ @Deprecated // Package private on 9
public synchronized int getPendingCount() {
return pendingCount;
}
@@ -487,6 +492,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
*
* @return The pending size.
*/
+ @Deprecated // Package private on 9
public synchronized int getPendingSize() {
return pendingSize;
}
@@ -497,6 +503,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
*
* @param maxCount The max count.
*/
+ @Deprecated // Remove on 9
public void setMaxPendingCount(int maxCount) {
maxPendingCount = maxCount;
}
@@ -505,6 +512,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
* Gets maximum number of messages that can be received without being
* replied to yet.
*/
+ @Deprecated // Remove on 9
public int getMaxPendingCount() {
return maxPendingCount;
}
@@ -515,6 +523,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
*
* @param maxSize The max size.
*/
+ @Deprecated // Remove on 9
public void setMaxPendingSize(int maxSize) {
maxPendingSize = maxSize;
}
@@ -523,6 +532,7 @@ public class MessageBus implements ConfigHandler, NetworkOwner, MessageHandler,
* Gets maximum combined size of messages that can be received without
* being replied to yet.
*/
+ @Deprecated // Remove on 9
public int getMaxPendingSize() {
return maxPendingSize;
}
diff --git a/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCNetwork.java b/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCNetwork.java
index 811d8a25459..b4fa7d8f887 100644
--- a/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCNetwork.java
+++ b/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCNetwork.java
@@ -32,6 +32,7 @@ import com.yahoo.messagebus.routing.RoutingNode;
import java.io.PrintWriter;
import java.io.StringWriter;
+import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@@ -240,7 +241,7 @@ public class RPCNetwork implements Network, MethodHandler {
@Override
public void send(Message msg, List<RoutingNode> recipients) {
SendContext ctx = new SendContext(this, msg, recipients);
- double timeout = ctx.msg.getTimeRemainingNow() / 1000.0;
+ Duration timeout = Duration.ofMillis(ctx.msg.getTimeRemainingNow());
for (RoutingNode recipient : ctx.recipients) {
RPCServiceAddress address = (RPCServiceAddress)recipient.getServiceAddress();
address.getTarget().resolveVersion(timeout, ctx);
diff --git a/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCTarget.java b/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCTarget.java
index 85f50051e34..6fbab1a4b7f 100755
--- a/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCTarget.java
+++ b/messagebus/src/main/java/com/yahoo/messagebus/network/rpc/RPCTarget.java
@@ -7,6 +7,8 @@ import com.yahoo.jrt.RequestWaiter;
import com.yahoo.jrt.Spec;
import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
+
+import java.time.Duration;
import java.util.logging.Level;
import com.yahoo.text.Utf8Array;
@@ -95,7 +97,7 @@ public class RPCTarget implements RequestWaiter {
* @param timeout The timeout for the request in seconds.
* @param handler The handler to be called once the version is available.
*/
- void resolveVersion(double timeout, VersionHandler handler) {
+ void resolveVersion(Duration timeout, VersionHandler handler) {
boolean hasVersion = false;
boolean shouldInvoke = false;
boolean shouldLog = log.isLoggable(Level.FINE);
@@ -158,8 +160,7 @@ public class RPCTarget implements RequestWaiter {
/**
* <p>Declares a version handler used when resolving the version of a
* target. An instance of this is passed to {@link
- * RPCTarget#resolveVersion(double,
- * com.yahoo.messagebus.network.rpc.RPCTarget.VersionHandler)}, and invoked
+ * RPCTarget#resolveVersion(Duration, RPCTarget.VersionHandler)}, and invoked
* either synchronously or asynchronously, depending on whether or not the
* version is already available.</p>
*/
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
index 60ec6c400a9..a8a1fc33284 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
@@ -10,17 +10,13 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -32,7 +28,7 @@ public class ChokeTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -45,7 +41,7 @@ public class ChokeTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -55,7 +51,8 @@ public class ChokeTestCase {
}
@Test
- public void testMaxCount() {
+ @SuppressWarnings("deprecation")
+ void testMaxCount() {
int max = 10;
dstServer.mb.setMaxPendingCount(max);
List<Message> lst = new ArrayList<>();
@@ -67,11 +64,11 @@ public class ChokeTestCase {
}
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
if (i < max) {
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
lst.add(msg);
} else {
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.SESSION_BUSY, reply.getError(0).getCode());
@@ -81,13 +78,13 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
assertNotNull(msg = reply.getMessage());
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
lst.add(msg);
}
while (!lst.isEmpty()) {
@@ -95,7 +92,7 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
}
@@ -103,7 +100,8 @@ public class ChokeTestCase {
}
@Test
- public void testMaxSize() {
+ @SuppressWarnings("deprecation")
+ void testMaxSize() {
int size = createMessage("msg").getApproxSize();
int max = size * 10;
dstServer.mb.setMaxPendingSize(max);
@@ -116,11 +114,11 @@ public class ChokeTestCase {
}
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
if (i < max) {
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
lst.add(msg);
} else {
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.SESSION_BUSY, reply.getError(0).getCode());
@@ -130,13 +128,13 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
assertNotNull(msg = reply.getMessage());
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
lst.add(msg);
}
while (!lst.isEmpty()) {
@@ -144,7 +142,7 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
index a32175ff414..ad8e8a7c94e 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
@@ -4,26 +4,24 @@ package com.yahoo.messagebus;
import com.yahoo.config.subscription.ConfigSet;
import com.yahoo.config.subscription.ConfigURI;
import com.yahoo.messagebus.routing.RoutingSpec;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
*/
public class ConfigAgentTestCase {
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void testRoutingConfig() throws InterruptedException {
+ void testRoutingConfig() throws InterruptedException {
LocalHandler handler = new LocalHandler();
assertFalse(testHalf(handler.spec));
assertFalse(testFull(handler.spec));
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java b/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
index 9307396ceab..8f9ed2323d7 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
@@ -3,7 +3,7 @@ package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayDeque;
import java.util.Collections;
@@ -16,7 +16,7 @@ import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toUnmodifiableList;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* These tests are based on a simulated server, the {@link MockServer} below.
@@ -37,7 +37,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void singlePolicyWithSmallWindows() {
+ void singlePolicyWithSmallWindows() {
long operations = 1_000_000;
int numberOfWorkers = 1;
int maximumTasksPerWorker = 16;
@@ -48,8 +48,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -66,8 +66,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double maxMaxPending = numberOfWorkers * maximumTasksPerWorker;
@@ -82,8 +82,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -96,7 +96,7 @@ public class DynamicThrottlePolicyTest {
/** Sort of a dummy test, as the conditions are perfect. In a more realistic scenario, below, the algorithm needs luck to climb this high. */
@Test
- public void singlePolicySingleWorkerWithIncreasingParallelism() {
+ void singlePolicySingleWorkerWithIncreasingParallelism() {
for (int exponent = 0; exponent < 4; exponent++) {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
@@ -119,7 +119,7 @@ public class DynamicThrottlePolicyTest {
/** A more realistic test, where throughput gradually flattens with increasing window size, and with more variance in throughput. */
@Test
- public void singlePolicyIncreasingWorkersWithNoParallelism() {
+ void singlePolicyIncreasingWorkersWithNoParallelism() {
for (int exponent = 0; exponent < 4; exponent++) {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
@@ -149,7 +149,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void twoWeightedPoliciesWithUnboundedTaskQueue() {
+ void twoWeightedPoliciesWithUnboundedTaskQueue() {
for (int repeat = 0; repeat < 3; repeat++) {
long operations = 1_000_000;
int workPerSuccess = 6 + (int) (30 * Math.random());
@@ -173,7 +173,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void tenPoliciesVeryParallelServerWithShortTaskQueue() {
+ void tenPoliciesVeryParallelServerWithShortTaskQueue() {
for (int repeat = 0; repeat < 2; repeat++) {
long operations = 1_000_000;
int workPerSuccess = 6;
@@ -183,11 +183,11 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
int p = 10;
DynamicThrottlePolicy[] policies = IntStream.range(0, p)
- .mapToObj(j -> new DynamicThrottlePolicy(timer)
- .setWeight((j + 1.0) / p)
- .setWindowSizeIncrement(5)
- .setMinWindowSize(1))
- .toArray(DynamicThrottlePolicy[]::new);
+ .mapToObj(j -> new DynamicThrottlePolicy(timer)
+ .setWeight((j + 1.0) / p)
+ .setWindowSizeIncrement(5)
+ .setMinWindowSize(1))
+ .toArray(DynamicThrottlePolicy[]::new);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policies);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -198,8 +198,8 @@ public class DynamicThrottlePolicyTest {
double imperfectionFactor = 1.6;
// Actual shares are not distributed perfectly proportionally to weights, but close enough.
assertInRange(minMaxPending * expectedShare / imperfectionFactor,
- summary.averageWindows[j],
- maxMaxPending * expectedShare * imperfectionFactor);
+ summary.averageWindows[j],
+ maxMaxPending * expectedShare * imperfectionFactor);
}
assertInRange(1.0, summary.inefficiency, 1.05);
assertInRange(0, summary.waste, 0.1);
@@ -208,8 +208,8 @@ public class DynamicThrottlePolicyTest {
static void assertInRange(double lower, double actual, double upper) {
System.err.printf("%10.4f <= %10.4f <= %10.4f\n", lower, actual, upper);
- assertTrue(actual + " should be not be smaller than " + lower, lower <= actual);
- assertTrue(actual + " should be not be greater than " + upper, upper >= actual);
+ assertTrue(lower <= actual, actual + " should be not be smaller than " + lower);
+ assertTrue(upper >= actual, actual + " should be not be greater than " + upper);
}
private Summary run(long operations, int workPerSuccess, int numberOfWorkers, int maximumTasksPerWorker,
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
index 82696d839d9..26e3661a137 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
@@ -7,11 +7,11 @@ import com.yahoo.messagebus.routing.RoutingTableSpec;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.*;
public class ErrorTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Error err = new Error(69, "foo");
assertEquals(69, err.getCode());
assertEquals("foo", err.getMessage());
@@ -31,7 +31,7 @@ public class ErrorTestCase {
}
@Test
- public void requireThatErrorIsPropagated() throws Exception {
+ void requireThatErrorIsPropagated() throws Exception {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("itr", "test/itr/session", Arrays.asList("test/itr/session"));
table.addHop("dst", "test/dst/session", Arrays.asList("test/dst/session"));
@@ -89,8 +89,9 @@ public class ErrorTestCase {
src.destroy();
slobrok.stop();
}
+
@Test
- public void testErrorCodeCategorization() {
+ void testErrorCodeCategorization() {
assertTrue(ErrorCode.isFatal(ErrorCode.FATAL_ERROR));
assertFalse(ErrorCode.isTransient(ErrorCode.FATAL_ERROR));
assertTrue(ErrorCode.isMBusError(ErrorCode.FATAL_ERROR));
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
index 69a5401a27e..314d8558735 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
@@ -14,24 +14,24 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class MessageBusTestCase {
@Test
- public void requireThatBucketSequencingWithResenderEnabledCausesError() throws ListenFailedException {
+ void requireThatBucketSequencingWithResenderEnabledCausesError() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams()
- .addProtocol(new SimpleProtocol())
- .setRetryPolicy(new RetryTransientErrorsPolicy()),
- new RPCNetworkParams()
- .setSlobrokConfigId(slobrok.configId()));
+ .addProtocol(new SimpleProtocol())
+ .setRetryPolicy(new RetryTransientErrorsPolicy()),
+ new RPCNetworkParams()
+ .setSlobrokConfigId(slobrok.configId()));
Receptor receptor = new Receptor();
SourceSession session = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(receptor));
@@ -51,7 +51,7 @@ public class MessageBusTestCase {
}
@Test
- public void testConnectionSpec() throws ListenFailedException, UnknownHostException {
+ void testConnectionSpec() throws ListenFailedException, UnknownHostException {
// Setup servers and sessions.
Slobrok slobrok = new Slobrok();
List<TestServer> servers = new ArrayList<>();
@@ -84,28 +84,28 @@ public class MessageBusTestCase {
assertTrue(src.send(msg, Route.parse(route.toString())).isAccepted());
for (IntermediateSession itr : sessions) {
// Received using session name.
- assertNotNull(msg = ((Receptor)itr.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
itr.forward(msg);
// Received using connection spec.
- assertNotNull(msg = ((Receptor)itr.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
itr.forward(msg);
}
- assertNotNull(msg = ((Receptor)dst.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dst.getMessageHandler()).getMessage(60));
dst.acknowledge(msg);
- for (int i = sessions.size(); --i >= 0;) {
+ for (int i = sessions.size(); --i >= 0; ) {
IntermediateSession itr = sessions.get(i);
// Received for connection spec.
- Reply reply = ((Receptor)itr.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) itr.getReplyHandler()).getReply(60);
assertNotNull(reply);
itr.forward(reply);
// Received for session name.
- assertNotNull(reply = ((Receptor)itr.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) itr.getReplyHandler()).getReply(60));
itr.forward(reply);
}
- assertNotNull(((Receptor)src.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) src.getReplyHandler()).getReply(60));
// Cleanup.
for (IntermediateSession session : sessions) {
@@ -118,13 +118,13 @@ public class MessageBusTestCase {
}
@Test
- public void testRoutingPolicyCache() throws ListenFailedException, UnknownHostException {
+ void testRoutingPolicyCache() throws ListenFailedException, UnknownHostException {
Slobrok slobrok = new Slobrok();
String config = "slobrok[1]\nslobrok[0].connectionspec \"" + new Spec("localhost", slobrok.port()).toString() + "\"\n";
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
MessageBus bus = new MessageBus(new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId("raw:" + config)),
- new MessageBusParams().addProtocol(protocol));
+ new MessageBusParams().addProtocol(protocol));
RoutingPolicy all = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", null);
assertNotNull(all);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
index 5bfb36f194b..cacbd08ab1c 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class MessengerTestCase {
@Test
- public void requireThatSyncWithSelfDoesNotCauseDeadLock() throws InterruptedException {
+ void requireThatSyncWithSelfDoesNotCauseDeadLock() throws InterruptedException {
final Messenger msn = new Messenger();
msn.start();
@@ -35,14 +35,14 @@ public class MessengerTestCase {
}
@Test
- public void requireThatTaskIsExecuted() throws InterruptedException {
+ void requireThatTaskIsExecuted() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
assertTrue(tryMessenger(msn));
}
@Test
- public void requireThatRunExceptionIsCaught() throws InterruptedException {
+ void requireThatRunExceptionIsCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
@@ -60,7 +60,7 @@ public class MessengerTestCase {
}
@Test
- public void requireThatDestroyExceptionIsCaught() throws InterruptedException {
+ void requireThatDestroyExceptionIsCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
@@ -78,7 +78,7 @@ public class MessengerTestCase {
}
@Test
- public void requireThatRunAndDestroyExceptionsAreCaught() throws InterruptedException {
+ void requireThatRunAndDestroyExceptionsAreCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
index af2b4148a3c..c587550a2f5 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.messagebus;
import com.yahoo.messagebus.routing.RoutingContext;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.*;
public class ProtocolRepositoryTestCase {
@Test
- public void requireThatPolicyCanBeNull() {
+ void requireThatPolicyCanBeNull() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
repo.putProtocol(protocol);
@@ -22,7 +22,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyCanBeCreated() {
+ void requireThatPolicyCanBeCreated() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -31,7 +31,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyIsCached() {
+ void requireThatPolicyIsCached() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -46,7 +46,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyParamIsPartOfCacheKey() {
+ void requireThatPolicyParamIsPartOfCacheKey() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -61,7 +61,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatCreatePolicyExceptionIsCaught() {
+ void requireThatCreatePolicyExceptionIsCaught() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
index f52cb1df2fe..5e579f5d622 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
@@ -2,15 +2,15 @@
package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
public class RateThrottlingTestCase {
@Test
- public void testPending() {
+ void testPending() {
CustomTimer timer = new CustomTimer();
RateThrottlingPolicy policy = new RateThrottlingPolicy(5.0, timer);
policy.setMaxPendingCount(200);
@@ -35,7 +35,7 @@ public class RateThrottlingTestCase {
}
@Test
- public void testRates() {
+ void testRates() {
assertEquals(10, getActualRate(0.1), 1);
assertEquals(1000, getActualRate(10), 100);
assertEquals(500, getActualRate(5), 50);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
index ca60bb8024c..9802a7099d8 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
@@ -8,22 +8,18 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class RoutableTestCase {
private final double delta = 0.00000001;
@Test
- public void testMessageContext() throws ListenFailedException {
+ void testMessageContext() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer srcServer = new TestServer("src", null, slobrok, null);
TestServer dstServer = new TestServer("dst", null, slobrok, null);
@@ -39,10 +35,10 @@ public class RoutableTestCase {
msg.setContext(context);
assertTrue(srcSession.send(msg, "dst/session", true).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertSame(reply.getContext(), context);
@@ -54,7 +50,7 @@ public class RoutableTestCase {
}
@Test
- public void testMessageSwapState() {
+ void testMessageSwapState() {
Message foo = new SimpleMessage("foo");
Route fooRoute = Route.parse("foo");
foo.setRoute(fooRoute);
@@ -80,7 +76,7 @@ public class RoutableTestCase {
}
@Test
- public void testReplySwapState() {
+ void testReplySwapState() {
Reply foo = new SimpleReply("foo");
Message fooMsg = new SimpleMessage("foo");
foo.setMessage(fooMsg);
@@ -104,7 +100,7 @@ public class RoutableTestCase {
}
@Test
- public void testMessageDiscard() {
+ void testMessageDiscard() {
Receptor handler = new Receptor();
Message msg = new SimpleMessage("foo");
msg.pushHandler(handler);
@@ -114,7 +110,7 @@ public class RoutableTestCase {
}
@Test
- public void testReplyDiscard() {
+ void testReplyDiscard() {
Receptor handler = new Receptor();
Message msg = new SimpleMessage("foo");
msg.pushHandler(handler);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
index b51fc2da3de..2cce53c51e1 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
@@ -13,18 +13,15 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -36,7 +33,7 @@ public class SendProxyTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -49,7 +46,7 @@ public class SendProxyTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -59,7 +56,7 @@ public class SendProxyTestCase {
}
@Test
- public void testTraceByLogLevel() {
+ void testTraceByLogLevel() {
Logger log = Logger.getLogger(SendProxy.class.getName());
LogHandler logHandler = new LogHandler();
log.addHandler(logHandler);
@@ -77,17 +74,17 @@ public class SendProxyTestCase {
sendMessage(0, new Error(ErrorCode.FATAL_ERROR, "err"));
assertEquals("Trace for reply with error(s):\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " [FATAL_ERROR @ localhost]: err\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 2) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " [FATAL_ERROR @ localhost]: err\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 2) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
log.setLevel(Level.FINEST);
@@ -96,16 +93,16 @@ public class SendProxyTestCase {
sendMessage(0, null);
assertEquals("Trace for reply:\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 0) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 0) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
sendMessage(1, new Error(ErrorCode.FATAL_ERROR, "err"));
@@ -113,17 +110,17 @@ public class SendProxyTestCase {
sendMessage(0, new Error(ErrorCode.FATAL_ERROR, "err"));
assertEquals("Trace for reply with error(s):\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " [FATAL_ERROR @ localhost]: err\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 2) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " [FATAL_ERROR @ localhost]: err\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 2) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
index 07de8f238bc..c3166a578b5 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
@@ -2,14 +2,12 @@
package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.Queue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -17,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class SequencerTestCase {
@Test
- public void testSyncNone() {
+ void testSyncNone() {
TestQueue src = new TestQueue();
TestQueue dst = new TestQueue();
QueueSender sender = new QueueSender(dst);
@@ -49,7 +47,7 @@ public class SequencerTestCase {
}
@Test
- public void testSyncId() {
+ void testSyncId() {
TestQueue src = new TestQueue();
TestQueue dst = new TestQueue();
QueueSender sender = new QueueSender(dst);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
index f13749ae213..0f930c51152 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
@@ -11,11 +11,9 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -23,32 +21,32 @@ import static org.junit.Assert.assertTrue;
public class SimpleTripTestCase {
@Test
- public void testSimpleTrip() throws ListenFailedException {
+ void testSimpleTrip() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
- new RPCNetworkParams()
- .setIdentity(new Identity("srv"))
- .setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
+ new RPCNetworkParams()
+ .setIdentity(new Identity("srv"))
+ .setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
DestinationSession dst = server.mb.createDestinationSession(new DestinationSessionParams().setName("session").setMessageHandler(new Receptor()));
SourceSession src = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(new Receptor()));
assertTrue(server.waitSlobrok("srv/session", 1));
assertTrue(src.send(new SimpleMessage("msg"), Route.parse("srv/session")).isAccepted());
- Message msg = ((Receptor)dst.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dst.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertEquals(SimpleProtocol.NAME, msg.getProtocol());
assertEquals(SimpleProtocol.MESSAGE, msg.getType());
- assertEquals("msg", ((SimpleMessage)msg).getValue());
+ assertEquals("msg", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("reply");
reply.swapState(msg);
dst.reply(reply);
- assertNotNull(reply = ((Receptor)src.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) src.getReplyHandler()).getReply(60));
assertEquals(SimpleProtocol.NAME, reply.getProtocol());
assertEquals(SimpleProtocol.REPLY, reply.getType());
- assertEquals("reply", ((SimpleReply)reply).getValue());
+ assertEquals("reply", ((SimpleReply) reply).getValue());
src.destroy();
dst.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
index c308380dbb2..045dc1177db 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
@@ -10,16 +10,13 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -29,7 +26,7 @@ public class ThrottlerTestCase {
Slobrok slobrok;
TestServer src, dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("dst", "test/dst/session", Arrays.asList("test/dst/session"));
@@ -39,7 +36,7 @@ public class ThrottlerTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
src.destroy();
@@ -47,7 +44,7 @@ public class ThrottlerTestCase {
}
@Test
- public void testMaxCount() {
+ void testMaxCount() {
// Prepare a source session with throttle enabled.
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
StaticThrottlePolicy policy = new StaticThrottlePolicy();
@@ -71,7 +68,7 @@ public class ThrottlerTestCase {
// Acknowledge one message at a time, then attempt to send two more.
for (int i = 0; i < 10; i++) {
assertTrue(dst_q.waitSize(policy.getMaxPendingCount(), 60));
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertTrue(src_s.send(new SimpleMessage("msg"), "test").isAccepted());
@@ -80,7 +77,7 @@ public class ThrottlerTestCase {
assertTrue(dst_q.waitSize(policy.getMaxPendingCount(), 60));
while (!dst_q.isEmpty()) {
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
}
src_s.close();
@@ -88,7 +85,7 @@ public class ThrottlerTestCase {
}
@Test
- public void testMaxSize() {
+ void testMaxSize() {
// Prepare a source session with throttle enabled.
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
StaticThrottlePolicy policy = new StaticThrottlePolicy();
@@ -110,17 +107,17 @@ public class ThrottlerTestCase {
assertTrue(dst_q.waitSize(2, 60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertTrue(src_s.send(new SimpleMessage("12"), "test").isAccepted());
assertTrue(dst_q.waitSize(1, 60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
// Close sessions.
@@ -129,12 +126,12 @@ public class ThrottlerTestCase {
}
@Test
- public void testDynamicWindowSize() {
+ void testDynamicWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setResizeRate(1);
+ .setResizeRate(1);
double windowSize = getWindowSize(policy, timer, 100);
assertTrue(windowSize >= 90 && windowSize <= 105);
@@ -153,13 +150,13 @@ public class ThrottlerTestCase {
}
@Test
- public void testIdleTimePeriod() {
+ void testIdleTimePeriod() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setMinWindowSize(1)
- .setResizeRate(1);
+ .setMinWindowSize(1)
+ .setResizeRate(1);
double windowSize = getWindowSize(policy, timer, 100);
assertTrue(windowSize >= 90 && windowSize <= 110);
@@ -180,20 +177,20 @@ public class ThrottlerTestCase {
}
@Test
- public void testMinWindowSize() {
+ void testMinWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setResizeRate(1)
- .setMinWindowSize(150);
+ .setResizeRate(1)
+ .setMinWindowSize(150);
double windowSize = getWindowSize(policy, timer, 200);
assertTrue(windowSize >= 150 && windowSize <= 210);
}
@Test
- public void testMaxWindowSize() {
+ void testMaxWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
index a834b27156a..3957b7de985 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -43,12 +43,12 @@ public class TimeoutTestCase {
new SourceSessionParams().setTimeout(600.0).setReplyHandler(new Receptor()));
}
- @Before
+ @BeforeEach
public void waitForSlobrokRegistration() {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void destroyResources() {
slobrok.stop();
dstSession.destroy();
@@ -63,17 +63,17 @@ public class TimeoutTestCase {
}
@Test
- public void requireThatMessageCanTimeout() throws ListenFailedException, UnknownHostException {
+ void requireThatMessageCanTimeout() throws ListenFailedException, UnknownHostException {
srcSession.setTimeout(1);
assertSend(srcSession, newMessage(), "dst/session");
- assertTimeout(((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertTimeout(((Receptor) srcSession.getReplyHandler()).getReply(60));
}
@Test
- public void requireThatZeroTimeoutMeansImmediateTimeout() throws ListenFailedException, UnknownHostException {
+ void requireThatZeroTimeoutMeansImmediateTimeout() throws ListenFailedException, UnknownHostException {
srcSession.setTimeout(0);
assertSend(srcSession, newMessage(), "dst/session");
- assertTimeout(((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertTimeout(((Receptor) srcSession.getReplyHandler()).getReply(60));
}
private static void assertSend(SourceSession session, Message msg, String route) {
@@ -82,7 +82,7 @@ public class TimeoutTestCase {
private static void assertTimeout(Reply reply) {
assertNotNull(reply);
- assertTrue(reply.getTrace().toString(), hasError(reply, ErrorCode.TIMEOUT));
+ assertTrue(hasError(reply, ErrorCode.TIMEOUT), reply.getTrace().toString());
}
private static Message newMessage() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
index 7408079b7ac..2a6534a9445 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class TraceTestCase {
@Test
- public void testEncodeDecode() {
+ void testEncodeDecode() {
assertEquals("()", TraceNode.decode("").encode());
assertEquals("()", TraceNode.decode("[xyz").encode());
assertEquals("([xyz][])", TraceNode.decode("[xyz][]").encode());
@@ -25,12 +24,12 @@ public class TraceTestCase {
assertEquals("([])", TraceNode.decode("([])").encode());
assertTrue(TraceNode.decode("").isEmpty());
- assertTrue(!TraceNode.decode("([note])").isEmpty());
+ assertFalse(TraceNode.decode("([note])").isEmpty());
String str =
"([[17/Jun/2009:09:02:30 +0200\\] Message (type 1) received at 'dst' for session 'session'.]" +
- "[[17/Jun/2009:09:02:30 +0200\\] [APP_TRANSIENT_ERROR @ localhost\\]: err1]" +
- "[[17/Jun/2009:09:02:30 +0200\\] Sending reply (version 4.2) from 'dst'.])";
+ "[[17/Jun/2009:09:02:30 +0200\\] [APP_TRANSIENT_ERROR @ localhost\\]: err1]" +
+ "[[17/Jun/2009:09:02:30 +0200\\] Sending reply (version 4.2) from 'dst'.])";
System.out.println(TraceNode.decode(str).toString());
assertEquals(str, TraceNode.decode(str).encode());
@@ -40,7 +39,7 @@ public class TraceTestCase {
assertTrue(t.isRoot());
assertTrue(t.isStrict());
- assertTrue(!t.isLeaf());
+ assertFalse(t.isLeaf());
assertEquals(4, t.getNumChildren());
{
@@ -55,8 +54,8 @@ public class TraceTestCase {
}
{
TraceNode c = t.getChild(2);
- assertTrue(!c.isLeaf());
- assertTrue(!c.isStrict());
+ assertFalse(c.isLeaf());
+ assertFalse(c.isStrict());
assertEquals(1, c.getNumChildren());
{
TraceNode d = c.getChild(0);
@@ -66,12 +65,12 @@ public class TraceTestCase {
}
{
TraceNode c = t.getChild(3);
- assertTrue(!c.isStrict());
+ assertFalse(c.isStrict());
assertEquals(2, c.getNumChildren());
{
TraceNode d = c.getChild(0);
assertTrue(d.isStrict());
- assertTrue(!d.isLeaf());
+ assertFalse(d.isLeaf());
assertEquals(1, d.getNumChildren());
{
TraceNode e = d.getChild(0);
@@ -85,7 +84,7 @@ public class TraceTestCase {
assertEquals(1, d.getNumChildren());
{
TraceNode e = d.getChild(0);
- assertTrue(!e.isStrict());
+ assertFalse(e.isStrict());
assertEquals(1, e.getNumChildren());
{
TraceNode f = e.getChild(0);
@@ -98,7 +97,7 @@ public class TraceTestCase {
}
@Test
- public void testReservedChars() {
+ void testReservedChars() {
TraceNode t = new TraceNode();
t.addChild("abc(){}[]\\xyz");
assertEquals("abc(){}[]\\xyz", t.getChild(0).getNote());
@@ -108,7 +107,7 @@ public class TraceTestCase {
TraceNode t2 = new TraceNode();
assertTrue(t2.isEmpty());
t2.swap(t);
- assertTrue(!t2.isEmpty());
+ assertFalse(t2.isEmpty());
assertEquals("abc(){}[]\\xyz", t2.getChild(0).getNote());
assertEquals("([abc(){}[\\]\\\\xyz])", t2.encode());
t2.clear();
@@ -117,7 +116,7 @@ public class TraceTestCase {
}
@Test
- public void testAdd() {
+ void testAdd() {
TraceNode t1 = TraceNode.decode("([x])");
TraceNode t2 = TraceNode.decode("([y])");
TraceNode t3 = TraceNode.decode("([z])");
@@ -137,14 +136,14 @@ public class TraceTestCase {
}
@Test
- public void testStrict() {
+ void testStrict() {
assertEquals("{}", TraceNode.decode("()").setStrict(false).encode());
assertEquals("{[x]}", TraceNode.decode("([x])").setStrict(false).encode());
assertEquals("{[x][y]}", TraceNode.decode("([x][y])").setStrict(false).encode());
}
@Test
- public void testTraceLevel() {
+ void testTraceLevel() {
Trace t = new Trace();
t.setLevel(4);
assertEquals(4, t.getLevel());
@@ -171,7 +170,7 @@ public class TraceTestCase {
}
@Test
- public void testCompact() {
+ void testCompact() {
assertEquals("()", TraceNode.decode("()").compact().encode());
assertEquals("()", TraceNode.decode("(())").compact().encode());
assertEquals("()", TraceNode.decode("(()())").compact().encode());
@@ -201,7 +200,7 @@ public class TraceTestCase {
}
@Test
- public void testSort() {
+ void testSort() {
assertEquals("([b][a][c])", TraceNode.decode("([b][a][c])").sort().encode());
assertEquals("({[a][b][c]})", TraceNode.decode("({[b][a][c]})").sort().encode());
assertEquals("(([c][a])([b]))", TraceNode.decode("(([c][a])([b]))").sort().encode());
@@ -211,7 +210,7 @@ public class TraceTestCase {
}
@Test
- public void testNormalize() {
+ void testNormalize() {
TraceNode t1 = TraceNode.decode("({([a][b]{[x][y]([p][q])})([c][d])([e][f])})");
TraceNode t2 = TraceNode.decode("({([a][b]{[y][x]([p][q])})([c][d])([e][f])})");
TraceNode t3 = TraceNode.decode("({([a][b]{[y]([p][q])[x]})([c][d])([e][f])})");
@@ -224,13 +223,13 @@ public class TraceTestCase {
assertEquals("({([a][b]{[x][y]([p][q])})([c][d])([e][f])})", t1.compact().encode());
- assertTrue(!t1.compact().encode().equals(t2.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t3.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t4.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t5.compact().encode()));
- assertTrue(!t1.compact().encode().equals(tx.compact().encode()));
- assertTrue(!t1.compact().encode().equals(ty.compact().encode()));
- assertTrue(!t1.compact().encode().equals(tz.compact().encode()));
+ assertNotEquals(t1.compact().encode(), t2.compact().encode());
+ assertNotEquals(t1.compact().encode(), t3.compact().encode());
+ assertNotEquals(t1.compact().encode(), t4.compact().encode());
+ assertNotEquals(t1.compact().encode(), t5.compact().encode());
+ assertNotEquals(t1.compact().encode(), tx.compact().encode());
+ assertNotEquals(t1.compact().encode(), ty.compact().encode());
+ assertNotEquals(t1.compact().encode(), tz.compact().encode());
System.out.println("1: " + t1.normalize().encode());
System.out.println("2: " + t2.normalize().encode());
@@ -240,19 +239,19 @@ public class TraceTestCase {
System.out.println("x: " + tx.normalize().encode());
System.out.println("y: " + ty.normalize().encode());
System.out.println("z: " + tz.normalize().encode());
- assertTrue(t1.normalize().encode().equals(t2.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t3.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t4.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t5.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(tx.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(ty.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(tz.normalize().encode()));
+ assertEquals(t1.normalize().encode(), t2.normalize().encode());
+ assertEquals(t1.normalize().encode(), t3.normalize().encode());
+ assertEquals(t1.normalize().encode(), t4.normalize().encode());
+ assertEquals(t1.normalize().encode(), t5.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), tx.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), ty.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), tz.normalize().encode());
assertEquals("({([c][d])([e][f])([a][b]{[x][y]([p][q])})})", t1.normalize().encode());
}
@Test
- public void testTraceDump() {
+ void testTraceDump() {
{
Trace big = new Trace();
TraceNode b1 = new TraceNode();
@@ -283,17 +282,17 @@ public class TraceTestCase {
assertEquals("...\n", s1.toString(0));
assertEquals("<trace>\n...\n", s1.toString(1));
assertEquals("<trace>\n" + // 8 8
- " <trace>\n" + // 12 20
- " test\n" + // 13 33
- "...\n", s1.toString(33));
+ " <trace>\n" + // 12 20
+ " test\n" + // 13 33
+ "...\n", s1.toString(33));
assertEquals("<trace>\n" + // 8 8
- " test\n" + // 9 17
- " test\n" + // 9 26
- "...\n", s2.toString(26));
+ " test\n" + // 9 17
+ " test\n" + // 9 26
+ "...\n", s2.toString(26));
assertEquals("<trace>\n" + // 8 8
- " test\n" + // 9 17
- " test\n" + // 9 26
- "</trace>\n", s2.toString(27));
+ " test\n" + // 9 17
+ " test\n" + // 9 26
+ "</trace>\n", s2.toString(27));
assertEquals(s2.toString(27), s2.toString());
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
index cc3e689e33e..e8d2fd72a47 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
@@ -8,14 +8,15 @@ import com.yahoo.messagebus.routing.RoutingTableSpec;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +28,7 @@ public class TraceTripTestCase {
TestServer pxy;
TestServer dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME)
.addHop("pxy", "test/pxy/session", Arrays.asList("test/pxy/session"))
@@ -40,7 +41,7 @@ public class TraceTripTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
pxy.destroy();
@@ -49,7 +50,7 @@ public class TraceTripTestCase {
}
@Test
- public void testTrip() {
+ void testTrip() {
Receptor src_rr = new Receptor();
SourceSession src_s = src.mb.createSourceSession(src_rr);
@@ -66,18 +67,18 @@ public class TraceTripTestCase {
src_s.send(msg, "test");
Reply reply = src_rr.getReply(60);
reply.getTrace().trace(1, "Client reply", false);
- assertTrue(reply.getNumErrors() == 0);
+ assertEquals(reply.getNumErrors(), 0);
TraceNode t = new TraceNode()
- .addChild("Client message")
- .addChild("Proxy message")
- .addChild("Server message")
- .addChild("Server reply")
- .addChild("Proxy reply")
- .addChild("Client reply");
+ .addChild("Client message")
+ .addChild("Proxy message")
+ .addChild("Server message")
+ .addChild("Server reply")
+ .addChild("Proxy reply")
+ .addChild("Client reply");
System.out.println("reply: " + reply.getTrace().getRoot().encode());
System.out.println("want : " + t.encode());
- assertTrue(reply.getTrace().getRoot().encode().equals(t.encode()));
+ assertEquals(reply.getTrace().getRoot().encode(), t.encode());
}
private static class Proxy implements MessageHandler, ReplyHandler {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java
index 4309d17a407..5d2ca40df1a 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.network;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -12,14 +12,14 @@ import static org.junit.Assert.assertNotNull;
public class IdentityTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Identity id = new Identity("foo");
assertNotNull(id.getHostname());
assertEquals("foo", id.getServicePrefix());
}
@Test
- public void requireThatCopyConstructorWorks() {
+ void requireThatCopyConstructorWorks() {
Identity lhs = new Identity("foo");
Identity rhs = new Identity(lhs);
assertEquals(lhs.getHostname(), rhs.getHostname());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java b/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
index 58145bb4f25..60da1b49d90 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
@@ -19,10 +19,7 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author jonmv
@@ -30,7 +27,7 @@ import static org.junit.Assert.fail;
public class NetworkMultiplexerTest {
@Test
- public void testShared() {
+ void testShared() {
MockNetwork net = new MockNetwork();
MockOwner owner1 = new MockOwner();
MockOwner owner2 = new MockOwner();
@@ -95,7 +92,7 @@ public class NetworkMultiplexerTest {
}
@Test
- public void testDedicated() {
+ void testDedicated() {
MockNetwork net = new MockNetwork();
MockOwner owner = new MockOwner();
NetworkMultiplexer dedicated = NetworkMultiplexer.dedicated(net);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java b/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
index b3fec784d38..60618744c83 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
@@ -24,15 +24,13 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -40,7 +38,7 @@ import static org.junit.Assert.assertTrue;
public class LocalNetworkTest {
@Test
- public void requireThatLocalNetworkCanSendAndReceive() throws InterruptedException {
+ void requireThatLocalNetworkCanSendAndReceive() throws InterruptedException {
final LocalWire wire = new LocalWire();
final Server serverA = new Server(wire);
@@ -54,29 +52,29 @@ public class LocalNetworkTest {
Message msg = new SimpleMessage("foo");
msg.setRoute(new Route().addHop(Hop.parse(intermediate.getConnectionSpec()))
- .addHop(Hop.parse(destination.getConnectionSpec())));
+ .addHop(Hop.parse(destination.getConnectionSpec())));
assertTrue(source.send(msg).isAccepted());
msg = serverB.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
intermediate.forward(msg);
msg = serverC.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("bar");
reply.swapState(msg);
destination.reply(reply);
reply = serverB.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
intermediate.forward(reply);
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
serverA.mbus.destroy();
serverB.mbus.destroy();
@@ -84,7 +82,7 @@ public class LocalNetworkTest {
}
@Test
- public void requireThatUnknownServiceRepliesWithNoAddressForService() throws InterruptedException {
+ void requireThatUnknownServiceRepliesWithNoAddressForService() throws InterruptedException {
final Server server = new Server(new LocalWire());
final SourceSession source = server.newSourceSession();
@@ -97,7 +95,7 @@ public class LocalNetworkTest {
}
@Test
- public void requireThatBlockingSendTimeOutInSendQ() throws InterruptedException {
+ void requireThatBlockingSendTimeOutInSendQ() throws InterruptedException {
final LocalWire wire = new LocalWire();
final Server serverA = new Server(wire);
@@ -124,24 +122,24 @@ public class LocalNetworkTest {
assertEquals(ErrorCode.TIMEOUT, res.getError().getCode());
assertTrue(res.getError().getMessage().endsWith("Timed out in sendQ"));
long end = SystemTimer.INSTANCE.milliTime();
- assertTrue(end >= start+TIMEOUT);
- assertTrue(end < start+5*TIMEOUT);
+ assertTrue(end >= start + TIMEOUT);
+ assertTrue(end < start + 5 * TIMEOUT);
msg = serverB.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
intermediate.forward(msg);
msg = serverC.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("bar");
reply.swapState(msg);
destination.reply(reply);
reply = serverB.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
intermediate.forward(reply);
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
@@ -150,7 +148,7 @@ public class LocalNetworkTest {
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
serverA.mbus.destroy();
serverB.mbus.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
index 4134e352757..ffe15a7da29 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
@@ -13,16 +13,14 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -35,7 +33,7 @@ public class BasicNetworkTestCase {
TestServer pxy;
TestServer dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("pxy", "test/pxy/session", Arrays.asList("test/pxy/session"));
@@ -47,7 +45,7 @@ public class BasicNetworkTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
pxy.destroy();
@@ -56,7 +54,7 @@ public class BasicNetworkTestCase {
}
@Test
- public void testNetwork() {
+ void testNetwork() {
// set up receptors
Receptor src_rr = new Receptor();
Receptor pxy_mr = new Receptor();
@@ -126,7 +124,7 @@ public class BasicNetworkTestCase {
}
@Test
- public void testTimeoutsFollowMessage() {
+ void testTimeoutsFollowMessage() {
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
SourceSession ss = src.mb.createSourceSession(new Receptor(), params);
DestinationSession ds = dst.mb.createDestinationSession("session", true, new Receptor());
@@ -138,24 +136,24 @@ public class BasicNetworkTestCase {
long now = SystemTimer.INSTANCE.milliTime();
assertTrue(ss.send(msg, Route.parse("dst")).isAccepted());
- assertNotNull(msg = ((Receptor)ds.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) ds.getMessageHandler()).getMessage(60));
assertTrue(msg.getTimeReceived() >= now);
assertTrue(params.getTimeout() * 1000 >= msg.getTimeRemaining());
ds.acknowledge(msg);
- assertNotNull(((Receptor)ss.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) ss.getReplyHandler()).getReply(60));
// Test default timeouts being overwritten.
msg = new SimpleMessage("msg");
msg.getTrace().setLevel(9);
- msg.setTimeRemaining(2 * (long)(params.getTimeout() * 1000));
+ msg.setTimeRemaining(2 * (long) (params.getTimeout() * 1000));
assertTrue(ss.send(msg, Route.parse("dst")).isAccepted());
- assertNotNull(msg = ((Receptor)ds.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) ds.getMessageHandler()).getMessage(60));
assertTrue(params.getTimeout() * 1000 < msg.getTimeRemaining());
ds.acknowledge(msg);
- assertNotNull(((Receptor)ss.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) ss.getReplyHandler()).getReply(60));
ss.destroy();
ds.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
index 8ade06335f5..0856fb09318 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
@@ -9,12 +9,12 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.QueueAdapter;
import com.yahoo.messagebus.test.SimpleMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author havardpe
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue;
public class LoadBalanceTestCase {
@Test
- public void testLoadBalance() throws ListenFailedException {
+ void testLoadBalance() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer src = new TestServer("src", null, slobrok, null);
TestServer dst1 = new TestServer("dst/1", null, slobrok, null);
@@ -32,14 +32,14 @@ public class LoadBalanceTestCase {
// set up handlers
final QueueAdapter sq = new QueueAdapter();
SourceSession ss = src.mb.createSourceSession(new SourceSessionParams().setTimeout(600.0).setThrottlePolicy(null)
- .setReplyHandler(new ReplyHandler() {
- @Override
- public void handleReply(Reply reply) {
- System.out.println(Thread.currentThread().getName() + ": Reply '" +
- ((SimpleMessage)reply.getMessage()).getValue() + "' received at source.");
- sq.handleReply(reply);
- }
- }));
+ .setReplyHandler(new ReplyHandler() {
+ @Override
+ public void handleReply(Reply reply) {
+ System.out.println(Thread.currentThread().getName() + ": Reply '" +
+ ((SimpleMessage) reply.getMessage()).getValue() + "' received at source.");
+ sq.handleReply(reply);
+ }
+ }));
SimpleDestination h1 = new SimpleDestination(dst1.mb, dst1.net.getIdentity());
SimpleDestination h2 = new SimpleDestination(dst2.mb, dst2.net.getIdentity());
SimpleDestination h3 = new SimpleDestination(dst3.mb, dst3.net.getIdentity());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
index 0c42c592624..e8ea5f60715 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
@@ -17,12 +17,12 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.PrintWriter;
import java.io.StringWriter;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -30,12 +30,12 @@ import static org.junit.Assert.*;
public class RPCNetworkTestCase {
@Test
- public void requireThatProtocolEncodeExceptionIsCaught() throws Exception {
+ void requireThatProtocolEncodeExceptionIsCaught() throws Exception {
RuntimeException e = new RuntimeException();
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams().addProtocol(MyProtocol.newEncodeException(e)),
- new RPCNetworkParams().setSlobrokConfigId(slobrok.configId()));
+ new RPCNetworkParams().setSlobrokConfigId(slobrok.configId()));
Receptor receptor = new Receptor();
SourceSession src = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(receptor));
@@ -50,7 +50,7 @@ public class RPCNetworkTestCase {
e.printStackTrace(new PrintWriter(expected));
String actual = reply.getError(0).toString();
- assertTrue(actual, actual.contains(expected.toString()));
+ assertTrue(actual.contains(expected.toString()), actual);
}
private static class MyMessage extends Message {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
index 437be44ea25..c4cbf8ce6fb 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
@@ -21,18 +21,15 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -53,7 +50,7 @@ public class SendAdapterTestCase {
DestinationSession dstSession;
TestProtocol srcProtocol, itrProtocol, dstProtocol;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
slobrok = new Slobrok();
dstServer = new TestServer(
@@ -74,7 +71,7 @@ public class SendAdapterTestCase {
assertTrue(srcServer.waitSlobrok("*/session", 2));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -92,16 +89,16 @@ public class SendAdapterTestCase {
////////////////////////////////////////////////////////////////////////////////
@Test
- public void requireCorrectVersionSelection() {
- assertNull(srcServer.net.getSendAdapter(new Version(4,999)));
- assertNull(srcServer.net.getSendAdapter(new Version(5,0)));
- assertNull(srcServer.net.getSendAdapter(new Version(6,148)));
- assertTrue(srcServer.net.getSendAdapter(new Version(6,149)) instanceof RPCSendV2);
- assertTrue(srcServer.net.getSendAdapter(new Version(9,9999)) instanceof RPCSendV2);
+ void requireCorrectVersionSelection() {
+ assertNull(srcServer.net.getSendAdapter(new Version(4, 999)));
+ assertNull(srcServer.net.getSendAdapter(new Version(5, 0)));
+ assertNull(srcServer.net.getSendAdapter(new Version(6, 148)));
+ assertTrue(srcServer.net.getSendAdapter(new Version(6, 149)) instanceof RPCSendV2);
+ assertTrue(srcServer.net.getSendAdapter(new Version(9, 9999)) instanceof RPCSendV2);
}
@Test
- public void requireThatMessagesCanBeSentAcrossAllSupportedVersions() {
+ void requireThatMessagesCanBeSentAcrossAllSupportedVersions() {
List<Version> versions = Arrays.asList(
new Version(6, 149),
new Version(9, 999)
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
index bbf1b827c87..af039dc46cb 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
@@ -6,17 +6,14 @@ import com.yahoo.jrt.Spec;
import com.yahoo.jrt.slobrok.api.Mirror;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.Identity;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -26,7 +23,7 @@ public class ServiceAddressTestCase {
private Slobrok slobrok;
private RPCNetwork network;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
slobrok = new Slobrok();
network = new RPCNetwork(new RPCNetworkParams()
@@ -35,14 +32,14 @@ public class ServiceAddressTestCase {
new Spec("localhost", slobrok.port()).toString() + "\"\n"));
}
- @After
+ @AfterEach
public void tearDown() {
network.shutdown();
slobrok.stop();
}
@Test
- public void testAddrServiceAddress() {
+ void testAddrServiceAddress() {
assertNullAddress("tcp");
assertNullAddress("tcp/");
assertNullAddress("tcp/localhost");
@@ -56,7 +53,7 @@ public class ServiceAddressTestCase {
}
@Test
- public void testNameServiceAddress() {
+ void testNameServiceAddress() {
network.unregisterSession("session");
assertTrue(waitSlobrok("foo/session", 0));
assertNullAddress("foo/session");
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
index 4bb39e99a48..ed085c73b54 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
@@ -4,10 +4,9 @@ package com.yahoo.messagebus.network.rpc;
import com.yahoo.jrt.ListenFailedException;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.rpc.test.TestServer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -15,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class ServicePoolTestCase {
@Test
- public void testMaxSize() throws ListenFailedException {
+ void testMaxSize() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
RPCNetwork net = new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
RPCServicePool pool = new RPCServicePool(net, 2);
@@ -23,30 +22,30 @@ public class ServicePoolTestCase {
pool.resolve("foo");
assertEquals(1, pool.getSize());
assertTrue(pool.hasService("foo"));
- assertTrue(!pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("bar"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("foo");
assertEquals(1, pool.getSize());
assertTrue(pool.hasService("foo"));
- assertTrue(!pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("bar"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("bar");
assertEquals(2, pool.getSize());
assertTrue(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("baz");
assertEquals(2, pool.getSize());
- assertTrue(!pool.hasService("foo"));
+ assertFalse(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
assertTrue(pool.hasService("baz"));
pool.resolve("bar");
assertEquals(2, pool.getSize());
- assertTrue(!pool.hasService("foo"));
+ assertFalse(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
assertTrue(pool.hasService("baz"));
@@ -54,7 +53,7 @@ public class ServicePoolTestCase {
assertEquals(2, pool.getSize());
assertTrue(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("baz"));
slobrok.stop();
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
index 931fed596e5..35dad077809 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
@@ -7,15 +7,15 @@ import com.yahoo.jrt.Spec;
import com.yahoo.jrt.slobrok.api.Mirror;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.Identity;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -81,7 +81,7 @@ public class SlobrokTestCase {
assertTrue(false);
}
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
String slobrokCfgId = "raw:slobrok[1]\nslobrok[0].connectionspec \"" + new Spec("localhost", slobrok.port()).toString() + "\"\n";
@@ -93,7 +93,7 @@ public class SlobrokTestCase {
port3 = net3.getPort();
}
- @After
+ @AfterEach
public void tearDown() {
net3.shutdown();
net2.shutdown();
@@ -102,7 +102,7 @@ public class SlobrokTestCase {
}
@Test
- public void testSlobrok() {
+ void testSlobrok() {
net1.registerSession("foo");
net2.registerSession("foo");
net2.registerSession("bar");
@@ -111,43 +111,43 @@ public class SlobrokTestCase {
net3.registerSession("baz");
check(net1, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
check(net2, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
check(net3, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
net2.unregisterSession("bar");
net3.unregisterSession("bar");
net3.unregisterSession("baz");
check(net1, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
check(net2, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
check(net3, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
index 4dde73ad8c5..afeaa1304a1 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
@@ -7,17 +7,14 @@ import com.yahoo.jrt.Transport;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.concurrent.Timer;
import com.yahoo.messagebus.network.rpc.test.TestServer;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -28,14 +25,14 @@ public class TargetPoolTestCase {
private List<TestServer> servers;
private Supervisor orb;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
servers = new ArrayList<>();
orb = new Supervisor(new Transport());
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
for (TestServer server : servers) {
@@ -45,7 +42,7 @@ public class TargetPoolTestCase {
}
@Test
- public void testConnectionCycling() {
+ void testConnectionCycling() {
// Necessary setup to be able to resolve targets.
RPCServiceAddress adr1 = registerServer();
@@ -75,8 +72,9 @@ public class TargetPoolTestCase {
target3.subRef();
target4.subRef();
}
+
@Test
- public void testConnectionExpire() {
+ void testConnectionExpire() {
// Necessary setup to be able to resolve targets.
RPCServiceAddress adr1 = registerServer();
RPCServiceAddress adr2 = registerServer();
@@ -87,9 +85,12 @@ public class TargetPoolTestCase {
// Assert that all connections expire.
RPCTarget target;
- assertNotNull(target = pool.getTarget(orb, adr1)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr1));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
for (int i = 0; i < 10; ++i) {
pool.flushTargets(false);
@@ -100,20 +101,26 @@ public class TargetPoolTestCase {
assertEquals(0, pool.size());
// Assert that only idle connections expire.
- assertNotNull(target = pool.getTarget(orb, adr1)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr1));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
timer.millis += 444;
pool.flushTargets(false);
assertEquals(3, pool.size());
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
timer.millis += 444;
pool.flushTargets(false);
assertEquals(2, pool.size());
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
timer.millis += 444;
pool.flushTargets(false);
assertEquals(1, pool.size());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
index 3e6f345fb93..37024456878 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
@@ -20,16 +20,13 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -41,7 +38,7 @@ public class AdvancedRoutingTestCase {
SourceSession srcSession;
DestinationSession dstFoo, dstBar, dstBaz;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -56,7 +53,7 @@ public class AdvancedRoutingTestCase {
assertTrue(srcServer.waitSlobrok("dst/*", 3));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstFoo.destroy();
@@ -68,53 +65,53 @@ public class AdvancedRoutingTestCase {
}
@Test
- public void testAdvanced() {
+ void testAdvanced() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("bar", "dst/bar"))
- .addHop(new HopSpec("baz", "dst/baz"))
- .addRoute(new RouteSpec("baz").addHop("baz")));
+ .addHop(new HopSpec("bar", "dst/bar"))
+ .addHop(new HopSpec("baz", "dst/baz"))
+ .addRoute(new RouteSpec("baz").addHop("baz")));
Message msg = new SimpleMessage("msg");
msg.getTrace().setLevel(9);
assertTrue(srcSession.send(msg, Route.parse("[Custom:" + dstFoo.getConnectionSpec() + ",bar,route:baz,dst/cox,?dst/unknown]")).isAccepted());
// Initial send.
- assertNotNull(msg = ((Receptor)dstFoo.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstFoo.getMessageHandler()).getMessage(60));
dstFoo.acknowledge(msg);
- assertNotNull(msg = ((Receptor)dstBar.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBar.getMessageHandler()).getMessage(60));
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "bar"));
dstBar.reply(reply);
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "baz1"));
dstBaz.reply(reply);
// First retry.
- assertNull(((Receptor)dstFoo.getMessageHandler()).getMessage(0));
- assertNotNull(msg = ((Receptor)dstBar.getMessageHandler()).getMessage(60));
+ assertNull(((Receptor) dstFoo.getMessageHandler()).getMessage(0));
+ assertNotNull(msg = ((Receptor) dstBar.getMessageHandler()).getMessage(60));
dstBar.acknowledge(msg);
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "baz2"));
dstBaz.reply(reply);
// Second retry.
- assertNull(((Receptor)dstFoo.getMessageHandler()).getMessage(0));
- assertNull(((Receptor)dstBar.getMessageHandler()).getMessage(0));
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNull(((Receptor) dstFoo.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstBar.getMessageHandler()).getMessage(0));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.FATAL_ERROR, "baz3"));
dstBaz.reply(reply);
// Done.
- reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
index 375b247d286..3bc607f169b 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
@@ -19,15 +19,11 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -40,7 +36,7 @@ public class ResenderTestCase {
DestinationSession dstSession;
RetryTransientErrorsPolicy retryPolicy;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -55,7 +51,7 @@ public class ResenderTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -65,94 +61,94 @@ public class ResenderTestCase {
}
@Test
- public void testRetryTag() {
+ void testRetryTag() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
assertEquals(i, msg.getRetry());
assertEquals(true, msg.getRetryEnabled());
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
System.out.println(reply.getTrace());
}
@Test
- public void testRetryEnabledTag() {
+ void testRetryEnabledTag() {
Message msg = createMessage("msg");
msg.setRetryEnabled(false);
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
assertEquals(false, msg.getRetryEnabled());
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
System.out.println(reply.getTrace());
}
@Test
- public void testTransientError() {
+ void testTransientError() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testFatalError() {
+ void testFatalError() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testDisableRetry() {
+ void testDisableRetry() {
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasErrors());
- assertTrue(!reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertFalse(reply.hasFatalErrors());
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testRetryDelay() {
+ void testRetryDelay() {
retryPolicy.setBaseDelay(0.01);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, -1);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
String trace = reply.getTrace().toString();
assertTrue(trace.contains("retry 1 in 0.0"));
@@ -163,19 +159,19 @@ public class ResenderTestCase {
}
@Test
- public void testRequestRetryDelay() {
+ void testRequestRetryDelay() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, i / 50.0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
String trace = reply.getTrace().toString();
System.out.println(trace);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
index 5095de0b2e7..6d3790e1407 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
@@ -2,11 +2,9 @@
package com.yahoo.messagebus.routing;
import com.yahoo.messagebus.ErrorCode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -15,12 +13,12 @@ public class RetryPolicyTestCase {
private static final double SMALL = 0.00000000000000000001;
@Test
- public void testSimpleRetryPolicy() {
+ void testSimpleRetryPolicy() {
RetryTransientErrorsPolicy policy = new RetryTransientErrorsPolicy();
assertEquals(0.0, policy.getRetryDelay(0), SMALL);
assertEquals(0.0, policy.getRetryDelay(1), SMALL);
for (int i = 2; i < 15; i++) {
- assertEquals(0.001*(1 << (i-1)), policy.getRetryDelay(i), SMALL);
+ assertEquals(0.001 * (1 << (i - 1)), policy.getRetryDelay(i), SMALL);
}
assertEquals(10.0, policy.getRetryDelay(15), SMALL);
assertEquals(10.0, policy.getRetryDelay(20), SMALL);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java
index 20fc66825d7..aef61a05263 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.routing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class RouteParserTestCase {
@Test
- public void testHopParser() {
+ void testHopParser() {
Hop hop = Hop.parse("foo");
assertNotNull(hop);
assertEquals(1, hop.getNumDirectives());
@@ -34,45 +32,45 @@ public class RouteParserTestCase {
assertNotNull(hop = Hop.parse("[Extern:tcp/localhost:3619;foo/bar]"));
assertEquals(1, hop.getNumDirectives());
- assertPolicyDirective(hop.getDirective(0), "Extern","tcp/localhost:3619;foo/bar");
+ assertPolicyDirective(hop.getDirective(0), "Extern", "tcp/localhost:3619;foo/bar");
assertNotNull(hop = Hop.parse("[AND:foo bar]"));
assertEquals(1, hop.getNumDirectives());
- assertPolicyDirective(hop.getDirective(0), "AND","foo bar");
+ assertPolicyDirective(hop.getDirective(0), "AND", "foo bar");
assertNotNull(hop = Hop.parse("[DocumentRouteSelector:raw:route[2]\n" +
- "route[0].name \"foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"\n" +
- "route[1].name \"bar\"\n" +
- "route[1].selector \"other\"\n" +
- "route[1].feed \"myfeed\"\n" +
- "]"));
+ "route[0].name \"foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"\n" +
+ "route[1].name \"bar\"\n" +
+ "route[1].selector \"other\"\n" +
+ "route[1].feed \"myfeed\"\n" +
+ "]"));
assertEquals(1, hop.getNumDirectives());
assertPolicyDirective(hop.getDirective(0), "DocumentRouteSelector",
- "raw:route[2]\n" +
- "route[0].name \"foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"\n" +
- "route[1].name \"bar\"\n" +
- "route[1].selector \"other\"\n" +
- "route[1].feed \"myfeed\"");
+ "raw:route[2]\n" +
+ "route[0].name \"foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"\n" +
+ "route[1].name \"bar\"\n" +
+ "route[1].selector \"other\"\n" +
+ "route[1].feed \"myfeed\"");
assertNotNull(hop = Hop.parse("[DocumentRouteSelector:raw:route[1]\n" +
- "route[0].name \"docproc/cluster.foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"" +
- "]"));
+ "route[0].name \"docproc/cluster.foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"" +
+ "]"));
assertEquals(1, hop.getNumDirectives());
assertPolicyDirective(hop.getDirective(0), "DocumentRouteSelector",
- "raw:route[1]\n" +
- "route[0].name \"docproc/cluster.foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"");
+ "raw:route[1]\n" +
+ "route[0].name \"docproc/cluster.foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"");
}
@Test
- public void testHopParserErrors() {
+ void testHopParserErrors() {
assertError(Hop.parse(""), "Failed to parse empty string.");
assertError(Hop.parse("[foo"), "Unterminated '[' in '[foo'");
assertError(Hop.parse("foo/[bar]]"), "Unexpected token ']' in 'foo/[bar]]'");
@@ -80,7 +78,7 @@ public class RouteParserTestCase {
}
@Test
- public void testShortRoute() {
+ void testShortRoute() {
Route shortRoute = Route.parse("c");
assertNotNull(shortRoute);
assertEquals(1, shortRoute.getNumHops());
@@ -91,7 +89,7 @@ public class RouteParserTestCase {
}
@Test
- public void testShortHops() {
+ void testShortHops() {
Route shortRoute = Route.parse("a b c");
assertNotNull(shortRoute);
assertEquals(3, shortRoute.getNumHops());
@@ -102,7 +100,7 @@ public class RouteParserTestCase {
}
@Test
- public void testRouteParser() {
+ void testRouteParser() {
Route route = Route.parse("foo bar/baz");
assertNotNull(route);
assertEquals(2, route.getNumHops());
@@ -126,7 +124,7 @@ public class RouteParserTestCase {
}
@Test
- public void testRouteParserErrors() {
+ void testRouteParserErrors() {
assertError(Route.parse(""), "Failed to parse empty string.");
assertError(Route.parse("foo [bar"), "Unterminated '[' in '[bar'");
assertError(Route.parse("foo bar/[baz]]"), "Unexpected token ']' in 'bar/[baz]]'");
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
index 2efbc0724d7..42a6b244508 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
@@ -11,17 +11,17 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -35,7 +35,7 @@ public class RoutingContextTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -48,7 +48,7 @@ public class RoutingContextTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -58,7 +58,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testSingleDirective() {
+ void testSingleDirective() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(
false,
@@ -68,10 +68,10 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "[Custom]")
- .addRecipient("foo").addRecipient("bar").addRecipient("baz/cox")));
+ .addRecipient("foo").addRecipient("bar").addRecipient("baz/cox")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -79,7 +79,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testMoreDirectives() {
+ void testMoreDirectives() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(
false,
@@ -89,12 +89,12 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "foo/[Custom]/baz")
- .addRecipient("foo").addRecipient("foo/bar")
- .addRecipient("foo/bar0/baz").addRecipient("foo/bar1/baz")
- .addRecipient("foo/bar/baz/cox")));
+ .addRecipient("foo").addRecipient("foo/bar")
+ .addRecipient("foo/bar0/baz").addRecipient("foo/bar1/baz")
+ .addRecipient("foo/bar/baz/cox")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -102,7 +102,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testRecipientsRemain() {
+ void testRecipientsRemain() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("First", new CustomPolicyFactory(true, Arrays.asList("foo/bar"), Arrays.asList("foo/[Second]")));
protocol.addPolicyFactory("Second", new CustomPolicyFactory(false, Arrays.asList("foo/bar"), Arrays.asList("foo/bar")));
@@ -110,10 +110,10 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "[First]/[Second]")
- .addRecipient("foo/bar")));
+ .addRecipient("foo/bar")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -121,15 +121,15 @@ public class RoutingContextTestCase {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("node : null, directive: 1, errors: [], selectOnRetry: true context: null", new RoutingContext(null, 1).toString());
}
@Test
- public void testConstRoute() {
+ void testConstRoute() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("DocumentRouteSelector",
- new CustomPolicyFactory(true, Arrays.asList("dst"), Arrays.asList("dst")));
+ new CustomPolicyFactory(true, Arrays.asList("dst"), Arrays.asList("dst")));
srcServer.mb.putProtocol(protocol);
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("default").addHop("indexing"))
@@ -137,10 +137,10 @@ public class RoutingContextTestCase {
.addHop(new HopSpec("dst", "dst/session")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("route:default")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(TIMEOUT_SECS);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(TIMEOUT_SECS);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
index 0f492e65421..28dcadf1896 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
@@ -3,16 +3,14 @@ package com.yahoo.messagebus.routing;
import com.yahoo.messagebus.ConfigAgent;
import com.yahoo.messagebus.ConfigHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -20,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class RoutingSpecTestCase {
@Test
- public void testConfig() {
+ void testConfig() {
assertConfig(new RoutingSpec());
assertConfig(new RoutingSpec().addTable(new RoutingTableSpec("mytable1")));
assertConfig(new RoutingSpec().addTable(new RoutingTableSpec("mytable1")
@@ -42,239 +40,239 @@ public class RoutingSpecTestCase {
.addRoute(new RouteSpec("myroute12").addHop("myhop1").addHop("myhop2")))
.addTable(new RoutingTableSpec("mytable2")));
assertEquals("routingtable[2]\n" +
- "routingtable[0].protocol \"mytable1\"\n" +
- "routingtable[1].protocol \"mytable2\"\n" +
- "routingtable[1].hop[3]\n" +
- "routingtable[1].hop[0].name \"myhop1\"\n" +
- "routingtable[1].hop[0].selector \"myselector1\"\n" +
- "routingtable[1].hop[1].name \"myhop2\"\n" +
- "routingtable[1].hop[1].selector \"myselector2\"\n" +
- "routingtable[1].hop[1].ignoreresult true\n" +
- "routingtable[1].hop[2].name \"myhop1\"\n" +
- "routingtable[1].hop[2].selector \"myselector3\"\n" +
- "routingtable[1].hop[2].recipient[2]\n" +
- "routingtable[1].hop[2].recipient[0] \"myrecipient1\"\n" +
- "routingtable[1].hop[2].recipient[1] \"myrecipient2\"\n" +
- "routingtable[1].route[1]\n" +
- "routingtable[1].route[0].name \"myroute1\"\n" +
- "routingtable[1].route[0].hop[1]\n" +
- "routingtable[1].route[0].hop[0] \"myhop1\"\n",
- new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable1"))
- .addTable(new RoutingTableSpec("mytable2")
- .addHop(new HopSpec("myhop1", "myselector1"))
- .addHop(new HopSpec("myhop2", "myselector2").setIgnoreResult(true))
- .addHop(new HopSpec("myhop1", "myselector3")
- .addRecipient("myrecipient1")
- .addRecipient("myrecipient2"))
- .addRoute(new RouteSpec("myroute1").addHop("myhop1"))).toString());
+ "routingtable[0].protocol \"mytable1\"\n" +
+ "routingtable[1].protocol \"mytable2\"\n" +
+ "routingtable[1].hop[3]\n" +
+ "routingtable[1].hop[0].name \"myhop1\"\n" +
+ "routingtable[1].hop[0].selector \"myselector1\"\n" +
+ "routingtable[1].hop[1].name \"myhop2\"\n" +
+ "routingtable[1].hop[1].selector \"myselector2\"\n" +
+ "routingtable[1].hop[1].ignoreresult true\n" +
+ "routingtable[1].hop[2].name \"myhop1\"\n" +
+ "routingtable[1].hop[2].selector \"myselector3\"\n" +
+ "routingtable[1].hop[2].recipient[2]\n" +
+ "routingtable[1].hop[2].recipient[0] \"myrecipient1\"\n" +
+ "routingtable[1].hop[2].recipient[1] \"myrecipient2\"\n" +
+ "routingtable[1].route[1]\n" +
+ "routingtable[1].route[0].name \"myroute1\"\n" +
+ "routingtable[1].route[0].hop[1]\n" +
+ "routingtable[1].route[0].hop[0] \"myhop1\"\n",
+ new RoutingSpec()
+ .addTable(new RoutingTableSpec("mytable1"))
+ .addTable(new RoutingTableSpec("mytable2")
+ .addHop(new HopSpec("myhop1", "myselector1"))
+ .addHop(new HopSpec("myhop2", "myselector2").setIgnoreResult(true))
+ .addHop(new HopSpec("myhop1", "myselector3")
+ .addRecipient("myrecipient1")
+ .addRecipient("myrecipient2"))
+ .addRoute(new RouteSpec("myroute1").addHop("myhop1"))).toString());
}
@Test
- public void testApplicationSpec() {
+ void testApplicationSpec() {
assertApplicationSpec(Arrays.asList("foo"),
- Arrays.asList("foo",
- "*"));
+ Arrays.asList("foo",
+ "*"));
assertApplicationSpec(Arrays.asList("foo/bar"),
- Arrays.asList("foo/bar",
- "foo/*",
- "*/bar",
- "*/*"));
+ Arrays.asList("foo/bar",
+ "foo/*",
+ "*/bar",
+ "*/*"));
assertApplicationSpec(Arrays.asList("foo/0/baz",
- "foo/1/baz",
- "foo/2/baz"),
- Arrays.asList("foo/0/baz",
- "foo/1/baz",
- "foo/2/baz",
- "foo/0/*",
- "foo/1/*",
- "foo/2/*",
- "foo/*/baz",
- "*/0/baz",
- "*/1/baz",
- "*/2/baz",
- "foo/*/*",
- "*/0/*",
- "*/1/*",
- "*/2/*",
- "*/*/baz",
- "*/*/*"));
+ "foo/1/baz",
+ "foo/2/baz"),
+ Arrays.asList("foo/0/baz",
+ "foo/1/baz",
+ "foo/2/baz",
+ "foo/0/*",
+ "foo/1/*",
+ "foo/2/*",
+ "foo/*/baz",
+ "*/0/baz",
+ "*/1/baz",
+ "*/2/baz",
+ "foo/*/*",
+ "*/0/*",
+ "*/1/*",
+ "*/2/*",
+ "*/*/baz",
+ "*/*/*"));
}
@Test
- public void testVeriyfOk() {
+ void testVeriyfOk() {
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "myservice1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("route1").addHop("myservice1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "myservice1"))
.addRoute(new RouteSpec("route1").addHop("hop1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "route:route2"))
.addHop(new HopSpec("hop2", "myservice1"))
.addRoute(new RouteSpec("route1").addHop("hop1"))
.addRoute(new RouteSpec("route2").addHop("hop2"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("myhop1", "foo/[bar]/baz").addRecipient("foo/0/baz").addRecipient("foo/1/baz"))),
- new ApplicationSpec()
- .addService("mytable", "foo/0/baz")
- .addService("mytable", "foo/1/baz"));
+ new ApplicationSpec()
+ .addService("mytable", "foo/0/baz")
+ .addService("mytable", "foo/1/baz"));
}
@Test
- public void testVerifyToggle() {
+ void testVerifyToggle() {
assertVerifyOk(new RoutingSpec(false)
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")),
- new ApplicationSpec());
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")),
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable", false)
.addHop(new HopSpec("foo", "bar"))
.addHop(new HopSpec("foo", "baz"))),
- new ApplicationSpec());
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "", false))),
- new ApplicationSpec());
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo", false))),
- new ApplicationSpec());
+ new ApplicationSpec());
}
@Test
- public void testVerifyFail() {
+ void testVerifyFail() {
// Duplicate table.
assertVerifyFail(new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")),
- new ApplicationSpec(),
- Arrays.asList("Routing table 'mytable' is defined 2 times."));
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")),
+ new ApplicationSpec(),
+ Arrays.asList("Routing table 'mytable' is defined 2 times."));
// Duplicate hop.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar"))
.addHop(new HopSpec("foo", "baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Hop 'foo' in routing table 'mytable' is defined 2 times."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' is defined 2 times."));
// Duplicate route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar"))
.addRoute(new RouteSpec("foo").addHop("baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Route 'foo' in routing table 'mytable' is defined 2 times."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Route 'foo' in routing table 'mytable' is defined 2 times."));
// Empty hop.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", ""))),
- new ApplicationSpec(),
- Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to parse empty string."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to parse empty string."));
// Empty route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo"))),
- new ApplicationSpec(),
- Arrays.asList("Route 'foo' in routing table 'mytable' has no hops."));
+ new ApplicationSpec(),
+ Arrays.asList("Route 'foo' in routing table 'mytable' has no hops."));
// Hop error.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop error in recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "[bar]").addRecipient("bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For recipient 'bar/baz cox' in hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For recipient 'bar/baz cox' in hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop error in route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For hop 1 in route 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 1 in route 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references 'bar' which is neither a service, a route nor another hop."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references 'bar' which is neither a service, a route nor another hop."));
// Mismatched recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/[baz]/cox").addRecipient("cox/0/bar"))),
- new ApplicationSpec(),
- Arrays.asList("Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'foo' in routing table 'mytable'."));
+ new ApplicationSpec(),
+ Arrays.asList("Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'foo' in routing table 'mytable'."));
// Route not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "route:bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
// Route not found in route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("route:bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
// Service not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/baz"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 'foo' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop."));
// Unexpected recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar").addRecipient("baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Hop 'foo' in routing table 'mytable' has recipients but no policy directive."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' has recipients but no policy directive."));
// Multiple errors.
assertVerifyFail(new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")
- .addHop(new HopSpec("hop1", "bar"))
- .addHop(new HopSpec("hop1", "baz"))
- .addHop(new HopSpec("hop2", ""))
- .addHop(new HopSpec("hop3", "bar/baz cox"))
- .addHop(new HopSpec("hop4", "[bar]").addRecipient("bar/baz cox"))
- .addHop(new HopSpec("hop5", "bar/[baz]/cox").addRecipient("cox/0/bar"))
- .addHop(new HopSpec("hop6", "route:route69"))
- .addHop(new HopSpec("hop7", "bar/baz"))
- .addHop(new HopSpec("hop8", "bar").addRecipient("baz"))
- .addRoute(new RouteSpec("route1").addHop("bar"))
- .addRoute(new RouteSpec("route1").addHop("baz"))
- .addRoute(new RouteSpec("route2").addHop(""))
- .addRoute(new RouteSpec("route3").addHop("bar/baz cox"))
- .addRoute(new RouteSpec("route4").addHop("hop69"))
- .addRoute(new RouteSpec("route5").addHop("route:route69"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Routing table 'mytable' is defined 2 times.",
- "For hop 'hop2' in routing table 'mytable'; Failed to parse empty string.",
- "For hop 'hop3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "For hop 1 in route 'route2' in routing table 'mytable'; Failed to parse empty string.",
- "For hop 1 in route 'route3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "For recipient 'bar/baz cox' in hop 'hop4' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "Hop 'hop1' in routing table 'mytable' is defined 2 times.",
- "Hop 'hop6' in routing table 'mytable' references route 'route69' which does not exist.",
- "Hop 'hop7' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop.",
- "Hop 'hop8' in routing table 'mytable' has recipients but no policy directive.",
- "Hop 1 in route 'route4' in routing table 'mytable' references 'hop69' which is neither a service, a route nor another hop.",
- "Hop 1 in route 'route5' in routing table 'mytable' references route 'route69' which does not exist.",
- "Route 'route1' in routing table 'mytable' is defined 2 times.",
- "Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'hop5' in routing table 'mytable'."));
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")
+ .addHop(new HopSpec("hop1", "bar"))
+ .addHop(new HopSpec("hop1", "baz"))
+ .addHop(new HopSpec("hop2", ""))
+ .addHop(new HopSpec("hop3", "bar/baz cox"))
+ .addHop(new HopSpec("hop4", "[bar]").addRecipient("bar/baz cox"))
+ .addHop(new HopSpec("hop5", "bar/[baz]/cox").addRecipient("cox/0/bar"))
+ .addHop(new HopSpec("hop6", "route:route69"))
+ .addHop(new HopSpec("hop7", "bar/baz"))
+ .addHop(new HopSpec("hop8", "bar").addRecipient("baz"))
+ .addRoute(new RouteSpec("route1").addHop("bar"))
+ .addRoute(new RouteSpec("route1").addHop("baz"))
+ .addRoute(new RouteSpec("route2").addHop(""))
+ .addRoute(new RouteSpec("route3").addHop("bar/baz cox"))
+ .addRoute(new RouteSpec("route4").addHop("hop69"))
+ .addRoute(new RouteSpec("route5").addHop("route:route69"))),
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Routing table 'mytable' is defined 2 times.",
+ "For hop 'hop2' in routing table 'mytable'; Failed to parse empty string.",
+ "For hop 'hop3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "For hop 1 in route 'route2' in routing table 'mytable'; Failed to parse empty string.",
+ "For hop 1 in route 'route3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "For recipient 'bar/baz cox' in hop 'hop4' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "Hop 'hop1' in routing table 'mytable' is defined 2 times.",
+ "Hop 'hop6' in routing table 'mytable' references route 'route69' which does not exist.",
+ "Hop 'hop7' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop.",
+ "Hop 'hop8' in routing table 'mytable' has recipients but no policy directive.",
+ "Hop 1 in route 'route4' in routing table 'mytable' references 'hop69' which is neither a service, a route nor another hop.",
+ "Hop 1 in route 'route5' in routing table 'mytable' references route 'route69' which does not exist.",
+ "Route 'route1' in routing table 'mytable' is defined 2 times.",
+ "Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'hop5' in routing table 'mytable'."));
}
private static void assertVerifyOk(RoutingSpec routing, ApplicationSpec app) {
@@ -297,7 +295,7 @@ public class RoutingSpecTestCase {
ConfigStore store = new ConfigStore();
ConfigAgent subscriber = new ConfigAgent("raw:" + routing.toString(), store);
subscriber.subscribe();
- assertTrue(store.routing.equals(routing));
+ assertEquals(store.routing, routing);
}
private static void assertApplicationSpec(List<String> services, List<String> patterns) {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
index 2640fbc8db3..db5dce04af0 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
@@ -23,11 +23,11 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.ArrayList;
@@ -36,11 +36,7 @@ import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author havardpe
@@ -60,7 +56,7 @@ public class RoutingTestCase {
String sessName = "session";
String dstSessName = "dst/session";
- @BeforeClass
+ @BeforeAll
public static void commonSetup() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer("dst", null, slobrok, new SimpleProtocol());
@@ -70,7 +66,7 @@ public class RoutingTestCase {
slobrok);
}
- @AfterClass
+ @AfterAll
public static void commonTeardown() {
dstServer.destroy();
srcServer.destroy();
@@ -80,7 +76,7 @@ public class RoutingTestCase {
slobrok = null;
}
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
// reset some params:
retryPolicy.setEnabled(true);
@@ -99,7 +95,7 @@ public class RoutingTestCase {
assertTrue(srcServer.waitSlobrok(dstSessName, 1));
}
- @After
+ @AfterEach
public void tearDown() {
dstSession.destroy();
srcSession.destroy();
@@ -108,10 +104,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatNullRouteIsCaught() {
+ void requireThatNullRouteIsCaught() {
log.log(Level.INFO, "Starting: requireThatNullRouteIsCaught");
assertTrue(srcSession.send(createMessage("msg")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -120,10 +116,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptyRouteIsCaught() {
+ void requireThatEmptyRouteIsCaught() {
log.log(Level.INFO, "Starting: requireThatEmptyRouteIsCaught");
assertTrue(srcSession.send(createMessage("msg"), new Route()).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -132,15 +128,15 @@ public class RoutingTestCase {
}
@Test
- public void requireThatHopNameIsExpanded() {
+ void requireThatHopNameIsExpanded() {
log.log(Level.INFO, "Starting: requireThatHopNameIsExpanded");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("dst", dstSessName)));
+ .addHop(new HopSpec("dst", dstSessName)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -148,16 +144,16 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteDirectiveWorks() {
+ void requireThatRouteDirectiveWorks() {
log.log(Level.INFO, "Starting: requireThatRouteDirectiveWorks");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("dst").addHop(dstSessName))
- .addHop(new HopSpec("dir", "route:dst")));
+ .addRoute(new RouteSpec("dst").addHop(dstSessName))
+ .addHop(new HopSpec("dir", "route:dst")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dir")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -165,15 +161,15 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteNameIsExpanded() {
+ void requireThatRouteNameIsExpanded() {
log.log(Level.INFO, "Starting: requireThatRouteNameIsExpanded");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("dst").addHop(dstSessName)));
+ .addRoute(new RouteSpec("dst").addHop(dstSessName)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -181,13 +177,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatHopResolutionOverflowIsCaught() {
+ void requireThatHopResolutionOverflowIsCaught() {
log.log(Level.INFO, "Starting: requireThatHopResolutionOverflowIsCaught");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("foo", "bar"))
- .addHop(new HopSpec("bar", "foo")));
+ .addHop(new HopSpec("foo", "bar"))
+ .addHop(new HopSpec("bar", "foo")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("foo")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -196,12 +192,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteResolutionOverflowIsCaught() {
+ void requireThatRouteResolutionOverflowIsCaught() {
log.log(Level.INFO, "Starting: requireThatRouteResolutionOverflowIsCaught");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("foo").addHop("route:foo")));
+ .addRoute(new RouteSpec("foo").addHop("route:foo")));
assertTrue(srcSession.send(createMessage("msg"), "foo").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -210,18 +206,18 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteExpansionOnlyReplacesFirstHop() {
+ void requireThatRouteExpansionOnlyReplacesFirstHop() {
log.log(Level.INFO, "Starting: requireThatRouteExpansionOnlyReplacesFirstHop");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("foo").addHop(dstSessName).addHop("bar")));
+ .addRoute(new RouteSpec("foo").addHop(dstSessName).addHop("bar")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("route:foo baz")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertEquals(2, msg.getRoute().getNumHops());
assertEquals("bar", msg.getRoute().getHop(0).toString());
assertEquals("baz", msg.getRoute().getHop(1).toString());
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -229,12 +225,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatErrorDirectiveWorks() {
+ void requireThatErrorDirectiveWorks() {
log.log(Level.INFO, "Starting: requireThatErrorDirectiveWorks");
Route route = Route.parse("foo/bar/baz");
route.getHop(0).setDirective(1, new ErrorDirective("err"));
assertTrue(srcSession.send(createMessage("msg"), route).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -244,7 +240,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIllegalSelectIsCaught() {
+ void requireThatIllegalSelectIsCaught() {
log.log(Level.INFO, "Starting: requireThatIllegalSelectIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
@@ -252,7 +248,7 @@ public class RoutingTestCase {
Route route = Route.parse("[Custom: ]");
assertNotNull(route);
assertTrue(srcSession.send(createMessage("msg"), route).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -261,13 +257,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptySelectIsCaught() {
+ void requireThatEmptySelectIsCaught() {
log.log(Level.INFO, "Starting: requireThatEmptySelectIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -276,16 +272,16 @@ public class RoutingTestCase {
}
@Test
- public void requireThatPolicySelectWorks() {
+ void requireThatPolicySelectWorks() {
log.log(Level.INFO, "Starting: requireThatPolicySelectWorks");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -293,110 +289,110 @@ public class RoutingTestCase {
}
@Test
- public void requireThatTransientErrorsAreRetried() {
+ void requireThatTransientErrorsAreRetried() {
log.log(Level.INFO, "Starting: requireThatTransientErrorsAreRetried");
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err1"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err2"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("[APP_TRANSIENT_ERROR @ localhost]: err1",
- "-[APP_TRANSIENT_ERROR @ localhost]: err1",
- "[APP_TRANSIENT_ERROR @ localhost]: err2",
- "-[APP_TRANSIENT_ERROR @ localhost]: err2"),
- reply.getTrace());
+ "-[APP_TRANSIENT_ERROR @ localhost]: err1",
+ "[APP_TRANSIENT_ERROR @ localhost]: err2",
+ "-[APP_TRANSIENT_ERROR @ localhost]: err2"),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatTransientErrorsAreRetried");
}
@Test
- public void requireThatTransientErrorsAreRetriedWithPolicy() {
+ void requireThatTransientErrorsAreRetriedWithPolicy() {
log.log(Level.INFO, "Starting: requireThatTransientErrorsAreRetriedWithPolicy");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err1"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err2"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("Source session accepted a 3 byte message. 1 message(s) now pending.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "[APP_TRANSIENT_ERROR @ localhost]: err1",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Message scheduled for retry 1 in 0.0 seconds.",
- "Resender resending message.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "[APP_TRANSIENT_ERROR @ localhost]: err2",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Message scheduled for retry 2 in 0.0 seconds.",
- "Resender resending message.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Source session received reply. 0 message(s) now pending."),
- reply.getTrace());
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "[APP_TRANSIENT_ERROR @ localhost]: err1",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Message scheduled for retry 1 in 0.0 seconds.",
+ "Resender resending message.",
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "[APP_TRANSIENT_ERROR @ localhost]: err2",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Message scheduled for retry 2 in 0.0 seconds.",
+ "Resender resending message.",
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Source session received reply. 0 message(s) now pending."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatTransientErrorsAreRetriedWithPolicy");
}
@Test
- public void requireThatRetryCanBeDisabled() {
+ void requireThatRetryCanBeDisabled() {
log.log(Level.INFO, "Starting: requireThatRetryCanBeDisabled");
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -405,120 +401,120 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRetryCallsSelect() {
+ void requireThatRetryCallsSelect() {
log.log(Level.INFO, "Starting: requireThatRetryCallsSelect");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+"].",
- "[APP_TRANSIENT_ERROR @ localhost]",
- "-[APP_TRANSIENT_ERROR @ localhost]",
- "Merged ["+dstSessName+"].",
- "Selecting ["+dstSessName+"].",
- "Sending reply",
- "Merged ["+dstSessName+"]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + "].",
+ "[APP_TRANSIENT_ERROR @ localhost]",
+ "-[APP_TRANSIENT_ERROR @ localhost]",
+ "Merged [" + dstSessName + "].",
+ "Selecting [" + dstSessName + "].",
+ "Sending reply",
+ "Merged [" + dstSessName + "]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatRetryCallsSelect");
}
@Test
- public void requireThatPolicyCanDisableReselectOnRetry() {
+ void requireThatPolicyCanDisableReselectOnRetry() {
log.log(Level.INFO, "Starting: requireThatPolicyCanDisableReselectOnRetry");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false));
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+"].",
- "[APP_TRANSIENT_ERROR @ localhost]",
- "-[APP_TRANSIENT_ERROR @ localhost]",
- "Merged ["+dstSessName+"].",
- "-Selecting ["+dstSessName+"].",
- "Sending reply",
- "Merged ["+dstSessName+"]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + "].",
+ "[APP_TRANSIENT_ERROR @ localhost]",
+ "-[APP_TRANSIENT_ERROR @ localhost]",
+ "Merged [" + dstSessName + "].",
+ "-Selecting [" + dstSessName + "].",
+ "Sending reply",
+ "Merged [" + dstSessName + "]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyCanDisableReselectOnRetry");
}
@Test
- public void requireThatPolicyCanConsumeErrors() {
+ void requireThatPolicyCanConsumeErrors() {
log.log(Level.INFO, "Starting: requireThatPolicyCanConsumeErrors");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(true, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+",dst/unknown]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + ",dst/unknown]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+", dst/unknown].",
- "[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Sending reply",
- "Merged ["+dstSessName+", dst/unknown]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + ", dst/unknown].",
+ "[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Sending reply",
+ "Merged [" + dstSessName + ", dst/unknown]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyCanConsumeErrors");
}
@Test
- public void requireThatPolicyOnlyConsumesDeclaredErrors() {
+ void requireThatPolicyOnlyConsumesDeclaredErrors() {
log.log(Level.INFO, "Starting: requireThatPolicyOnlyConsumesDeclaredErrors");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:dst/unknown]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode());
assertTrace(Arrays.asList("Selecting [dst/unknown].",
- "[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Merged [dst/unknown]."),
- reply.getTrace());
+ "[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Merged [dst/unknown]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyOnlyConsumesDeclaredErrors");
}
@Test
- public void requireThatPolicyCanExpandToPolicy() {
+ void requireThatPolicyCanExpandToPolicy() {
log.log(Level.INFO, "Starting: requireThatPolicyCanExpandToPolicy");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(true, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[Custom:"+dstSessName+"],[Custom:dst/unknown]]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[Custom:[Custom:" + dstSessName + "],[Custom:dst/unknown]]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -527,7 +523,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatReplyCanBeRemovedFromChildNodes() {
+ void requireThatReplyCanBeRemovedFromChildNodes() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeRemovedFromChildNodes");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
@@ -535,32 +531,32 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new RemoveReplyPolicy(true,
- Arrays.asList(ErrorCode.NO_ADDRESS_FOR_SERVICE),
- CustomPolicyFactory.parseRoutes(param),
- 0);
+ Arrays.asList(ErrorCode.NO_ADDRESS_FOR_SERVICE),
+ CustomPolicyFactory.parseRoutes(param),
+ 0);
}
});
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[Custom:"+dstSessName+"],[Custom:dst/unknown]]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[Custom:[Custom:" + dstSessName + "],[Custom:dst/unknown]]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "-[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Sending message",
- "-Sending message"),
- reply.getTrace());
+ "-[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Sending message",
+ "-Sending message"),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatReplyCanBeRemovedFromChildNodes");
}
@Test
- public void requireThatSetReplyWorks() {
+ void requireThatSetReplyWorks() {
log.log(Level.INFO, "Starting: requireThatSetReplyWorks");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Select", new CustomPolicyFactory(true, ErrorCode.APP_FATAL_ERROR));
@@ -574,11 +570,11 @@ public class RoutingTestCase {
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(
- srcSession.send(createMessage("msg"), Route.parse("[Select:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ srcSession.send(createMessage("msg"), Route.parse("[Select:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -588,7 +584,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatReplyCanBeReusedOnRetry() {
+ void requireThatReplyCanBeReusedOnRetry() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeReusedOnRetry");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("ReuseReply", new SimpleProtocol.PolicyFactory() {
@@ -596,8 +592,8 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new ReuseReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_FATAL_ERROR),
- CustomPolicyFactory.parseRoutes(param));
+ Arrays.asList(ErrorCode.APP_FATAL_ERROR),
+ CustomPolicyFactory.parseRoutes(param));
}
});
protocol.addPolicyFactory("SetReply", new SimpleProtocol.PolicyFactory() {
@@ -605,29 +601,29 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[ReuseReply:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[ReuseReply:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
log.log(Level.INFO, "Finished: requireThatReplyCanBeReusedOnRetry");
}
@Test
- public void requireThatReplyCanBeRemovedAndRetried() {
+ void requireThatReplyCanBeRemovedAndRetried() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeRemovedAndRetried");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("RemoveReply", new SimpleProtocol.PolicyFactory() {
@@ -635,9 +631,9 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new RemoveReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR),
- CustomPolicyFactory.parseRoutes(param),
- 0);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR),
+ CustomPolicyFactory.parseRoutes(param),
+ 0);
}
});
protocol.addPolicyFactory("SetReply", new SimpleProtocol.PolicyFactory() {
@@ -645,71 +641,71 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession
- .send(createMessage("msg"), Route.parse("[RemoveReply:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ .send(createMessage("msg"), Route.parse("[RemoveReply:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.APP_FATAL_ERROR, reply.getError(0).getCode());
assertEquals("foo", reply.getError(0).getMessage());
assertTrace(Arrays.asList("Resolving '[SetReply:foo]'.",
- "Resolving '"+dstSessName+"'.",
- "Resender resending message.",
- "Resolving '"+dstSessName+"'.",
- "Resolving '[SetReply:foo]'."),
- reply.getTrace());
+ "Resolving '" + dstSessName + "'.",
+ "Resender resending message.",
+ "Resolving '" + dstSessName + "'.",
+ "Resolving '[SetReply:foo]'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatReplyCanBeRemovedAndRetried");
}
@Test
- public void requireThatIgnoreResultWorks() {
+ void requireThatIgnoreResultWorks() {
log.log(Level.INFO, "Starting: requireThatIgnoreResultWorks");
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("?"+dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("?" + dstSessName)).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_FATAL_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Not waiting for a reply from '"+dstSessName+"'."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Not waiting for a reply from '" + dstSessName + "'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatIgnoreResultWorks");
}
@Test
- public void requireThatIgnoreResultCanBeSetInHopBlueprint() {
+ void requireThatIgnoreResultCanBeSetInHopBlueprint() {
log.log(Level.INFO, "Starting: requireThatIgnoreResultCanBeSetInHopBlueprint");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("foo", dstSessName).setIgnoreResult(true)));
+ .addHop(new HopSpec("foo", dstSessName).setIgnoreResult(true)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("foo")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_FATAL_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Not waiting for a reply from '"+dstSessName+"'."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Not waiting for a reply from '" + dstSessName + "'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatIgnoreResultCanBeSetInHopBlueprint");
}
@Test
- public void requireThatIgnoreFlagPersistsThroughHopLookup() {
+ void requireThatIgnoreFlagPersistsThroughHopLookup() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughHopLookup");
setupRouting(new RoutingTableSpec(SimpleProtocol.NAME).addHop(new HopSpec("foo", "dst/unknown")));
assertSend("?foo");
@@ -718,7 +714,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagPersistsThroughRouteLookup() {
+ void requireThatIgnoreFlagPersistsThroughRouteLookup() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughRouteLookup");
setupRouting(new RoutingTableSpec(SimpleProtocol.NAME).addRoute(new RouteSpec("foo").addHop("dst/unknown")));
assertSend("?foo");
@@ -727,7 +723,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagPersistsThroughPolicySelect() {
+ void requireThatIgnoreFlagPersistsThroughPolicySelect() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughPolicySelect");
setupPolicy("Custom", MyPolicy.newSelectAndMerge("dst/unknown"));
assertSend("?[Custom]");
@@ -736,10 +732,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagIsSerializedWithMessage() {
+ void requireThatIgnoreFlagIsSerializedWithMessage() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagIsSerializedWithMessage");
- assertSend(dstSessName+" foo ?bar");
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertSend(dstSessName + " foo ?bar");
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Route route = msg.getRoute();
assertEquals(2, route.getNumHops());
@@ -755,7 +751,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagDoesNotInterfere() {
+ void requireThatIgnoreFlagDoesNotInterfere() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagDoesNotInterfere");
setupPolicy("Custom", MyPolicy.newSelectAndMerge(dstSessName));
assertSend("?[Custom]");
@@ -764,7 +760,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptySelectionCanBeIgnored() {
+ void requireThatEmptySelectionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatEmptySelectionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newEmptySelection());
assertSend("?[Custom]");
@@ -773,7 +769,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectErrorCanBeIgnored() {
+ void requireThatSelectErrorCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectErrorCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectError(ErrorCode.APP_FATAL_ERROR, "foo"));
assertSend("?[Custom]");
@@ -782,7 +778,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectExceptionCanBeIgnored() {
+ void requireThatSelectExceptionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectExceptionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectException(new RuntimeException()));
assertSend("?[Custom]");
@@ -791,7 +787,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectAndThrowCanBeIgnored() {
+ void requireThatSelectAndThrowCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectAndThrowCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectAndThrow(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -800,7 +796,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptyMergeCanBeIgnored() {
+ void requireThatEmptyMergeCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatEmptyMergeCanBeIgnored");
setupPolicy("Custom", MyPolicy.newEmptyMerge(dstSessName));
assertSend("?[Custom]");
@@ -810,7 +806,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeErrorCanBeIgnored() {
+ void requireThatMergeErrorCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeErrorCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeError(dstSessName, ErrorCode.APP_FATAL_ERROR, "foo"));
assertSend("?[Custom]");
@@ -820,7 +816,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeExceptionCanBeIgnored() {
+ void requireThatMergeExceptionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeExceptionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeException(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -830,7 +826,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeAndThrowCanBeIgnored() {
+ void requireThatMergeAndThrowCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeAndThrowCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeAndThrow(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -840,7 +836,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatAllocServiceAddressCanBeIgnored() {
+ void requireThatAllocServiceAddressCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatAllocServiceAddressCanBeIgnored");
assertSend("?dst/unknown");
assertTrace("Ignoring errors in reply.");
@@ -848,7 +844,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatDepthLimitCanBeIgnored() {
+ void requireThatDepthLimitCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatDepthLimitCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectAndMerge("[Custom]"));
assertSend("?[Custom]");
@@ -857,21 +853,21 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteCanBeEmptyInDestination() {
+ void requireThatRouteCanBeEmptyInDestination() {
log.log(Level.INFO, "Starting: requireThatRouteCanBeEmptyInDestination");
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertNull(msg.getRoute());
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
log.log(Level.INFO, "Finished: requireThatRouteCanBeEmptyInDestination");
}
@Test
- public void requireThatOnlyActiveNodesAreAborted() {
+ void requireThatOnlyActiveNodesAreAborted() {
log.log(Level.INFO, "Starting: requireThatOnlyActiveNodesAreAborted");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false));
@@ -880,16 +876,16 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR,
- ErrorCode.APP_TRANSIENT_ERROR,
- ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR,
+ ErrorCode.APP_TRANSIENT_ERROR,
+ ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[SetReply:foo],?bar,"+dstSessName+"]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Route.parse("[Custom:[SetReply:foo],?bar," + dstSessName + "]")).isAccepted());
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
@@ -899,12 +895,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatTimeoutWorks() {
+ void requireThatTimeoutWorks() {
log.log(Level.INFO, "Starting: requireThatTimeoutWorks");
retryPolicy.setBaseDelay(0.01);
srcSession.setTimeout(0.5);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/unknown")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
@@ -914,10 +910,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatUnknownPolicyIsCaught() {
+ void requireThatUnknownPolicyIsCaught() {
log.log(Level.INFO, "Starting: requireThatUnknownPolicyIsCaught");
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Unknown]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -950,13 +946,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectExceptionIsCaught() {
+ void requireThatSelectExceptionIsCaught() {
log.log(Level.INFO, "Starting: requireThatSelectExceptionIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", exceptionOnSelectThrowingMockFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -966,12 +962,12 @@ public class RoutingTestCase {
}
@Test
- public void selectExceptionIncludesStackTraceInMessage() {
+ void selectExceptionIncludesStackTraceInMessage() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", exceptionOnSelectThrowingMockFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertEquals(ErrorCode.POLICY_ERROR, reply.getError(0).getCode());
// Attempting any sort of full matching of the stack trace is brittle, so
// simplify by assuming any message which mentions the source file of the
@@ -980,7 +976,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeExceptionIsCaught() {
+ void requireThatMergeExceptionIsCaught() {
log.log(Level.INFO, "Starting: requireThatMergeExceptionIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
@@ -1008,10 +1004,10 @@ public class RoutingTestCase {
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -1066,11 +1062,11 @@ public class RoutingTestCase {
String line = expected.get(i).replaceFirst("\\$\\{VERSION\\}", Vtag.currentVersion.toString());
if (line.charAt(0) == '-') {
String str = line.substring(1);
- assertTrue("Line " + i + " '" + str + "' not expected.",
- actual.indexOf(str, pos + 1) < 0);
+ assertTrue(actual.indexOf(str, pos + 1) < 0,
+ "Line " + i + " '" + str + "' not expected.");
} else {
pos = actual.indexOf(line, pos + 1);
- assertTrue("Line " + i + " '" + line + "' missing.", pos >= 0);
+ assertTrue(pos >= 0, "Line " + i + " '" + line + "' missing.");
}
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
index 3147587aa96..f23a4325d79 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.messagebus.test;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ public class QueueAdapterTestCase {
private static final int WAIT_FOREVER = 60;
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
QueueAdapter queue = new QueueAdapter();
assertTrue(queue.isEmpty());
assertEquals(0, queue.size());
@@ -39,7 +39,7 @@ public class QueueAdapterTestCase {
}
@Test
- public void requireThatSizeCanBeWaitedFor() {
+ void requireThatSizeCanBeWaitedFor() {
final QueueAdapter queue = new QueueAdapter();
assertTrue(queue.waitSize(0, NO_WAIT));
assertFalse(queue.waitSize(1, NO_WAIT));
@@ -64,7 +64,7 @@ public class QueueAdapterTestCase {
}
@Test
- public void requireThatWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatWaitCanBeInterrupted() throws InterruptedException {
final QueueAdapter queue = new QueueAdapter();
final AtomicReference<Boolean> result = new AtomicReference<>();
Thread thread = new Thread() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
index 2e60f68eb43..59a93df17ed 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.messagebus.test;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.*;
public class ReceptorTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Receptor receptor = new Receptor();
assertNull(receptor.getMessage(0));
Message msg = new MyMessage();
@@ -30,7 +30,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessagesAndRepliesAreTrackedIndividually() {
+ void requireThatMessagesAndRepliesAreTrackedIndividually() {
Receptor receptor = new Receptor();
receptor.handleMessage(new MyMessage());
receptor.handleReply(new MyReply());
@@ -44,7 +44,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessagesCanBeWaitedFor() {
+ void requireThatMessagesCanBeWaitedFor() {
final Receptor receptor = new Receptor();
Thread thread = new Thread() {
@@ -63,7 +63,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessageWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatMessageWaitCanBeInterrupted() throws InterruptedException {
final Receptor receptor = new Receptor();
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread() {
@@ -80,7 +80,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatRepliesCanBeWaitedFor() {
+ void requireThatRepliesCanBeWaitedFor() {
final Receptor receptor = new Receptor();
Thread thread = new Thread() {
@@ -99,7 +99,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatReplyWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatReplyWaitCanBeInterrupted() throws InterruptedException {
final Receptor receptor = new Receptor();
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java
index 217f5347f40..7e3d9e926b9 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class SimpleMessageTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
SimpleMessage msg = new SimpleMessage("foo");
assertEquals(SimpleProtocol.MESSAGE, msg.getType());
assertEquals(SimpleProtocol.NAME, msg.getProtocol());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
index 76d6a1ee778..a8406cd5d1f 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.messagebus.test;
import com.yahoo.component.Version;
import com.yahoo.messagebus.EmptyReply;
import com.yahoo.messagebus.Routable;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,45 +17,45 @@ public class SimpleProtocolTestCase {
private static final SimpleProtocol PROTOCOL = new SimpleProtocol();
@Test
- public void requireThatNameIsSet() {
+ void requireThatNameIsSet() {
assertEquals(SimpleProtocol.NAME, PROTOCOL.getName());
}
@Test
- public void requireThatMessageCanBeEncodedAndDecoded() {
+ void requireThatMessageCanBeEncodedAndDecoded() {
SimpleMessage msg = new SimpleMessage("foo");
byte[] buf = PROTOCOL.encode(Version.emptyVersion, msg);
Routable routable = PROTOCOL.decode(Version.emptyVersion, buf);
assertNotNull(routable);
assertEquals(SimpleMessage.class, routable.getClass());
- msg = (SimpleMessage)routable;
+ msg = (SimpleMessage) routable;
assertEquals("foo", msg.getValue());
}
@Test
- public void requireThatReplyCanBeDecoded() {
+ void requireThatReplyCanBeDecoded() {
SimpleReply reply = new SimpleReply("foo");
byte[] buf = PROTOCOL.encode(Version.emptyVersion, reply);
Routable routable = PROTOCOL.decode(Version.emptyVersion, buf);
assertNotNull(routable);
assertEquals(SimpleReply.class, routable.getClass());
- reply = (SimpleReply)routable;
+ reply = (SimpleReply) routable;
assertEquals("foo", reply.getValue());
}
@Test
- public void requireThatUnknownRoutablesAreNotEncoded() {
+ void requireThatUnknownRoutablesAreNotEncoded() {
assertNull(PROTOCOL.encode(VERSION, new EmptyReply()));
}
@Test
- public void requireThatEmptyBufferIsNotDecoded() {
+ void requireThatEmptyBufferIsNotDecoded() {
assertNull(PROTOCOL.decode(VERSION, new byte[0]));
}
@Test
- public void requireThatUnknownBufferIsNotDecoded() {
- assertNull(PROTOCOL.decode(VERSION, new byte[] { 'U' }));
+ void requireThatUnknownBufferIsNotDecoded() {
+ assertNull(PROTOCOL.decode(VERSION, new byte[]{'U'}));
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
index 0d3f67bcb3c..bbb72a6b637 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class SimpleReplyTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
SimpleReply reply = new SimpleReply("foo");
assertEquals(SimpleProtocol.REPLY, reply.getType());
assertEquals(SimpleProtocol.NAME, reply.getProtocol());
diff --git a/messagebus/src/tests/messenger/messenger.cpp b/messagebus/src/tests/messenger/messenger.cpp
index 1ee34b386ae..acd4406a7dc 100644
--- a/messagebus/src/tests/messenger/messenger.cpp
+++ b/messagebus/src/tests/messenger/messenger.cpp
@@ -39,7 +39,7 @@ public:
TEST("messenger_test") {
- Messenger msn(true, true);
+ Messenger msn;
msn.start();
vespalib::Barrier barrier(2);
diff --git a/messagebus/src/vespa/messagebus/messagebus.cpp b/messagebus/src/vespa/messagebus/messagebus.cpp
index b4b29b84793..97be5955e9d 100644
--- a/messagebus/src/vespa/messagebus/messagebus.cpp
+++ b/messagebus/src/vespa/messagebus/messagebus.cpp
@@ -82,13 +82,13 @@ public:
namespace mbus {
-MessageBus::MessageBus(INetwork &net, ProtocolSet protocols, bool skip_request_thread, bool skip_reply_thread) :
+MessageBus::MessageBus(INetwork &net, ProtocolSet protocols) :
_network(net),
_lock(),
_routingTables(),
_sessions(),
_protocolRepository(std::make_unique<ProtocolRepository>()),
- _msn(std::make_unique<Messenger>(skip_request_thread, skip_reply_thread)),
+ _msn(std::make_unique<Messenger>()),
_resender(),
_maxPendingCount(0),
_maxPendingSize(0),
@@ -111,7 +111,7 @@ MessageBus::MessageBus(INetwork &net, const MessageBusParams &params) :
_routingTables(),
_sessions(),
_protocolRepository(std::make_unique<ProtocolRepository>()),
- _msn(std::make_unique<Messenger>(true, true)),
+ _msn(std::make_unique<Messenger>()),
_resender(),
_maxPendingCount(params.getMaxPendingCount()),
_maxPendingSize(params.getMaxPendingSize()),
diff --git a/messagebus/src/vespa/messagebus/messagebus.h b/messagebus/src/vespa/messagebus/messagebus.h
index d2e82835f3e..d270a0f3491 100644
--- a/messagebus/src/vespa/messagebus/messagebus.h
+++ b/messagebus/src/vespa/messagebus/messagebus.h
@@ -82,7 +82,7 @@ public:
* @param network The network to associate with.
* @param protocols An array of protocols to register.
*/
- MessageBus(INetwork &net, ProtocolSet protocols, bool skip_request_thread, bool skip_reply_thread);
+ MessageBus(INetwork &net, ProtocolSet protocols);
/**
* Constructs an instance of message bus. This requires a network object that it will associate with. This
diff --git a/messagebus/src/vespa/messagebus/messenger.cpp b/messagebus/src/vespa/messagebus/messenger.cpp
index 13ca5317148..1423876e95b 100644
--- a/messagebus/src/vespa/messagebus/messenger.cpp
+++ b/messagebus/src/vespa/messagebus/messenger.cpp
@@ -155,14 +155,12 @@ public:
namespace mbus {
-Messenger::Messenger(bool skip_request_thread, bool skip_reply_thread)
+Messenger::Messenger()
: _lock(),
_pool(128000),
_children(),
_queue(),
- _closed(false),
- _skip_request_thread(skip_request_thread),
- _skip_reply_thread(skip_reply_thread)
+ _closed(false)
{}
Messenger::~Messenger()
@@ -246,21 +244,13 @@ Messenger::start()
void
Messenger::deliverMessage(Message::UP msg, IMessageHandler &handler)
{
- if (_skip_request_thread) {
- handler.handleMessage(std::move(msg));
- } else {
- enqueue(std::make_unique<MessageTask>(std::move(msg), handler));
- }
+ handler.handleMessage(std::move(msg));
}
void
Messenger::deliverReply(Reply::UP reply, IReplyHandler &handler)
{
- if (_skip_reply_thread) {
- handler.handleReply(std::move(reply));
- } else {
- enqueue(std::make_unique<ReplyTask>(std::move(reply), handler));
- }
+ handler.handleReply(std::move(reply));
}
void
diff --git a/messagebus/src/vespa/messagebus/messenger.h b/messagebus/src/vespa/messagebus/messenger.h
index be4dbdb10d8..0d36e6006cb 100644
--- a/messagebus/src/vespa/messagebus/messenger.h
+++ b/messagebus/src/vespa/messagebus/messenger.h
@@ -42,17 +42,15 @@ private:
mutable std::mutex _lock;
std::condition_variable _cond;
FastOS_ThreadPool _pool;
- std::vector<ITask*> _children;
+ std::vector<ITask*> _children;
vespalib::ArrayQueue<ITask*> _queue;
bool _closed;
- const bool _skip_request_thread;
- const bool _skip_reply_thread;
protected:
void Run(FastOS_ThreadInterface *thread, void *arg) override;
public:
- Messenger(bool skip_request_thread, bool skip_reply_thread);
+ Messenger();
/**
* Frees any allocated resources. Also destroys all queued tasks.
diff --git a/messagebus/src/vespa/messagebus/network/rpcnetwork.cpp b/messagebus/src/vespa/messagebus/network/rpcnetwork.cpp
index 77d8ca24cfc..412dc29d4f2 100644
--- a/messagebus/src/vespa/messagebus/network/rpcnetwork.cpp
+++ b/messagebus/src/vespa/messagebus/network/rpcnetwork.cpp
@@ -17,7 +17,7 @@
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/stringfmt.h>
-#include <vespa/vespalib/util/threadstackexecutor.h>
+#include <vespa/vespalib/util/gate.h>
#include <vespa/fastos/thread.h>
#include <thread>
@@ -84,7 +84,8 @@ toFNETConfig(const RPCNetworkParams & params) {
return fnet::TransportConfig(params.getNumNetworkThreads())
.maxInputBufferSize(params.getMaxInputBufferSize())
.maxOutputBufferSize(params.getMaxOutputBufferSize())
- .tcpNoDelay(params.getTcpNoDelay());
+ .tcpNoDelay(params.getTcpNoDelay())
+ .events_before_wakeup(params.events_before_wakeup());
}
}
@@ -135,12 +136,9 @@ RPCNetwork::RPCNetwork(const RPCNetworkParams &params) :
_targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs(), params.getNumRpcTargets())),
_targetPoolTask(std::make_unique<TargetPoolTask>(_scheduler, *_targetPool)),
_servicePool(std::make_unique<RPCServicePool>(*_mirror, 4_Ki)),
- _executor(std::make_unique<vespalib::ThreadStackExecutor>(params.getNumThreads(), 64_Ki)),
_sendV2(std::make_unique<RPCSendV2>()),
_sendAdapters(),
- _compressionConfig(params.getCompressionConfig()),
- _allowDispatchForEncode(params.getDispatchOnEncode()),
- _allowDispatchForDecode(params.getDispatchOnDecode())
+ _compressionConfig(params.getCompressionConfig())
{
}
@@ -412,7 +410,6 @@ void
RPCNetwork::sync()
{
SyncTask task(_scheduler);
- _executor->sync();
task.await();
}
@@ -423,7 +420,6 @@ RPCNetwork::shutdown()
_scheduler.Kill(_targetPoolTask.get());
_transport->ShutDown(true);
_threadPool->Close();
- _executor->shutdown().sync();
}
void
diff --git a/messagebus/src/vespa/messagebus/network/rpcnetwork.h b/messagebus/src/vespa/messagebus/network/rpcnetwork.h
index e706431f90d..b95c0c77b3c 100644
--- a/messagebus/src/vespa/messagebus/network/rpcnetwork.h
+++ b/messagebus/src/vespa/messagebus/network/rpcnetwork.h
@@ -65,12 +65,9 @@ private:
std::unique_ptr<RPCTargetPool> _targetPool;
std::unique_ptr<FNET_Task> _targetPoolTask;
std::unique_ptr<RPCServicePool> _servicePool;
- std::unique_ptr<vespalib::SyncableThreadExecutor> _executor;
std::unique_ptr<RPCSendAdapter> _sendV2;
SendAdapterMap _sendAdapters;
CompressionConfig _compressionConfig;
- bool _allowDispatchForEncode;
- bool _allowDispatchForDecode;
/**
* Resolves and assigns a service address for the given recipient using the
@@ -222,10 +219,6 @@ public:
const slobrok::api::IMirrorAPI &getMirror() const override;
CompressionConfig getCompressionConfig() { return _compressionConfig; }
void invoke(FRT_RPCRequest *req);
- vespalib::Executor & getExecutor() const { return *_executor; }
- bool allowDispatchForEncode() const { return _allowDispatchForEncode; }
- bool allowDispatchForDecode() const { return _allowDispatchForDecode; }
-
};
} // namespace mbus
diff --git a/messagebus/src/vespa/messagebus/network/rpcnetworkparams.cpp b/messagebus/src/vespa/messagebus/network/rpcnetworkparams.cpp
index a4cdd25040b..fc060b48fc2 100644
--- a/messagebus/src/vespa/messagebus/network/rpcnetworkparams.cpp
+++ b/messagebus/src/vespa/messagebus/network/rpcnetworkparams.cpp
@@ -15,14 +15,10 @@ RPCNetworkParams::RPCNetworkParams(config::ConfigUri configUri) :
_listenPort(0),
_maxInputBufferSize(256_Ki),
_maxOutputBufferSize(256_Ki),
- _numThreads(4),
_numNetworkThreads(1),
_numRpcTargets(1),
+ _events_before_wakeup(1),
_tcpNoDelay(true),
- _dispatchOnEncode(true),
- _dispatchOnDecode(false),
- _skip_request_thread(false),
- _skip_reply_thread(false),
_connectionExpireSecs(600),
_compressionConfig(CompressionConfig::LZ4, 6, 90, 1024)
{ }
diff --git a/messagebus/src/vespa/messagebus/network/rpcnetworkparams.h b/messagebus/src/vespa/messagebus/network/rpcnetworkparams.h
index 01834074e6f..4a4d92ba797 100644
--- a/messagebus/src/vespa/messagebus/network/rpcnetworkparams.h
+++ b/messagebus/src/vespa/messagebus/network/rpcnetworkparams.h
@@ -19,14 +19,10 @@ private:
int _listenPort;
uint32_t _maxInputBufferSize;
uint32_t _maxOutputBufferSize;
- uint32_t _numThreads;
uint32_t _numNetworkThreads;
uint32_t _numRpcTargets;
+ uint32_t _events_before_wakeup;
bool _tcpNoDelay;
- bool _dispatchOnEncode;
- bool _dispatchOnDecode;
- bool _skip_request_thread;
- bool _skip_reply_thread;
double _connectionExpireSecs;
CompressionConfig _compressionConfig;
@@ -114,19 +110,6 @@ public:
return *this;
}
- /**
- * Sets number of threads for the thread pool.
- *
- * @param numThreads number of threads for thread pool
- * @return This, to allow chaining.
- */
- RPCNetworkParams &setNumThreads(uint32_t numThreads) {
- _numThreads = numThreads;
- return *this;
- }
-
- uint32_t getNumThreads() const { return _numThreads; }
-
RPCNetworkParams &setTcpNoDelay(bool tcpNoDelay) {
_tcpNoDelay = tcpNoDelay;
return *this;
@@ -164,19 +147,6 @@ public:
}
/**
- * Sets the maximum input buffer size allowed for the underlying FNET connection. Using the value 0 means that there
- * is no limit; the connection will not free any allocated memory until it is cleaned up. This might potentially
- * save alot of allocation time.
- *
- * @param maxInputBufferSize The maximum number of bytes.
- * @return This, to allow chaining.
- */
- RPCNetworkParams &setMaxInputBufferSize(uint32_t maxInputBufferSize) {
- _maxInputBufferSize = maxInputBufferSize;
- return *this;
- }
-
- /**
* Returns the maximum output buffer size allowed for the underlying FNET connection.
*
* @return The maximum number of bytes.
@@ -185,53 +155,17 @@ public:
return _maxOutputBufferSize;
}
- /**
- * Sets the maximum output buffer size allowed for the underlying FNET connection. Using the value 0 means that there
- * is no limit; the connection will not free any allocated memory until it is cleaned up. This might potentially
- * save alot of allocation time.
- *
- * @param maxOutputBufferSize The maximum number of bytes.
- * @return This, to allow chaining.
- */
- RPCNetworkParams &setMaxOutputBufferSize(uint32_t maxOutputBufferSize) {
- _maxOutputBufferSize = maxOutputBufferSize;
- return *this;
- }
-
RPCNetworkParams &setCompressionConfig(CompressionConfig compressionConfig) {
_compressionConfig = compressionConfig;
return *this;
}
CompressionConfig getCompressionConfig() const { return _compressionConfig; }
-
- RPCNetworkParams &setDispatchOnDecode(bool dispatchOnDecode) {
- _dispatchOnDecode = dispatchOnDecode;
- return *this;
- }
-
- bool getDispatchOnDecode() const { return _dispatchOnDecode; }
-
- RPCNetworkParams &setDispatchOnEncode(bool dispatchOnEncode) {
- _dispatchOnEncode = dispatchOnEncode;
+ RPCNetworkParams &events_before_wakeup(uint32_t value) {
+ _events_before_wakeup = value;
return *this;
}
-
- bool getDispatchOnEncode() const { return _dispatchOnEncode; }
-
- RPCNetworkParams &setSkipRequestThread(bool skip_request_thread) {
- _skip_request_thread = skip_request_thread;
- return *this;
- }
-
- bool getSkipRequestThread() const { return _skip_request_thread; }
-
- RPCNetworkParams &setSkipReplyThread(bool skip_reply_thread) {
- _skip_reply_thread = skip_reply_thread;
- return *this;
- }
-
- bool getSkipReplyThread() const { return _skip_reply_thread; }
+ uint32_t events_before_wakeup() const { return _events_before_wakeup; }
};
}
diff --git a/messagebus/src/vespa/messagebus/network/rpcsend.cpp b/messagebus/src/vespa/messagebus/network/rpcsend.cpp
index 7627aa876b3..ff77a1bb639 100644
--- a/messagebus/src/vespa/messagebus/network/rpcsend.cpp
+++ b/messagebus/src/vespa/messagebus/network/rpcsend.cpp
@@ -220,14 +220,7 @@ RPCSend::decode(vespalib::stringref protocolName, const vespalib::Version & vers
void
RPCSend::handleReply(Reply::UP reply)
{
- if (!_net->allowDispatchForEncode()) {
- doHandleReply(std::move(reply));
- } else {
- auto rejected = _net->getExecutor().execute(makeLambdaTask([this, reply = std::move(reply)]() mutable {
- doHandleReply(std::move(reply));
- }));
- assert (!rejected);
- }
+ doHandleReply(std::move(reply));
}
void
@@ -256,15 +249,7 @@ void
RPCSend::invoke(FRT_RPCRequest *req)
{
req->Detach();
-
- if (!_net->allowDispatchForDecode()) {
- doRequest(req);
- } else {
- auto rejected = _net->getExecutor().execute(makeLambdaTask([this, req]() {
- doRequest(req);
- }));
- assert (!rejected);
- }
+ doRequest(req);
}
void
diff --git a/messagebus/src/vespa/messagebus/rpcmessagebus.cpp b/messagebus/src/vespa/messagebus/rpcmessagebus.cpp
index a79171f5af2..0e4b6673d20 100644
--- a/messagebus/src/vespa/messagebus/rpcmessagebus.cpp
+++ b/messagebus/src/vespa/messagebus/rpcmessagebus.cpp
@@ -25,7 +25,7 @@ RPCMessageBus::RPCMessageBus(const ProtocolSet &protocols,
const RPCNetworkParams &rpcParams,
const config::ConfigUri &routingCfgUri) :
_net(rpcParams),
- _bus(_net, protocols, rpcParams.getSkipRequestThread(), rpcParams.getSkipReplyThread()),
+ _bus(_net, protocols),
_agent(_bus),
_subscriber(routingCfgUri.getContext())
{
diff --git a/messagebus/src/vespa/messagebus/testlib/testserver.cpp b/messagebus/src/vespa/messagebus/testlib/testserver.cpp
index 80d9eaefe29..d289c372fda 100644
--- a/messagebus/src/vespa/messagebus/testlib/testserver.cpp
+++ b/messagebus/src/vespa/messagebus/testlib/testserver.cpp
@@ -25,7 +25,7 @@ TestServer::TestServer(const Identity &ident,
const Slobrok &slobrok,
IProtocol::SP protocol) :
net(RPCNetworkParams(slobrok.config()).setIdentity(ident)),
- mb(net, ProtocolSet().add(std::make_shared<SimpleProtocol>()).add(protocol), true, true)
+ mb(net, ProtocolSet().add(std::make_shared<SimpleProtocol>()).add(protocol))
{
mb.setupRouting(spec);
}
diff --git a/metrics-proxy/pom.xml b/metrics-proxy/pom.xml
index fc63d453738..4aafff72af0 100644
--- a/metrics-proxy/pom.xml
+++ b/metrics-proxy/pom.xml
@@ -89,12 +89,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
<!-- compile scope -->
diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/MetricsFormatter.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/MetricsFormatter.java
index 64a21a54999..dd249c4a21f 100644
--- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/MetricsFormatter.java
+++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/MetricsFormatter.java
@@ -54,12 +54,12 @@ public class MetricsFormatter {
return name;
}
- // E.g. container/qrserver.1 -> 'container.qrserver.1'
+ // E.g. container/default.1 -> 'container.default.1'
private static String toServiceId(String configId) {
return "'" + configId.replace("/", ".") + "'";
}
- // E.g. container/qrserver.1 -> container.'qrserver.1'
+ // E.g. container/default.1 -> container.'default.1'
private static String toSystemServiceId(String configId) {
String name = configId.replace("/", ".");
name = name.replaceFirst("\\.", ".'") + "'";
diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/ConfigSentinelClient.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/ConfigSentinelClient.java
index 6d41fc93c25..ec5bd53cb21 100644
--- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/ConfigSentinelClient.java
+++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/ConfigSentinelClient.java
@@ -3,6 +3,8 @@ package ai.vespa.metricsproxy.service;
import com.yahoo.component.annotation.Inject;
import com.yahoo.component.AbstractComponent;
+
+import java.time.Duration;
import java.util.logging.Level;
import com.yahoo.jrt.ErrorCode;
@@ -170,7 +172,7 @@ public class ConfigSentinelClient extends AbstractComponent {
}
if (connection.isValid()) {
Request req = new Request("sentinel.ls");
- connection.invokeSync(req, 5.0);
+ connection.invokeSync(req, Duration.ofSeconds(5));
if (req.errorCode() == ErrorCode.NONE &&
req.checkReturnTypes("s"))
{
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/http/application/ApplicationMetricsHandlerTest.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/http/application/ApplicationMetricsHandlerTest.java
index 4d1fb802afc..2e7f7c7a936 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/http/application/ApplicationMetricsHandlerTest.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/http/application/ApplicationMetricsHandlerTest.java
@@ -188,7 +188,7 @@ public class ApplicationMetricsHandlerTest {
assertEquals("us-west", dimensions.get(PublicDimensions.ZONE));
assertEquals("search/", dimensions.get(PublicDimensions.API));
assertEquals("music", dimensions.get(PublicDimensions.DOCUMENT_TYPE));
- assertEquals("qrserver0", dimensions.get(PublicDimensions.SERVICE_ID));
+ assertEquals("default0", dimensions.get(PublicDimensions.SERVICE_ID));
assertFalse(dimensions.containsKey("non-public"));
}
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/IntegrationTester.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/IntegrationTester.java
index 961c8f91223..859c3c3dd10 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/IntegrationTester.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/IntegrationTester.java
@@ -38,7 +38,7 @@ public class IntegrationTester implements AutoCloseable {
static final String MONITORING_SYSTEM = "test-system";
static final ConsumerId CUSTOM_CONSUMER_ID = toConsumerId("custom-consumer");
- static final String SERVICE_1_CONFIG_ID = "container/qrserver.0";
+ static final String SERVICE_1_CONFIG_ID = "container/default.0";
static final String SERVICE_2_CONFIG_ID = "storage/cluster.storage/storage/0";
private final RpcConnector connector;
@@ -104,7 +104,7 @@ public class IntegrationTester implements AutoCloseable {
private VespaServicesConfig servicesConfig() {
return new VespaServicesConfig.Builder()
- .service(createService(toServiceId("qrserver"), SERVICE_1_CONFIG_ID, httpPort()))
+ .service(createService(toServiceId("container"), SERVICE_1_CONFIG_ID, httpPort()))
.service(createService(toServiceId("storagenode"), SERVICE_2_CONFIG_ID, httpPort()))
.build();
}
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcHealthMetricsTest.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcHealthMetricsTest.java
index 71a4466ea95..cf3610fe0bb 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcHealthMetricsTest.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcHealthMetricsTest.java
@@ -14,6 +14,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
+import java.time.Duration;
import java.util.List;
import static ai.vespa.metricsproxy.TestUtil.getFileContents;
@@ -35,7 +36,7 @@ public class RpcHealthMetricsTest {
getFileContents("health-check-failed.response.json");
private static final String WANTED_RPC_RESPONSE =
getFileContents("rpc-json-output-check.json").trim();
- private static final double RPC_INVOKE_TIMEOUT = 60.0;
+ private static final Duration RPC_INVOKE_TIMEOUT = Duration.ofSeconds(60);
@Rule
@@ -49,19 +50,19 @@ public class RpcHealthMetricsTest {
List<VespaService> services = tester.vespaServices().getInstancesById(SERVICE_1_CONFIG_ID);
assertEquals(1, services.size());
- VespaService qrserver = services.get(0);
- HealthMetric h = qrserver.getHealth();
+ VespaService container = services.get(0);
+ HealthMetric h = container.getHealth();
assertNotNull("Health metric should never be null", h);
assertTrue("Status failed, reason = " + h.getMessage(), h.isOk());
assertEquals("WORKING", h.getMessage());
mockHttpServer.setResponse(HEALTH_FAILED_RESPONSE);
- h = qrserver.getHealth();
+ h = container.getHealth();
assertNotNull("Health metric should never be null", h);
assertFalse("Status should be failed" + h.getMessage(), h.isOk());
assertEquals("SOMETHING FAILED", h.getMessage());
- String jsonRPCMessage = getHealthMetrics(tester, qrserver.getMonitoringName().id);
+ String jsonRPCMessage = getHealthMetrics(tester, container.getMonitoringName().id);
assertEquals(WANTED_RPC_RESPONSE, jsonRPCMessage);
}
}
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcMetricsTest.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcMetricsTest.java
index a52e1daf878..1e7a398b3d0 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcMetricsTest.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/rpc/RpcMetricsTest.java
@@ -19,6 +19,7 @@ import org.junit.Test;
import org.junit.rules.Timeout;
import java.io.IOException;
+import java.time.Duration;
import java.util.List;
import static ai.vespa.metricsproxy.TestUtil.getFileContents;
@@ -45,7 +46,7 @@ public class RpcMetricsTest {
private static final String METRICS_RESPONSE = getFileContents("metrics-storage-simple.json").trim();
private static final String EXTRA_APP = "extra";
- private static final double RPC_INVOKE_TIMEOUT = 60.0;
+ private static final Duration RPC_INVOKE_TIMEOUT = Duration.ofSeconds(60);
private static class RpcClient implements AutoCloseable {
private final Supervisor supervisor;
@@ -106,10 +107,10 @@ public class RpcMetricsTest {
assertEquals("#Services should be 1 for config id " + SERVICE_1_CONFIG_ID, 1, services.size());
- VespaService qrserver = services.get(0);
- assertEquals(MONITORING_SYSTEM + VespaService.SEPARATOR + "qrserver", qrserver.getMonitoringName().id);
+ VespaService container = services.get(0);
+ assertEquals(MONITORING_SYSTEM + VespaService.SEPARATOR + "container", container.getMonitoringName().id);
- Metrics metrics = qrserver.getMetrics();
+ Metrics metrics = container.getMetrics();
assertEquals("Fetched number of metrics is not correct", 2, metrics.size());
Metric m = getMetric("foo.count", metrics);
assertNotNull("Did not find expected metric with name 'foo.count'", m);
@@ -117,7 +118,7 @@ public class RpcMetricsTest {
assertNotNull("Did not find expected metric with name 'bar.count'", m2);
try (RpcClient rpcClient = new RpcClient(tester.rpcPort())) {
- verifyMetricsFromRpcRequest(qrserver, rpcClient);
+ verifyMetricsFromRpcRequest(container, rpcClient);
services = tester.vespaServices().getInstancesById(SERVICE_2_CONFIG_ID);
assertEquals("#Services should be 1 for config id " + SERVICE_2_CONFIG_ID, 1, services.size());
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelClientTest.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelClientTest.java
index 0ace697d545..fb93f04af74 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelClientTest.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelClientTest.java
@@ -10,7 +10,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
-
/**
* @author Unknown
*/
@@ -22,18 +21,18 @@ public class ConfigSentinelClientTest {
List<VespaService> services = new ArrayList<>();
VespaService docproc = new VespaService("docprocservice", "docproc/cluster.x.indexing/0");
VespaService searchnode4 = new VespaService("searchnode4", "search/cluster.x/g0/c1/r1");
- VespaService qrserver = new VespaService("qrserver", "container/qrserver.0");
+ VespaService container = new VespaService("container", "container/default.0");
services.add(searchnode4);
- services.add(qrserver);
+ services.add(container);
services.add(docproc);
try (MockConfigSentinelClient client = new MockConfigSentinelClient(configsentinel)) {
client.updateServiceStatuses(services);
- assertEquals(6520, qrserver.getPid());
- assertEquals("RUNNING", qrserver.getState());
- assertTrue(qrserver.isAlive());
+ assertEquals(6520, container.getPid());
+ assertEquals("RUNNING", container.getState());
+ assertTrue(container.isAlive());
assertEquals(6534, searchnode4.getPid());
assertEquals("RUNNING", searchnode4.getState());
assertTrue(searchnode4.isAlive());
@@ -50,16 +49,16 @@ public class ConfigSentinelClientTest {
assertEquals("RUNNING", docproc.getState());
assertTrue(docproc.isAlive());
- //qrserver has yet not been checked
- assertTrue(qrserver.isAlive());
+ // container has yet not been checked
+ assertTrue(container.isAlive());
client.updateServiceStatuses(services);
assertEquals(100, docproc.getPid());
assertEquals("RUNNING", docproc.getState());
assertTrue(docproc.isAlive());
- //qrserver is no longer running on this node - so should be false
- assertFalse(qrserver.isAlive());
+ // container is no longer running on this node - so should be false
+ assertFalse(container.isAlive());
}
}
@@ -81,8 +80,7 @@ public class ConfigSentinelClientTest {
VespaService container = VespaService.create("container", "get/container.0", -1);
- VespaService containerClusterController =
- VespaService.create("container-clustercontroller", "get/container.0", -1);
+ VespaService containerClusterController = VespaService.create("container-clustercontroller", "get/container.0", -1);
VespaService notPresent = VespaService.create("dummy","fake", -1);
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelDummy.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelDummy.java
index 4af3c934198..a2a4852ace4 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelDummy.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/ConfigSentinelDummy.java
@@ -11,7 +11,7 @@ public class ConfigSentinelDummy {
+ "fleetcontroller state=RUNNING mode=AUTO pid=6543 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"storage/cluster.storage/fleetcontroller/0\"\n"
+ "storagenode state=RUNNING mode=AUTO pid=6539 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"storage/cluster.storage/storage/0\"\n"
+ "searchnode4 state=RUNNING mode=AUTO pid=6534 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c1/r1\"\n"
- + "qrserver2 state=RUNNING mode=AUTO pid=6521 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/qrserver.1\"\n"
+ + "container2 state=RUNNING mode=AUTO pid=6521 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/default.1\"\n"
+ "logserver state=RUNNING mode=AUTO pid=6518 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"admin/logserver\"\n"
+ "logd state=RUNNING mode=AUTO pid=6517 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"hosts/dell-bl5s7.trondheim.corp.yahoo.com/logd\"\n"
+ "searchnode2 state=RUNNING mode=AUTO pid=6527 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c0/r1\"\n"
@@ -20,7 +20,7 @@ public class ConfigSentinelDummy {
+ "slobrok state=RUNNING mode=AUTO pid=6519 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"client\"\n"
+ "searchnode3 state=RUNNING mode=AUTO pid=6529 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c1/r0\"\n"
+ "searchnode state=RUNNING mode=AUTO pid=6526 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c0/r0\"\n"
- + "qrserver state=RUNNING mode=AUTO pid=6520 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/qrserver.0\"\n"
+ + "container state=RUNNING mode=AUTO pid=6520 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/default.0\"\n"
+ "\n";
@@ -37,7 +37,7 @@ public class ConfigSentinelDummy {
+ "fleetcontroller state=RUNNING mode=AUTO pid=6543 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"storage/cluster.storage/fleetcontroller/0\"\n"
+ "storagenode state=RUNNING mode=AUTO pid=6539 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"storage/cluster.storage/storage/0\"\n"
+ "searchnode4 state=RUNNING mode=AUTO pid=6534 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c1/r1\"\n"
- + "qrserver2 state=RUNNING mode=AUTO pid=6521 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/qrserver.1\"\n"
+ + "container2 state=RUNNING mode=AUTO pid=6521 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"container/default.1\"\n"
+ "logserver state=RUNNING mode=AUTO pid=6518 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"admin/logserver\"\n"
+ "logd state=RUNNING mode=AUTO pid=6517 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"hosts/dell-bl5s7.trondheim.corp.yahoo.com/logd\"\n"
+ "searchnode2 state=RUNNING mode=AUTO pid=6527 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"search/cluster.x/g0/c0/r1\"\n"
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockConfigSentinelClient.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockConfigSentinelClient.java
index 3f0d36b0c1a..14cfd2ccf3c 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockConfigSentinelClient.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockConfigSentinelClient.java
@@ -1,16 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.service;
-import java.util.logging.Logger;
-
/**
* Mock config sentinel
*
* @author hmusum
*/
public class MockConfigSentinelClient extends ConfigSentinelClient implements AutoCloseable {
+
private final ConfigSentinelDummy configSentinel;
- private final static Logger log = Logger.getLogger(MockConfigSentinelClient.class.getPackage().getName());
public MockConfigSentinelClient(ConfigSentinelDummy configSentinel) {
super();
diff --git a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/VespaServiceTest.java b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/VespaServiceTest.java
index 6c0e1865dcd..1e9e067ec0e 100644
--- a/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/VespaServiceTest.java
+++ b/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/VespaServiceTest.java
@@ -36,18 +36,18 @@ public class VespaServiceTest {
@Test
public void testService() {
- VespaService service = new VespaService("qrserver", "container/qrserver.0");
- assertEquals("qrserver", service.getServiceName());
- assertEquals("qrserver", service.getInstanceName());
+ VespaService service = new VespaService("container", "container/container.0");
+ assertEquals("container", service.getServiceName());
+ assertEquals("container", service.getInstanceName());
assertEquals(-1, service.getPid());
- assertEquals("container/qrserver.0", service.getConfigId());
+ assertEquals("container/container.0", service.getConfigId());
- service = VespaService.create("qrserver2", "container/qrserver.0", -1);
- assertEquals("qrserver", service.getServiceName());
- assertEquals("qrserver2", service.getInstanceName());
+ service = VespaService.create("container2", "container/container.0", -1);
+ assertEquals("container", service.getServiceName());
+ assertEquals("container2", service.getInstanceName());
assertEquals(-1, service.getPid());
- assertEquals("container/qrserver.0", service.getConfigId());
+ assertEquals("container/container.0", service.getConfigId());
}
@Test
diff --git a/metrics-proxy/src/test/resources/generic-sample.json b/metrics-proxy/src/test/resources/generic-sample.json
index c9b02696e69..13302121507 100644
--- a/metrics-proxy/src/test/resources/generic-sample.json
+++ b/metrics-proxy/src/test/resources/generic-sample.json
@@ -36,7 +36,7 @@
"applicationId": "music.default",
"clustertype": "container",
"clusterid": "default",
- "instance": "qrserver0",
+ "instance": "default0",
"zone": "us-west",
"api": "search/",
"documenttype": "music",
diff --git a/metrics-proxy/src/test/resources/rpc-json-output-check.json b/metrics-proxy/src/test/resources/rpc-json-output-check.json
index 701a06d82b2..4cd553e91f7 100644
--- a/metrics-proxy/src/test/resources/rpc-json-output-check.json
+++ b/metrics-proxy/src/test/resources/rpc-json-output-check.json
@@ -1 +1 @@
-{"metrics":[{"status_code":1,"application":"test-system.qrserver","dimensions":{"metrictype":"health","instance":"qrserver"},"status_msg":"SOMETHING FAILED"}]} \ No newline at end of file
+{"metrics":[{"status_code":1,"application":"test-system.container","dimensions":{"metrictype":"health","instance":"container"},"status_msg":"SOMETHING FAILED"}]} \ No newline at end of file
diff --git a/metrics/src/vespa/metrics/metric.cpp b/metrics/src/vespa/metrics/metric.cpp
index c29f4ce454e..fe9b5550104 100644
--- a/metrics/src/vespa/metrics/metric.cpp
+++ b/metrics/src/vespa/metrics/metric.cpp
@@ -52,7 +52,7 @@ Tag::Tag(vespalib::stringref k, vespalib::stringref v)
_value(NameRepo::tagValueId(v))
{ }
-Tag::Tag(const Tag &) = default;
+Tag::Tag(const Tag &) noexcept = default;
Tag & Tag::operator = (const Tag &) = default;
Tag::~Tag() {}
diff --git a/metrics/src/vespa/metrics/metric.h b/metrics/src/vespa/metrics/metric.h
index c1c5eac69fb..89b772bf750 100644
--- a/metrics/src/vespa/metrics/metric.h
+++ b/metrics/src/vespa/metrics/metric.h
@@ -87,9 +87,9 @@ struct Tag
Tag(vespalib::stringref k);
Tag(vespalib::stringref k, vespalib::stringref v);
- Tag(const Tag &);
+ Tag(const Tag &) noexcept;
Tag & operator = (const Tag &);
- Tag(Tag &&) = default;
+ Tag(Tag &&) noexcept = default;
Tag & operator = (Tag &&) = default;
~Tag();
diff --git a/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelTester.java b/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelTester.java
index a36215e005f..ab2f53db863 100644
--- a/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelTester.java
+++ b/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelTester.java
@@ -2,7 +2,6 @@
package ai.vespa.models.evaluation;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.config.subscription.FileSource;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
import com.yahoo.path.Path;
import com.yahoo.searchlib.rankingexpression.ExpressionFunction;
@@ -10,7 +9,6 @@ import com.yahoo.vespa.config.search.RankProfilesConfig;
import com.yahoo.vespa.config.search.core.OnnxModelsConfig;
import com.yahoo.vespa.config.search.core.RankingConstantsConfig;
import com.yahoo.vespa.config.search.core.RankingExpressionsConfig;
-
import java.util.Map;
import static org.junit.Assert.assertEquals;
@@ -31,8 +29,8 @@ public class ModelTester {
public Map<String, Model> models() { return models; }
+ @SuppressWarnings("deprecation")
private static Map<String, Model> createModels(String path) {
-
RankProfilesConfig config = ConfigGetter.getConfig(RankProfilesConfig.class, fileConfigId(path, "rank-profiles.cfg"));
RankingConstantsConfig constantsConfig = ConfigGetter.getConfig(RankingConstantsConfig.class, fileConfigId(path, "ranking-constants.cfg"));
RankingExpressionsConfig expressionsConfig = ConfigGetter.getConfig(RankingExpressionsConfig.class, fileConfigId(path, "ranking-expressions.cfg"));
diff --git a/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelsEvaluatorTest.java b/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelsEvaluatorTest.java
index 540c534925e..c4e859bec9f 100644
--- a/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelsEvaluatorTest.java
+++ b/model-evaluation/src/test/java/ai/vespa/models/evaluation/ModelsEvaluatorTest.java
@@ -2,7 +2,6 @@
package ai.vespa.models.evaluation;
import com.yahoo.config.subscription.ConfigGetter;
-import com.yahoo.config.subscription.FileSource;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
import com.yahoo.path.Path;
import com.yahoo.searchlib.rankingexpression.ExpressionFunction;
@@ -15,7 +14,6 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig;
import com.yahoo.vespa.config.search.core.RankingExpressionsConfig;
import com.yahoo.yolean.Exceptions;
import org.junit.Test;
-
import java.util.ArrayList;
import java.util.List;
@@ -128,6 +126,7 @@ public class ModelsEvaluatorTest {
// TODO: Test argument-less function
// TODO: Test with nested functions
+ @SuppressWarnings("deprecation")
private ModelsEvaluator createModels() {
RankProfilesConfig config = ConfigGetter.getConfig(RankProfilesConfig.class, fileConfigId("rank-profiles.cfg"));
RankingConstantsConfig constantsConfig = ConfigGetter.getConfig(RankingConstantsConfig.class, fileConfigId("ranking-constants.cfg"));
diff --git a/model-evaluation/src/test/java/ai/vespa/models/evaluation/OnnxEvaluatorTest.java b/model-evaluation/src/test/java/ai/vespa/models/evaluation/OnnxEvaluatorTest.java
index 27d1c08ea39..992dae22aaf 100644
--- a/model-evaluation/src/test/java/ai/vespa/models/evaluation/OnnxEvaluatorTest.java
+++ b/model-evaluation/src/test/java/ai/vespa/models/evaluation/OnnxEvaluatorTest.java
@@ -51,6 +51,7 @@ public class OnnxEvaluatorTest {
assertEquals(function.evaluate(), Tensor.from("tensor<float>(d0[2],d1[1]):[0.63931,0.67574]"));
}
+ @SuppressWarnings("deprecation")
private ModelsEvaluator createModels() {
RankProfilesConfig config = ConfigGetter.getConfig(RankProfilesConfig.class, fileConfigId("rank-profiles.cfg"));
RankingConstantsConfig constantsConfig = ConfigGetter.getConfig(RankingConstantsConfig.class, fileConfigId("ranking-constants.cfg"));
diff --git a/model-evaluation/src/test/java/ai/vespa/models/handler/ModelsEvaluationHandlerTest.java b/model-evaluation/src/test/java/ai/vespa/models/handler/ModelsEvaluationHandlerTest.java
index 7790f8a60d0..0de8ce5f061 100644
--- a/model-evaluation/src/test/java/ai/vespa/models/handler/ModelsEvaluationHandlerTest.java
+++ b/model-evaluation/src/test/java/ai/vespa/models/handler/ModelsEvaluationHandlerTest.java
@@ -257,6 +257,7 @@ public class ModelsEvaluationHandlerTest {
handler.assertResponse(url, properties, 200, expected);
}
+ @SuppressWarnings("deprecation")
static private ModelsEvaluator createModels() {
RankProfilesConfig config = ConfigGetter.getConfig(RankProfilesConfig.class, fileConfigId("rank-profiles.cfg"));
RankingConstantsConfig constantsConfig = ConfigGetter.getConfig(RankingConstantsConfig.class, fileConfigId("ranking-constants.cfg"));
diff --git a/model-evaluation/src/test/java/ai/vespa/models/handler/OnnxEvaluationHandlerTest.java b/model-evaluation/src/test/java/ai/vespa/models/handler/OnnxEvaluationHandlerTest.java
index f065435ec15..8ab282668da 100644
--- a/model-evaluation/src/test/java/ai/vespa/models/handler/OnnxEvaluationHandlerTest.java
+++ b/model-evaluation/src/test/java/ai/vespa/models/handler/OnnxEvaluationHandlerTest.java
@@ -117,6 +117,7 @@ public class OnnxEvaluationHandlerTest {
handler.assertResponse(url, properties, 200, expected);
}
+ @SuppressWarnings("deprecation")
static private ModelsEvaluator createModels() {
RankProfilesConfig config = ConfigGetter.getConfig(RankProfilesConfig.class, fileConfigId("rank-profiles.cfg"));
RankingConstantsConfig constantsConfig = ConfigGetter.getConfig(RankingConstantsConfig.class, fileConfigId("ranking-constants.cfg"));
diff --git a/node-admin/pom.xml b/node-admin/pom.xml
index ae7e6ac2bce..8ef8e934cd8 100644
--- a/node-admin/pom.xml
+++ b/node-admin/pom.xml
@@ -87,21 +87,11 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>application</artifactId>
<version>${project.version}</version>
@@ -136,6 +126,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- Needed for node repo mock -->
<dependency>
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/ConnectionException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/ConnectionException.java
index da93083a6de..c78d60e9950 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/ConnectionException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/ConnectionException.java
@@ -15,7 +15,7 @@ import java.net.SocketTimeoutException;
public class ConnectionException extends ConvergenceException {
private ConnectionException(String message, Throwable cause) {
- super(message, cause);
+ super(message, cause, true);
}
/**
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/HttpException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/HttpException.java
index 4de7582fb7b..53e15b6c647 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/HttpException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/HttpException.java
@@ -14,20 +14,15 @@ public class HttpException extends ConvergenceException {
private final boolean isRetryable;
private HttpException(int statusCode, String message, boolean isRetryable) {
- super("HTTP status code " + statusCode + ": " + message);
+ super("HTTP status code " + statusCode + ": " + message, null, !isRetryable);
this.isRetryable = isRetryable;
}
private HttpException(Response.Status status, String message, boolean isRetryable) {
- super(status.toString() + " (" + status.getStatusCode() + "): " + message);
+ super(status.toString() + " (" + status.getStatusCode() + "): " + message, null, !isRetryable);
this.isRetryable = isRetryable;
}
- private HttpException(String message) {
- super(message);
- this.isRetryable = false;
- }
-
boolean isRetryable() {
return isRetryable;
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeRepositoryException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeRepositoryException.java
index a0b0499bb1e..636813a2169 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeRepositoryException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeRepositoryException.java
@@ -5,10 +5,6 @@ import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
public class NodeRepositoryException extends ConvergenceException {
public NodeRepositoryException(String message) {
- super(message);
- }
-
- public NodeRepositoryException(String message, Exception exception) {
- super(message, exception);
+ super(message, null, true);
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorException.java
index 9b8a749c33d..917b65b606c 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorException.java
@@ -5,7 +5,12 @@ import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
@SuppressWarnings("serial")
public class OrchestratorException extends ConvergenceException {
+ /** Creates a transient convergence exception. */
public OrchestratorException(String message) {
- super(message);
+ this(message, true);
+ }
+
+ protected OrchestratorException(String message, boolean isError) {
+ super(message, null, isError);
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImpl.java
index 281d43e0afc..858bce27ed8 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImpl.java
@@ -59,7 +59,7 @@ public class OrchestratorImpl implements Orchestrator {
} catch (HttpException e) {
throw new OrchestratorException("Failed to suspend " + hostName + ": " + e.toString());
} catch (ConnectionException e) {
- throw new ConvergenceException("Failed to suspend " + hostName + ": " + e.getMessage());
+ throw ConvergenceException.ofTransient("Failed to suspend " + hostName + ": " + e.getMessage());
} catch (RuntimeException e) {
throw new RuntimeException("Got error on suspend", e);
}
@@ -105,7 +105,7 @@ public class OrchestratorImpl implements Orchestrator {
} catch (HttpException e) {
throw new OrchestratorException("Failed to batch suspend for " + parentHostName + ": " + e.toString());
} catch (ConnectionException e) {
- throw new ConvergenceException("Failed to batch suspend for " + parentHostName + ": " + e.getMessage());
+ throw ConvergenceException.ofTransient("Failed to batch suspend for " + parentHostName + ": " + e.getMessage());
} catch (RuntimeException e) {
throw new RuntimeException("Got error on batch suspend for " + parentHostName + ", with nodes " + hostNames, e);
}
@@ -126,7 +126,7 @@ public class OrchestratorImpl implements Orchestrator {
} catch (HttpException e) {
throw new OrchestratorException("Failed to resume " + hostName + ": " + e.toString());
} catch (ConnectionException e) {
- throw new ConvergenceException("Failed to resume " + hostName + ": " + e.getMessage());
+ throw ConvergenceException.ofTransient("Failed to resume " + hostName + ": " + e.getMessage());
} catch (RuntimeException e) {
throw new RuntimeException("Got error on resume", e);
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorNotFoundException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorNotFoundException.java
index 3b016aac03f..a6a54807e56 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorNotFoundException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorNotFoundException.java
@@ -4,6 +4,6 @@ package com.yahoo.vespa.hosted.node.admin.configserver.orchestrator;
@SuppressWarnings("serial")
public class OrchestratorNotFoundException extends OrchestratorException {
public OrchestratorNotFoundException(String message) {
- super(message);
+ super(message, true);
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
index c893f7ffee4..062a7ce018d 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainer.java
@@ -120,7 +120,7 @@ public class StorageMaintainer {
String[] results = output.split("\t");
if (results.length != 2) {
- throw new ConvergenceException("Result from disk usage command not as expected: " + output);
+ throw ConvergenceException.ofError("Result from disk usage command not as expected: " + output);
}
return DiskSize.of(Long.parseLong(results[0]), DiskSize.Unit.kiB);
@@ -226,11 +226,11 @@ public class StorageMaintainer {
String output = uncheck(() -> Files.readAllLines(Paths.get("/proc/cpuinfo")).stream()
.filter(line -> line.startsWith("microcode"))
.findFirst()
- .orElseThrow(() -> new ConvergenceException("No microcode information found in /proc/cpuinfo")));
+ .orElseThrow(() -> ConvergenceException.ofError("No microcode information found in /proc/cpuinfo")));
String[] results = output.split(":");
if (results.length != 2) {
- throw new ConvergenceException("Result from detect microcode command not as expected: " + output);
+ throw ConvergenceException.ofError("Result from detect microcode command not as expected: " + output);
}
return results[1].trim();
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
index 45dbfd07209..0933f22dee3 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollector.java
@@ -51,7 +51,7 @@ public class CoreCollector {
Matcher matcher = CORE_GENERATOR_PATH_PATTERN.matcher(result.getOutput());
if (! matcher.find()) {
- throw new ConvergenceException(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
+ throw ConvergenceException.ofError(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
asString(result), Arrays.toString(wrappedCommand)));
}
return matcher.group("path").split(" ")[0];
@@ -62,7 +62,7 @@ public class CoreCollector {
try {
CommandResult result = container.executeCommandInContainer(context, context.users().root(), command);
if (result.getExitCode() != 0) {
- throw new ConvergenceException("file command failed with " + asString(result));
+ throw ConvergenceException.ofError("file command failed with " + asString(result));
}
Matcher execfnMatcher = EXECFN_PATH_PATTERN.matcher(result.getOutput());
@@ -89,7 +89,7 @@ public class CoreCollector {
CommandResult result = container.executeCommandInContainer(context, context.users().root(), command);
if (result.getExitCode() != 0)
- throw new ConvergenceException("Failed to read backtrace " + asString(result) + ", Command: " + Arrays.toString(command));
+ throw ConvergenceException.ofError("Failed to read backtrace " + asString(result) + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
@@ -99,7 +99,7 @@ public class CoreCollector {
CommandResult result = container.executeCommandInContainer(context, context.users().root(), command);
if (result.getExitCode() != 0)
- throw new ConvergenceException("Failed to read jstack " + asString(result) + ", Command: " + Arrays.toString(command));
+ throw ConvergenceException.ofError("Failed to read jstack " + asString(result) + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
index 6295765a95f..ece494a34d7 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandler.java
@@ -95,7 +95,7 @@ public class CoredumpHandler {
.map(FileFinder.FileAttributes::filename)
.toList();
if (!pendingCores.isEmpty())
- throw new ConvergenceException(String.format("Cannot process %s coredumps: Still being written",
+ throw ConvergenceException.ofError(String.format("Cannot process %s coredumps: Still being written",
pendingCores.size() < 5 ? pendingCores : pendingCores.size()));
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
index 93195a3c340..b526c573c05 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/VespaServiceDumperImpl.java
@@ -194,13 +194,28 @@ public class VespaServiceDumperImpl implements VespaServiceDumper {
@Override
public int servicePid() {
if (pid == -1) {
- ContainerPath findPidBinary = nodeAgentCtx.paths().underVespaHome("libexec/vespa/find-pid");
- CommandResult findPidResult = executeCommandInNode(List.of(findPidBinary.pathInContainer(), serviceId()), true);
- this.pid = Integer.parseInt(findPidResult.getOutput());
+ try {
+ pid = findServicePid(serviceId());
+ } catch (RuntimeException e1) {
+ try {
+ // Workaround for Vespa 7 container clusters having service name 'qrserver'
+ if (serviceId().equals("container")) pid = findServicePid("qrserver");
+ else throw e1;
+ } catch (RuntimeException e2) {
+ e1.addSuppressed(e2);
+ throw e1;
+ }
+ }
}
return pid;
}
+ private int findServicePid(String serviceId) {
+ ContainerPath findPidBinary = nodeAgentCtx.paths().underVespaHome("libexec/vespa/find-pid");
+ CommandResult findPidResult = executeCommandInNode(List.of(findPidBinary.pathInContainer(), serviceId), true);
+ return Integer.parseInt(findPidResult.getOutput());
+ }
+
@Override
public CommandResult executeCommandInNode(List<String> command, boolean logOutput) {
CommandResult result = container.executeCommandInContainer(nodeAgentCtx, nodeAgentCtx.users().vespa(), command.toArray(new String[0]));
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ConvergenceException.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ConvergenceException.java
index 16a5eb022ad..c1b86fc7fe2 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ConvergenceException.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ConvergenceException.java
@@ -8,11 +8,34 @@ package com.yahoo.vespa.hosted.node.admin.nodeadmin;
*/
@SuppressWarnings("serial")
public class ConvergenceException extends RuntimeException {
- public ConvergenceException(String message) {
- super(message);
+ /** Create an exception that will NOT increment the monitored unhandled_exceptions metric. */
+ public static ConvergenceException ofTransient(String message) { return ofTransient(message, null); }
+
+ /** Create an exception that will NOT increment the monitored unhandled_exceptions metric. */
+ public static ConvergenceException ofTransient(String message, Throwable t) { return new ConvergenceException(message, t, false); }
+
+ /** Create an exception that increments the monitored unhandled_exceptions metric. */
+ public static ConvergenceException ofError(String message) { return ofError(message, null); }
+
+ /** Create an exception that increments the monitored unhandled_exceptions metric. */
+ public static ConvergenceException ofError(String message, Throwable t) { return new ConvergenceException(message, t, true); }
+
+ /** Create an exception with the same transient/error as the cause. */
+ public static ConvergenceException ofNested(String message, ConvergenceException cause) { return new ConvergenceException(message, cause, cause.isError); }
+
+ private final boolean isError;
+
+ /** @param isError whether the exception should increment the monitored unhandled_exception metric. */
+ protected ConvergenceException(String message, boolean isError) {
+ this(message, null, isError);
}
- public ConvergenceException(String message, Throwable t) {
+ /** @param isError whether the exception should increment the monitored unhandled_exception metric. */
+ protected ConvergenceException(String message, Throwable t, boolean isError) {
super(message, t);
+ this.isError = isError;
}
+
+ /** Whether the exception signals an error someone may want to look at, or whether it is expected to be transient (false). */
+ public boolean isError() { return isError; }
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImpl.java
index a5edd3bd74d..a371cdcde25 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImpl.java
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.nodeadmin;
+import com.yahoo.vespa.hosted.node.admin.container.ContainerStats;
import com.yahoo.vespa.hosted.node.admin.container.metrics.Counter;
import com.yahoo.vespa.hosted.node.admin.container.metrics.Dimensions;
import com.yahoo.vespa.hosted.node.admin.container.metrics.Gauge;
@@ -11,12 +12,14 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextManager;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentFactory;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentScheduler;
+import java.nio.file.FileSystem;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
@@ -42,24 +45,28 @@ public class NodeAdminImpl implements NodeAdmin {
private Instant startOfFreezeConvergence;
private final Map<String, NodeAgentWithScheduler> nodeAgentWithSchedulerByHostname = new ConcurrentHashMap<>();
+ private final ProcMeminfoReader procMeminfoReader;
private final Gauge jvmHeapUsed;
private final Gauge jvmHeapFree;
private final Gauge jvmHeapTotal;
+ private final Gauge memoryOverhead;
+ private final Gauge containerCount;
private final Counter numberOfUnhandledExceptions;
- public NodeAdminImpl(NodeAgentFactory nodeAgentFactory, Metrics metrics, Clock clock) {
+ public NodeAdminImpl(NodeAgentFactory nodeAgentFactory, Metrics metrics, Clock clock, FileSystem fileSystem) {
this(nodeAgentContext -> create(clock, nodeAgentFactory, nodeAgentContext),
- metrics, clock, NODE_AGENT_FREEZE_TIMEOUT, NODE_AGENT_SPREAD);
+ metrics, clock, NODE_AGENT_FREEZE_TIMEOUT, NODE_AGENT_SPREAD, new ProcMeminfoReader(fileSystem));
}
public NodeAdminImpl(NodeAgentFactory nodeAgentFactory, Metrics metrics,
- Clock clock, Duration freezeTimeout, Duration spread) {
+ Clock clock, Duration freezeTimeout, Duration spread, ProcMeminfoReader procMeminfoReader) {
this(nodeAgentContext -> create(clock, nodeAgentFactory, nodeAgentContext),
- metrics, clock, freezeTimeout, spread);
+ metrics, clock, freezeTimeout, spread, procMeminfoReader);
}
NodeAdminImpl(NodeAgentWithSchedulerFactory nodeAgentWithSchedulerFactory,
- Metrics metrics, Clock clock, Duration freezeTimeout, Duration spread) {
+ Metrics metrics, Clock clock, Duration freezeTimeout, Duration spread,
+ ProcMeminfoReader procMeminfoReader) {
this.nodeAgentWithSchedulerFactory = nodeAgentWithSchedulerFactory;
this.clock = clock;
this.freezeTimeout = freezeTimeout;
@@ -71,9 +78,12 @@ public class NodeAdminImpl implements NodeAdmin {
this.numberOfUnhandledExceptions = metrics.declareCounter("unhandled_exceptions",
new Dimensions(Map.of("src", "node-agents")));
+ this.procMeminfoReader = procMeminfoReader;
this.jvmHeapUsed = metrics.declareGauge("mem.heap.used");
this.jvmHeapFree = metrics.declareGauge("mem.heap.free");
this.jvmHeapTotal = metrics.declareGauge("mem.heap.total");
+ this.memoryOverhead = metrics.declareGauge("mem.system.overhead");
+ this.containerCount = metrics.declareGauge("container.count");
}
@Override
@@ -103,20 +113,33 @@ public class NodeAdminImpl implements NodeAdmin {
@Override
public void updateMetrics(boolean isSuspended) {
+ long numContainers = 0;
+ long totalContainerMemoryBytes = 0;
+
for (NodeAgentWithScheduler nodeAgentWithScheduler : nodeAgentWithSchedulerByHostname.values()) {
- if (!isSuspended) numberOfUnhandledExceptions.add(nodeAgentWithScheduler.getAndResetNumberOfUnhandledExceptions());
- nodeAgentWithScheduler.updateContainerNodeMetrics(isSuspended);
+ int count = nodeAgentWithScheduler.getAndResetNumberOfUnhandledExceptions();
+ if (!isSuspended) numberOfUnhandledExceptions.add(count);
+ Optional<ContainerStats> containerStats = nodeAgentWithScheduler.updateContainerNodeMetrics(isSuspended);
+ if (containerStats.isPresent()) {
+ ++numContainers;
+ totalContainerMemoryBytes += containerStats.get().getMemoryStats().getUsage();
+ }
}
+ Runtime runtime = Runtime.getRuntime();
+ runtime.gc();
+ long freeMemory = runtime.freeMemory();
+ long totalMemory = runtime.totalMemory();
+ long usedMemory = totalMemory - freeMemory;
+ jvmHeapFree.sample(freeMemory);
+ jvmHeapUsed.sample(usedMemory);
+ jvmHeapTotal.sample(totalMemory);
+
+ // No container stats are found while suspended, so skip setting these if so.
if (!isSuspended) {
- Runtime runtime = Runtime.getRuntime();
- runtime.gc();
- long freeMemory = runtime.freeMemory();
- long totalMemory = runtime.totalMemory();
- long usedMemory = totalMemory - freeMemory;
- jvmHeapFree.sample(freeMemory);
- jvmHeapUsed.sample(usedMemory);
- jvmHeapTotal.sample(totalMemory);
+ containerCount.sample(numContainers);
+ ProcMeminfo meminfo = procMeminfoReader.read();
+ memoryOverhead.sample(meminfo.memTotalBytes() - meminfo.memAvailableBytes() - totalContainerMemoryBytes);
}
}
@@ -205,7 +228,7 @@ public class NodeAdminImpl implements NodeAdmin {
void start() { nodeAgent.start(currentContext()); }
void stopForHostSuspension() { nodeAgent.stopForHostSuspension(currentContext()); }
void stopForRemoval() { nodeAgent.stopForRemoval(currentContext()); }
- void updateContainerNodeMetrics(boolean isSuspended) { nodeAgent.updateContainerNodeMetrics(currentContext(), isSuspended); }
+ Optional<ContainerStats> updateContainerNodeMetrics(boolean isSuspended) { return nodeAgent.updateContainerNodeMetrics(currentContext(), isSuspended); }
int getAndResetNumberOfUnhandledExceptions() { return nodeAgent.getAndResetNumberOfUnhandledExceptions(); }
@Override public void scheduleTickWith(NodeAgentContext context, Instant at) { nodeAgentScheduler.scheduleTickWith(context, at); }
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdater.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdater.java
index dda404797d9..314844dc6eb 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdater.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdater.java
@@ -110,7 +110,7 @@ public class NodeAdminStateUpdater {
if (hostIsActiveInNR) orchestrator.resume(hostHostname);
- throw new ConvergenceException("Timed out trying to freeze all nodes: will force an unfrozen tick");
+ throw ConvergenceException.ofTransient("Timed out trying to freeze all nodes: will force an unfrozen tick");
}
boolean wantFrozen = wantedState != RESUMED;
@@ -118,7 +118,7 @@ public class NodeAdminStateUpdater {
currentState = TRANSITIONING;
if (!nodeAdmin.setFrozen(wantFrozen))
- throw new ConvergenceException("NodeAdmin is not yet " + (wantFrozen ? "frozen" : "unfrozen"));
+ throw ConvergenceException.ofTransient("NodeAdmin is not yet " + (wantFrozen ? "frozen" : "unfrozen"));
switch (wantedState) {
case RESUMED:
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfo.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfo.java
new file mode 100644
index 00000000000..a1f750a34e3
--- /dev/null
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfo.java
@@ -0,0 +1,12 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.node.admin.nodeadmin;
+
+/**
+ * Represents /proc/meminfo, see proc(5).
+ *
+ * @param memTotalBytes Total usable RAM (i.e., physical RAM minus a few reserved bits and the kernel binary code).
+ * @param memAvailableBytes An estimate of how much memory is available for starting new applications, without swapping.
+ *
+ * @author hakon
+ */
+public record ProcMeminfo(long memTotalBytes, long memAvailableBytes) { }
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfoReader.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfoReader.java
new file mode 100644
index 00000000000..17abe6c7b46
--- /dev/null
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/ProcMeminfoReader.java
@@ -0,0 +1,42 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.node.admin.nodeadmin;
+
+import com.yahoo.yolean.Exceptions;
+
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Reads /proc/meminfo, see proc(5).
+ *
+ * @author hakon
+ */
+public class ProcMeminfoReader {
+ private static final String PROC_MEMINFO = "/proc/meminfo";
+ private static final Pattern MEM_TOTAL_PATTERN = Pattern.compile("MemTotal: *([0-9]+) kB");
+ private static final Pattern MEM_AVAILABLE_PATTERN = Pattern.compile("MemAvailable: *([0-9]+) kB");
+
+ private final FileSystem fileSystem;
+
+ public ProcMeminfoReader(FileSystem fileSystem) {
+ this.fileSystem = fileSystem;
+ }
+
+ public ProcMeminfo read() {
+ return read(Exceptions.uncheck(() -> Files.readString(fileSystem.getPath(PROC_MEMINFO))));
+ }
+
+ static ProcMeminfo read(String meminfoContent) {
+ return new ProcMeminfo(readKbGroup(meminfoContent, MEM_TOTAL_PATTERN),
+ readKbGroup(meminfoContent, MEM_AVAILABLE_PATTERN));
+ }
+
+ private static long readKbGroup(String string, Pattern pattern) {
+ Matcher matcher = pattern.matcher(string);
+ if (!matcher.find())
+ throw new IllegalArgumentException(pattern + " did not match anything in " + PROC_MEMINFO);
+ return Long.parseLong(matcher.group(1)) * 1024;
+ }
+}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgent.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgent.java
index 5b9bcee83bf..18c981fdf17 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgent.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgent.java
@@ -1,6 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.nodeagent;
+import com.yahoo.vespa.hosted.node.admin.container.ContainerStats;
+
+import java.util.Optional;
+
/**
* Responsible for management of a single node over its lifecycle.
* May own its own resources, threads etc. Runs independently, but receives signals
@@ -28,9 +32,9 @@ public interface NodeAgent {
void stopForRemoval(NodeAgentContext context);
/**
- * Updates metric receiver with the latest node-agent stats
+ * Updates metric receiver with the latest node-agent stats, and returns the container stats if available.
*/
- default void updateContainerNodeMetrics(NodeAgentContext context, boolean isSuspended) {}
+ default Optional<ContainerStats> updateContainerNodeMetrics(NodeAgentContext context, boolean isSuspended) { return Optional.empty(); }
/**
* Returns and resets number of unhandled exceptions
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
index 09bc58bdaa2..6408132fe0b 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
@@ -244,7 +244,7 @@ public class NodeAgentImpl implements NodeAgent {
hasResumedNode = false;
context.log(logger, "Container successfully started, new containerState is " + containerState);
return containerOperations.getContainer(context).orElseThrow(() ->
- new ConvergenceException("Did not find container that was just started"));
+ ConvergenceException.ofError("Did not find container that was just started"));
}
private Optional<Container> removeContainerIfNeededUpdateContainerState(
@@ -399,7 +399,7 @@ public class NodeAgentImpl implements NodeAgent {
// Only update CPU resources
containerOperations.updateContainer(context, existingContainer.id(), wantedContainerResources.withMemoryBytes(existingContainer.resources().memoryBytes()));
return containerOperations.getContainer(context).orElseThrow(() ->
- new ConvergenceException("Did not find container that was just updated"));
+ ConvergenceException.ofError("Did not find container that was just updated"));
}
private ContainerResources getContainerResources(NodeAgentContext context) {
@@ -435,6 +435,8 @@ public class NodeAgentImpl implements NodeAgent {
context.log(logger, Level.INFO, "Converged");
} catch (ConvergenceException e) {
context.log(logger, e.getMessage());
+ if (e.isError())
+ numberOfUnhandledException++;
} catch (Throwable e) {
numberOfUnhandledException++;
context.log(logger, Level.SEVERE, "Unhandled exception, ignoring", e);
@@ -501,7 +503,7 @@ public class NodeAgentImpl implements NodeAgent {
Duration timeLeft = Duration.between(clock.instant(), firstSuccessfulHealthCheckInstant.get().plus(warmUpDuration(context)));
if (!container.get().resources().equalsCpu(getContainerResources(context)))
- throw new ConvergenceException("Refusing to resume until warm up period ends (" +
+ throw ConvergenceException.ofTransient("Refusing to resume until warm up period ends (" +
(timeLeft.isNegative() ? "next tick" : "in " + timeLeft) + ")");
}
serviceDumper.processServiceDumpRequest(context);
@@ -536,7 +538,7 @@ public class NodeAgentImpl implements NodeAgent {
nodeRepository.setNodeState(context.hostname().value(), NodeState.ready);
break;
default:
- throw new ConvergenceException("UNKNOWN STATE " + node.state().name());
+ throw ConvergenceException.ofError("UNKNOWN STATE " + node.state().name());
}
}
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddresses.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddresses.java
index fc181eb3107..148d80c9803 100644
--- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddresses.java
+++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddresses.java
@@ -67,12 +67,21 @@ public interface IPAddresses {
if (ipv6addresses.size() <= 1) return ipv6addresses.stream().findFirst();
String addresses = ipv6addresses.stream().map(InetAddresses::toAddrString).collect(Collectors.joining(","));
- throw new ConvergenceException(
+ throw ConvergenceException.ofError(
String.format(
"Multiple IPv6 addresses found: %s. Perhaps a missing DNS entry or multiple AAAA records in DNS?",
addresses));
}
+ /** Returns the hostname of given inetAddress */
+ default String getHostname(InetAddress inetAddress) {
+ String hostname = inetAddress.getHostName();
+ if (hostname.equals(inetAddress.getHostAddress())) {
+ throw new IllegalArgumentException("Could not find hostname for address " + inetAddress.getHostAddress());
+ }
+ return hostname;
+ }
+
/**
* Get the IPv4 address for the host if any.
*
@@ -94,7 +103,7 @@ public interface IPAddresses {
if (siteLocalIPv4Addresses.size() == 1) return Optional.of(siteLocalIPv4Addresses.get(0));
String addresses = ipv4Addresses.stream().map(InetAddresses::toAddrString).collect(Collectors.joining(","));
- throw new ConvergenceException(
+ throw ConvergenceException.ofError(
String.format(
"Multiple IPv4 addresses found: %s. Perhaps a missing DNS entry or multiple A records in DNS?",
addresses));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
index 866b7d2877a..9014875d780 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
@@ -9,8 +9,8 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicStatusLine;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -21,10 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -55,7 +52,7 @@ public class ConfigServerApiImplTest {
private ConfigServerApiImpl configServerApi;
private int mockReturnCode = 200;
- @Before
+ @BeforeEach
public void initExecutor() throws IOException {
CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
@@ -83,24 +80,26 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testBasicParsingSingleServer() {
+ void testBasicParsingSingleServer() {
TestPojo answer = configServerApi.get("/path", TestPojo.class);
assertEquals(answer.foo, "bar");
assertLogStringContainsGETForAHost();
}
- @Test(expected = HttpException.class)
- public void testBasicFailure() {
- // Server is returning 400, no retries.
- mockReturnCode = 400;
-
- TestPojo testPojo = configServerApi.get("/path", TestPojo.class);
- assertEquals(testPojo.errorCode.intValue(), mockReturnCode);
- assertLogStringContainsGETForAHost();
+ @Test
+ void testBasicFailure() {
+ assertThrows(HttpException.class, () -> {
+ // Server is returning 400, no retries.
+ mockReturnCode = 400;
+
+ TestPojo testPojo = configServerApi.get("/path", TestPojo.class);
+ assertEquals(testPojo.errorCode.intValue(), mockReturnCode);
+ assertLogStringContainsGETForAHost();
+ });
}
@Test
- public void testBasicSuccessWithNoRetries() {
+ void testBasicSuccessWithNoRetries() {
// Server is returning 201, no retries.
mockReturnCode = 201;
@@ -110,7 +109,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testBasicSuccessWithCustomTimeouts() {
+ void testBasicSuccessWithCustomTimeouts() {
mockReturnCode = TIMEOUT_RETURN_CODE;
var params = new ConfigServerApi.Params<TestPojo>();
@@ -126,7 +125,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testRetries() {
+ void testRetries() {
// Client is throwing exception, should be retries.
mockReturnCode = FAIL_RETURN_CODE;
try {
@@ -141,7 +140,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testNoRetriesOnBadHttpResponseCode() {
+ void testNoRetriesOnBadHttpResponseCode() {
// Client is throwing exception, should be retries.
mockReturnCode = 503;
try {
@@ -155,7 +154,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testForbidden() {
+ void testForbidden() {
mockReturnCode = 403;
try {
configServerApi.get("/path", TestPojo.class);
@@ -167,7 +166,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testNotFound() {
+ void testNotFound() {
// Server is returning 404, special exception is thrown.
mockReturnCode = 404;
try {
@@ -180,7 +179,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testConflict() {
+ void testConflict() {
// Server is returning 409, no exception is thrown.
mockReturnCode = 409;
configServerApi.get("/path", TestPojo.class);
@@ -189,7 +188,7 @@ public class ConfigServerApiImplTest {
private void assertLogStringContainsGETForAHost() {
String logString = mockLog.toString();
- assertTrue("log does not contain expected entries:" + logString,
- (logString.equals("GET http://host1:666/path ") || logString.equals("GET http://host2:666/path ")));
+ assertTrue((logString.equals("GET http://host1:666/path ") || logString.equals("GET http://host2:666/path ")),
+ "log does not contain expected entries:" + logString);
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
index 8c914530122..74bb644ea9d 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
@@ -6,13 +6,13 @@ import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.wire.WireFlagData;
import com.yahoo.vespa.flags.json.wire.WireFlagDataList;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -26,7 +26,7 @@ public class RealFlagRepositoryTest {
private final RealFlagRepository repository = new RealFlagRepository(configServerApi);
@Test
- public void test() {
+ void test() {
WireFlagDataList list = new WireFlagDataList();
list.flags = new ArrayList<>();
list.flags.add(new WireFlagData());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
index 87f3d71ec7a..78971dc30c7 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
*
@@ -27,7 +27,7 @@ public class AclTest {
Set.of());
@Test
- public void no_trusted_ports() {
+ void no_trusted_ports() {
String listRulesIpv4 = String.join("\n", aclWithoutPorts.toRules(IPVersion.IPv4));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -42,7 +42,7 @@ public class AclTest {
}
@Test
- public void ipv4_rules() {
+ void ipv4_rules() {
String listRulesIpv4 = String.join("\n", aclCommon.toRules(IPVersion.IPv4));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -58,7 +58,7 @@ public class AclTest {
}
@Test
- public void ipv6_rules() {
+ void ipv6_rules() {
String listRulesIpv6 = String.join("\n", aclCommon.toRules(IPVersion.IPv6));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -75,43 +75,43 @@ public class AclTest {
}
@Test
- public void ipv6_rules_stable_order() {
+ void ipv6_rules_stable_order() {
Acl aclCommonDifferentOrder = new Acl(
Set.of(453, 1234),
testNodes("fe80::2", "192.1.2.2", "fb00::1", "fe80::3"),
Set.of());
- for (IPVersion ipVersion: IPVersion.values()) {
+ for (IPVersion ipVersion : IPVersion.values()) {
assertEquals(aclCommon.toRules(ipVersion), aclCommonDifferentOrder.toRules(ipVersion));
}
}
@Test
- public void trusted_networks() {
+ void trusted_networks() {
Acl acl = new Acl(Set.of(4080), testNodes("127.0.0.1"), Set.of("10.0.0.0/24", "2001:db8::/32"));
assertEquals("-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
- "-A INPUT -s 127.0.0.1/32 -j ACCEPT\n" +
- "-A INPUT -s 10.0.0.0/24 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable",
- String.join("\n", acl.toRules(IPVersion.IPv4)));
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
+ "-A INPUT -s 127.0.0.1/32 -j ACCEPT\n" +
+ "-A INPUT -s 10.0.0.0/24 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable",
+ String.join("\n", acl.toRules(IPVersion.IPv4)));
assertEquals("-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
- "-A INPUT -s 2001:db8::/32 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable",
- String.join("\n", acl.toRules(IPVersion.IPv6)));
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
+ "-A INPUT -s 2001:db8::/32 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable",
+ String.join("\n", acl.toRules(IPVersion.IPv6)));
}
private static Set<Acl.Node> testNodes(String... address) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
index e1cd7b45b86..ad909bd2583 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository;
import com.yahoo.vespa.hosted.provision.Node;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class NodeStateTest {
@Test
- public void is_equal_to_node_repository_states() {
+ void is_equal_to_node_repository_states() {
Set<String> nodeRepositoryStates = Stream.of(Node.State.values()).map(Enum::name).collect(Collectors.toSet());
Set<String> nodeAdminStates = Stream.of(NodeState.values()).map(Enum::name).collect(Collectors.toSet());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
index 98a85085b4a..1ad8a4326e7 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
@@ -11,9 +11,9 @@ import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApiImpl;
import com.yahoo.vespa.hosted.provision.restapi.NodesV2ApiHandler;
import com.yahoo.vespa.hosted.provision.testutils.ContainerConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
@@ -23,10 +23,7 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the NodeRepository class used for talking to the node repository. It uses a mock from the node repository
@@ -54,7 +51,7 @@ public class RealNodeRepositoryTest {
* {@link NodesV2ApiHandler}
* These classes define some test data that is used in these tests.
*/
- @Before
+ @BeforeEach
public void startContainer() throws Exception {
Exception lastException = null;
@@ -89,7 +86,7 @@ public class RealNodeRepositoryTest {
throw new RuntimeException("Could not get answer from container.");
}
- @After
+ @AfterEach
public void stopContainer() {
if (container != null) {
container.close();
@@ -97,7 +94,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainersToRunApi() {
+ void testGetContainersToRunApi() {
String dockerHostHostname = "dockerhost1.yahoo.com";
List<NodeSpec> containersToRun = nodeRepositoryApi.getNodes(dockerHostHostname);
@@ -114,7 +111,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainer() {
+ void testGetContainer() {
String hostname = "host4.yahoo.com";
Optional<NodeSpec> node = nodeRepositoryApi.getOptionalNode(hostname);
assertTrue(node.isPresent());
@@ -122,14 +119,14 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainerForNonExistingNode() {
+ void testGetContainerForNonExistingNode() {
String hostname = "host-that-does-not-exist";
Optional<NodeSpec> node = nodeRepositoryApi.getOptionalNode(hostname);
assertFalse(node.isPresent());
}
@Test
- public void testUpdateNodeAttributes() {
+ void testUpdateNodeAttributes() {
String hostname = "host4.yahoo.com";
nodeRepositoryApi.updateNodeAttributes(
hostname,
@@ -139,7 +136,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testMarkAsReady() {
+ void testMarkAsReady() {
nodeRepositoryApi.setNodeState("host5.yahoo.com", NodeState.dirty);
nodeRepositoryApi.setNodeState("host5.yahoo.com", NodeState.ready);
@@ -159,13 +156,13 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testAddNodes() {
+ void testAddNodes() {
AddNode host = AddNode.forHost("host123.domain.tld",
- "id1",
- "default",
- Optional.of(FlavorOverrides.ofDisk(123)),
- NodeType.confighost,
- Set.of("::1"), Set.of("::2", "::3"));
+ "id1",
+ "default",
+ Optional.of(FlavorOverrides.ofDisk(123)),
+ NodeType.confighost,
+ Set.of("::1"), Set.of("::2", "::3"));
NodeResources nodeResources = new NodeResources(1, 2, 3, 4, NodeResources.DiskSpeed.slow, NodeResources.StorageType.local);
AddNode node = AddNode.forNode("host123-1.domain.tld", "id1", "host123.domain.tld", nodeResources, NodeType.config, Set.of("::2", "::3"));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
index 055bdb5c1f5..92d0cfc8483 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
@@ -9,12 +9,12 @@ import com.yahoo.test.json.JsonTestHelper;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeAttributes;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.RealNodeRepository;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -31,7 +31,7 @@ public class NodeRepositoryNodeTest {
* NodeAttributes -> NodeRepositoryNode -> JSON.
*/
@Test
- public void testReportsSerialization() {
+ void testReportsSerialization() {
// Make sure we don't accidentally patch with "reports": null, as that actually means removing all reports.
assertEquals(JsonInclude.Include.NON_NULL, NodeRepositoryNode.class.getAnnotation(JsonInclude.class).value());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
index 72a42911426..6d51c6fb53c 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
@@ -2,13 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports;
import com.yahoo.test.json.JsonTestHelper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport.Type.SOFT_FAIL;
import static com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport.Type.UNSPECIFIED;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -18,7 +16,7 @@ public class BaseReportTest {
private static final String JSON_2 = "{\"createdMillis\": 1, \"description\": \"desc\", \"type\": \"SOFT_FAIL\"}";
@Test
- public void testSerialization1() {
+ void testSerialization1() {
JsonTestHelper.assertJsonEquals(new BaseReport(1L, "desc", SOFT_FAIL).toJsonNode(),
JSON_2);
JsonTestHelper.assertJsonEquals(new BaseReport(null, "desc", SOFT_FAIL).toJsonNode(),
@@ -39,7 +37,7 @@ public class BaseReportTest {
}
@Test
- public void testShouldUpdate() {
+ void testShouldUpdate() {
BaseReport report = new BaseReport(1L, "desc", SOFT_FAIL);
assertFalse(report.updates(report));
@@ -58,7 +56,7 @@ public class BaseReportTest {
}
@Test
- public void testJsonSerialization() {
+ void testJsonSerialization() {
BaseReport report = BaseReport.fromJson(JSON_2);
assertEquals(1L, (long) report.getCreatedMillisOrNull());
assertEquals("desc", report.getDescriptionOrNull());
@@ -67,9 +65,9 @@ public class BaseReportTest {
}
@Test
- public void testUnspecifiedType() {
+ void testUnspecifiedType() {
BaseReport report = new BaseReport(1L, "desc", null);
- assertEquals(null, report.getTypeOrNull());
+ assertNull(report.getTypeOrNull());
assertEquals(UNSPECIFIED, report.getType());
}
} \ No newline at end of file
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
index 7f2c584303b..2bc6561dbf9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
@@ -6,11 +6,12 @@ import com.yahoo.vespa.hosted.node.admin.configserver.HttpException;
import com.yahoo.vespa.orchestrator.restapi.wire.BatchOperationResult;
import com.yahoo.vespa.orchestrator.restapi.wire.HostStateChangeDenialReason;
import com.yahoo.vespa.orchestrator.restapi.wire.UpdateHostResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
@@ -27,9 +28,9 @@ public class OrchestratorImplTest {
private final OrchestratorImpl orchestrator = new OrchestratorImpl(configServerApi);
@Test
- public void testSuspendCall() {
+ void testSuspendCall() {
when(configServerApi.put(
- eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended"),
+ eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended"),
eq(Optional.empty()),
eq(UpdateHostResponse.class),
any()
@@ -38,75 +39,87 @@ public class OrchestratorImplTest {
orchestrator.suspend(hostName);
}
- @Test(expected=OrchestratorException.class)
- public void testSuspendCallWithFailureReason() {
- when(configServerApi.put(
- eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended"),
- eq(Optional.empty()),
- eq(UpdateHostResponse.class),
- any()
- )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
-
- orchestrator.suspend(hostName);
+ @Test
+ void testSuspendCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ when(configServerApi.put(
+ eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended"),
+ eq(Optional.empty()),
+ eq(UpdateHostResponse.class),
+ any()
+ )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
+
+ orchestrator.suspend(hostName);
+ });
}
- @Test(expected=OrchestratorNotFoundException.class)
- public void testSuspendCallWithNotFound() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new HttpException.NotFoundException("Not Found"));
+ @Test
+ void testSuspendCallWithNotFound() {
+ assertThrows(OrchestratorNotFoundException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new HttpException.NotFoundException("Not Found"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testSuspendCallWithSomeOtherException() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new RuntimeException("Some parameter was wrong"));
+ @Test
+ void testSuspendCallWithSomeOtherException() {
+ assertThrows(RuntimeException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new RuntimeException("Some parameter was wrong"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
@Test
- public void testResumeCall() {
+ void testResumeCall() {
when(configServerApi.delete(
- OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended",
+ OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended",
UpdateHostResponse.class
)).thenReturn(new UpdateHostResponse(hostName, null));
orchestrator.resume(hostName);
}
- @Test(expected=OrchestratorException.class)
- public void testResumeCallWithFailureReason() {
- when(configServerApi.delete(
- OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended",
- UpdateHostResponse.class
- )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
-
- orchestrator.resume(hostName);
+ @Test
+ void testResumeCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ when(configServerApi.delete(
+ OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended",
+ UpdateHostResponse.class
+ )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
+
+ orchestrator.resume(hostName);
+ });
}
- @Test(expected=OrchestratorNotFoundException.class)
- public void testResumeCallWithNotFound() {
- when(configServerApi.delete(
- any(String.class),
- any()
- )).thenThrow(new HttpException.NotFoundException("Not Found"));
-
- orchestrator.resume(hostName);
+ @Test
+ void testResumeCallWithNotFound() {
+ assertThrows(OrchestratorNotFoundException.class, () -> {
+ when(configServerApi.delete(
+ any(String.class),
+ any()
+ )).thenThrow(new HttpException.NotFoundException("Not Found"));
+
+ orchestrator.resume(hostName);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testResumeCallWithSomeOtherException() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new RuntimeException("Some parameter was wrong"));
+ @Test
+ void testResumeCallWithSomeOtherException() {
+ assertThrows(RuntimeException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new RuntimeException("Some parameter was wrong"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
@Test
- public void testBatchSuspendCall() {
+ void testBatchSuspendCall() {
String parentHostName = "host1.test.yahoo.com";
List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
@@ -120,36 +133,40 @@ public class OrchestratorImplTest {
orchestrator.suspend(parentHostName, hostNames);
}
- @Test(expected=OrchestratorException.class)
- public void testBatchSuspendCallWithFailureReason() {
- String parentHostName = "host1.test.yahoo.com";
- List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
- String failureReason = "Failed to suspend";
-
- when(configServerApi.put(
- eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
- eq(Optional.empty()),
- eq(BatchOperationResult.class),
- any()
- )).thenReturn(new BatchOperationResult(failureReason));
-
- orchestrator.suspend(parentHostName, hostNames);
+ @Test
+ void testBatchSuspendCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ String parentHostName = "host1.test.yahoo.com";
+ List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
+ String failureReason = "Failed to suspend";
+
+ when(configServerApi.put(
+ eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
+ eq(Optional.empty()),
+ eq(BatchOperationResult.class),
+ any()
+ )).thenReturn(new BatchOperationResult(failureReason));
+
+ orchestrator.suspend(parentHostName, hostNames);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testBatchSuspendCallWithSomeException() {
- String parentHostName = "host1.test.yahoo.com";
- List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
- String exceptionMessage = "Exception: Something crashed!";
-
- when(configServerApi.put(
- eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
- eq(Optional.empty()),
- eq(BatchOperationResult.class),
- any()
- )).thenThrow(new RuntimeException(exceptionMessage));
-
- orchestrator.suspend(parentHostName, hostNames);
+ @Test
+ void testBatchSuspendCallWithSomeException() {
+ assertThrows(RuntimeException.class, () -> {
+ String parentHostName = "host1.test.yahoo.com";
+ List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
+ String exceptionMessage = "Exception: Something crashed!";
+
+ when(configServerApi.put(
+ eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
+ eq(Optional.empty()),
+ eq(BatchOperationResult.class),
+ any()
+ )).thenThrow(new RuntimeException(exceptionMessage));
+
+ orchestrator.suspend(parentHostName, hostNames);
+ });
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
index 18feee9cb63..4f213f0acf9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.configserver.state;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.vespa.hosted.node.admin.configserver.state.bindings.HealthResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class HealthResponseTest {
@Test
- public void deserializationOfNormalResponse() throws Exception {
+ void deserializationOfNormalResponse() throws Exception {
String jsonResponse = "{\n" +
" \"metrics\": {\n" +
" \"snapshot\": {\n" +
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
index 3184f36b75e..190e4f772be 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.hosted.node.admin.configserver.state;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
import com.yahoo.vespa.hosted.node.admin.configserver.ConnectionException;
import com.yahoo.vespa.hosted.node.admin.configserver.state.bindings.HealthResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.ConnectException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -18,7 +18,7 @@ public class StateImplTest {
private final StateImpl state = new StateImpl(api);
@Test
- public void testWhenUp() {
+ void testWhenUp() {
HealthResponse response = new HealthResponse();
response.status.code = "up";
when(api.get(any(), any())).thenReturn(response);
@@ -28,7 +28,7 @@ public class StateImplTest {
}
@Test
- public void connectException() {
+ void connectException() {
RuntimeException exception =
ConnectionException.handleException("Error: ", new ConnectException("connection refused"));
when(api.get(any(), any())).thenThrow(exception);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
index bff3fb34663..aec559d7d76 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
@@ -1,45 +1,52 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.container;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author freva
*/
public class ContainerNameTest {
@Test
- public void testAlphanumericalContainerName() {
+ void testAlphanumericalContainerName() {
String name = "container123";
ContainerName containerName = new ContainerName(name);
assertEquals(containerName.asString(), name);
}
@Test
- public void testAlphanumericalWithDashContainerName() {
+ void testAlphanumericalWithDashContainerName() {
String name = "container-123";
ContainerName containerName = new ContainerName(name);
assertEquals(containerName.asString(), name);
}
@Test
- public void testContainerNameFromHostname() {
+ void testContainerNameFromHostname() {
assertEquals(new ContainerName("container-123"), ContainerName.fromHostname("container-123.sub.domain.tld"));
}
- @Test(expected=IllegalArgumentException.class)
- public void testAlphanumericalWithSlashContainerName() {
- new ContainerName("container/123");
+ @Test
+ void testAlphanumericalWithSlashContainerName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ContainerName("container/123");
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void testEmptyContainerName() {
- new ContainerName("");
+ @Test
+ void testEmptyContainerName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ContainerName("");
+ });
}
- @Test(expected=NullPointerException.class)
- public void testNullContainerName() {
- new ContainerName(null);
+ @Test
+ void testNullContainerName() {
+ assertThrows(NullPointerException.class, () -> {
+ new ContainerName(null);
+ });
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
index d0c54dd4e04..9a5ca8c805e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.container;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.time.Instant;
@@ -13,9 +13,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author mpolden
@@ -28,7 +26,7 @@ public class ContainerOperationsTest {
private final ContainerOperations containerOperations = new ContainerOperations(containerEngine, new CGroupV2(fileSystem), fileSystem);
@Test
- public void no_managed_containers_running() {
+ void no_managed_containers_running() {
Container c1 = createContainer("c1", true);
Container c2 = createContainer("c2", false);
@@ -43,7 +41,7 @@ public class ContainerOperationsTest {
}
@Test
- public void retain_managed_containers() {
+ void retain_managed_containers() {
Container c1 = createContainer("c1", true);
Container c2 = createContainer("c2", true);
Container c3 = createContainer("c3", false);
@@ -53,9 +51,9 @@ public class ContainerOperationsTest {
containerOperations.retainManagedContainers(context, Set.of(c1.name()));
assertEquals(List.of(c1.name(), c3.name()), containerEngine.listContainers(context).stream()
- .map(PartialContainer::name)
- .sorted()
- .collect(Collectors.toList()));
+ .map(PartialContainer::name)
+ .sorted()
+ .collect(Collectors.toList()));
}
private Container createContainer(String name, boolean managed) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java
index 12f928f0d44..e7a3b4ec9b1 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.container;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author freva
@@ -12,14 +12,14 @@ import static org.junit.Assert.fail;
public class ContainerResourcesTest {
@Test
- public void verify_unlimited() {
+ void verify_unlimited() {
assertEquals(-1, ContainerResources.UNLIMITED.cpuQuota());
assertEquals(100_000, ContainerResources.UNLIMITED.cpuPeriod());
assertEquals(0, ContainerResources.UNLIMITED.cpuShares());
}
@Test
- public void validate_shares() {
+ void validate_shares() {
new ContainerResources(0, 0, 0);
new ContainerResources(0, 2, 0);
new ContainerResources(0, 2048, 0);
@@ -31,7 +31,7 @@ public class ContainerResourcesTest {
}
@Test
- public void cpu_shares_scaling() {
+ void cpu_shares_scaling() {
ContainerResources resources = ContainerResources.from(5.3, 2.5, 0);
assertEquals(530_000, resources.cpuQuota());
assertEquals(100_000, resources.cpuPeriod());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
index 7df5309961f..79c7558ea9e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.container;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -16,8 +16,8 @@ import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TH
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TOTAL_PERIODS;
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TOTAL_USAGE_USEC;
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.USER_USAGE_USEC;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -31,11 +31,11 @@ public class ContainerStatsCollectorTest {
private final CGroup cgroup = mock(CGroup.class);
@Test
- public void collect() throws IOException {
+ void collect() throws IOException {
ContainerStatsCollector collector = new ContainerStatsCollector(cgroup, fileSystem, 24);
ContainerId containerId = new ContainerId("id1");
int containerPid = 42;
- assertTrue("No stats found", collector.collect(containerId, containerPid, "eth0").isEmpty());
+ assertTrue(collector.collect(containerId, containerPid, "eth0").isEmpty(), "No stats found");
mockMemoryStats(containerId);
mockCpuStats(containerId);
@@ -44,13 +44,13 @@ public class ContainerStatsCollectorTest {
Optional<ContainerStats> stats = collector.collect(containerId, containerPid, "eth0");
assertTrue(stats.isPresent());
assertEquals(new ContainerStats.CpuStats(24, 6049374780000L, 691675615472L,
- 262190000000L, 3L, 1L, 2L),
- stats.get().getCpuStats());
+ 262190000000L, 3L, 1L, 2L),
+ stats.get().getCpuStats());
assertEquals(new ContainerStats.MemoryStats(470790144L, 1228017664L, 2147483648L),
- stats.get().getMemoryStats());
+ stats.get().getMemoryStats());
assertEquals(Map.of("eth0", new ContainerStats.NetworkStats(22280813L, 4L, 3L,
- 19859383L, 6L, 5L)),
- stats.get().getNetworks());
+ 19859383L, 6L, 5L)),
+ stats.get().getNetworks());
}
private void mockNetworkStats(int pid) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
index 7db8cb79949..9fd14e7e665 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
@@ -6,29 +6,31 @@ import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.container.ContainerEngineMock;
import com.yahoo.vespa.hosted.node.admin.container.RegistryCredentials;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
*/
public class ContainerImageDownloaderTest {
- @Test(timeout = 5_000)
- public void test_download() {
+ @Test
+ @Timeout(5_000)
+ void test_download() {
ContainerEngineMock podman = new ContainerEngineMock().asyncImageDownload(true);
ContainerImageDownloader downloader = new ContainerImageDownloader(podman);
TaskContext context = new TestTaskContext();
DockerImage image = DockerImage.fromString("registry.example.com/repo/vespa:7.42");
- assertFalse("Download started", downloader.get(context, image, RegistryCredentials.none));
- assertFalse("Download pending", downloader.get(context, image, RegistryCredentials.none));
+ assertFalse(downloader.get(context, image, RegistryCredentials.none), "Download started");
+ assertFalse(downloader.get(context, image, RegistryCredentials.none), "Download pending");
podman.completeDownloadOf(image);
boolean downloadCompleted;
- while (!(downloadCompleted = downloader.get(context, image, RegistryCredentials.none)));
- assertTrue("Download completed", downloadCompleted);
+ while (!(downloadCompleted = downloader.get(context, image, RegistryCredentials.none))) ;
+ assertTrue(downloadCompleted, "Download completed");
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
index a7307b5d1de..2ef6780dff6 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.node.admin.container.ContainerEngineMock;
import com.yahoo.vespa.hosted.node.admin.container.ContainerId;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.container.ContainerResources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -18,7 +18,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -29,90 +29,90 @@ public class ContainerImagePrunerTest {
private final Tester tester = new Tester();
@Test
- public void noImagesMeansNoUnusedImages() {
+ void noImagesMeansNoUnusedImages() {
tester.withExistingImages()
- .expectDeletedImages();
+ .expectDeletedImages();
}
@Test
- public void singleImageWithoutContainersIsUnused() {
+ void singleImageWithoutContainersIsUnused() {
tester.withExistingImages(image("image-1"))
- // Even though nothing is using the image, we will keep it for at least 1h
- .expectDeletedImagesAfterMinutes(0)
- .expectDeletedImagesAfterMinutes(30)
- .expectDeletedImagesAfterMinutes(30, "image-1");
+ // Even though nothing is using the image, we will keep it for at least 1h
+ .expectDeletedImagesAfterMinutes(0)
+ .expectDeletedImagesAfterMinutes(30)
+ .expectDeletedImagesAfterMinutes(30, "image-1");
}
@Test
- public void singleImageWithContainerIsUsed() {
+ void singleImageWithContainerIsUsed() {
tester.withExistingImages(image("image-1"))
- .withExistingContainers(container("container-1", "image-1"))
- .expectDeletedImages();
+ .withExistingContainers(container("container-1", "image-1"))
+ .expectDeletedImages();
}
@Test
- public void multipleUnusedImagesAreIdentified() {
+ void multipleUnusedImagesAreIdentified() {
tester.withExistingImages(image("image-1"), image("image-2"))
- .expectDeletedImages("image-1", "image-2");
+ .expectDeletedImages("image-1", "image-2");
}
@Test
- public void unusedImagesWithMultipleTags() {
+ void unusedImagesWithMultipleTags() {
tester.withExistingImages(image("image-1", "vespa-6", "vespa-6.28", "vespa:latest"))
- .expectDeletedImages("vespa-6", "vespa-6.28", "vespa:latest");
+ .expectDeletedImages("vespa-6", "vespa-6.28", "vespa:latest");
}
@Test
- public void unusedImagesWithMultipleUntagged() {
+ void unusedImagesWithMultipleUntagged() {
tester.withExistingImages(image("image1", "<none>:<none>"),
- image("image2", "<none>:<none>"))
- .expectDeletedImages("image1", "image2");
+ image("image2", "<none>:<none>"))
+ .expectDeletedImages("image1", "image2");
}
@Test
- public void taggedImageWithNoContainersIsUnused() {
+ void taggedImageWithNoContainersIsUnused() {
tester.withExistingImages(image("image-1", "vespa-6"))
- .expectDeletedImages("vespa-6");
+ .expectDeletedImages("vespa-6");
}
@Test
- public void reDownloadingImageIsNotImmediatelyDeleted() {
+ void reDownloadingImageIsNotImmediatelyDeleted() {
tester.withExistingImages(image("image"))
- .expectDeletedImages("image") // After 1h we delete image
- .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
- .expectDeletedImagesAfterMinutes(10)
- .expectDeletedImages("image"); // 1h after re-download it is deleted again
+ .expectDeletedImages("image") // After 1h we delete image
+ .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
+ .expectDeletedImagesAfterMinutes(10)
+ .expectDeletedImages("image"); // 1h after re-download it is deleted again
}
@Test
- public void reDownloadingImageIsNotImmediatelyDeletedWhenDeletingByTag() {
+ void reDownloadingImageIsNotImmediatelyDeletedWhenDeletingByTag() {
tester.withExistingImages(image("image", "my-tag"))
- .expectDeletedImages("my-tag") // After 1h we delete image
- .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
- .expectDeletedImagesAfterMinutes(10)
- .expectDeletedImages("my-tag"); // 1h after re-download it is deleted again
+ .expectDeletedImages("my-tag") // After 1h we delete image
+ .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
+ .expectDeletedImagesAfterMinutes(10)
+ .expectDeletedImages("my-tag"); // 1h after re-download it is deleted again
}
/** Same scenario as in {@link #multipleUnusedImagesAreIdentified()} */
@Test
- public void doesNotDeleteExcludedByIdImages() {
+ void doesNotDeleteExcludedByIdImages() {
tester.withExistingImages(image("image-1"), image("image-2"))
- // Normally, image-1 should also be deleted, but because we exclude image-1 only image-2 is deleted
- .expectDeletedImages(List.of("image-1"), "image-2");
+ // Normally, image-1 should also be deleted, but because we exclude image-1 only image-2 is deleted
+ .expectDeletedImages(List.of("image-1"), "image-2");
}
/** Same as in {@link #doesNotDeleteExcludedByIdImages()} but with tags */
@Test
- public void doesNotDeleteExcludedByTagImages() {
+ void doesNotDeleteExcludedByTagImages() {
tester.withExistingImages(image("image-1", "vespa:6.288.16"), image("image-2", "vespa:6.289.94"))
- .expectDeletedImages(List.of("vespa:6.288.16"), "vespa:6.289.94");
+ .expectDeletedImages(List.of("vespa:6.288.16"), "vespa:6.289.94");
}
@Test
- public void excludingNotDownloadedImageIsNoop() {
+ void excludingNotDownloadedImageIsNoop() {
tester.withExistingImages(image("image-1", "vespa:6.288.16"),
- image("image-2", "vespa:6.289.94"))
- .expectDeletedImages(List.of("vespa:6.300.1"), "vespa:6.288.16", "vespa:6.289.94", "rhel-6");
+ image("image-2", "vespa:6.289.94"))
+ .expectDeletedImages(List.of("vespa:6.300.1"), "vespa:6.288.16", "vespa:6.289.94", "rhel-6");
}
private static Image image(String id, String... tags) {
@@ -174,8 +174,8 @@ public class ContainerImagePrunerTest {
int newValue = removalCountByImageId.getOrDefault(imageId, 0) + 1;
removalCountByImageId.put(imageId, newValue);
- assertTrue("Image " + imageId + " removed",
- containerEngine.listImages(context).stream().noneMatch(image -> image.id().equals(imageId)));
+ assertTrue(containerEngine.listImages(context).stream().noneMatch(image -> image.id().equals(imageId)),
+ "Image " + imageId + " removed");
});
return this;
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java
index c7f7058d4f5..3de3c1a3d32 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.container.metrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics.APPLICATION_HOST;
import static com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics.DimensionType.DEFAULT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -18,38 +18,38 @@ public class MetricsTest {
private final Metrics metrics = new Metrics();
@Test
- public void testDefaultValue() {
+ void testDefaultValue() {
metrics.declareCounter("some.name", hostDimension);
assertEquals(getMetricsForDimension(hostDimension).get("some.name"), 0L);
}
@Test
- public void testSimpleIncrementMetric() {
+ void testSimpleIncrementMetric() {
Counter counter = metrics.declareCounter("a_counter.value", hostDimension);
counter.add(5);
counter.add(8);
Map<String, Number> latestMetrics = getMetricsForDimension(hostDimension);
- assertEquals("Expected only 1 metric value to be set", 1, latestMetrics.size());
+ assertEquals(1, latestMetrics.size(), "Expected only 1 metric value to be set");
assertEquals(latestMetrics.get("a_counter.value"), 13L); // 5 + 8
}
@Test
- public void testSimpleGauge() {
+ void testSimpleGauge() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
gauge.sample(-342.23);
Map<String, Number> latestMetrics = getMetricsForDimension(hostDimension);
- assertEquals("Expected only 1 metric value to be set", 1, latestMetrics.size());
+ assertEquals(1, latestMetrics.size(), "Expected only 1 metric value to be set");
assertEquals(latestMetrics.get("test.gauge"), -342.23);
}
@Test
- public void testRedeclaringSameGauge() {
+ void testRedeclaringSameGauge() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
@@ -62,7 +62,7 @@ public class MetricsTest {
}
@Test
- public void testSameMetricNameButDifferentDimensions() {
+ void testSameMetricNameButDifferentDimensions() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
@@ -76,7 +76,7 @@ public class MetricsTest {
}
@Test
- public void testDeletingMetric() {
+ void testDeletingMetric() {
metrics.declareGauge("test.gauge", hostDimension);
Dimensions differentDimension = new Dimensions.Builder().add("host", "abcd.yahoo.com").build();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
index c22f2b0ab50..0edc03cc33e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -22,7 +22,7 @@ import static org.mockito.Mockito.verify;
public class ContainerFailTest {
@Test
- public void test() {
+ void test() {
DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image");
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
ContainerName containerName = new ContainerName("host1");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerTester.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerTester.java
index a2312a23925..1773eb4be25 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerTester.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerTester.java
@@ -17,6 +17,8 @@ import com.yahoo.vespa.hosted.node.admin.maintenance.StorageMaintainer;
import com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.VespaServiceDumper;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater;
+import com.yahoo.vespa.hosted.node.admin.nodeadmin.ProcMeminfo;
+import com.yahoo.vespa.hosted.node.admin.nodeadmin.ProcMeminfoReader;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextFactory;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
@@ -36,7 +38,6 @@ import java.util.Optional;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import static org.mockito.ArgumentMatchers.any;
@@ -87,6 +88,8 @@ public class ContainerTester implements AutoCloseable {
Clock clock = Clock.systemUTC();
Metrics metrics = new Metrics();
FileSystem fileSystem = TestFileSystem.create();
+ ProcMeminfoReader procMeminfoReader = mock(ProcMeminfoReader.class);
+ when(procMeminfoReader.read()).thenReturn(new ProcMeminfo(1, 2));
NodeAgentFactory nodeAgentFactory = (contextSupplier, nodeContext) ->
new NodeAgentImpl(contextSupplier, nodeRepository, orchestrator, containerOperations, () -> RegistryCredentials.none,
@@ -106,7 +109,7 @@ public class ContainerTester implements AutoCloseable {
phaser.arriveAndDeregister();
}
};
- nodeAdmin = new NodeAdminImpl(nodeAgentFactory, metrics, clock, Duration.ofMillis(10), Duration.ZERO);
+ nodeAdmin = new NodeAdminImpl(nodeAgentFactory, metrics, clock, Duration.ofMillis(10), Duration.ZERO, procMeminfoReader);
NodeAgentContextFactory nodeAgentContextFactory = (nodeSpec, acl) ->
NodeAgentContextImpl.builder(nodeSpec).acl(acl).fileSystem(fileSystem).build();
nodeAdminStateUpdater = new NodeAdminStateUpdater(nodeAgentContextFactory, nodeRepository, orchestrator,
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
index eab320733ee..8a5c4faeddc 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeState;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -20,7 +20,7 @@ import static org.mockito.ArgumentMatchers.eq;
public class MultiContainerTest {
@Test
- public void test() {
+ void test() {
DockerImage image1 = DockerImage.fromString("registry.example.com/repo/image1");
DockerImage image2 = DockerImage.fromString("registry.example.com/repo/image2");
try (ContainerTester tester = new ContainerTester(List.of(image1, image2))) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
index 8498fa57084..0a405cd38b2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
@@ -5,13 +5,13 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.vespa.hosted.node.admin.integration.ContainerTester.HOST_HOSTNAME;
import static com.yahoo.vespa.hosted.node.admin.integration.ContainerTester.containerMatcher;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -26,7 +26,7 @@ public class RebootTest {
private final DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image");
@Test
- public void test() {
+ void test() {
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
tester.addChildNodeRepositoryNode(NodeSpec.Builder.testSpec(hostname).wantedDockerImage(dockerImage).build());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
index 9a481959c63..62bde5ff1a8 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeAttributes;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -21,7 +21,7 @@ import static org.mockito.ArgumentMatchers.eq;
public class RestartTest {
@Test
- public void test() {
+ void test() {
DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image:1.2.3");
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
String hostname = "host1.test.yahoo.com";
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
index 42661bdfdd0..d98ca5d84f2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
@@ -14,8 +14,8 @@ import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -29,7 +29,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -51,7 +51,7 @@ public class StorageMaintainerTest {
fileSystem.getPath("/data/vespa/storage/container-archive"));
@Test
- public void testDiskUsed() {
+ void testDiskUsed() {
NodeAgentContext context = NodeAgentContextImpl.builder("host-1.domain.tld").fileSystem(fileSystem).build();
terminal.expectCommand("du -xsk /data/vespa/storage/host-1 2>&1", 0, "321\t/data/vespa/storage/host-1/");
@@ -62,13 +62,13 @@ public class StorageMaintainerTest {
}
@Test
- public void testNonExistingDiskUsed() {
+ void testNonExistingDiskUsed() {
DiskSize size = storageMaintainer.getDiskUsed(null, Paths.get("/fake/path"));
assertEquals(DiskSize.ZERO, size);
}
@Test
- public void archive_container_data_test() throws IOException {
+ void archive_container_data_test() throws IOException {
// Create some files in containers
NodeAgentContext context1 = createNodeAgentContextAndContainerStorage(fileSystem, "container-1");
createNodeAgentContextAndContainerStorage(fileSystem, "container-2");
@@ -141,7 +141,7 @@ public class StorageMaintainerTest {
}
@Test
- public void not_run_if_not_enough_used() throws IOException {
+ void not_run_if_not_enough_used() throws IOException {
NodeAgentContext context = NodeAgentContextImpl.builder(
NodeSpec.Builder.testSpec("h123a.domain.tld").realResources(new NodeResources(1, 1, 1, 1)).build())
.fileSystem(fileSystem).build();
@@ -152,7 +152,7 @@ public class StorageMaintainerTest {
}
@Test
- public void deletes_correct_amount() throws IOException {
+ void deletes_correct_amount() throws IOException {
NodeAgentContext context = NodeAgentContextImpl.builder(
NodeSpec.Builder.testSpec("h123a.domain.tld").realResources(new NodeResources(1, 1, 1, 1)).build())
.fileSystem(fileSystem).build();
@@ -164,7 +164,7 @@ public class StorageMaintainerTest {
verify(diskCleanup).cleanup(eq(context), any(), eq(272_800_000L));
}
- @After
+ @AfterEach
public void after() {
terminal.verifyAllCommandsExecuted();
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
index 80fde82a89f..6b2ac98ad0b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
@@ -10,15 +10,15 @@ import com.yahoo.vespa.hosted.node.admin.task.util.network.IPAddressesMock;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
@@ -45,7 +45,7 @@ public class AclMaintainerTest {
private final List<String> writtenFileContents = new ArrayList<>();
@Test
- public void configures_full_container_acl_from_empty() {
+ void configures_full_container_acl_from_empty() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443)
.withTrustedNode("hostname1", "3001::abcd")
.withTrustedNode("hostname2", "3001::1234")
@@ -71,54 +71,54 @@ public class AclMaintainerTest {
List<String> expected = List.of(
// IPv4 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 172.16.5.234/32 -j ACCEPT\n" +
- "-A INPUT -s 192.168.0.5/32 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 172.16.5.234/32 -j ACCEPT\n" +
+ "-A INPUT -s 192.168.0.5/32 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n",
// IPv6 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::1234/128 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::1234/128 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
+ "COMMIT\n",
// IPv4 nat table restore
"*nat\n" +
- "-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 10.0.0.1/32 -j REDIRECT\n" +
- "COMMIT\n",
+ "-P PREROUTING ACCEPT\n" +
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 10.0.0.1/32 -j REDIRECT\n" +
+ "COMMIT\n",
// IPv6 nat table restore
"*nat\n" +
- "-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n" +
- "COMMIT\n");
+ "-P PREROUTING ACCEPT\n" +
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void configures_minimal_container_acl_from_empty() {
+ void configures_minimal_container_acl_from_empty() {
// The ACL spec is empty and our this node's addresses do not resolve
Acl acl = new Acl.Builder().withTrustedPorts().build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -138,30 +138,30 @@ public class AclMaintainerTest {
List<String> expected = List.of(
// IPv4 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n",
// IPv6 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
- "COMMIT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void only_configure_iptables_for_ipversion_that_differs() {
+ void only_configure_iptables_for_ipversion_that_differs() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443).withTrustedNode("hostname1", "3001::abcd").build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -170,20 +170,20 @@ public class AclMaintainerTest {
whenListRules(context, "filter", IPVersion.IPv4, EMPTY_FILTER_TABLE);
whenListRules(context, "filter", IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
whenListRules(context, "nat", IPVersion.IPv6,
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
aclMaintainer.converge(context);
@@ -194,20 +194,20 @@ public class AclMaintainerTest {
List<String> expected = List.of(
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void rollback_is_attempted_when_applying_acl_fail() {
+ void rollback_is_attempted_when_applying_acl_fail() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443).withTrustedNode("hostname1", "3001::abcd").build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -216,20 +216,20 @@ public class AclMaintainerTest {
whenListRules(context, "filter", IPVersion.IPv4, EMPTY_FILTER_TABLE);
whenListRules(context, "filter", IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
whenListRules(context, "nat", IPVersion.IPv6,
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
when(containerOperations.executeCommandInNetworkNamespace(eq(context), eq("iptables-restore"), any()))
.thenThrow(new RuntimeException("iptables restore failed"));
@@ -244,7 +244,7 @@ public class AclMaintainerTest {
aclMaintainer.converge(context);
}
- @Before
+ @BeforeEach
public void setup() {
doAnswer(invoc -> {
String path = invoc.getArgument(2);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
index 6aa3a0420ff..6cd4038975b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
@@ -4,12 +4,12 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.acl;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Acl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.Editor;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -17,44 +17,44 @@ import static org.junit.Assert.assertEquals;
public class FilterTableLineEditorTest {
@Test
- public void filter_set_wanted_rules() {
+ void filter_set_wanted_rules() {
Acl acl = new Acl.Builder().withTrustedPorts(22).withTrustedNode("hostname", "3001::1").build();
assertFilterTableLineEditorResult(
acl, IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n",
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n",
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22 -j ACCEPT\n" +
- "-A INPUT -s 3001::1/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22 -j ACCEPT\n" +
+ "-A INPUT -s 3001::1/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable");
}
@Test
- public void produces_minimal_diff_simple() {
+ void produces_minimal_diff_simple() {
assertFilterTableDiff(List.of(2, 5, 3, 6, 1, 4), List.of(2, 5, 6, 1, 4),
"Patching file table:\n" +
- "--A INPUT -s 2001::3/128 -j ACCEPT\n");
+ "--A INPUT -s 2001::3/128 -j ACCEPT\n");
}
@Test
- public void produces_minimal_diff_complex() {
+ void produces_minimal_diff_complex() {
assertFilterTableDiff(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), List.of(5, 11, 6, 3, 10, 4, 8, 12),
"Patching file table:\n" +
- "--A INPUT -s 2001::1/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::2/128 -j ACCEPT\n" +
- "+-A INPUT -s 2001::11/128 -j ACCEPT\n" +
- "+-A INPUT -s 2001::12/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::7/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::9/128 -j ACCEPT\n");
+ "--A INPUT -s 2001::1/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::2/128 -j ACCEPT\n" +
+ "+-A INPUT -s 2001::11/128 -j ACCEPT\n" +
+ "+-A INPUT -s 2001::12/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::7/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::9/128 -j ACCEPT\n");
}
private static void assertFilterTableLineEditorResult(
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
index 015181c7ca4..999b7bda9bb 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.maintenance.acl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.Editor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -14,74 +14,74 @@ import static org.junit.Assert.assertEquals;
public class NatTableLineEditorTest {
@Test
- public void nat_set_redirect_rule_without_touching_docker_rules() {
+ void nat_set_redirect_rule_without_touching_docker_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-N DOCKER_OUTPUT\n" +
- "-N DOCKER_POSTROUTING\n" +
- "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
- "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-N DOCKER_OUTPUT\n" +
+ "-N DOCKER_POSTROUTING\n" +
+ "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
+ "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-N DOCKER_OUTPUT\n" +
- "-N DOCKER_POSTROUTING\n" +
- "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
- "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-N DOCKER_OUTPUT\n" +
+ "-N DOCKER_POSTROUTING\n" +
+ "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
+ "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
@Test
- public void nat_cleanup_wrong_redirect_rules() {
+ void nat_cleanup_wrong_redirect_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::2/128 -j REDIRECT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::2/128 -j REDIRECT\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
@Test
- public void nat_delete_duplicate_rules() {
+ void nat_delete_duplicate_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::2/128 -j REDIRECT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT\n" +
- "-A OUTPUT -d 3001::4/128 -j REDIRECT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::2/128 -j REDIRECT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT\n" +
+ "-A OUTPUT -d 3001::4/128 -j REDIRECT\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
private static void assertNatTableLineEditorResult(String redirectRule, String currentNatTable, String expectedNatTable) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
index 5c334837040..c0bf6ebbeb3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
@@ -7,15 +7,15 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.node.admin.maintenance.coredump.CoreCollector.GDB_PATH_RHEL8;
import static com.yahoo.vespa.hosted.node.admin.maintenance.coredump.CoreCollector.JAVA_HEAP_DUMP_METADATA;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -37,7 +37,7 @@ public class CoreCollectorTest {
"#0 0x00000000004004d8 in main (argv=...) at main.c:4");
@Test
- public void extractsBinaryPathTest() {
+ void extractsBinaryPathTest() {
final String[] cmd = {"file", TEST_CORE_PATH.pathInContainer()};
mockExec(cmd,
@@ -73,7 +73,7 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBinaryPathUsingGdbTest() {
+ void extractsBinaryPathUsingGdbTest() {
final String[] cmd = new String[]{"/bin/sh", "-c",
GDB_PATH_RHEL8 + " -n -batch -core /tmp/core.1234 | grep '^Core was generated by'"};
@@ -91,14 +91,14 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBacktraceUsingGdb() {
+ void extractsBacktraceUsingGdb() {
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
assertEquals(GDB_BACKTRACE, coreCollector.readBacktrace(context, TEST_CORE_PATH, TEST_BIN_PATH, false));
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
"", "Failure");
try {
coreCollector.readBacktrace(context, TEST_CORE_PATH, TEST_BIN_PATH, false);
@@ -111,7 +111,7 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBacktraceFromAllThreadsUsingGdb() {
+ void extractsBacktraceFromAllThreadsUsingGdb() {
mockExec(new String[]{GDB_PATH_RHEL8, "-n",
"-ex", "set print frame-arguments none",
"-ex", "thread apply all bt", "-batch",
@@ -121,15 +121,15 @@ public class CoreCollectorTest {
}
@Test
- public void collectsDataTest() {
+ void collectsDataTest() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"/tmp/core.1234: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from " +
"'/usr/bin/program'");
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "thread apply all bt", "-batch",
+ "-ex", "thread apply all bt", "-batch",
"/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
@@ -141,7 +141,7 @@ public class CoreCollectorTest {
}
@Test
- public void collectsPartialIfBacktraceFailsTest() {
+ void collectsPartialIfBacktraceFailsTest() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"/tmp/core.1234: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from " +
"'/usr/bin/program'");
@@ -153,7 +153,7 @@ public class CoreCollectorTest {
}
@Test
- public void reportsJstackInsteadOfGdbForJdkCores() {
+ void reportsJstackInsteadOfGdbForJdkCores() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"dump.core.5954: ELF 64-bit LSB core file x86-64, version 1 (SYSV), too many program header sections (33172)");
@@ -171,7 +171,7 @@ public class CoreCollectorTest {
}
@Test
- public void metadata_for_java_heap_dump() {
+ void metadata_for_java_heap_dump() {
assertEquals(JAVA_HEAP_DUMP_METADATA, coreCollector.collect(context, context.paths().of("/dump_java_pid123.hprof")));
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
index 5c681ddc129..31579fb7c9b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -28,8 +28,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -59,7 +58,7 @@ public class CoredumpHandlerTest {
@Test
- public void coredump_enqueue_test() throws IOException {
+ void coredump_enqueue_test() throws IOException {
ContainerPath crashPath = context.paths().of("/some/crash/path");
ContainerPath processingDir = context.paths().of("/some/other/processing");
@@ -93,7 +92,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void enqueue_with_hs_err_files() throws IOException {
+ void enqueue_with_hs_err_files() throws IOException {
ContainerPath crashPath = context.paths().of("/some/crash/path");
ContainerPath processingDir = context.paths().of("/some/other/processing");
Files.createDirectories(crashPath);
@@ -114,7 +113,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void coredump_to_process_test() throws IOException {
+ void coredump_to_process_test() throws IOException {
ContainerPath processingDir = context.paths().of("/some/other/processing");
// Initially there are no core dumps
@@ -138,7 +137,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void get_metadata_test() throws IOException {
+ void get_metadata_test() throws IOException {
Map<String, Object> metadata = new HashMap<>();
metadata.put("bin_path", "/bin/bash");
metadata.put("backtrace", List.of("call 1", "function 2", "something something"));
@@ -174,21 +173,25 @@ public class CoredumpHandlerTest {
verify(coreCollector, times(1)).collect(any(), any());
}
- @Test(expected = IllegalStateException.class)
- public void cant_get_metadata_if_no_core_file() throws IOException {
- coredumpHandler.getMetadata(context, context.paths().of("/fake/path"), Map::of);
+ @Test
+ void cant_get_metadata_if_no_core_file() throws IOException {
+ assertThrows(IllegalStateException.class, () -> {
+ coredumpHandler.getMetadata(context, context.paths().of("/fake/path"), Map::of);
+ });
}
- @Test(expected = IllegalStateException.class)
- public void fails_to_get_core_file_if_only_compressed() throws IOException {
- ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
- Files.createDirectories(coredumpDirectory);
- Files.createFile(coredumpDirectory.resolve("dump_bash.core.431.zstd"));
- coredumpHandler.findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ @Test
+ void fails_to_get_core_file_if_only_compressed() throws IOException {
+ assertThrows(IllegalStateException.class, () -> {
+ ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
+ Files.createDirectories(coredumpDirectory);
+ Files.createFile(coredumpDirectory.resolve("dump_bash.core.431.zstd"));
+ coredumpHandler.findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ });
}
@Test
- public void process_single_coredump_test() throws IOException {
+ void process_single_coredump_test() throws IOException {
ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
Files.createDirectories(coredumpDirectory);
Files.write(coredumpDirectory.resolve("metadata.json"), "metadata".getBytes());
@@ -204,7 +207,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void report_enqueued_and_processed_metrics() throws IOException {
+ void report_enqueued_and_processed_metrics() throws IOException {
Path processingPath = containerCrashPath.resolve("processing");
Files.createFile(containerCrashPath.resolve("dump-1"));
Files.createFile(containerCrashPath.resolve("dump-2"));
@@ -225,7 +228,7 @@ public class CoredumpHandlerTest {
assertEquals(1, values.get("coredumps.processed").intValue());
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
Files.createDirectories(containerCrashPath.pathOnHost());
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
index 272fdba7e9a..9bd746e3ddf 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -16,7 +16,7 @@ import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.PrioritizedFileAttributes;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -26,7 +26,7 @@ public class CoredumpCleanupRuleTest {
private final FileSystem fileSystem = TestFileSystem.create();
@Test
- public void for_container_test() throws IOException {
+ void for_container_test() throws IOException {
Path path = fileSystem.getPath("/test/path");
DiskCleanupRule rule = CoredumpCleanupRule.forContainer(path);
@@ -56,7 +56,7 @@ public class CoredumpCleanupRuleTest {
}
@Test
- public void for_host_test() throws IOException {
+ void for_host_test() throws IOException {
Path path = fileSystem.getPath("/test/path");
DiskCleanupRule rule = CoredumpCleanupRule.forHost(path);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
index 1386177d17a..44367f37dd9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -21,10 +21,10 @@ import java.util.Set;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder.FileAttributes;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -36,7 +36,7 @@ public class DiskCleanupTest {
private final DiskCleanup diskCleanup = new DiskCleanup();
@Test
- public void nothing_deleted() throws IOException {
+ void nothing_deleted() throws IOException {
assertFalse(diskCleanup.cleanup(context, List.of(), 0));
assertFalse(diskCleanup.cleanup(context, List.of(), 10));
@@ -56,7 +56,7 @@ public class DiskCleanupTest {
}
@Test
- public void delete_test() throws IOException {
+ void delete_test() throws IOException {
tester.createFile("/opt/vespa/var/db/do-not-delete-1.db", 1);
tester.createFile("/opt/vespa/var/db/do-not-delete-2.db", 1);
tester.createFile("/opt/vespa/var/zookeeper/do-not-delete-3", 1);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
index 55a379054d4..1ef876d7e04 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
@@ -1,16 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder.FileAttributes;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.PrioritizedFileAttributes;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -19,27 +20,29 @@ import static org.mockito.Mockito.mock;
public class LinearCleanupRuleTest {
@Test
- public void basic() {
+ void basic() {
assertRule(Map.of(), Priority.LOWEST, Priority.HIGHEST);
assertRule(Map.of(0.0, Priority.LOW, 0.5, Priority.LOW, 1.0, Priority.LOW), Priority.LOW, Priority.LOW);
assertRule(Map.of(0.0, Priority.LOW, 0.5, Priority.MEDIUM, 1.0, Priority.MEDIUM), Priority.LOW, Priority.MEDIUM);
assertRule(Map.of(
- -5.0, Priority.LOW,
- 0.0, Priority.LOW,
- 0.2, Priority.LOW,
- 0.35, Priority.MEDIUM,
- 0.65, Priority.MEDIUM,
- 0.8, Priority.HIGH,
- 1.0, Priority.HIGH,
- 5.0, Priority.HIGH),
+ -5.0, Priority.LOW,
+ 0.0, Priority.LOW,
+ 0.2, Priority.LOW,
+ 0.35, Priority.MEDIUM,
+ 0.65, Priority.MEDIUM,
+ 0.8, Priority.HIGH,
+ 1.0, Priority.HIGH,
+ 5.0, Priority.HIGH),
Priority.LOW, Priority.HIGH);
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_if_high_priority_lower_than_low() {
- assertRule(Map.of(), Priority.HIGHEST, Priority.LOWEST);
+ @Test
+ void fail_if_high_priority_lower_than_low() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ assertRule(Map.of(), Priority.HIGHEST, Priority.LOWEST);
+ });
}
private static void assertRule(Map<Double, Priority> expectedPriorities, Priority low, Priority high) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
index 4e34d936d85..fd7d0d8c1c0 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
@@ -6,7 +6,8 @@ import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
index 94c2ce6d106..8be1ef23bb2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.sync;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.file.FileSystem;
@@ -15,7 +15,7 @@ import java.util.Optional;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo.Compression.NONE;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo.Compression.ZSTD;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -37,7 +37,7 @@ public class SyncFileInfoTest {
private static final Path zkLogPath1 = fileSystem.getPath("/opt/vespa/logs/zookeeper.configserver.1.log");
@Test
- public void access_logs() {
+ void access_logs() {
assertForLogFile(accessLogPath1, null, null, true);
assertForLogFile(accessLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/access/access.log.20210211.zst", ZSTD, false);
@@ -52,7 +52,7 @@ public class SyncFileInfoTest {
}
@Test
- public void connection_logs() {
+ void connection_logs() {
assertForLogFile(connectionLogPath1, null, null, true);
assertForLogFile(connectionLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/connection/ConnectionLog.20210210.zst", ZSTD, false);
@@ -61,7 +61,7 @@ public class SyncFileInfoTest {
}
@Test
- public void vespa_logs() {
+ void vespa_logs() {
assertForLogFile(vespaLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/vespa/vespa.log.zst", ZSTD, Duration.ofHours(1), true);
assertForLogFile(vespaLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/vespa/vespa.log.zst", ZSTD, Duration.ZERO, false);
@@ -70,7 +70,7 @@ public class SyncFileInfoTest {
}
@Test
- public void zookeeper_logs() {
+ void zookeeper_logs() {
assertForLogFile(zkLogPath0, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/zookeeper/zookeeper.log.zst", ZSTD, Duration.ofHours(1), true);
assertForLogFile(zkLogPath0, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/zookeeper/zookeeper.log.zst", ZSTD, Duration.ZERO, false);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java
index ab43c3fd5fc..e6963175977 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.sync;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -10,8 +10,8 @@ import java.io.UncheckedIOException;
import java.util.Random;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.ZstdCompressingInputStream.compressor;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class ZstdCompressingInputStreamTest {
@Test
- public void compression_test() throws Exception {
+ void compression_test() throws Exception {
Random rnd = new Random();
byte[] data = new byte[(int) (100_000 * (10 + rnd.nextDouble()))];
rnd.nextBytes(data);
@@ -27,9 +27,9 @@ public class ZstdCompressingInputStreamTest {
}
@Test
- public void compress_empty_file_test() {
+ void compress_empty_file_test() {
byte[] compressedData = compress(new byte[0], 1 << 10);
- assertEquals("zstd compressing an empty file results in a 13 bytes file", 13, compressedData.length);
+ assertEquals(13, compressedData.length, "zstd compressing an empty file results in a 13 bytes file");
}
private static void assertCompression(byte[] data, int bufferSize) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
index f8dc05b5eda..96c18517bfe 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.time.Duration;
@@ -17,9 +17,7 @@ import java.util.Set;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl.NodeAgentWithScheduler;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl.NodeAgentWithSchedulerFactory;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
@@ -37,12 +35,12 @@ public class NodeAdminImplTest {
private final NodeAgentWithSchedulerFactory nodeAgentWithSchedulerFactory = mock(NodeAgentWithSchedulerFactory.class);
private final ManualClock clock = new ManualClock();
-
+ private final ProcMeminfoReader procMeminfoReader = mock(ProcMeminfoReader.class);
private final NodeAdminImpl nodeAdmin = new NodeAdminImpl(nodeAgentWithSchedulerFactory,
- new Metrics(), clock, Duration.ZERO, Duration.ZERO);
+ new Metrics(), clock, Duration.ZERO, Duration.ZERO, procMeminfoReader);
@Test
- public void nodeAgentsAreProperlyLifeCycleManaged() {
+ void nodeAgentsAreProperlyLifeCycleManaged() {
final NodeAgentContext context1 = createNodeAgentContext("host1.test.yahoo.com");
final NodeAgentContext context2 = createNodeAgentContext("host2.test.yahoo.com");
final NodeAgentWithScheduler nodeAgent1 = mockNodeAgentWithSchedulerFactory(context1);
@@ -80,7 +78,7 @@ public class NodeAdminImplTest {
}
@Test
- public void testSetFrozen() {
+ void testSetFrozen() {
Set<NodeAgentContext> contexts = new HashSet<>();
List<NodeAgentWithScheduler> nodeAgents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
@@ -127,7 +125,7 @@ public class NodeAdminImplTest {
}
@Test
- public void testSubsystemFreezeDuration() {
+ void testSubsystemFreezeDuration() {
// Initially everything is frozen to force convergence
assertTrue(nodeAdmin.isFrozen());
assertTrue(nodeAdmin.subsystemFreezeDuration().isZero());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
index 995712c6dda..1197fd1469b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Orchestrato
import com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.Orchestrator;
import com.yahoo.vespa.hosted.node.admin.integration.NodeRepoMock;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
@@ -23,8 +23,8 @@ import java.util.stream.IntStream;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.RESUMED;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.SUSPENDED;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.SUSPENDED_NODE_ADMIN;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.argThat;
@@ -54,7 +54,7 @@ public class NodeAdminStateUpdaterTest {
@Test
- public void state_convergence() {
+ void state_convergence() {
mockNodeRepo(NodeState.active, 4);
List<String> activeHostnames = nodeRepository.getNodes(hostHostname.value()).stream()
.map(NodeSpec::hostname)
@@ -132,7 +132,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void half_transition_revert() {
+ void half_transition_revert() {
final String exceptionMsg = "Cannot allow to suspend because some reason";
mockNodeRepo(NodeState.active, 3);
@@ -174,7 +174,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void do_not_orchestrate_host_when_not_active() {
+ void do_not_orchestrate_host_when_not_active() {
when(nodeAdmin.subsystemFreezeDuration()).thenReturn(Duration.ofHours(1));
when(nodeAdmin.setFrozen(anyBoolean())).thenReturn(true);
mockNodeRepo(NodeState.ready, 3);
@@ -196,7 +196,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_aligned() {
+ void node_spec_and_acl_aligned() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 3);
mockAcl(acl, 1, 2, 3);
@@ -213,7 +213,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_mismatch_missing_one_acl() {
+ void node_spec_and_acl_mismatch_missing_one_acl() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 3);
mockAcl(acl, 1, 2); // Acl for 3 is missing
@@ -231,7 +231,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_mismatch_additional_acl() {
+ void node_spec_and_acl_mismatch_additional_acl() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 2);
mockAcl(acl, 1, 2, 3); // Acl for 3 is extra
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
index 9a6a358d9f0..061cd6e264b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
@@ -4,15 +4,13 @@ package com.yahoo.vespa.hosted.node.admin.nodeagent;
import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.flags.PermanentFlags;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author freva
@@ -23,7 +21,7 @@ public class NodeAgentContextImplTest {
.fileSystem(fileSystem).build();
@Test
- public void path_on_host_from_path_in_node_test() {
+ void path_on_host_from_path_in_node_test() {
assertEquals(
"/data/vespa/storage/container-1",
context.paths().of("/").pathOnHost().toString());
@@ -33,35 +31,43 @@ public class NodeAgentContextImplTest {
context.paths().of("/dev/null").pathOnHost().toString());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_in_container_must_be_absolute() {
- context.paths().of("some/relative/path");
+ @Test
+ void path_in_container_must_be_absolute() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().of("some/relative/path");
+ });
}
@Test
- public void path_in_node_from_path_on_host_test() {
+ void path_in_node_from_path_on_host_test() {
assertEquals(
"/dev/null",
context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-1/dev/null")).pathInContainer());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_absolute() {
- context.paths().fromPathOnHost(Path.of("some/relative/path"));
+ @Test
+ void path_on_host_must_be_absolute() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(Path.of("some/relative/path"));
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_inside_container_storage_of_context() {
- context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-2/dev/null"));
+ @Test
+ void path_on_host_must_be_inside_container_storage_of_context() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-2/dev/null"));
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_inside_container_storage() {
- context.paths().fromPathOnHost(fileSystem.getPath("/home"));
+ @Test
+ void path_on_host_must_be_inside_container_storage() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(fileSystem.getPath("/home"));
+ });
}
@Test
- public void path_under_vespa_host_in_container_test() {
+ void path_under_vespa_host_in_container_test() {
assertEquals(
"/opt/vespa",
context.paths().underVespaHome("").pathInContainer());
@@ -71,13 +77,15 @@ public class NodeAgentContextImplTest {
context.paths().underVespaHome("logs/vespa/vespa.log").pathInContainer());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_under_vespa_home_must_be_relative() {
- context.paths().underVespaHome("/home");
+ @Test
+ void path_under_vespa_home_must_be_relative() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().underVespaHome("/home");
+ });
}
@Test
- public void disabledTasksTest() {
+ void disabledTasksTest() {
NodeAgentContext context1 = createContextWithDisabledTasks();
assertFalse(context1.isDisabled(NodeAgentTask.DiskCleanup));
assertFalse(context1.isDisabled(NodeAgentTask.CoreDumps));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
index 9502fc48911..82c3f79f39f 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
@@ -2,7 +2,8 @@
package com.yahoo.vespa.hosted.node.admin.nodeagent;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.time.Clock;
import java.time.Duration;
@@ -12,10 +13,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextSupplier.ContextSupplierInterruptedException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author freva
@@ -28,8 +26,9 @@ public class NodeAgentContextManagerTest {
private final NodeAgentContext initialContext = generateContext();
private final NodeAgentContextManager manager = new NodeAgentContextManager(clock, initialContext);
- @Test(timeout = TIMEOUT)
- public void context_is_ignored_unless_scheduled_while_waiting() {
+ @Test
+ @Timeout(TIMEOUT)
+ void context_is_ignored_unless_scheduled_while_waiting() {
NodeAgentContext context1 = generateContext();
manager.scheduleTickWith(context1, clock.instant());
assertSame(initialContext, manager.currentContext());
@@ -45,8 +44,9 @@ public class NodeAgentContextManagerTest {
assertSame(context2, manager.currentContext());
}
- @Test(timeout = TIMEOUT)
- public void returns_no_earlier_than_at_given_time() {
+ @Test
+ @Timeout(TIMEOUT)
+ void returns_no_earlier_than_at_given_time() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
@@ -60,8 +60,9 @@ public class NodeAgentContextManagerTest {
assertFalse(clock.instant().plusMillis(1).isBefore(returnAt));
}
- @Test(timeout = TIMEOUT)
- public void blocks_in_nextContext_until_one_is_scheduled() {
+ @Test
+ @Timeout(TIMEOUT)
+ void blocks_in_nextContext_until_one_is_scheduled() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
assertFalse(async.isCompleted());
@@ -74,8 +75,9 @@ public class NodeAgentContextManagerTest {
assertFalse(async.exception.isPresent());
}
- @Test(timeout = TIMEOUT)
- public void blocks_in_nextContext_until_interrupt() {
+ @Test
+ @Timeout(TIMEOUT)
+ void blocks_in_nextContext_until_interrupt() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
assertFalse(async.isCompleted());
@@ -87,8 +89,9 @@ public class NodeAgentContextManagerTest {
assertFalse(async.response.isPresent());
}
- @Test(timeout = TIMEOUT)
- public void setFrozen_does_not_block_with_no_timeout() {
+ @Test
+ @Timeout(TIMEOUT)
+ void setFrozen_does_not_block_with_no_timeout() {
assertFalse(manager.setFrozen(false, Duration.ZERO));
// Generate new context and get it from the supplier, this completes the unfreeze
@@ -101,8 +104,9 @@ public class NodeAgentContextManagerTest {
assertTrue(manager.setFrozen(false, Duration.ZERO));
}
- @Test(timeout = TIMEOUT)
- public void setFrozen_blocks_at_least_for_duration_of_timeout() {
+ @Test
+ @Timeout(TIMEOUT)
+ void setFrozen_blocks_at_least_for_duration_of_timeout() {
long wantedDurationMillis = 100;
long start = clock.millis();
assertFalse(manager.setFrozen(false, Duration.ofMillis(wantedDurationMillis)));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
index d31c341532f..e4c2f595164 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
@@ -28,8 +28,8 @@ import com.yahoo.vespa.hosted.node.admin.maintenance.identity.CredentialsMaintai
import com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.VespaServiceDumper;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.nio.file.FileSystem;
@@ -39,8 +39,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
@@ -76,7 +76,7 @@ public class NodeAgentImplTest {
private final ManualClock clock = new ManualClock(Instant.now());
private final FileSystem fileSystem = TestFileSystem.create();
- @Before
+ @BeforeEach
public void setUp() {
when(containerOperations.suspendNode(any())).thenReturn("");
when(containerOperations.resumeNode(any())).thenReturn("");
@@ -86,7 +86,7 @@ public class NodeAgentImplTest {
}
@Test
- public void upToDateContainerIsUntouched() {
+ void upToDateContainerIsUntouched() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -111,7 +111,7 @@ public class NodeAgentImplTest {
}
@Test
- public void verifyRemoveOldFilesIfDiskFull() {
+ void verifyRemoveOldFilesIfDiskFull() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -127,7 +127,7 @@ public class NodeAgentImplTest {
}
@Test
- public void startsAfterStoppingServices() {
+ void startsAfterStoppingServices() {
final InOrder inOrder = inOrder(containerOperations);
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
@@ -161,7 +161,7 @@ public class NodeAgentImplTest {
}
@Test
- public void absentContainerCausesStart() {
+ void absentContainerCausesStart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -192,7 +192,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsNotStoppedIfNewImageMustBePulled() {
+ void containerIsNotStoppedIfNewImageMustBePulled() {
final DockerImage newDockerImage = DockerImage.fromString("registry.example.com/repo/new-image");
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(newDockerImage).currentDockerImage(dockerImage)
@@ -216,7 +216,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsUpdatedIfCpuChanged() {
+ void containerIsUpdatedIfCpuChanged() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -263,7 +263,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsRecreatedIfMemoryChanged() {
+ void containerIsRecreatedIfMemoryChanged() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -294,7 +294,7 @@ public class NodeAgentImplTest {
}
@Test
- public void noRestartIfOrchestratorSuspendFails() {
+ void noRestartIfOrchestratorSuspendFails() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -308,7 +308,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to throw an exception");
- } catch (OrchestratorException ignored) { }
+ } catch (OrchestratorException ignored) {
+ }
verify(containerOperations, never()).createContainer(eq(context), any());
verify(containerOperations, never()).startContainer(eq(context));
@@ -320,7 +321,7 @@ public class NodeAgentImplTest {
}
@Test
- public void recreatesContainerIfRebootWanted() {
+ void recreatesContainerIfRebootWanted() {
final long wantedRebootGeneration = 2;
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
@@ -333,12 +334,13 @@ public class NodeAgentImplTest {
when(nodeRepository.getOptionalNode(hostName)).thenReturn(Optional.of(node));
when(containerOperations.pullImageAsyncIfNeeded(any(), eq(dockerImage), any())).thenReturn(false);
- doThrow(new ConvergenceException("Connection refused")).doNothing()
+ doThrow(ConvergenceException.ofTransient("Connection refused")).doNothing()
.when(healthChecker).verifyHealth(eq(context));
try {
nodeAgent.doConverge(context);
- } catch (ConvergenceException ignored) {}
+ } catch (ConvergenceException ignored) {
+ }
// First time we fail to resume because health verification fails
verify(orchestrator, times(1)).suspend(eq(hostName));
@@ -359,7 +361,7 @@ public class NodeAgentImplTest {
}
@Test
- public void failedNodeRunningContainerShouldStillBeRunning() {
+ void failedNodeRunningContainerShouldStillBeRunning() {
final NodeSpec node = nodeBuilder(NodeState.failed)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -378,11 +380,11 @@ public class NodeAgentImplTest {
}
@Test
- public void readyNodeLeadsToNoAction() {
+ void readyNodeLeadsToNoAction() {
final NodeSpec node = nodeBuilder(NodeState.ready).build();
NodeAgentContext context = createContext(node);
- NodeAgentImpl nodeAgent = makeNodeAgent(null,false);
+ NodeAgentImpl nodeAgent = makeNodeAgent(null, false);
when(nodeRepository.getOptionalNode(hostName)).thenReturn(Optional.of(node));
@@ -400,7 +402,7 @@ public class NodeAgentImplTest {
}
@Test
- public void inactiveNodeRunningContainerShouldStillBeRunning() {
+ void inactiveNodeRunningContainerShouldStillBeRunning() {
final NodeSpec node = nodeBuilder(NodeState.inactive)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -421,7 +423,7 @@ public class NodeAgentImplTest {
}
@Test
- public void reservedNodeDoesNotUpdateNodeRepoWithVersion() {
+ void reservedNodeDoesNotUpdateNodeRepoWithVersion() {
final NodeSpec node = nodeBuilder(NodeState.reserved)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -470,17 +472,17 @@ public class NodeAgentImplTest {
}
@Test
- public void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycled() {
+ void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycled() {
nodeRunningContainerIsTakenDownAndCleanedAndRecycled(NodeState.dirty, Optional.of(1L));
}
@Test
- public void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycledNoRestartGeneration() {
+ void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycledNoRestartGeneration() {
nodeRunningContainerIsTakenDownAndCleanedAndRecycled(NodeState.dirty, Optional.empty());
}
@Test
- public void provisionedNodeIsMarkedAsReady() {
+ void provisionedNodeIsMarkedAsReady() {
final NodeSpec node = nodeBuilder(NodeState.provisioned)
.wantedDockerImage(dockerImage)
.build();
@@ -494,7 +496,7 @@ public class NodeAgentImplTest {
}
@Test
- public void testRestartDeadContainerAfterNodeAdminRestart() {
+ void testRestartDeadContainerAfterNodeAdminRestart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.currentDockerImage(dockerImage).wantedDockerImage(dockerImage)
.currentVespaVersion(vespaVersion)
@@ -513,7 +515,7 @@ public class NodeAgentImplTest {
}
@Test
- public void resumeProgramRunsUntilSuccess() {
+ void resumeProgramRunsUntilSuccess() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.currentVespaVersion(vespaVersion)
@@ -535,7 +537,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to throw an exception");
- } catch (RuntimeException ignored) { }
+ } catch (RuntimeException ignored) {
+ }
inOrder.verify(containerOperations, times(1)).resumeNode(any());
inOrder.verifyNoMoreInteractions();
@@ -549,7 +552,7 @@ public class NodeAgentImplTest {
}
@Test
- public void start_container_subtask_failure_leads_to_container_restart() {
+ void start_container_subtask_failure_leads_to_container_restart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -565,7 +568,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to get RuntimeException");
- } catch (RuntimeException ignored) { }
+ } catch (RuntimeException ignored) {
+ }
verify(containerOperations, never()).removeContainer(eq(context), any());
verify(containerOperations, times(1)).createContainer(eq(context), any());
@@ -584,7 +588,7 @@ public class NodeAgentImplTest {
}
@Test
- public void testRunningConfigServer() {
+ void testRunningConfigServer() {
final NodeSpec node = nodeBuilder(NodeState.active)
.type(NodeType.config)
.wantedDockerImage(dockerImage)
@@ -617,7 +621,7 @@ public class NodeAgentImplTest {
// Tests that only containers without owners are stopped
@Test
- public void testThatStopContainerDependsOnOwnerPresent() {
+ void testThatStopContainerDependsOnOwnerPresent() {
verifyThatContainerIsStopped(NodeState.parked, Optional.empty());
verifyThatContainerIsStopped(NodeState.parked, Optional.of(ApplicationId.defaultId()));
verifyThatContainerIsStopped(NodeState.failed, Optional.empty());
@@ -626,7 +630,7 @@ public class NodeAgentImplTest {
}
@Test
- public void initial_cpu_cap_test() {
+ void initial_cpu_cap_test() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion);
@@ -636,7 +640,7 @@ public class NodeAgentImplTest {
InOrder inOrder = inOrder(orchestrator, containerOperations);
- ConvergenceException healthCheckException = new ConvergenceException("Not yet up");
+ ConvergenceException healthCheckException = ConvergenceException.ofTransient("Not yet up");
doThrow(healthCheckException).when(healthChecker).verifyHealth(any());
for (int i = 0; i < 3; i++) {
try {
@@ -678,7 +682,7 @@ public class NodeAgentImplTest {
}
@Test
- public void resumes_normally_if_container_is_already_capped_on_start() {
+ void resumes_normally_if_container_is_already_capped_on_start() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -700,7 +704,7 @@ public class NodeAgentImplTest {
}
@Test
- public void uncaps_and_caps_cpu_for_services_restart() {
+ void uncaps_and_caps_cpu_for_services_restart() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java
index fd16b974e18..b7099a5f2bd 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.provider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class DebugHandlerHelperTest {
@Test
- public void trivial() {
+ void trivial() {
DebugHandlerHelper helper = new DebugHandlerHelper();
helper.addConstant("constant-key", "constant-value");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
index 3869ec26d02..bc461af0eb3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.hosted.node.admin.task.util;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -13,9 +13,7 @@ import java.nio.file.Paths;
import java.util.logging.Logger;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -26,8 +24,8 @@ import static org.mockito.Mockito.verify;
*/
public class DefaultEnvWriterTest {
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
private static final Path EXAMPLE_FILE = Paths.get("src/test/resources/default-env-example.txt");
private static final Path EXPECTED_RESULT_FILE = Paths.get("src/test/resources/default-env-rewritten.txt");
@@ -35,8 +33,8 @@ public class DefaultEnvWriterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void default_env_is_correctly_rewritten() throws IOException {
- Path tempFile = temporaryFolder.newFile().toPath();
+ void default_env_is_correctly_rewritten() throws IOException {
+ Path tempFile = File.createTempFile("junit", null, temporaryFolder).toPath();
Files.copy(EXAMPLE_FILE, tempFile, REPLACE_EXISTING);
DefaultEnvWriter writer = new DefaultEnvWriter();
@@ -57,7 +55,7 @@ public class DefaultEnvWriterTest {
}
@Test
- public void generates_default_env_content() throws IOException {
+ void generates_default_env_content() throws IOException {
DefaultEnvWriter writer = new DefaultEnvWriter();
writer.addOverride("VESPA_HOSTNAME", "my-new-hostname");
writer.addFallback("VESPA_CONFIGSERVER", "new-fallback-configserver");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
index a66d77edbfa..4f8e28cf53c 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
@@ -2,22 +2,19 @@
package com.yahoo.vespa.hosted.node.admin.task.util.editor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class StringEditorTest {
private final StringEditor editor = new StringEditor();
private final Cursor cursor = editor.cursor();
@Test
- public void testBasics() {
+ void testBasics() {
assertCursor(0, 0, "");
cursor.write("hello");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
index 584b7c2c906..ca95fada774 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.hosted.node.admin.task.util.editor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class TextBufferImplTest {
private final TextBufferImpl textBuffer = new TextBufferImpl();
@Test
- public void testWrite() {
+ void testWrite() {
assertEquals("", textBuffer.getString());
assertWrite(2, 0, "foo\nbar\n",
0, 0, "foo\nbar\n");
@@ -25,7 +25,7 @@ public class TextBufferImplTest {
}
@Test
- public void testDelete() {
+ void testDelete() {
write(0, 0, "foo\nbar\nzoo\n");
delete(0, 2, 2, 1);
assertEquals("fooo\n", textBuffer.getString());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
index 9c7bad3b130..8d8f9437495 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class DiskSizeTest {
@Test
- public void bytes_to_display_count_test() {
+ void bytes_to_display_count_test() {
assertEquals("-1 bytes", DiskSize.of(-1).asString());
assertEquals("123 bytes", DiskSize.of(123).asString());
assertEquals("1 kB", DiskSize.of(1_000).asString());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
index 59bc7864ef5..25c1063c92f 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
@@ -3,15 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.FileSystem;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -23,7 +21,7 @@ public class EditorTest {
private final UnixPath path = new UnixPath(fileSystem.getPath("/file"));
@Test
- public void testEdit() {
+ void testEdit() {
path.writeUtf8File(joinLines("first", "second", "third"));
LineEditor lineEditor = mock(LineEditor.class);
@@ -51,7 +49,7 @@ public class EditorTest {
}
@Test
- public void testInsert() {
+ void testInsert() {
path.writeUtf8File(joinLines("second", "eight", "fifth", "seventh"));
LineEditor lineEditor = mock(LineEditor.class);
@@ -86,7 +84,7 @@ public class EditorTest {
}
@Test
- public void noop() {
+ void noop() {
path.writeUtf8File("line\n");
LineEditor lineEditor = mock(LineEditor.class);
@@ -107,7 +105,7 @@ public class EditorTest {
}
@Test
- public void testMissingFile() {
+ void testMissingFile() {
LineEditor lineEditor = mock(LineEditor.class);
when(lineEditor.onComplete()).thenReturn(List.of("line"));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
index 9a2ada2bebe..8c9188a9409 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -16,7 +14,7 @@ import static org.mockito.Mockito.when;
public class FileAttributesCacheTest {
@Test
- public void exists() {
+ void exists() {
UnixPath unixPath = mock(UnixPath.class);
FileAttributesCache cache = new FileAttributesCache(unixPath);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
index 32eb7708f68..9184ac2daa0 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -22,7 +22,7 @@ public class FileContentCacheTest {
private final byte[] newContent = "new-content".getBytes(StandardCharsets.UTF_8);
@Test
- public void get() {
+ void get() {
when(unixPath.readBytes()).thenReturn(content);
assertArrayEquals(content, cache.get(Instant.ofEpochMilli(0)));
verify(unixPath, times(1)).readBytes();
@@ -49,7 +49,7 @@ public class FileContentCacheTest {
}
@Test
- public void updateWith() {
+ void updateWith() {
cache.updateWith(content, Instant.ofEpochMilli(2));
assertArrayEquals(content, cache.get(Instant.ofEpochMilli(2)));
verifyNoMoreInteractions(unixPath);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
index 5cf7f950c4f..360ffacca8d 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
public class FileDeleterTest {
@@ -18,7 +18,7 @@ public class FileDeleterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void deleteExisting() {
+ void deleteExisting() {
assertFalse(deleter.converge(context));
path.createParents().writeUtf8File("bar");
assertTrue(deleter.converge(context));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
index 0bb820bbfdc..ce193059fb2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
@@ -3,10 +3,9 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.runners.Enclosed;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -27,24 +26,24 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Set.of;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
/**
* @author freva
*/
-@RunWith(Enclosed.class)
+
public class FileFinderTest {
- public static class GeneralLogicTests {
+ @Nested
+ public class GeneralLogicTests {
private final FileSystem fileSystem = TestFileSystem.create();
@Test
- public void all_files_non_recursive() {
+ void all_files_non_recursive() {
assertFileHelper(FileFinder.files(testRoot())
.maxDepth(1),
@@ -53,7 +52,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive() {
+ void all_files_recursive() {
assertFileHelper(FileFinder.files(testRoot()),
of("file-1.json", "test.json", "test.txt", "test/file.txt", "test/data.json", "test/subdir-1/test"),
@@ -61,7 +60,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive_with_prune_relative() {
+ void all_files_recursive_with_prune_relative() {
assertFileHelper(FileFinder.files(testRoot()).prune(fileSystem.getPath("test")),
of("file-1.json", "test.json", "test.txt"),
@@ -69,20 +68,22 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive_with_prune_absolute() {
+ void all_files_recursive_with_prune_absolute() {
assertFileHelper(FileFinder.files(testRoot()).prune(testRoot().resolve("test/subdir-1")),
of("file-1.json", "test.json", "test.txt", "test/file.txt", "test/data.json"),
of("test", "test/subdir-1", "test/subdir-1/test", "test/subdir-2"));
}
- @Test(expected = IllegalArgumentException.class)
- public void throws_if_prune_path_not_under_base_path() {
- FileFinder.files(Paths.get("/some/path")).prune(Paths.get("/other/path"));
+ @Test
+ void throws_if_prune_path_not_under_base_path() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ FileFinder.files(Paths.get("/some/path")).prune(Paths.get("/other/path"));
+ });
}
@Test
- public void with_file_filter_recursive() {
+ void with_file_filter_recursive() {
assertFileHelper(FileFinder.files(testRoot())
.match(FileFinder.nameEndsWith(".json")),
@@ -91,7 +92,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_limited_depth() {
+ void all_files_limited_depth() {
assertFileHelper(FileFinder.files(testRoot())
.maxDepth(2),
@@ -100,7 +101,7 @@ public class FileFinderTest {
}
@Test
- public void directory_with_filter() {
+ void directory_with_filter() {
assertFileHelper(FileFinder.directories(testRoot())
.match(FileFinder.nameStartsWith("subdir"))
.maxDepth(2),
@@ -110,7 +111,7 @@ public class FileFinderTest {
}
@Test
- public void match_file_and_directory_with_same_name() {
+ void match_file_and_directory_with_same_name() {
assertFileHelper(FileFinder.from(testRoot())
.match(FileFinder.nameEndsWith("test")),
@@ -119,7 +120,7 @@ public class FileFinderTest {
}
@Test
- public void all_contents() {
+ void all_contents() {
assertFileHelper(FileFinder.from(testRoot())
.maxDepth(1),
@@ -129,7 +130,7 @@ public class FileFinderTest {
assertTrue(Files.exists(testRoot()));
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
Path root = testRoot();
Files.createDirectories(root);
@@ -185,12 +186,13 @@ public class FileFinderTest {
}
}
- public static class FilterUnitTests {
+ @Nested
+ public class FilterUnitTests {
private final BasicFileAttributes attributes = mock(BasicFileAttributes.class);
@Test
- public void age_filter_test() {
+ void age_filter_test() {
Path path = Paths.get("/my/fake/path");
when(attributes.lastModifiedTime()).thenReturn(FileTime.from(Instant.now().minus(Duration.ofHours(1))));
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
@@ -203,7 +205,7 @@ public class FileFinderTest {
}
@Test
- public void size_filters() {
+ void size_filters() {
Path path = Paths.get("/my/fake/path");
when(attributes.size()).thenReturn(100L);
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
@@ -216,7 +218,7 @@ public class FileFinderTest {
}
@Test
- public void filename_filters() {
+ void filename_filters() {
Path path = Paths.get("/my/fake/path/some-12352-file.json");
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
index 54291188397..8e09ac64e26 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
@@ -2,14 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -21,7 +18,7 @@ public class FileSnapshotTest {
private FileSnapshot fileSnapshot = FileSnapshot.forPath(path.toPath());
@Test
- public void fileDoesNotExist() {
+ void fileDoesNotExist() {
assertFalse(fileSnapshot.exists());
assertFalse(fileSnapshot.attributes().isPresent());
assertFalse(fileSnapshot.content().isPresent());
@@ -29,7 +26,7 @@ public class FileSnapshotTest {
}
@Test
- public void directory() {
+ void directory() {
path.createParents().createDirectory();
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
@@ -38,7 +35,7 @@ public class FileSnapshotTest {
}
@Test
- public void regularFile() {
+ void regularFile() {
path.createParents().writeUtf8File("file content");
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
@@ -52,7 +49,7 @@ public class FileSnapshotTest {
}
@Test
- public void fileRemoval() {
+ void fileRemoval() {
path.createParents().writeUtf8File("file content");
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
index 2355f047b00..5c7becdb9f1 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Files;
@@ -12,10 +12,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class FileSyncTest {
private final TestTaskContext taskContext = new TestTaskContext();
@@ -31,7 +28,7 @@ public class FileSyncTest {
private String permissions = "rw-r-xr--";
@Test
- public void trivial() {
+ void trivial() {
assertConvergence("Creating file /dir/file.txt",
"Changing user ID of /dir/file.txt from 1 to 123",
"Changing group ID of /dir/file.txt from 2 to 456",
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
index 0f11a4c9a7a..03f91c5d48a 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
@@ -4,15 +4,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -24,7 +22,7 @@ public class FileWriterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void testWrite() {
+ void testWrite() {
final String content = "content";
final String permissions = "rwxr-xr-x";
final int owner = 123;
@@ -52,7 +50,7 @@ public class FileWriterTest {
}
@Test
- public void testAtomicWrite() {
+ void testAtomicWrite() {
FileWriter writer = new FileWriter(fileSystem.getPath("/foo/bar"))
.atomicWrite(true);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
index b2c02690443..bcd65fd45dd 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UncheckedIOException;
import java.nio.file.FileSystem;
@@ -11,10 +11,7 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -29,7 +26,7 @@ public class MakeDirectoryTest {
private int groupId = 456;
@Test
- public void newDirectory() {
+ void newDirectory() {
verifySystemModifications(
"Creating directory " + path,
"Changing user ID of /parent/dir from 1 to 123",
@@ -62,7 +59,7 @@ public class MakeDirectoryTest {
}
@Test
- public void exceptionIfMissingParent() {
+ void exceptionIfMissingParent() {
String path = "/parent/dir";
MakeDirectory makeDirectory = new MakeDirectory(fileSystem.getPath(path));
@@ -78,7 +75,7 @@ public class MakeDirectoryTest {
}
@Test
- public void okIfParentExists() {
+ void okIfParentExists() {
String path = "/dir";
MakeDirectory makeDirectory = new MakeDirectory(fileSystem.getPath(path));
assertTrue(makeDirectory.converge(context));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
index a34f4b93a4d..67b3bf815d9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
@@ -3,15 +3,15 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
@@ -24,7 +24,7 @@ public class StoredBooleanTest {
private final StoredBoolean storedBoolean = new StoredBoolean(path);
@Test
- public void storedBoolean() {
+ void storedBoolean() {
assertFalse(storedBoolean.value());
storedBoolean.set(context);
assertTrue(storedBoolean.value());
@@ -33,7 +33,7 @@ public class StoredBooleanTest {
}
@Test
- public void testCompatibility() throws IOException {
+ void testCompatibility() throws IOException {
StoredInteger storedInteger = new StoredInteger(path);
assertFalse(storedBoolean.value());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
index d82bd517cae..50a18cc83b3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
@@ -4,19 +4,19 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
public class TemplateTest {
@Test
- public void basic() {
+ void basic() {
FileSystem fileSystem = TestFileSystem.create();
Path templatePath = fileSystem.getPath("/example.vm");
String templateContent = "a $x, $y b";
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
index 01c7e9265ac..ad8c6ea3a35 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
@@ -3,19 +3,15 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.ComparisonFailure;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.opentest4j.AssertionFailedError;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -25,7 +21,7 @@ public class UnixPathTest {
private final FileSystem fs = TestFileSystem.create();
@Test
- public void createParents() {
+ void createParents() {
Path parentDirectory = fs.getPath("/a/b/c");
Path filePath = parentDirectory.resolve("bar");
UnixPath path = new UnixPath(filePath);
@@ -36,7 +32,7 @@ public class UnixPathTest {
}
@Test
- public void utf8File() {
+ void utf8File() {
String original = "foo\nbar\n";
UnixPath path = new UnixPath(fs.getPath("example.txt"));
path.writeUtf8File(original);
@@ -45,7 +41,7 @@ public class UnixPathTest {
}
@Test
- public void permissions() {
+ void permissions() {
String expectedPermissions = "rwxr-x---";
UnixPath path = new UnixPath(fs.getPath("file.txt"));
path.writeUtf8File("foo");
@@ -53,13 +49,15 @@ public class UnixPathTest {
assertEquals(expectedPermissions, path.getPermissions());
}
- @Test(expected = IllegalArgumentException.class)
- public void badPermissionsString() {
- new UnixPath(fs.getPath("file.txt")).setPermissions("abcdefghi");
+ @Test
+ void badPermissionsString() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new UnixPath(fs.getPath("file.txt")).setPermissions("abcdefghi");
+ });
}
@Test
- public void owner() {
+ void owner() {
Path path = fs.getPath("file.txt");
UnixPath unixPath = new UnixPath(path);
unixPath.writeUtf8File("foo");
@@ -72,7 +70,7 @@ public class UnixPathTest {
}
@Test
- public void createDirectoryWithPermissions() {
+ void createDirectoryWithPermissions() {
Path path = fs.getPath("dir");
UnixPath unixPath = new UnixPath(path);
String permissions = "rwxr-xr--";
@@ -82,7 +80,7 @@ public class UnixPathTest {
}
@Test
- public void createSymbolicLink() {
+ void createSymbolicLink() {
String original = "foo\nbar\n";
UnixPath path = new UnixPath(fs.getPath("example.txt"));
path.writeUtf8File(original);
@@ -94,7 +92,7 @@ public class UnixPathTest {
}
@Test
- public void readBytesIfExists() {
+ void readBytesIfExists() {
UnixPath path = new UnixPath(fs.getPath("example.txt"));
assertFalse(path.readBytesIfExists().isPresent());
path.writeBytes(new byte[]{42});
@@ -102,7 +100,7 @@ public class UnixPathTest {
}
@Test
- public void deleteRecursively() throws Exception {
+ void deleteRecursively() throws Exception {
// Create the following file tree:
//
// /dir1
@@ -118,17 +116,17 @@ public class UnixPathTest {
var link1 = Files.createSymbolicLink(fs.getPath("/link1"), dir2);
new UnixPath(link1).deleteRecursively();
- assertTrue("Deleting " + link1 + " recursively does not remove " + dir2, Files.exists(dir2));
- assertTrue("Deleting " + link1 + " recursively does not remove " + file1, Files.exists(file1));
+ assertTrue(Files.exists(dir2), "Deleting " + link1 + " recursively does not remove " + dir2);
+ assertTrue(Files.exists(file1), "Deleting " + link1 + " recursively does not remove " + file1);
new UnixPath(dir1).deleteRecursively();
- assertFalse(dir1 + " deleted recursively", Files.exists(file1));
- assertFalse(dir1 + " deleted recursively", Files.exists(dir2));
- assertFalse(dir1 + " deleted recursively", Files.exists(dir1));
+ assertFalse(Files.exists(file1), dir1 + " deleted recursively");
+ assertFalse(Files.exists(dir2), dir1 + " deleted recursively");
+ assertFalse(Files.exists(dir1), dir1 + " deleted recursively");
}
@Test
- public void isEmptyDirectory() {
+ void isEmptyDirectory() {
var path = new UnixPath((fs.getPath("/foo")));
assertFalse(path.isEmptyDirectory());
@@ -144,7 +142,7 @@ public class UnixPathTest {
}
@Test
- public void atomicWrite() {
+ void atomicWrite() {
var path = new UnixPath(fs.getPath("/dir/foo"));
path.createParents();
path.writeUtf8File("bar");
@@ -153,7 +151,7 @@ public class UnixPathTest {
}
@Test
- public void testParentAndFilename() {
+ void testParentAndFilename() {
var absolutePath = new UnixPath("/foo/bar");
assertEquals("/foo", absolutePath.getParent().toString());
assertEquals("bar", absolutePath.getFilename());
@@ -176,7 +174,7 @@ public class UnixPathTest {
fail("No exception was thrown");
} catch (RuntimeException e) {
if (!baseClass.isInstance(e)) {
- throw new ComparisonFailure("Exception class mismatch", baseClass.getName(), e.getClass().getName());
+ throw new AssertionFailedError("Exception class mismatch", baseClass.getName(), e.getClass().getName());
}
assertEquals(message, e.getMessage());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
index 703b81af9ae..ed2fad3e979 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
@@ -2,12 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.task.util.network;
import com.google.common.net.InetAddresses;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.Inet6Address;
import java.net.InetAddress;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author smorgrav
@@ -17,7 +18,7 @@ public class IPAddressesTest {
private final IPAddressesMock mock = new IPAddressesMock();
@Test
- public void choose_sitelocal_ipv4_over_public() {
+ void choose_sitelocal_ipv4_over_public() {
mock.addAddress("localhost", "38.3.4.2")
.addAddress("localhost", "10.0.2.2")
.addAddress("localhost", "fe80::1")
@@ -27,7 +28,7 @@ public class IPAddressesTest {
}
@Test
- public void choose_ipv6_public_over_local() {
+ void choose_ipv6_public_over_local() {
mock.addAddress("localhost", "38.3.4.2")
.addAddress("localhost", "10.0.2.2")
.addAddress("localhost", "fe80::1")
@@ -36,23 +37,27 @@ public class IPAddressesTest {
assertEquals(InetAddresses.forString("2001::1"), mock.getIPv6Address("localhost").get());
}
- @Test(expected = RuntimeException.class)
- public void throws_when_multiple_ipv6_addresses() {
- mock.addAddress("localhost", "2001::1")
- .addAddress("localhost", "2001::2");
- mock.getIPv6Address("localhost");
+ @Test
+ void throws_when_multiple_ipv6_addresses() {
+ assertThrows(RuntimeException.class, () -> {
+ mock.addAddress("localhost", "2001::1")
+ .addAddress("localhost", "2001::2");
+ mock.getIPv6Address("localhost");
+ });
}
- @Test(expected = RuntimeException.class)
- public void throws_when_multiple_private_ipv4_addresses() {
- mock.addAddress("localhost", "38.3.4.2")
- .addAddress("localhost", "10.0.2.2")
- .addAddress("localhost", "10.0.2.3");
- mock.getIPv4Address("localhost");
+ @Test
+ void throws_when_multiple_private_ipv4_addresses() {
+ assertThrows(RuntimeException.class, () -> {
+ mock.addAddress("localhost", "38.3.4.2")
+ .addAddress("localhost", "10.0.2.2")
+ .addAddress("localhost", "10.0.2.3");
+ mock.getIPv4Address("localhost");
+ });
}
@Test
- public void translator_with_valid_parameters() {
+ void translator_with_valid_parameters() {
// Test simplest possible address
Inet6Address original = (Inet6Address) InetAddresses.forString("2001:db8::1");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
index a4220956272..f209290cb14 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
@@ -3,8 +3,8 @@ package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.jdisc.Timer;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -14,8 +14,8 @@ import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
@@ -31,13 +31,13 @@ public class ChildProcess2ImplTest {
private final ProcessApi2 processApi = mock(ProcessApi2.class);
private Path temporaryFile;
- @Before
+ @BeforeEach
public void setUp() throws IOException {
temporaryFile = Files.createTempFile(fileSystem.getPath("/"), "", "");
}
@Test
- public void testSuccess() throws Exception {
+ void testSuccess() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofHours(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -52,13 +52,13 @@ public class ChildProcess2ImplTest {
when(processApi.waitFor(anyLong(), any())).thenReturn(true);
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
child.waitForTermination();
}
}
@Test
- public void testTimeout() throws Exception {
+ void testTimeout() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -73,7 +73,7 @@ public class ChildProcess2ImplTest {
when(processApi.waitFor(anyLong(), any())).thenReturn(true);
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
@@ -86,7 +86,7 @@ public class ChildProcess2ImplTest {
}
@Test
- public void testMaxOutputBytes() throws Exception {
+ void testMaxOutputBytes() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -103,7 +103,7 @@ public class ChildProcess2ImplTest {
Files.write(temporaryFile, "1234567890123".getBytes(StandardCharsets.UTF_8));
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
@@ -116,7 +116,7 @@ public class ChildProcess2ImplTest {
}
@Test
- public void testUnkillable() throws Exception {
+ void testUnkillable() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -133,7 +133,7 @@ public class ChildProcess2ImplTest {
Files.write(temporaryFile, "1234567890123".getBytes(StandardCharsets.UTF_8));
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
index e434274aacc..872a730c342 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
@@ -2,31 +2,28 @@
package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class CommandLineTest {
private final TestTerminal terminal = new TestTerminal();
private final TestTaskContext context = new TestTaskContext();
private final CommandLine commandLine = terminal.newCommandLine(context);
- @After
+ @AfterEach
public void tearDown() {
terminal.verifyAllCommandsExecuted();
}
@Test
- public void testStrings() {
+ void testStrings() {
terminal.expectCommand(
"/bin/bash \"with space\" \"speci&l\" \"\" \"double\\\"quote\" 2>&1",
0,
@@ -36,7 +33,7 @@ public class CommandLineTest {
}
@Test
- public void testBasicExecute() {
+ void testBasicExecute() {
terminal.expectCommand("foo bar 2>&1", 0, "line1\nline2\n\n");
CommandResult result = commandLine.add("foo", "bar").execute();
assertEquals(0, result.getExitCode());
@@ -48,14 +45,14 @@ public class CommandLineTest {
List<CommandLine> commandLines = terminal.getTestProcessFactory().getMutableCommandLines();
assertEquals(1, commandLines.size());
- assertTrue(commandLine == commandLines.get(0));
+ assertEquals(commandLine, commandLines.get(0));
int lines = result.map(r -> r.getOutputLines().size());
assertEquals(2, lines);
}
@Test
- public void verifyDefaults() {
+ void verifyDefaults() {
assertEquals(CommandLine.DEFAULT_TIMEOUT, commandLine.getTimeout());
assertEquals(CommandLine.DEFAULT_MAX_OUTPUT_BYTES, commandLine.getMaxOutputBytes());
assertEquals(CommandLine.DEFAULT_SIGTERM_GRACE_PERIOD, commandLine.getSigTermGracePeriod());
@@ -70,7 +67,7 @@ public class CommandLineTest {
}
@Test
- public void executeSilently() {
+ void executeSilently() {
terminal.ignoreCommand("");
commandLine.add("foo", "bar").executeSilently();
assertEquals(0, context.getSystemModificationLog().size());
@@ -79,16 +76,20 @@ public class CommandLineTest {
assertEquals("Executed command: foo bar 2>&1", context.getSystemModificationLog().get(0));
}
- @Test(expected = NegativeArraySizeException.class)
- public void processFactorySpawnFails() {
- terminal.interceptCommand(
- commandLine.toString(),
- command -> { throw new NegativeArraySizeException(); });
- commandLine.add("foo").execute();
+ @Test
+ void processFactorySpawnFails() {
+ assertThrows(NegativeArraySizeException.class, () -> {
+ terminal.interceptCommand(
+ commandLine.toString(),
+ command -> {
+ throw new NegativeArraySizeException();
+ });
+ commandLine.add("foo").execute();
+ });
}
@Test
- public void waitingForTerminationExceptionStillClosesChild() {
+ void waitingForTerminationExceptionStillClosesChild() {
TestChildProcess2 child = new TestChildProcess2(0, "");
child.throwInWaitForTermination(new NegativeArraySizeException());
terminal.interceptCommand(commandLine.toString(), command -> child);
@@ -104,7 +105,7 @@ public class CommandLineTest {
}
@Test
- public void programFails() {
+ void programFails() {
terminal.expectCommand("foo 2>&1", 1, "");
try {
commandLine.add("foo").execute();
@@ -117,22 +118,24 @@ public class CommandLineTest {
}
@Test
- public void mapException() {
+ void mapException() {
terminal.ignoreCommand("output");
CommandResult result = terminal.newCommandLine(context).add("program").execute();
IllegalArgumentException exception = new IllegalArgumentException("foo");
try {
- result.mapOutput(output -> { throw exception; });
+ result.mapOutput(output -> {
+ throw exception;
+ });
fail();
} catch (UnexpectedOutputException e) {
assertEquals("Command 'program 2>&1' output was not of the expected format: " +
"Failed to map output: stdout/stderr: 'output'", e.getMessage());
- assertTrue(e.getCause() == exception);
+ assertEquals(e.getCause(), exception);
}
}
@Test
- public void testMapEachLine() {
+ void testMapEachLine() {
assertEquals(
1 + 2 + 3,
terminal.ignoreCommand("1\n2\n3\n")
@@ -146,7 +149,7 @@ public class CommandLineTest {
}
@Test
- public void addTokensWithMultipleWhiteSpaces() {
+ void addTokensWithMultipleWhiteSpaces() {
terminal.expectCommand("iptables -L 2>&1");
commandLine.addTokens("iptables -L").execute();
@@ -154,7 +157,7 @@ public class CommandLineTest {
}
@Test
- public void addTokensWithSpecialCharacters() {
+ void addTokensWithSpecialCharacters() {
terminal.expectCommand("find . ! -name hei 2>&1");
commandLine.addTokens("find . ! -name hei").execute();
@@ -162,7 +165,7 @@ public class CommandLineTest {
}
@Test
- public void testEnvironment() {
+ void testEnvironment() {
terminal.expectCommand("env k1=v1 -u k2 \"key 3=value 3\" programname 2>&1");
commandLine.add("programname")
.setEnvironmentVariable("key 3", "value 3")
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
index 722abe1f7bd..ebf5f45f51e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.jdisc.test.TestTimer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.Files;
@@ -16,9 +16,7 @@ import java.util.Optional;
import java.util.Set;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -29,7 +27,7 @@ public class ProcessFactoryImplTest {
private final ProcessFactoryImpl processFactory = new ProcessFactoryImpl(starter, timer);
@Test
- public void testSpawn() {
+ void testSpawn() {
CommandLine commandLine = mock(CommandLine.class);
when(commandLine.getArguments()).thenReturn(List.of("program"));
when(commandLine.getRedirectStderrToStdoutInsteadOfDiscard()).thenReturn(true);
@@ -53,17 +51,22 @@ public class ProcessFactoryImplTest {
}
@Test
- public void testSpawnWithPersistentOutputFile() {
+ void testSpawnWithPersistentOutputFile() {
class TemporaryFile implements AutoCloseable {
private final Path path;
+
private TemporaryFile() {
String outputFileName = ProcessFactoryImplTest.class.getSimpleName() + "-temporary-test-file.out";
FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString("rw-------"));
path = uncheck(() -> Files.createTempFile(outputFileName, ".out", fileAttribute));
}
- @Override public void close() { uncheck(() -> Files.deleteIfExists(path)); }
+
+ @Override
+ public void close() {
+ uncheck(() -> Files.deleteIfExists(path));
+ }
}
try (TemporaryFile outputPath = new TemporaryFile()) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
index eea6c744bab..8eb1fca9210 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
@@ -4,11 +4,9 @@ package com.yahoo.vespa.hosted.node.admin.task.util.systemd;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.ChildProcessFailureException;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
/**
@@ -20,18 +18,18 @@ public class SystemCtlTest {
private final TestTerminal terminal = new TestTerminal();
@Test
- public void enable() {
+ void enable() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "")
.expectCommand("systemctl enable docker 2>&1")
.expectCommand("systemctl --quiet is-enabled docker 2>&1");
SystemCtl.SystemCtlEnable enableDockerService = new SystemCtl(terminal).enable("docker");
assertTrue(enableDockerService.converge(taskContext));
- assertFalse("Already converged", enableDockerService.converge(taskContext));
+ assertFalse(enableDockerService.converge(taskContext), "Already converged");
}
@Test
- public void enableCommandFailure() {
+ void enableCommandFailure() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "")
.expectCommand("systemctl enable docker 2>&1", 1, "error enabling service");
SystemCtl.SystemCtlEnable enableDockerService = new SystemCtl(terminal).enable("docker");
@@ -45,13 +43,13 @@ public class SystemCtlTest {
@Test
- public void start() {
+ void start() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=failed\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=failed\n" +
+ "bar=zoo\n")
.expectCommand("systemctl start docker 2>&1", 0, "");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
@@ -59,13 +57,13 @@ public class SystemCtlTest {
}
@Test
- public void startIsNoop() {
+ void startIsNoop() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=active\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=active\n" +
+ "bar=zoo\n")
.expectCommand("systemctl start docker 2>&1", 0, "");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
@@ -74,7 +72,7 @@ public class SystemCtlTest {
@Test
- public void startCommandFailre() {
+ void startCommandFailre() {
terminal.expectCommand("systemctl show docker 2>&1", 1, "error");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
try {
@@ -87,36 +85,36 @@ public class SystemCtlTest {
@Test
- public void disable() {
+ void disable() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1")
.expectCommand("systemctl disable docker 2>&1")
.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "");
assertTrue(new SystemCtl(terminal).disable("docker").converge(taskContext));
- assertFalse("Already converged", new SystemCtl(terminal).disable("docker").converge(taskContext));
+ assertFalse(new SystemCtl(terminal).disable("docker").converge(taskContext), "Already converged");
}
@Test
- public void stop() {
+ void stop() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=active\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=active\n" +
+ "bar=zoo\n")
.expectCommand("systemctl stop docker 2>&1", 0, "");
assertTrue(new SystemCtl(terminal).stop("docker").converge(taskContext));
}
@Test
- public void restart() {
+ void restart() {
terminal.expectCommand("systemctl restart docker 2>&1", 0, "");
assertTrue(new SystemCtl(terminal).restart("docker").converge(taskContext));
}
@Test
- public void testUnitExists() {
+ void testUnitExists() {
SystemCtl systemCtl = new SystemCtl(terminal);
terminal.expectCommand("systemctl list-unit-files foo.service 2>&1", 0,
@@ -142,7 +140,7 @@ public class SystemCtlTest {
}
@Test
- public void withSudo() {
+ void withSudo() {
SystemCtl systemCtl = new SystemCtl(terminal).withSudo();
terminal.expectCommand("sudo systemctl restart docker 2>&1", 0, "");
assertTrue(systemCtl.restart("docker").converge(taskContext));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
index 7b18f741941..bbdb707c294 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.systemd;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -21,7 +21,7 @@ public class SystemCtlTesterTest {
private final TestTaskContext context = new TestTaskContext();
@Test
- public void return_expectations() {
+ void return_expectations() {
assertSystemCtlMethod(sct -> sct.expectEnable(unit), sc -> sc.enable(unit).converge(context));
assertSystemCtlMethod(sct -> sct.expectDisable(unit), sc -> sc.disable(unit).converge(context));
assertSystemCtlMethod(sct -> sct.expectStart(unit), sc -> sc.start(unit).converge(context));
@@ -31,7 +31,7 @@ public class SystemCtlTesterTest {
}
@Test
- public void void_tests() {
+ void void_tests() {
systemCtl.expectRestart(unit);
systemCtl.restart(unit).converge(context);
terminal.verifyAllCommandsExecuted();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
index 0ff98e2b5fe..d32447d9052 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.yum;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -16,7 +13,7 @@ import static org.junit.Assert.fail;
public class YumPackageNameTest {
@Test
- public void testBuilder() {
+ void testBuilder() {
YumPackageName yumPackage = new YumPackageName.Builder("docker")
.setEpoch("2")
.setVersion("1.12.6")
@@ -27,7 +24,7 @@ public class YumPackageNameTest {
}
@Test
- public void testAllValidFormats() {
+ void testAllValidFormats() {
// name
verifyPackageName(
"docker-engine-selinux",
@@ -63,13 +60,13 @@ public class YumPackageNameTest {
// name-ver
verifyPackageName("docker-engine-selinux-1.12.6",
- null,
- "docker-engine-selinux",
- "1.12.6",
- null,
- null,
- "docker-engine-selinux-0:1.12.6",
- null);
+ null,
+ "docker-engine-selinux",
+ "1.12.6",
+ null,
+ null,
+ "docker-engine-selinux-0:1.12.6",
+ null);
// name-ver-rel
verifyPackageName("docker-engine-selinux-1.12.6-1.el7",
@@ -135,9 +132,9 @@ public class YumPackageNameTest {
yumPackageName.toVersionLockName();
fail();
} catch (IllegalStateException e) {
- assertTrue("Exception message contains expected substring: " + e.getMessage(),
- e.getMessage().contains("Version is missing ") ||
- e.getMessage().contains("Release is missing "));
+ assertTrue(e.getMessage().contains("Version is missing ") ||
+ e.getMessage().contains("Release is missing "),
+ "Exception message contains expected substring: " + e.getMessage());
}
} else {
assertEquals(toVersionName, yumPackageName.toVersionLockName());
@@ -146,28 +143,28 @@ public class YumPackageNameTest {
private void assertPackageField(String field, String expected, Optional<String> actual) {
if (expected == null) {
- assertFalse(field + " is not present", actual.isPresent());
+ assertFalse(actual.isPresent(), field + " is not present");
} else {
- assertEquals(field + " has expected value", expected, actual.get());
+ assertEquals(expected, actual.get(), field + " has expected value");
}
}
@Test
- public void testArchitectures() {
+ void testArchitectures() {
assertEquals("x86_64", YumPackageName.fromString("docker.x86_64").getArchitecture().get());
assertEquals("i686", YumPackageName.fromString("docker.i686").getArchitecture().get());
assertEquals("noarch", YumPackageName.fromString("docker.noarch").getArchitecture().get());
}
@Test
- public void unrecognizedArchitectureGetsGobbledUp() {
+ void unrecognizedArchitectureGetsGobbledUp() {
YumPackageName packageName = YumPackageName.fromString("docker-engine-selinux-1.12.6-1.el7.i486");
// This is not a great feature - please use YumPackageName.Builder instead.
assertEquals("1.el7.i486", packageName.getRelease().get());
}
@Test
- public void failParsingOfPackageNameWithEpochAndArchitecture() {
+ void failParsingOfPackageNameWithEpochAndArchitecture() {
try {
YumPackageName.fromString("epoch:docker-engine-selinux-1.12.6-1.el7.x86_64");
fail();
@@ -177,7 +174,7 @@ public class YumPackageNameTest {
}
@Test
- public void testSubset() {
+ void testSubset() {
YumPackageName yumPackage = new YumPackageName.Builder("docker")
.setVersion("1.12.6")
.build();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
index 3376ba70500..8c9e36abb32 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
@@ -4,16 +4,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.ChildProcessFailureException;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
/**
@@ -25,13 +21,13 @@ public class YumTest {
private final TestTerminal terminal = new TestTerminal();
private final Yum yum = new Yum(terminal);
- @After
+ @AfterEach
public void after() {
terminal.verifyAllCommandsExecuted();
}
@Test
- public void testQueryInstalled() {
+ void testQueryInstalled() {
terminal.expectCommand(
"rpm -q docker --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
@@ -48,7 +44,7 @@ public class YumTest {
}
@Test
- public void testQueryInstalledPartial() {
+ void testQueryInstalledPartial() {
terminal.expectCommand(
"rpm -q vespa-node-admin --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
@@ -65,7 +61,7 @@ public class YumTest {
}
@Test
- public void testQueryNotInstalled() {
+ void testQueryNotInstalled() {
terminal.expectCommand(
"rpm -q fake-package --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
1,
@@ -77,20 +73,20 @@ public class YumTest {
}
@Test
- public void testQueryInstalledMultiplePackages() {
+ void testQueryInstalledMultiplePackages() {
terminal.expectCommand(
"rpm -q kernel-devel --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
"kernel-devel\n" +
- "(none)\n" +
- "4.18.0\n" +
- "305.7.1.el8_4\n" +
- "x86_64\n" +
- "kernel-devel\n" +
- "(none)\n" +
- "4.18.0\n" +
- "240.15.1.el8_3\n" +
- "x86_64\n");
+ "(none)\n" +
+ "4.18.0\n" +
+ "305.7.1.el8_4\n" +
+ "x86_64\n" +
+ "kernel-devel\n" +
+ "(none)\n" +
+ "4.18.0\n" +
+ "240.15.1.el8_3\n" +
+ "x86_64\n");
try {
yum.queryInstalled(taskContext, "kernel-devel");
fail("Expected exception");
@@ -100,30 +96,30 @@ public class YumTest {
}
@Test
- public void testAlreadyInstalled() {
+ void testAlreadyInstalled() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --enablerepo=repo1 --enablerepo=repo2 --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
0,
"foobar\nNothing to do.\n"); // Note trailing dot
assertFalse(yum.install("package-1", "package-2")
- .enableRepo("repo1", "repo2")
- .converge(taskContext));
+ .enableRepo("repo1", "repo2")
+ .converge(taskContext));
}
@Test
- public void testAlreadyUpgraded() {
+ void testAlreadyUpgraded() {
terminal.expectCommand(
"yum upgrade --assumeyes --setopt skip_missing_names_on_update=False package-1 package-2 2>&1",
0,
"foobar\nNothing to do.\n"); // Same message as yum install no-op
assertFalse(yum.upgrade("package-1", "package-2")
- .converge(taskContext));
+ .converge(taskContext));
}
@Test
- public void testAlreadyRemoved() {
+ void testAlreadyRemoved() {
mockRpmQuery("package-1", YumPackageName.fromString("package-1-1.2.3-1"));
terminal.expectCommand(
"yum remove --assumeyes package-1 package-2 2>&1",
@@ -131,18 +127,18 @@ public class YumTest {
"foobar\nNo packages marked for removal.\n"); // Different output
assertFalse(yum.remove("package-1", "package-2")
- .converge(taskContext));
+ .converge(taskContext));
}
@Test
- public void skipsYumRemoveNotInRpm() {
+ void skipsYumRemoveNotInRpm() {
mockRpmQuery("package-1", null);
mockRpmQuery("package-2", null);
assertFalse(yum.remove("package-1", "package-2").converge(taskContext));
}
@Test
- public void testInstall() {
+ void testInstall() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
@@ -155,14 +151,14 @@ public class YumTest {
}
@Test
- public void skipsYumInstallIfInRpm() {
+ void skipsYumInstallIfInRpm() {
mockRpmQuery("package-1-0:1.2.3-1", YumPackageName.fromString("package-1-1.2.3-1"));
mockRpmQuery("package-2", YumPackageName.fromString("1:package-2-1.2.3-1.el7.x86_64"));
assertFalse(yum.install("package-1-1.2.3-1", "package-2").converge(taskContext));
}
@Test
- public void testInstallWithEnablerepo() {
+ void testInstallWithEnablerepo() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
@@ -176,10 +172,10 @@ public class YumTest {
}
@Test
- public void testWithVersionLock() {
+ void testWithVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
- 0,
- "Last metadata expiration check: 0:51:26 ago on Thu 14 Jan 2021 09:39:24 AM UTC.\n");
+ 0,
+ "Last metadata expiration check: 0:51:26 ago on Thu 14 Jan 2021 09:39:24 AM UTC.\n");
terminal.expectCommand("yum versionlock add --assumeyes \"openssh-0:8.0p1-4.el8_1.*\" 2>&1");
terminal.expectCommand(
"yum install --assumeyes openssh-0:8.0p1-4.el8_1.x86_64 2>&1",
@@ -196,7 +192,7 @@ public class YumTest {
}
@Test
- public void testWithDifferentVersionLock() {
+ void testWithDifferentVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -220,7 +216,7 @@ public class YumTest {
}
@Test
- public void testWithExistingVersionLock() {
+ void testWithExistingVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -235,7 +231,7 @@ public class YumTest {
}
@Test
- public void testWithDowngrade() {
+ void testWithDowngrade() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -253,23 +249,25 @@ public class YumTest {
assertTrue(yum.installFixedVersion(YumPackageName.fromString("package-0:0.10-654.el7")).converge(taskContext));
}
- @Test(expected = ChildProcessFailureException.class)
- public void testFailedInstall() {
- mockRpmQuery("package-1", null);
- terminal.expectCommand(
- "yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
- 1,
- "error");
-
- yum
- .install("package-1", "package-2")
- .enableRepo("repo-name")
- .converge(taskContext);
- fail();
+ @Test
+ void testFailedInstall() {
+ assertThrows(ChildProcessFailureException.class, () -> {
+ mockRpmQuery("package-1", null);
+ terminal.expectCommand(
+ "yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
+ 1,
+ "error");
+
+ yum
+ .install("package-1", "package-2")
+ .enableRepo("repo-name")
+ .converge(taskContext);
+ fail();
+ });
}
@Test
- public void testUnknownPackages() {
+ void testUnknownPackages() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --setopt skip_missing_names_on_install=False package-1 package-2 package-3 2>&1",
@@ -290,19 +288,21 @@ public class YumTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void throwIfNoPackagesSpecified() {
- yum.install();
+ @Test
+ void throwIfNoPackagesSpecified() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ yum.install();
+ });
}
@Test
- public void allowToCallUpgradeWithNoPackages() {
+ void allowToCallUpgradeWithNoPackages() {
terminal.expectCommand("yum upgrade --assumeyes 2>&1", 0, "OK");
yum.upgrade().converge(taskContext);
}
@Test
- public void testDeleteVersionLock() {
+ void testDeleteVersionLock() {
terminal.expectCommand("yum versionlock delete openssh-0:8.0p1-4.el8_1.x86_64 2>&1");
YumPackageName pkg = new YumPackageName
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
index f5cb188d07a..59c138b51df 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -26,7 +26,7 @@ public class YumTesterTest {
private final TestTaskContext context = new TestTaskContext();
@Test
- public void generic_yum_methods() {
+ void generic_yum_methods() {
assertYumMethod(yum -> yum.expectInstall(packages).withEnableRepo(repos),
yum -> yum.install(List.of(packages)).enableRepo(repos).converge(context));
@@ -41,12 +41,12 @@ public class YumTesterTest {
// versionlock always returns success
assertYumMethodAlwaysSuccess(yum -> yum.expectDeleteVersionLock(minimalPackage.toName()),
- yum -> yum.deleteVersionLock(minimalPackage).converge(context));
+ yum -> yum.deleteVersionLock(minimalPackage).converge(context));
}
@Test
- public void expect_query_installed() {
+ void expect_query_installed() {
yum.expectQueryInstalled(packages[0]).andReturn(fullPackage);
assertEquals(Optional.of(fullPackage), yum.queryInstalled(context, packages[0]));
terminal.verifyAllCommandsExecuted();
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodeRepoStats.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodeRepoStats.java
index 085b89d1253..1460ce70686 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodeRepoStats.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/NodeRepoStats.java
@@ -26,16 +26,23 @@ import java.util.Set;
*/
public class NodeRepoStats {
+ private final double totalCost;
+ private final double totalAllocatedCost;
private final Load load;
private final Load activeLoad;
private final List<ApplicationStats> applicationStats;
- private NodeRepoStats(Load load, Load activeLoad, List<ApplicationStats> applicationStats) {
+ private NodeRepoStats(double totalCost, double totalAllocatedCost, Load load, Load activeLoad, List<ApplicationStats> applicationStats) {
+ this.totalCost = totalCost;
+ this.totalAllocatedCost = totalAllocatedCost;
this.load = load;
this.activeLoad = activeLoad;
this.applicationStats = List.copyOf(applicationStats);
}
+ public double totalCost() { return totalCost; }
+ public double totalAllocatedCost() { return totalAllocatedCost; }
+
/**
* Returns the current average work-extracting utilization in this node repo over all nodes.
* Capacity not allocated to active nodes are taken to have 0 utilization as it provides no useful work.
@@ -50,11 +57,15 @@ public class NodeRepoStats {
public static NodeRepoStats computeOver(NodeRepository nodeRepository) {
NodeList allNodes = nodeRepository.nodes().list();
- List<NodeTimeseries> allNodeTimeseries = nodeRepository.metricsDb().getNodeTimeseries(Duration.ofHours(1), Set.of());
+ double totalCost = allNodes.hosts().stream().mapToDouble(host -> host.resources().cost()).sum();
+ double totalAllocatedCost = allNodes.not().hosts().stream()
+ .filter(node -> node.allocation().isPresent())
+ .mapToDouble(node -> node.resources().cost()).sum();
+ List<NodeTimeseries> allNodeTimeseries = nodeRepository.metricsDb().getNodeTimeseries(Duration.ofHours(1), Set.of());
Pair<Load, Load> load = computeLoad(allNodes, allNodeTimeseries);
List<ApplicationStats> applicationStats = computeApplicationStats(allNodes, allNodeTimeseries);
- return new NodeRepoStats(load.getFirst(), load.getSecond(), applicationStats);
+ return new NodeRepoStats(totalCost, totalAllocatedCost, load.getFirst(), load.getSecond(), applicationStats);
}
private static Pair<Load, Load> computeLoad(NodeList allNodes, List<NodeTimeseries> allNodeTimeseries) {
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocatableClusterResources.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocatableClusterResources.java
index 88a4b492a0b..4a1545cc66c 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocatableClusterResources.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocatableClusterResources.java
@@ -64,6 +64,33 @@ public class AllocatableClusterResources {
this.fulfilment = fulfilment(realResources, idealResources);
}
+ private AllocatableClusterResources(int nodes,
+ int groups,
+ NodeResources realResources,
+ NodeResources advertisedResources,
+ ClusterSpec clusterSpec,
+ double fulfilment) {
+ this.nodes = nodes;
+ this.groups = groups;
+ this.realResources = realResources;
+ this.advertisedResources = advertisedResources;
+ this.clusterSpec = clusterSpec;
+ this.fulfilment = fulfilment;
+ }
+
+ /** Returns this with the redundant node or group removed from counts. */
+ public AllocatableClusterResources withoutRedundancy() {
+ int groupSize = nodes / groups;
+ int nodesAdjustedForRedundancy = nodes > 1 ? (groups == 1 ? nodes - 1 : nodes - groupSize) : nodes;
+ int groupsAdjustedForRedundancy = nodes > 1 ? (groups == 1 ? 1 : groups - 1) : groups;
+ return new AllocatableClusterResources(nodesAdjustedForRedundancy,
+ groupsAdjustedForRedundancy,
+ realResources,
+ advertisedResources,
+ clusterSpec,
+ fulfilment);
+ }
+
/**
* Returns the resources which will actually be available per node in this cluster with this allocation.
* These should be used for reasoning about allocation to meet measured demand.
@@ -83,11 +110,6 @@ public class AllocatableClusterResources {
public int nodes() { return nodes; }
public int groups() { return groups; }
- public int groupSize() {
- // ceil: If the division does not produce a whole number we assume some node is missing
- return (int)Math.ceil((double)nodes / groups);
- }
-
public ClusterSpec clusterSpec() { return clusterSpec; }
public double cost() { return nodes * advertisedResources.cost(); }
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocationOptimizer.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocationOptimizer.java
index 41fa9499353..2befd69f893 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocationOptimizer.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/AllocationOptimizer.java
@@ -2,7 +2,6 @@
package com.yahoo.vespa.hosted.provision.autoscale;
import com.yahoo.config.provision.ClusterResources;
-import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
@@ -20,11 +19,6 @@ public class AllocationOptimizer {
private static final int minimumNodes = 2; // Since this number includes redundancy it cannot be lower than 2
private static final int maximumNodes = 150;
- // When a query is issued on a node the cost is the sum of a fixed cost component and a cost component
- // proportional to document count. We must account for this when comparing configurations with more or fewer nodes.
- // TODO: Measure this, and only take it into account with queries
- private static final double fixedCpuCostFraction = 0.1;
-
private final NodeRepository nodeRepository;
public AllocationOptimizer(NodeRepository nodeRepository) {
@@ -32,13 +26,13 @@ public class AllocationOptimizer {
}
/**
- * Searches the space of possible allocations given a target
+ * Searches the space of possible allocations given a target relative load
* and (optionally) cluster limits and returns the best alternative.
*
* @return the best allocation, if there are any possible legal allocations, fulfilling the target
* fully or partially, within the limits
*/
- public Optional<AllocatableClusterResources> findBestAllocation(ResourceTarget target,
+ public Optional<AllocatableClusterResources> findBestAllocation(Load targetLoad,
AllocatableClusterResources current,
ClusterModel clusterModel,
Limits limits) {
@@ -53,18 +47,11 @@ public class AllocationOptimizer {
for (int groups = limits.min().groups(); groups <= limits.max().groups(); groups++) {
for (int nodes = limits.min().nodes(); nodes <= limits.max().nodes(); nodes++) {
if (nodes % groups != 0) continue;
- int groupSize = nodes / groups;
-
- // Adjust for redundancy: Node in group if groups = 1, an extra group if multiple groups
- // TODO: Make the best choice based on size and redundancy setting instead
- int nodesAdjustedForRedundancy = target.adjustForRedundancy() ? (groups == 1 ? nodes - 1 : nodes - groupSize) : nodes;
- int groupsAdjustedForRedundancy = target.adjustForRedundancy() ? (groups == 1 ? 1 : groups - 1) : groups;
ClusterResources next = new ClusterResources(nodes,
groups,
- nodeResourcesWith(nodesAdjustedForRedundancy,
- groupsAdjustedForRedundancy,
- limits, target, current, clusterModel));
+ nodeResourcesWith(nodes, groups,
+ limits, targetLoad, current, clusterModel));
var allocatableResources = AllocatableClusterResources.from(next, current.clusterSpec(), limits,
hosts, nodeRepository);
if (allocatableResources.isEmpty()) continue;
@@ -77,42 +64,25 @@ public class AllocationOptimizer {
/**
* For the observed load this instance is initialized with, returns the resources needed per node to be at
- * ideal load given a target node count
+ * the target relative load, given a target node and group count.
*/
private NodeResources nodeResourcesWith(int nodes,
int groups,
Limits limits,
- ResourceTarget target,
+ Load targetLoad,
AllocatableClusterResources current,
ClusterModel clusterModel) {
- double cpu, memory, disk;
- int groupSize = nodes / groups;
-
- if (current.clusterSpec().type() == ClusterSpec.Type.content) { // load scales with node share of content
- // Cpu: Query cpu scales with cluster size, write cpu scales with group size
- // Memory and disk: Scales with group size
-
- // The fixed cost portion of cpu does not scale with changes to the node count
- double queryCpuPerGroup = fixedCpuCostFraction * target.resources().vcpu() +
- (1 - fixedCpuCostFraction) * target.resources().vcpu() * current.groupSize() / groupSize;
- double queryCpu = queryCpuPerGroup * current.groups() / groups;
- double writeCpu = target.resources().vcpu() * current.groupSize() / groupSize;
- cpu = clusterModel.queryCpuFraction() * queryCpu + (1 - clusterModel.queryCpuFraction()) * writeCpu;
- memory = target.resources().memoryGb() * current.groupSize() / groupSize;
- disk = target.resources().diskGb() * current.groupSize() / groupSize;
- }
- else {
- cpu = target.resources().vcpu() * current.nodes() / nodes;
- memory = target.resources().memoryGb();
- disk = target.resources().diskGb();
- }
+ var scaled = targetLoad // redundancy aware target relative to current load
+ .multiply(clusterModel.loadWith(nodes, groups)) // redundancy aware adjustment with these counts
+ .divide(clusterModel.redundancyAdjustment()) // correct for double redundancy adjustment
+ .scaled(current.realResources().nodeResources());
// Combine the scaled resource values computed here
// with the currently configured non-scaled values, given in the limits, if any
- NodeResources nonScaled = limits.isEmpty() || limits.min().nodeResources().isUnspecified()
- ? current.advertisedResources().nodeResources()
- : limits.min().nodeResources(); // min=max for non-scaled
- return nonScaled.withVcpu(cpu).withMemoryGb(memory).withDiskGb(disk);
+ var nonScaled = limits.isEmpty() || limits.min().nodeResources().isUnspecified()
+ ? current.advertisedResources().nodeResources()
+ : limits.min().nodeResources(); // min=max for non-scaled
+ return nonScaled.withVcpu(scaled.vcpu()).withMemoryGb(scaled.memoryGb()).withDiskGb(scaled.diskGb());
}
/** Returns a copy of the given limits where the minimum nodes are at least the given value when allowed */
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Autoscaler.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Autoscaler.java
index c2e66d39861..7a02fa9eb7e 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Autoscaler.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Autoscaler.java
@@ -26,7 +26,7 @@ public class Autoscaler {
/** What cost difference is worth a reallocation? */
private static final double costDifferenceWorthReallocation = 0.1;
/** What resource difference is worth a reallocation? */
- private static final double resourceDifferenceWorthReallocation = 0.1;
+ private static final double resourceDifferenceWorthReallocation = 0.03;
private final NodeRepository nodeRepository;
private final AllocationOptimizer allocationOptimizer;
@@ -61,8 +61,8 @@ public class Autoscaler {
private Advice autoscale(Application application, Cluster cluster, NodeList clusterNodes, Limits limits) {
ClusterModel clusterModel = new ClusterModel(application,
- cluster,
clusterNodes.clusterSpec(),
+ cluster,
clusterNodes,
nodeRepository.metricsDb(),
nodeRepository.clock());
@@ -89,10 +89,8 @@ public class Autoscaler {
" nodes, but require from " + clusterNodes.size());
var currentAllocation = new AllocatableClusterResources(clusterNodes.asList(), nodeRepository);
- var target = ResourceTarget.idealLoad(clusterModel, currentAllocation);
-
Optional<AllocatableClusterResources> bestAllocation =
- allocationOptimizer.findBestAllocation(target, currentAllocation, clusterModel, limits);
+ allocationOptimizer.findBestAllocation(clusterModel.loadAdjustment(), currentAllocation, clusterModel, limits);
if (bestAllocation.isEmpty())
return Advice.dontScale(Status.insufficient, "No allocations are possible within configured limits");
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModel.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModel.java
index b7a5c1e7fe7..ae18e7ffb91 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModel.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModel.java
@@ -27,14 +27,17 @@ public class ClusterModel {
/** Containers typically use more cpu right after generation change, so discard those metrics */
public static final Duration warmupDuration = Duration.ofMinutes(5);
- private static final Duration currentLoadDuration = Duration.ofMinutes(5);
-
static final double idealQueryCpuLoad = 0.8;
static final double idealWriteCpuLoad = 0.95;
static final double idealMemoryLoad = 0.65;
static final double idealContainerDiskLoad = 0.95;
static final double idealContentDiskLoad = 0.6;
+ // When a query is issued on a node the cost is the sum of a fixed cost component and a cost component
+ // proportional to document count. We must account for this when comparing configurations with more or fewer nodes.
+ // TODO: Measure this, and only take it into account with queries
+ private static final double fixedCpuCostFraction = 0.1;
+
private final Application application;
private final ClusterSpec clusterSpec;
private final Cluster cluster;
@@ -50,8 +53,8 @@ public class ClusterModel {
private Double maxQueryGrowthRate = null;
public ClusterModel(Application application,
- Cluster cluster,
ClusterSpec clusterSpec,
+ Cluster cluster,
NodeList clusterNodes,
MetricsDb metricsDb,
Clock clock) {
@@ -76,7 +79,7 @@ public class ClusterModel {
this.application = application;
this.clusterSpec = clusterSpec;
this.cluster = cluster;
- this.nodes = null;
+ this.nodes = NodeList.of();
this.clock = clock;
this.scalingDuration = scalingDuration;
@@ -88,6 +91,20 @@ public class ClusterModel {
public ClusterSpec clusterSpec() { return clusterSpec; }
public Cluster cluster() { return cluster; }
+ /** Returns the relative load adjustment that should be made to this cluster given available measurements. */
+ public Load loadAdjustment() {
+ if (nodeTimeseries().measurementsPerNode() == 0) return Load.one(); // No info, no change
+ /*
+ // Should we scale up?
+ Load relativePeak = nodeTimeseries().peakLoad().divide(idealLoad());
+ if (relativePeak.any(v -> v > 1))
+ return relativePeak.max(Load.one()); // Don't downscale any dimension if we upscale
+
+ // Should we scale down?
+ */
+ return averageLoad().divide(idealLoad());
+ }
+
/** Returns the predicted duration of a rescaling of this cluster */
public Duration scalingDuration() { return scalingDuration; }
@@ -110,14 +127,78 @@ public class ClusterModel {
return queryFractionOfMax = clusterTimeseries().queryFractionOfMax(scalingDuration(), clock);
}
- /** Returns average load during the last {@link #currentLoadDuration} */
- public Load currentLoad() { return nodeTimeseries().averageLoad(clock.instant().minus(currentLoadDuration)); }
+ /** Returns average of the last load reading from each node. */
+ public Load currentLoad() { return nodeTimeseries().currentLoad(); }
/** Returns average load during the last {@link #scalingDuration()} */
public Load averageLoad() { return nodeTimeseries().averageLoad(clock.instant().minus(scalingDuration())); }
+ /** The number of nodes this cluster has, or will have if not deployed yet. */
+ // TODO: Make this the deployed, not current count
+ public int nodeCount() {
+ if ( ! nodes.isEmpty()) return (int)nodes.stream().count();
+ return cluster.minResources().nodes();
+ }
+
+ /** The number of groups this cluster has, or will have if not deployed yet. */
+ // TODO: Make this the deployed, not current count
+ public int groupCount() {
+ if ( ! nodes.isEmpty()) return (int)nodes.stream().mapToInt(node -> node.allocation().get().membership().cluster().group().get().index()).distinct().count();
+ return cluster.minResources().groups();
+ }
+
+ public int groupSize() {
+ // ceil: If the division does not produce a whole number we assume some node is missing
+ return (int)Math.ceil((double)nodeCount() / groupCount());
+ }
+
+ /** Returns the relative load adjustment accounting for redundancy in this. */
+ public Load redundancyAdjustment() {
+ return loadWith(nodeCount(), groupCount());
+ }
+
+ /**
+ * Returns the relative load adjustment accounting for redundancy given these nodes+groups
+ * relative to node nodes+groups in this.
+ */
+ public Load loadWith(int trueNodes, int trueGroups) {
+ int nodes = nodesAdjustedForRedundancy(trueNodes, trueGroups);
+ int groups = groupsAdjustedForRedundancy(trueNodes, trueGroups);
+ if (clusterSpec().type() == ClusterSpec.Type.content) { // load scales with node share of content
+ int groupSize = nodes / groups;
+
+ // Cpu: Query cpu scales with cluster size, write cpu scales with group size
+ // Memory and disk: Scales with group size
+
+ // The fixed cost portion of cpu does not scale with changes to the node count
+ double queryCpuPerGroup = fixedCpuCostFraction + (1 - fixedCpuCostFraction) * groupSize() / groupSize;
+
+ double queryCpu = queryCpuPerGroup * groupCount() / groups;
+ double writeCpu = (double)groupSize() / groupSize;
+ return new Load(queryCpuFraction() * queryCpu + (1 - queryCpuFraction()) * writeCpu,
+ (double)groupSize() / groupSize,
+ (double)groupSize() / groupSize);
+ }
+ else {
+ return new Load((double)nodeCount() / nodes, 1, 1);
+ }
+ }
+
+ /**
+ * Returns the ideal load across the nodes of this sich that each node will be at ideal load
+ * if one of the nodes go down.
+ */
public Load idealLoad() {
- return new Load(idealCpuLoad(), idealMemoryLoad, idealDiskLoad());
+ return new Load(idealCpuLoad(), idealMemoryLoad, idealDiskLoad()).divide(redundancyAdjustment());
+ }
+
+ public int nodesAdjustedForRedundancy(int nodes, int groups) {
+ int groupSize = (int)Math.ceil((double)nodes / groups);
+ return nodes > 1 ? (groups == 1 ? nodes - 1 : nodes - groupSize) : nodes;
+ }
+
+ public int groupsAdjustedForRedundancy(int nodes, int groups) {
+ return nodes > 1 ? (groups == 1 ? 1 : groups - 1) : groups;
}
/** Ideal cpu load must take the application traffic fraction into account */
@@ -171,7 +252,6 @@ public class ClusterModel {
// Assume we have missed timely recording completion if it is longer than 4 days
totalDuration = totalDuration.plus(maximum(Duration.ofDays(4), event.duration().get()));
}
-
if (completedEventCount == 0) { // Use defaults
if (clusterSpec.isStateful()) return Duration.ofHours(12);
return Duration.ofMinutes(10);
@@ -212,13 +292,13 @@ public class ClusterModel {
* as QuestDb is known to temporarily fail during reading of data.
*/
public static Optional<ClusterModel> create(Application application,
- Cluster cluster,
ClusterSpec clusterSpec,
+ Cluster cluster,
NodeList clusterNodes,
MetricsDb metricsDb,
Clock clock) {
try {
- return Optional.of(new ClusterModel(application, cluster, clusterSpec, clusterNodes, metricsDb, clock));
+ return Optional.of(new ClusterModel(application, clusterSpec, cluster, clusterNodes, metricsDb, clock));
}
catch (Exception e) {
log.log(Level.WARNING, "Failed creating a cluster model for " + application + " " + cluster, e);
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterNodesTimeseries.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterNodesTimeseries.java
index 5ad4ef2e263..ab5be045dd4 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterNodesTimeseries.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterNodesTimeseries.java
@@ -7,6 +7,8 @@ import com.yahoo.vespa.hosted.provision.applications.Cluster;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
+import java.util.Optional;
+import java.util.OptionalDouble;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -48,6 +50,7 @@ public class ClusterNodesTimeseries {
/** Returns the average number of measurements per node */
public int measurementsPerNode() {
+ if (clusterNodes.size() == 0) return 0;
int measurementCount = timeseries.stream().mapToInt(m -> m.size()).sum();
return measurementCount / clusterNodes.size();
}
@@ -69,6 +72,41 @@ public class ClusterNodesTimeseries {
return total.divide(count);
}
+ /** Returns average of the latest load reading from each node */
+ public Load currentLoad() {
+ Load total = Load.zero();
+ int count = 0;
+ for (var nodeTimeseries : timeseries) {
+ Optional<NodeMetricSnapshot> last = nodeTimeseries.last();
+ if (last.isEmpty()) continue;
+
+ total = total.add(last.get().load());
+ count++;
+ }
+ return total.divide(count);
+ }
+
+ /**
+ * Returns the "peak load" in this: Which is for each load dimension,
+ * the average of the highest reading for that dimension on each node.
+ */
+ public Load peakLoad() {
+ return new Load(peakLoad(Load.Dimension.cpu), peakLoad(Load.Dimension.memory), peakLoad(Load.Dimension.disk));
+ }
+
+ private double peakLoad(Load.Dimension dimension) {
+ double total = 0;
+ int count = 0;
+ for (var nodeTimeseries : timeseries) {
+ OptionalDouble value = nodeTimeseries.peak(dimension);
+ if (value.isEmpty()) continue;
+ total += value.getAsDouble();
+ count++;
+ }
+ if (count == 0) return 0;
+ return total / count;
+ }
+
private static List<NodeTimeseries> keep(List<NodeTimeseries> timeseries, Predicate<NodeMetricSnapshot> filter) {
return timeseries.stream().map(nodeTimeseries -> nodeTimeseries.keep(filter)).collect(Collectors.toList());
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Load.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Load.java
index a52b048a9e0..88c7e70cd35 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Load.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/Load.java
@@ -3,6 +3,12 @@ package com.yahoo.vespa.hosted.provision.autoscale;
import com.yahoo.config.provision.NodeResources;
+import java.util.Objects;
+import java.util.function.DoubleBinaryOperator;
+import java.util.function.DoubleFunction;
+import java.util.function.DoubleUnaryOperator;
+import java.util.function.Predicate;
+
/**
* The load of a node or system, measured as fractions of max (1.0) in three dimensions.
*
@@ -10,6 +16,8 @@ import com.yahoo.config.provision.NodeResources;
*/
public class Load {
+ public enum Dimension { cpu, memory, disk }
+
private final double cpu, memory, disk;
public Load(double cpu, double memory, double disk) {
@@ -23,27 +31,51 @@ public class Load {
public double disk() { return disk; }
public Load add(Load other) {
- return new Load(cpu + other.cpu(), memory + other.memory(), disk + other.disk());
+ return join(other, (a, b) -> a + b);
}
public Load multiply(NodeResources resources) {
return new Load(cpu * resources.vcpu(), memory * resources.memoryGb(), disk * resources.diskGb());
}
-
public Load multiply(double factor) {
- return new Load(cpu * factor, memory * factor, disk * factor);
+ return map(v -> v * factor);
+ }
+ public Load multiply(Load other) {
+ return join(other, (a, b) -> a * b);
}
+ public Load divide(Load divisor) {
+ return join(divisor, (a, b) -> divide(a, b));
+ }
+ public Load divide(double divisor) {
+ return map(v -> divide(v, divisor));
+ }
public Load divide(NodeResources resources) {
return new Load(divide(cpu, resources.vcpu()), divide(memory, resources.memoryGb()), divide(disk, resources.diskGb()));
}
- public Load divide(Load divisor) {
- return new Load(divide(cpu, divisor.cpu()), divide(memory, divisor.memory()), divide(disk, divisor.disk()));
+ /** Returns the load having the max value of this and the given load in each dimension. */
+ public Load max(Load other) {
+ return join(other, (a, b) -> Math.max(a, b));
}
- public Load divide(double divisor) {
- return new Load(divide(cpu, divisor), divide(memory, divisor), divide(disk, divisor));
+ /** Returns the load where the given function is applied to each dimension of this. */
+ public Load map(DoubleUnaryOperator f) {
+ return new Load(f.applyAsDouble(cpu),
+ f.applyAsDouble(memory),
+ f.applyAsDouble(disk));
+ }
+
+ /** Returns the load where the given function is applied to each dimension of this and the given load. */
+ public Load join(Load other, DoubleBinaryOperator f) {
+ return new Load(f.applyAsDouble(this.cpu(), other.cpu()),
+ f.applyAsDouble(this.memory(), other.memory()),
+ f.applyAsDouble(this.disk(), other.disk()));
+ }
+
+ /** Returns true if any dimension matches the predicate. */
+ public boolean any(Predicate<Double> test) {
+ return test.test(cpu) || test.test(memory) || test.test(disk);
}
public NodeResources scaled(NodeResources resources) {
@@ -52,6 +84,14 @@ public class Load {
.withDiskGb(disk * resources.diskGb());
}
+ public double get(Dimension dimension) {
+ return switch (dimension) {
+ case cpu -> cpu();
+ case memory -> memory();
+ case disk -> disk();
+ };
+ }
+
private double requireNormalized(double value, String name) {
if (Double.isNaN(value))
throw new IllegalArgumentException(name + " must be a number but is NaN");
@@ -60,17 +100,31 @@ public class Load {
return value;
}
+ private static double divide(double a, double b) {
+ if (a == 0 && b == 0) return 0;
+ return a / b;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this) return true;
+ if ( ! (o instanceof Load other)) return false;
+ if (other.cpu() != this.cpu()) return false;
+ if (other.memory() != this.memory()) return false;
+ if (other.disk() != this.disk()) return false;
+ return true;
+ }
+
+ @Override
+ public int hashCode() { return Objects.hash(cpu, memory, disk); }
+
@Override
public String toString() {
return "load: " + cpu + " cpu, " + memory + " memory, " + disk + " disk";
}
public static Load zero() { return new Load(0, 0, 0); }
-
- private static double divide(double a, double b) {
- if (a == 0 && b == 0) return 0;
- return a / b;
- }
+ public static Load one() { return new Load(1, 1, 1); }
public static Load byDividing(NodeResources a, NodeResources b) {
return new Load(divide(a.vcpu(), b.vcpu()), divide(a.memoryGb(), b.memoryGb()), divide(a.diskGb(), b.diskGb()));
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/NodeTimeseries.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/NodeTimeseries.java
index 4a5f8972e11..500dbf0f66f 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/NodeTimeseries.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/NodeTimeseries.java
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.OptionalDouble;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -40,6 +41,10 @@ public class NodeTimeseries {
return Optional.of(snapshots.get(snapshots.size() - 1));
}
+ public OptionalDouble peak(Load.Dimension dimension) {
+ return snapshots.stream().mapToDouble(snapshot -> snapshot.load().get(dimension)).max();
+ }
+
public List<NodeMetricSnapshot> asList() { return snapshots; }
public String hostname() { return hostname; }
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ResourceTarget.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ResourceTarget.java
deleted file mode 100644
index 72836baaf5b..00000000000
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/ResourceTarget.java
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.vespa.hosted.provision.autoscale;
-
-import com.yahoo.config.provision.NodeResources;
-import com.yahoo.vespa.hosted.provision.applications.Application;
-
-import java.time.Clock;
-import java.time.Duration;
-import java.util.OptionalDouble;
-
-/**
- * A resource target to hit for the allocation optimizer.
- * The target is measured in cpu, memory and disk per node in the allocation given by current.
- *
- * @author bratseth
- */
-public class ResourceTarget {
-
- private final boolean adjustForRedundancy;
-
- /** The target real resources per node, assuming the node assignment where this was decided */
- private final NodeResources resources;
-
- private ResourceTarget(NodeResources resources, boolean adjustForRedundancy) {
- this.resources = resources;
- this.adjustForRedundancy = adjustForRedundancy;
- }
-
- /** Are the target resources given by this including redundancy or not */
- public boolean adjustForRedundancy() { return adjustForRedundancy; }
-
- /** Returns the target resources per node in terms of the current allocation */
- public NodeResources resources() { return resources; }
-
- @Override
- public String toString() {
- return "target " + resources + (adjustForRedundancy ? "(with redundancy adjustment) " : "");
- }
-
- /** Create a target of achieving ideal load given a current load */
- public static ResourceTarget idealLoad(ClusterModel clusterModel,
- AllocatableClusterResources current) {
- var loadAdjustment = clusterModel.averageLoad().divide(clusterModel.idealLoad());
- return new ResourceTarget(loadAdjustment.scaled(current.realResources().nodeResources()), true);
- }
-
- /** Crete a target of preserving a current allocation */
- public static ResourceTarget preserve(AllocatableClusterResources current) {
- return new ResourceTarget(current.realResources().nodeResources(), false);
- }
-
-}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java
index 9c6eb2199f5..a9e7ded66e6 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainer.java
@@ -12,7 +12,6 @@ import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.jdisc.Metric;
import com.yahoo.lang.MutableInteger;
-import com.yahoo.transaction.Mutex;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.vespa.flags.JacksonFlag;
import com.yahoo.vespa.flags.ListFlag;
@@ -77,16 +76,14 @@ public class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
@Override
protected double maintain() {
- try (Mutex lock = nodeRepository().nodes().lockUnallocated()) {
- NodeList nodes = nodeRepository().nodes().list();
- resumeProvisioning(nodes, lock);
- convergeToCapacity(nodes);
- }
+ NodeList nodes = nodeRepository().nodes().list();
+ resumeProvisioning(nodes);
+ convergeToCapacity(nodes);
return 1.0;
}
/** Resume provisioning of already provisioned hosts and their children */
- private void resumeProvisioning(NodeList nodes, Mutex lock) {
+ private void resumeProvisioning(NodeList nodes) {
Map<String, Set<Node>> nodesByProvisionedParentHostname =
nodes.nodeType(NodeType.tenant, NodeType.config, NodeType.controller)
.asList()
@@ -97,9 +94,11 @@ public class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
nodes.state(Node.State.provisioned).nodeType(NodeType.host, NodeType.confighost, NodeType.controllerhost).forEach(host -> {
Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
try {
- List<Node> updatedNodes = hostProvisioner.provision(host, children);
- verifyDns(updatedNodes);
- nodeRepository().nodes().write(updatedNodes, lock);
+ try (var lock = nodeRepository().nodes().lockUnallocated()) {
+ List<Node> updatedNodes = hostProvisioner.provision(host, children);
+ verifyDns(updatedNodes);
+ nodeRepository().nodes().write(updatedNodes, lock);
+ }
} catch (IllegalArgumentException | IllegalStateException e) {
log.log(Level.INFO, "Could not provision " + host.hostname() + " with " + children.size() + " children, will retry in " +
interval() + ": " + Exceptions.toMessageString(e));
@@ -108,7 +107,7 @@ public class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
" children, failing out the host recursively", e);
// Fail out as operator to force a quick redeployment
nodeRepository().nodes().failOrMarkRecursively(
- host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
+ host.hostname(), Agent.DynamicProvisioningMaintainer, "Failed by HostProvisioner due to provisioning failure");
} catch (RuntimeException e) {
if (e.getCause() instanceof NameNotFoundException)
log.log(Level.INFO, "Could not provision " + host.hostname() + ", will retry in " + interval() + ": " + Exceptions.toMessageString(e));
@@ -187,29 +186,38 @@ public class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
.collect(Collectors.toList());
}
- private List<Node> candidatesForRemoval(List<Node> nodes) {
- Map<String, Node> hostsByHostname = new HashMap<>(nodes.stream()
- .filter(node -> {
- switch (node.type()) {
- case host:
- // TODO: Mark empty tenant hosts as wanttoretire & wanttodeprovision elsewhere, then handle as confighost here
- return node.state() != Node.State.parked || node.status().wantToDeprovision();
- case confighost:
- case controllerhost:
- return node.state() == Node.State.parked && node.status().wantToDeprovision();
- default:
- return false;
- }
- })
- .collect(Collectors.toMap(Node::hostname, Function.identity())));
+ private static List<Node> candidatesForRemoval(List<Node> nodes) {
+ Map<String, Node> removableHostsByHostname = new HashMap<>();
+ for (var node : nodes) {
+ if (canRemoveHost(node)) {
+ removableHostsByHostname.put(node.hostname(), node);
+ }
+ }
+ for (var node : nodes) {
+ if (node.parentHostname().isPresent() && !canRemoveNode(node)) {
+ removableHostsByHostname.remove(node.parentHostname().get());
+ }
+ }
+ return List.copyOf(removableHostsByHostname.values());
+ }
- nodes.stream()
- .filter(node -> node.allocation().isPresent())
- .flatMap(node -> node.parentHostname().stream())
- .distinct()
- .forEach(hostsByHostname::remove);
+ private static boolean canRemoveHost(Node host) {
+ return switch (host.type()) {
+ // TODO: Mark empty tenant hosts as wanttoretire & wanttodeprovision elsewhere, then handle as confighost here
+ case host -> host.state() != Node.State.parked || host.status().wantToDeprovision();
+ case confighost, controllerhost -> canDeprovision(host);
+ default -> false;
+ };
+ }
+
+ private static boolean canRemoveNode(Node node) {
+ if (node.type().isHost()) throw new IllegalArgumentException("Node " + node + " is not a child");
+ return node.allocation().isEmpty() || canDeprovision(node);
+ }
- return List.copyOf(hostsByHostname.values());
+ private static boolean canDeprovision(Node node) {
+ return node.status().wantToDeprovision() && (node.state() == Node.State.parked ||
+ node.state() == Node.State.failed);
}
private Map<String, Node> findSharedHosts(NodeList nodeList) {
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java
index 62557b275c8..67c1c7359f7 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporter.java
@@ -198,11 +198,6 @@ public class MetricsReporter extends NodeRepositoryMaintainer {
metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context);
metric.set("failReport", NodeFailer.reasonsToFailHost(node).isEmpty() ? 0 : 1, context);
- if (node.type().isHost()) {
- metric.set("wantToEncrypt", node.reports().getReport("wantToEncrypt").isPresent() ? 1 : 0, context);
- metric.set("diskEncrypted", node.reports().getReport("diskEncrypted").isPresent() ? 1 : 0, context);
- }
-
HostName hostname = new HostName(node.hostname());
serviceModel.getApplication(hostname)
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailer.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailer.java
index 3c5b20da4d0..3e7abe8f053 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailer.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailer.java
@@ -12,6 +12,7 @@ import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeMutex;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
+import com.yahoo.vespa.hosted.provision.node.Allocation;
import com.yahoo.vespa.hosted.provision.node.History;
import com.yahoo.vespa.orchestrator.ApplicationIdNotFoundException;
import com.yahoo.vespa.orchestrator.status.ApplicationInstanceStatus;
@@ -19,9 +20,11 @@ import com.yahoo.yolean.Exceptions;
import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
@@ -106,26 +109,6 @@ public class NodeFailer extends NodeRepositoryMaintainer {
failActive(failing);
}
- // Active hosts
- NodeList activeNodes = nodeRepository().nodes().list(Node.State.active);
- for (Node host : activeNodes.hosts().failing()) {
- if ( ! activeNodes.childrenOf(host).isEmpty()) continue;
- Optional<NodeMutex> locked = Optional.empty();
- try {
- attempts++;
- locked = nodeRepository().nodes().lockAndGet(host);
- if (locked.isEmpty()) continue;
- nodeRepository().nodes().fail(List.of(locked.get().node()), Agent.NodeFailer,
- "Host should be failed and have no tenant nodes");
- }
- catch (Exception e) {
- failures++;
- }
- finally {
- locked.ifPresent(NodeMutex::close);
- }
- }
-
int throttlingActive = Math.min(1, throttledHostFailures + throttledNodeFailures);
metric.set(throttlingActiveMetric, throttlingActive, null);
metric.set(throttledHostFailuresMetric, throttledHostFailures, null);
@@ -153,6 +136,9 @@ public class NodeFailer extends NodeRepositoryMaintainer {
Set<FailingNode> failingNodes = new HashSet<>();
NodeList activeNodes = nodeRepository().nodes().list(Node.State.active);
+ for (Node host : activeNodes.hosts().failing())
+ failingNodes.add(new FailingNode(host, "Host should be failed and have no tenant nodes"));
+
for (Node node : activeNodes) {
Instant graceTimeStart = clock().instant().minus(nodeRepository().nodes().suspended(node) ? suspendedDownTimeLimit : downTimeLimit);
if (node.isDown() && node.history().hasEventBefore(History.Event.Type.down, graceTimeStart) && !applicationSuspended(node)) {
@@ -241,42 +227,61 @@ public class NodeFailer extends NodeRepositoryMaintainer {
deployer.deployFromLocalActive(failing.node().allocation().get().owner(), Duration.ofMinutes(30));
if (deployment.isEmpty()) return false;
- try (Mutex lock = nodeRepository().nodes().lock(failing.node().allocation().get().owner())) {
- // If the active node that we are trying to fail is of type host, we need to successfully fail all
- // the children nodes running on it before we fail the host
- boolean allTenantNodesFailedOutSuccessfully = true;
+ // If the active node that we are trying to fail is of type host, we need to successfully fail all
+ // the children nodes running on it before we fail the host. Failing a child node in a dynamically
+ // provisioned zone may require provisioning new hosts that require the host application lock to be held,
+ // so we must release ours before failing the children.
+ List<FailingNode> activeChildrenToFail = new ArrayList<>();
+ try (NodeMutex lock = nodeRepository().nodes().lockAndGetRequired(failing.node())) {
+ // Now that we have gotten the node object under the proper lock, sanity-check it still makes sense to fail
+ if (!Objects.equals(failing.node().allocation().map(Allocation::owner), lock.node().allocation().map(Allocation::owner)))
+ return false;
+ if (lock.node().state() == Node.State.failed)
+ return true;
+ if (!Objects.equals(failing.node().state(), lock.node().state()))
+ return false;
+ failing = new FailingNode(lock.node(), failing.reason);
+
String reasonForChildFailure = "Failing due to parent host " + failing.node().hostname() + " failure: " + failing.reason();
for (Node failingTenantNode : nodeRepository().nodes().list().childrenOf(failing.node())) {
if (failingTenantNode.state() == Node.State.active) {
- allTenantNodesFailedOutSuccessfully &= failActive(new FailingNode(failingTenantNode, reasonForChildFailure));
- } else {
+ activeChildrenToFail.add(new FailingNode(failingTenantNode, reasonForChildFailure));
+ } else if (failingTenantNode.state() != Node.State.failed) {
nodeRepository().nodes().fail(failingTenantNode.hostname(), Agent.NodeFailer, reasonForChildFailure);
}
}
- if (! allTenantNodesFailedOutSuccessfully) return false;
- wantToFail(failing.node(), true, lock);
- try {
- deployment.get().activate();
- return true;
- } catch (TransientException e) {
- log.log(Level.INFO, "Failed to redeploy " + failing.node().allocation().get().owner() +
- " with a transient error, will be retried by application maintainer: " +
- Exceptions.toMessageString(e));
- return true;
- } catch (RuntimeException e) {
- // Reset want to fail: We'll retry failing unless it heals in the meantime
- nodeRepository().nodes().node(failing.node().hostname())
- .ifPresent(n -> wantToFail(n, false, lock));
- log.log(Level.WARNING, "Could not fail " + failing.node() + " for " + failing.node().allocation().get().owner() +
- " for " + failing.reason() + ": " + Exceptions.toMessageString(e));
- return false;
+ if (activeChildrenToFail.isEmpty()) {
+ wantToFail(failing.node(), true, lock);
+ try {
+ deployment.get().activate();
+ return true;
+ } catch (TransientException e) {
+ log.log(Level.INFO, "Failed to redeploy " + failing.node().allocation().get().owner() +
+ " with a transient error, will be retried by application maintainer: " +
+ Exceptions.toMessageString(e));
+ return true;
+ } catch (RuntimeException e) {
+ // Reset want to fail: We'll retry failing unless it heals in the meantime
+ nodeRepository().nodes().node(failing.node().hostname())
+ .ifPresent(n -> wantToFail(n, false, lock));
+ log.log(Level.WARNING, "Could not fail " + failing.node() + " for " + failing.node().allocation().get().owner() +
+ " for " + failing.reason() + ": " + Exceptions.toMessageString(e));
+ return false;
+ }
}
}
+
+ // In a dynamically provisioned zone the failing of the first child may require a new host to be provisioned,
+ // so failActive() may take a long time to complete, but the remaining children should be fast.
+ activeChildrenToFail.forEach(this::failActive);
+
+ return false;
}
private void wantToFail(Node node, boolean wantToFail, Mutex lock) {
- nodeRepository().nodes().write(node.withWantToFail(wantToFail, Agent.NodeFailer, clock().instant()), lock);
+ if (!node.status().wantToFail())
+ nodeRepository().nodes().write(node.withWantToFail(wantToFail, Agent.NodeFailer, clock().instant()), lock);
}
/** Returns true if node failing should be throttled */
@@ -284,16 +289,24 @@ public class NodeFailer extends NodeRepositoryMaintainer {
if (throttlePolicy == ThrottlePolicy.disabled) return false;
Instant startOfThrottleWindow = clock().instant().minus(throttlePolicy.throttleWindow);
NodeList allNodes = nodeRepository().nodes().list();
- NodeList recentlyFailedNodes = allNodes.state(Node.State.failed)
- .matching(n -> n.history().hasEventAfter(History.Event.Type.failed,
- startOfThrottleWindow));
+ NodeList recentlyFailedNodes = allNodes
+ .matching(n -> n.status().wantToFail() ||
+ (n.state() == Node.State.failed &&
+ n.history().hasEventAfter(History.Event.Type.failed, startOfThrottleWindow)));
// Allow failing any node within policy
if (recentlyFailedNodes.size() < throttlePolicy.allowedToFailOf(allNodes.size())) return false;
// Always allow failing a minimum number of hosts
- if (node.parentHostname().isEmpty() &&
- recentlyFailedNodes.parents().size() < throttlePolicy.minimumAllowedToFail) return false;
+ if (node.parentHostname().isEmpty()) {
+ Set<String> parentsOfRecentlyFailedNodes = recentlyFailedNodes.stream()
+ .map(n -> n.parentHostname().orElse(n.hostname()))
+ .collect(Collectors.toSet());
+ long potentiallyFailed = parentsOfRecentlyFailedNodes.contains(node.hostname()) ?
+ parentsOfRecentlyFailedNodes.size() :
+ parentsOfRecentlyFailedNodes.size() + 1;
+ if (potentiallyFailed <= throttlePolicy.minimumAllowedToFail) return false;
+ }
// Always allow failing children of a failed host
if (recentlyFailedNodes.parentOf(node).isPresent()) return false;
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java
index f32fd225427..aa1abb18d8c 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeRepositoryMaintenance.java
@@ -124,14 +124,14 @@ public class NodeRepositoryMaintenance extends AbstractComponent {
private final NodeFailer.ThrottlePolicy throttlePolicy;
DefaultTimes(Zone zone, Deployer deployer) {
- autoscalingInterval = Duration.ofMinutes(15);
+ autoscalingInterval = Duration.ofMinutes(5);
dynamicProvisionerInterval = Duration.ofMinutes(3);
failedExpirerInterval = Duration.ofMinutes(10);
failGrace = Duration.ofMinutes(30);
infrastructureProvisionInterval = Duration.ofMinutes(3);
loadBalancerExpirerInterval = Duration.ofMinutes(5);
metricsInterval = Duration.ofMinutes(1);
- nodeFailerInterval = Duration.ofMinutes(15);
+ nodeFailerInterval = Duration.ofMinutes(9);
nodeFailureStatusUpdateInterval = Duration.ofMinutes(2);
nodeMetricsCollectionInterval = Duration.ofMinutes(1);
expeditedChangeRedeployInterval = Duration.ofMinutes(3);
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/History.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/History.java
index ac804f99cd3..c2d4506a28c 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/History.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/History.java
@@ -4,6 +4,7 @@ package com.yahoo.vespa.hosted.provision.node;
import com.google.common.collect.ImmutableMap;
import com.yahoo.vespa.hosted.provision.Node;
+import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
@@ -50,6 +51,12 @@ public class History {
return builder.build();
}
+ /** Returns the age of this node as best as we can determine: The time since the first event registered for it */
+ public Duration age(Instant now) {
+ Instant oldestEventTime = events.values().stream().map(event -> event.at()).sorted().findFirst().orElse(now);
+ return Duration.between(oldestEventTime, now);
+ }
+
/** Returns the last event of given type, if it is present in this history */
public Optional<Event> event(Event.Type type) { return Optional.ofNullable(events.get(type)); }
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Nodes.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Nodes.java
index d750a3ef737..41a23ac21ff 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Nodes.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Nodes.java
@@ -212,12 +212,12 @@ public class Nodes {
return setReady(List.of(nodeToReady), agent, reason).get(0);
}
- /** Reserve nodes. This method does <b>not</b> lock the node repository */
+ /** Reserve nodes. This method does <b>not</b> lock the node repository. */
public List<Node> reserve(List<Node> nodes) {
return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty());
}
- /** Activate nodes. This method does <b>not</b> lock the node repository */
+ /** Activate nodes. This method does <b>not</b> lock the node repository. */
public List<Node> activate(List<Node> nodes, NestedTransaction transaction) {
return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction);
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/filter/NodeListFilter.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/filter/NodeListFilter.java
index 8578e3eb5ec..2b790ff7392 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/filter/NodeListFilter.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/filter/NodeListFilter.java
@@ -30,4 +30,5 @@ public class NodeListFilter {
public static Predicate<Node> from(List<Node> nodes) {
return makePredicate(nodes);
}
+
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/DelegatingOsUpgrader.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/DelegatingOsUpgrader.java
index 30fd2713017..4178d4a6328 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/DelegatingOsUpgrader.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/DelegatingOsUpgrader.java
@@ -7,6 +7,7 @@ import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.filter.NodeListFilter;
+import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;
@@ -39,8 +40,10 @@ public class DelegatingOsUpgrader implements OsUpgrader {
public void upgradeTo(OsVersionTarget target) {
NodeList activeNodes = nodeRepository.nodes().list(Node.State.active).nodeType(target.nodeType());
int numberToUpgrade = Math.max(0, maxActiveUpgrades - activeNodes.changingOsVersionTo(target.version()).size());
+ Instant now = nodeRepository.clock().instant();
NodeList nodesToUpgrade = activeNodes.not().changingOsVersionTo(target.version())
.osVersionIsBefore(target.version())
+ .matching(node -> canUpgradeAt(now, node))
.byIncreasingOsVersion()
.first(numberToUpgrade);
if (nodesToUpgrade.size() == 0) return;
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsUpgrader.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsUpgrader.java
index 5310ef339ed..4140de76368 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsUpgrader.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsUpgrader.java
@@ -2,6 +2,9 @@
package com.yahoo.vespa.hosted.provision.os;
import com.yahoo.config.provision.NodeType;
+import com.yahoo.vespa.hosted.provision.Node;
+
+import java.time.Instant;
/**
* Interface for an OS upgrader.
@@ -16,4 +19,9 @@ public interface OsUpgrader {
/** Disable OS upgrade for all nodes of given type */
void disableUpgrade(NodeType type);
+ /** Returns whether node can upgrade at given instant */
+ default boolean canUpgradeAt(Instant instant, Node node) {
+ return true;
+ }
+
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsVersions.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsVersions.java
index 7c6d1cb69db..440046ab818 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsVersions.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/OsVersions.java
@@ -84,7 +84,7 @@ public class OsVersions {
Version target = Optional.ofNullable(change.targets().get(nodeType))
.map(OsVersionTarget::version)
.orElse(Version.emptyVersion);
- chooseUpgrader(nodeType, target).disableUpgrade(nodeType);
+ chooseUpgrader(nodeType, Optional.of(target)).disableUpgrade(nodeType);
return change.withoutTarget(nodeType);
});
}
@@ -120,7 +120,7 @@ public class OsVersions {
try (Lock lock = db.lockOsVersionChange()) {
OsVersionTarget target = readChange().targets().get(nodeType);
if (target == null) return; // No target set for this type
- OsUpgrader upgrader = chooseUpgrader(nodeType, target.version());
+ OsUpgrader upgrader = chooseUpgrader(nodeType, Optional.of(target.version()));
if (resume) {
upgrader.upgradeTo(target);
} else {
@@ -129,17 +129,23 @@ public class OsVersions {
}
}
+ /** Returns whether node can be upgraded now */
+ public boolean canUpgrade(Node node) {
+ return chooseUpgrader(node.type(), Optional.empty()).canUpgradeAt(nodeRepository.clock().instant(), node);
+ }
+
/** Returns the upgrader to use when upgrading given node type to target */
- private OsUpgrader chooseUpgrader(NodeType nodeType, Version target) {
+ private OsUpgrader chooseUpgrader(NodeType nodeType, Optional<Version> target) {
if (reprovisionToUpgradeOs) {
return new RetiringOsUpgrader(nodeRepository);
}
// Require rebuild if we have any nodes of this type on a major version lower than target
- boolean rebuildRequired = nodeRepository.nodes().list(Node.State.active).nodeType(nodeType).stream()
+ boolean rebuildRequired = target.isPresent() &&
+ nodeRepository.nodes().list(Node.State.active).nodeType(nodeType).stream()
.map(Node::status)
.map(Status::osVersion)
.anyMatch(osVersion -> osVersion.current().isPresent() &&
- osVersion.current().get().getMajor() < target.getMajor());
+ osVersion.current().get().getMajor() < target.get().getMajor());
if (rebuildRequired) {
return new RebuildingOsUpgrader(nodeRepository);
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RebuildingOsUpgrader.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RebuildingOsUpgrader.java
index efc377e6cc3..f96effe9e10 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RebuildingOsUpgrader.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RebuildingOsUpgrader.java
@@ -47,7 +47,7 @@ public class RebuildingOsUpgrader implements OsUpgrader {
public void upgradeTo(OsVersionTarget target) {
NodeList allNodes = nodeRepository.nodes().list();
Instant now = nodeRepository.clock().instant();
- rebuildableHosts(target, allNodes).forEach(host -> rebuild(host, target.version(), now));
+ rebuildableHosts(target, allNodes, now).forEach(host -> rebuild(host, target.version(), now));
}
@Override
@@ -62,7 +62,7 @@ public class RebuildingOsUpgrader implements OsUpgrader {
return Math.max(0, limit - hostsOfType.rebuilding().size());
}
- private List<Node> rebuildableHosts(OsVersionTarget target, NodeList allNodes) {
+ private List<Node> rebuildableHosts(OsVersionTarget target, NodeList allNodes, Instant now) {
NodeList hostsOfTargetType = allNodes.nodeType(target.nodeType());
int rebuildLimit = rebuildLimit(target.nodeType(), hostsOfTargetType);
@@ -76,6 +76,7 @@ public class RebuildingOsUpgrader implements OsUpgrader {
NodeList candidates = hostsOfTargetType.state(Node.State.active)
.not().rebuilding()
.osVersionIsBefore(target.version())
+ .matching(node -> canUpgradeAt(now, node))
.byIncreasingOsVersion();
for (Node host : candidates) {
if (hostsToRebuild.size() == rebuildLimit) break;
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RetiringOsUpgrader.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RetiringOsUpgrader.java
index d923c78a929..79b7441cc34 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RetiringOsUpgrader.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/os/RetiringOsUpgrader.java
@@ -26,6 +26,9 @@ public class RetiringOsUpgrader implements OsUpgrader {
private static final Logger LOG = Logger.getLogger(RetiringOsUpgrader.class.getName());
+ /** The duration this leaves new nodes alone before scheduling any upgrade */
+ static final Duration GRACE_PERIOD = Duration.ofDays(30);
+
protected final NodeRepository nodeRepository;
public RetiringOsUpgrader(NodeRepository nodeRepository) {
@@ -33,21 +36,27 @@ public class RetiringOsUpgrader implements OsUpgrader {
}
@Override
- public final void upgradeTo(OsVersionTarget target) {
+ public void upgradeTo(OsVersionTarget target) {
NodeList allNodes = nodeRepository.nodes().list();
Instant now = nodeRepository.clock().instant();
NodeList candidates = candidates(now, target, allNodes);
candidates.not().deprovisioning()
+ .matching(node -> canUpgradeAt(now, node))
.byIncreasingOsVersion()
.first(1)
.forEach(node -> deprovision(node, target.version(), now));
}
@Override
- public final void disableUpgrade(NodeType type) {
+ public void disableUpgrade(NodeType type) {
// No action needed in this implementation.
}
+ @Override
+ public boolean canUpgradeAt(Instant instant, Node node) {
+ return node.history().age(instant).compareTo(GRACE_PERIOD) > 0;
+ }
+
/** Returns nodes that are candidates for upgrade */
private NodeList candidates(Instant instant, OsVersionTarget target, NodeList allNodes) {
NodeList activeNodes = allNodes.state(Node.State.active).nodeType(target.nodeType());
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/ArchiveUris.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/ArchiveUris.java
index 1cd8bb0fccd..e057fabc4fc 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/ArchiveUris.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/ArchiveUris.java
@@ -7,11 +7,11 @@ import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.node.Allocation;
import com.yahoo.vespa.hosted.provision.persistence.CuratorDatabaseClient;
-
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
+import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
@@ -63,7 +63,7 @@ public class ArchiveUris {
}));
}
- /** Set the docker image for nodes of given type */
+ /** Set (or remove, if archiveURI is empty) archive URI to use for given tenant */
public void setArchiveUri(TenantName tenant, Optional<String> archiveUri) {
try (Lock lock = db.lockArchiveUris()) {
Map<TenantName, String> archiveUris = new TreeMap<>(db.readArchiveUris());
@@ -73,7 +73,8 @@ public class ArchiveUris {
() -> archiveUris.remove(tenant));
db.writeArchiveUris(archiveUris);
this.archiveUris.invalidate(); // Throw away current cache
- log.info("Set archive URI for " + tenant + " to " + archiveUri.orElse(null));
+ log.log(Level.FINE, () -> archiveUri.map(s -> "Set archive URI for " + tenant + " to " + s)
+ .orElseGet(() -> "Remove archive URI for " + tenant));
}
}
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeRepositoryProvisioner.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeRepositoryProvisioner.java
index 64865c15529..065293ca5d8 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeRepositoryProvisioner.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodeRepositoryProvisioner.java
@@ -27,7 +27,7 @@ import com.yahoo.vespa.hosted.provision.autoscale.AllocatableClusterResources;
import com.yahoo.vespa.hosted.provision.autoscale.AllocationOptimizer;
import com.yahoo.vespa.hosted.provision.autoscale.ClusterModel;
import com.yahoo.vespa.hosted.provision.autoscale.Limits;
-import com.yahoo.vespa.hosted.provision.autoscale.ResourceTarget;
+import com.yahoo.vespa.hosted.provision.autoscale.Load;
import com.yahoo.vespa.hosted.provision.node.Allocation;
import com.yahoo.vespa.hosted.provision.node.filter.ApplicationFilter;
import com.yahoo.vespa.hosted.provision.node.filter.NodeHostFilter;
@@ -171,7 +171,7 @@ public class NodeRepositoryProvisioner implements Provisioner {
firstDeployment // start at min, preserve current resources otherwise
? new AllocatableClusterResources(initialResourcesFrom(requested, clusterSpec, application.id()), clusterSpec, nodeRepository)
: new AllocatableClusterResources(nodes.asList(), nodeRepository);
- var clusterModel = new ClusterModel(application, cluster, clusterSpec, nodes, nodeRepository.metricsDb(), nodeRepository.clock());
+ var clusterModel = new ClusterModel(application, clusterSpec, cluster, nodes, nodeRepository.metricsDb(), nodeRepository.clock());
return within(Limits.of(requested), currentResources, firstDeployment, clusterModel);
}
@@ -196,7 +196,7 @@ public class NodeRepositoryProvisioner implements Provisioner {
if (! firstDeployment && currentAsAdvertised.isWithin(limits.min(), limits.max())) return currentAsAdvertised;
// Otherwise, find an allocation that preserves the current resources as well as possible
- return allocationOptimizer.findBestAllocation(ResourceTarget.preserve(current),
+ return allocationOptimizer.findBestAllocation(Load.one(),
current,
clusterModel,
limits)
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/ApplicationSerializer.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/ApplicationSerializer.java
index f0b8e77ee56..1c10de8498a 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/ApplicationSerializer.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/ApplicationSerializer.java
@@ -62,7 +62,7 @@ public class ApplicationSerializer {
NodeList nodes = applicationNodes.not().retired().cluster(cluster.id());
if (nodes.isEmpty()) return;
ClusterResources currentResources = nodes.toResources();
- Optional<ClusterModel> clusterModel = ClusterModel.create(application, cluster, nodes.clusterSpec(), nodes, metricsDb, nodeRepository.clock());
+ Optional<ClusterModel> clusterModel = ClusterModel.create(application, nodes.clusterSpec(), cluster, nodes, metricsDb, nodeRepository.clock());
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
clusterObject.setString("type", nodes.clusterSpec().type().name());
toSlime(cluster.minResources(), clusterObject.setObject("min"));
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java
index 3659166c9da..87a9735f91e 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java
@@ -162,6 +162,9 @@ class NodesResponse extends SlimeJsonResponse {
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().current().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
node.status().osVersion().wanted().ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
+ if (node.type().isHost()) {
+ object.setBool("deferOsUpgrade", !nodeRepository.osVersions().canUpgrade(node));
+ }
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiHandler.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiHandler.java
index c5d8b2518e5..b3fbe124493 100644
--- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiHandler.java
+++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiHandler.java
@@ -44,6 +44,7 @@ import com.yahoo.vespa.hosted.provision.node.filter.ParentHostFilter;
import com.yahoo.vespa.hosted.provision.restapi.NodesResponse.ResponseType;
import com.yahoo.vespa.orchestrator.Orchestrator;
import com.yahoo.yolean.Exceptions;
+
import javax.inject.Inject;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -453,6 +454,8 @@ public class NodesV2ApiHandler extends ThreadedHttpRequestHandler {
Slime slime = new Slime();
Cursor root = slime.setObject();
+ root.setDouble("totalCost", stats.totalCost());
+ root.setDouble("totalAllocatedCost", stats.totalAllocatedCost());
toSlime(stats.load(), root.setObject("load"));
toSlime(stats.activeLoad(), root.setObject("activeLoad"));
Cursor applicationsArray = root.setArray("applications");
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/NodeRepoStatsTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/NodeRepoStatsTest.java
index 62c96af7629..788c56e08c6 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/NodeRepoStatsTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/NodeRepoStatsTest.java
@@ -31,9 +31,13 @@ public class NodeRepoStatsTest {
@Test
public void testEmpty() {
var tester = new NodeRepositoryTester();
- assertLoad(Load.zero(), tester.nodeRepository().computeStats().load());
- assertLoad(Load.zero(), tester.nodeRepository().computeStats().activeLoad());
- assertTrue(tester.nodeRepository().computeStats().applicationStats().isEmpty());
+ var stats = tester.nodeRepository().computeStats();
+
+ assertEquals(0, stats.totalCost(), delta);
+ assertEquals(0, stats.totalAllocatedCost(), delta);
+ assertLoad(Load.zero(), stats.load());
+ assertLoad(Load.zero(), stats.activeLoad());
+ assertTrue(stats.applicationStats().isEmpty());
}
@Test
@@ -42,9 +46,13 @@ public class NodeRepoStatsTest {
tester.addHost("host1", "default");
tester.addHost("host2", "default");
tester.addHost("host3", "small");
- assertLoad(Load.zero(), tester.nodeRepository().computeStats().load());
- assertLoad(Load.zero(), tester.nodeRepository().computeStats().activeLoad());
- assertTrue(tester.nodeRepository().computeStats().applicationStats().isEmpty());
+ var stats = tester.nodeRepository().computeStats();
+
+ assertEquals(0.76, stats.totalCost(), delta);
+ assertEquals(0, stats.totalAllocatedCost(), delta);
+ assertLoad(Load.zero(), stats.load());
+ assertLoad(Load.zero(), stats.activeLoad());
+ assertTrue(stats.applicationStats().isEmpty());
}
@Test
@@ -97,6 +105,9 @@ public class NodeRepoStatsTest {
var stats = tester.nodeRepository().computeStats();
+ assertEquals(26, stats.totalCost(), delta);
+ assertEquals(8.319999999999999, stats.totalAllocatedCost(), delta);
+
assertLoad(new Load(0.6180,0.5562,0.4944), stats.load());
assertLoad(new Load(0.4682,0.4214,0.3745), stats.activeLoad());
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingIntegrationTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingIntegrationTest.java
index 667dffef2a6..d8becdf7c80 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingIntegrationTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingIntegrationTest.java
@@ -1,22 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.autoscale;
-import com.yahoo.config.provision.ApplicationId;
-import com.yahoo.config.provision.Capacity;
import com.yahoo.config.provision.ClusterResources;
-import com.yahoo.config.provision.ClusterSpec;
-import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.test.ManualClock;
-import com.yahoo.transaction.Mutex;
-import com.yahoo.vespa.hosted.provision.applications.Application;
import com.yahoo.vespa.hosted.provision.testutils.OrchestratorMock;
import org.junit.Test;
import java.time.Duration;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
-import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -28,40 +22,27 @@ public class AutoscalingIntegrationTest {
@Test
public void testComponentIntegration() {
- NodeResources nodes = new NodeResources(1, 10, 100, 1);
- NodeResources hosts = new NodeResources(3, 20, 200, 1);
-
- AutoscalingTester tester = new AutoscalingTester(hosts);
- MetricsV2MetricsFetcher fetcher = new MetricsV2MetricsFetcher(tester.nodeRepository(),
+ var fixture = AutoscalingTester.fixture()
+ .hostResources(new NodeResources(3, 20, 200, 1))
+ .initialResources(Optional.of(new ClusterResources(2, 1,
+ new NodeResources(1, 10, 100, 1))))
+ .build();
+ MetricsV2MetricsFetcher fetcher = new MetricsV2MetricsFetcher(fixture.tester().nodeRepository(),
new OrchestratorMock(),
- new MockHttpClient(tester.clock()));
- Autoscaler autoscaler = new Autoscaler(tester.nodeRepository());
-
- ApplicationId application1 = tester.applicationId("test1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "test");
- Set<String> hostnames = tester.deploy(application1, cluster1, 2, 1, nodes)
- .stream().map(HostSpec::hostname)
- .collect(Collectors.toSet());
+ new MockHttpClient(fixture.tester().clock()));
+ Autoscaler autoscaler = new Autoscaler(fixture.tester().nodeRepository());
+
// The metrics response (below) hardcodes these hostnames:
- assertEquals(Set.of("node-1-of-host-1.yahoo.com", "node-1-of-host-10.yahoo.com"), hostnames);
+ assertEquals(Set.of("node-1-of-host-1.yahoo.com", "node-1-of-host-10.yahoo.com"), fixture.nodes().hostnames());
for (int i = 0; i < 1000; i++) {
- tester.clock().advance(Duration.ofSeconds(10));
- fetcher.fetchMetrics(application1).whenComplete((r, e) -> tester.nodeMetricsDb().addNodeMetrics(r.nodeMetrics()));
- tester.clock().advance(Duration.ofSeconds(10));
- tester.nodeMetricsDb().gc();
+ fixture.tester().clock().advance(Duration.ofSeconds(10));
+ fetcher.fetchMetrics(fixture.applicationId()).whenComplete((r, e) -> fixture.tester().nodeMetricsDb().addNodeMetrics(r.nodeMetrics()));
+ fixture.tester().clock().advance(Duration.ofSeconds(10));
+ fixture.tester().nodeMetricsDb().gc();
}
- ClusterResources min = new ClusterResources(2, 1, nodes);
- ClusterResources max = new ClusterResources(2, 1, nodes);
-
- Application application = tester.nodeRepository().applications().get(application1).orElse(Application.empty(application1))
- .withCluster(cluster1.id(), false, Capacity.from(min, max));
- try (Mutex lock = tester.nodeRepository().nodes().lock(application1)) {
- tester.nodeRepository().applications().put(application, lock);
- }
- var scaledResources = autoscaler.suggest(application, application.clusters().get(cluster1.id()),
- tester.nodeRepository().nodes().list().owner(application1));
+ var scaledResources = autoscaler.suggest(fixture.application(), fixture.cluster(), fixture.nodes());
assertTrue(scaledResources.isPresent());
}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTest.java
index 4140588d1c8..28f37546eb6 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTest.java
@@ -1,29 +1,28 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.autoscale;
-import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Capacity;
-import com.yahoo.config.provision.Cloud;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeResources.DiskSpeed;
+import static com.yahoo.config.provision.NodeResources.DiskSpeed.fast;
+import static com.yahoo.config.provision.NodeResources.DiskSpeed.slow;
import com.yahoo.config.provision.NodeResources.StorageType;
+import static com.yahoo.config.provision.NodeResources.StorageType.remote;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.RegionName;
-import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.Nodelike;
import com.yahoo.vespa.hosted.provision.provisioning.CapacityPolicies;
import com.yahoo.vespa.hosted.provision.provisioning.HostResourcesCalculator;
+import org.junit.Ignore;
import org.junit.Test;
import java.time.Duration;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
@@ -36,531 +35,398 @@ public class AutoscalingTest {
@Test
public void test_autoscaling_single_content_group() {
- NodeResources hostResources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1,
- new NodeResources(1, 1, 1, 1, NodeResources.DiskSpeed.any));
- ClusterResources max = new ClusterResources(20, 1,
- new NodeResources(100, 1000, 1000, 1, NodeResources.DiskSpeed.any));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 1, hostResources);
+ var fixture = AutoscalingTester.fixture().build();
- tester.clock().advance(Duration.ofDays(1));
- assertTrue("No measurements -> No change", tester.autoscale(application1, cluster1, capacity).isEmpty());
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ assertTrue("No measurements -> No change", fixture.autoscale().isEmpty());
- tester.addCpuMeasurements(0.25f, 1f, 59, application1);
- assertTrue("Too few measurements -> No change", tester.autoscale(application1, cluster1, capacity).isEmpty());
+ fixture.loader().applyCpuLoad(0.7f, 59);
+ assertTrue("Too few measurements -> No change", fixture.autoscale().isEmpty());
- tester.clock().advance(Duration.ofDays(1));
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- ClusterResources scaledResources = tester.assertResources("Scaling up since resource usage is too high",
- 15, 1, 1.2, 28.6, 28.6,
- tester.autoscale(application1, cluster1, capacity));
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ fixture.loader().applyCpuLoad(0.7f, 120);
+ ClusterResources scaledResources = fixture.tester().assertResources("Scaling up since resource usage is too high",
+ 9, 1, 2.8, 5.0, 50.0,
+ fixture.autoscale());
- tester.deploy(application1, cluster1, scaledResources);
- assertTrue("Cluster in flux -> No further change", tester.autoscale(application1, cluster1, capacity).isEmpty());
+ fixture.deploy(Capacity.from(scaledResources));
+ assertTrue("Cluster in flux -> No further change", fixture.autoscale().isEmpty());
- tester.deactivateRetired(application1, cluster1, scaledResources);
+ fixture.deactivateRetired(Capacity.from(scaledResources));
- tester.clock().advance(Duration.ofDays(2));
- tester.addCpuMeasurements(0.8f, 1f, 3, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyCpuLoad(0.8f, 3);
assertTrue("Load change is large, but insufficient measurements for new config -> No change",
- tester.autoscale(application1, cluster1, capacity).isEmpty());
+ fixture.autoscale().isEmpty());
- tester.addCpuMeasurements(0.19f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- assertEquals("Load change is small -> No change", Optional.empty(), tester.autoscale(application1, cluster1, capacity).target());
+ fixture.loader().applyCpuLoad(0.19f, 100);
+ assertEquals("Load change is small -> No change", Optional.empty(), fixture.autoscale().target());
- tester.addCpuMeasurements(0.1f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling down to minimum since usage has gone down significantly",
- 7, 1, 1.0, 66.7, 66.7,
- tester.autoscale(application1, cluster1, capacity));
+ fixture.loader().applyCpuLoad(0.1f, 120);
+ fixture.tester().assertResources("Scaling cpu down since usage has gone down significantly",
+ 9, 1, 1.0, 5.0, 50.0,
+ fixture.autoscale());
+ }
+
+ /** Using too many resources for a short period is proof we should scale up regardless of the time that takes. */
+ @Test
+ public void test_no_autoscaling_with_no_measurements() {
+ var fixture = AutoscalingTester.fixture().build();
+ System.out.println(fixture.autoscale());
+ assertTrue(fixture.autoscale().target().isEmpty());
+ }
- var events = tester.nodeRepository().applications().get(application1).get().cluster(cluster1.id()).get().scalingEvents();
+ /** Using too many resources for a short period is proof we should scale up regardless of the time that takes. */
+ @Test
+ @Ignore // TODO
+ public void test_autoscaling_up_is_fast() {
+ var fixture = AutoscalingTester.fixture().build();
+ fixture.loader().applyLoad(1.0, 1.0, 1.0, 1);
+ fixture.tester().assertResources("Scaling up since resource usage is too high",
+ 10, 1, 9.4, 8.5, 92.6,
+ fixture.autoscale());
}
/** We prefer fewer nodes for container clusters as (we assume) they all use the same disk and memory */
@Test
public void test_autoscaling_single_container_group() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(20, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 1, resources);
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- ClusterResources scaledResources = tester.assertResources("Scaling up since cpu usage is too high",
- 7, 1, 2.5, 80.0, 50.5,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.deploy(application1, cluster1, scaledResources);
- tester.deactivateRetired(application1, cluster1, scaledResources);
-
- tester.addCpuMeasurements(0.1f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling down since cpu usage has gone down",
- 4, 1, 2.5, 68.6, 27.4,
- tester.autoscale(application1, cluster1, capacity));
+ var fixture = AutoscalingTester.fixture().clusterType(ClusterSpec.Type.container).build();
+ fixture.loader().applyCpuLoad(0.25f, 120);
+ ClusterResources scaledResources = fixture.tester().assertResources("Scaling up since cpu usage is too high",
+ 5, 1, 3.8, 8.0, 50.5,
+ fixture.autoscale());
+ fixture.deploy(Capacity.from(scaledResources));
+ fixture.loader().applyCpuLoad(0.1f, 120);
+ fixture.tester().assertResources("Scaling down since cpu usage has gone down",
+ 4, 1, 2.5, 6.4, 25.5,
+ fixture.autoscale());
}
@Test
public void autoscaling_handles_disk_setting_changes() {
- NodeResources hostResources = new NodeResources(3, 100, 100, 1, NodeResources.DiskSpeed.slow);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
+ var resources = new NodeResources(3, 100, 100, 1, slow);
+ var fixture = AutoscalingTester.fixture()
+ .hostResources(resources)
+ .initialResources(Optional.of(new ClusterResources(5, 1, resources)))
+ .capacity(Capacity.from(new ClusterResources(5, 1, resources)))
+ .build();
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
+ assertTrue(fixture.tester().nodeRepository().nodes().list().owner(fixture.applicationId).stream()
+ .allMatch(n -> n.allocation().get().requestedResources().diskSpeed() == slow));
- // deploy with slow
- tester.deploy(application1, cluster1, 5, 1, hostResources);
- assertTrue(tester.nodeRepository().nodes().list().owner(application1).stream()
- .allMatch(n -> n.allocation().get().requestedResources().diskSpeed() == NodeResources.DiskSpeed.slow));
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyCpuLoad(0.25, 120);
- tester.clock().advance(Duration.ofDays(2));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
// Changing min and max from slow to any
ClusterResources min = new ClusterResources( 2, 1,
- new NodeResources(1, 1, 1, 1, NodeResources.DiskSpeed.any));
+ new NodeResources(1, 1, 1, 1, DiskSpeed.any));
ClusterResources max = new ClusterResources(20, 1,
- new NodeResources(100, 1000, 1000, 1, NodeResources.DiskSpeed.any));
+ new NodeResources(100, 1000, 1000, 1, DiskSpeed.any));
var capacity = Capacity.from(min, max);
- ClusterResources scaledResources = tester.assertResources("Scaling up since resource usage is too high",
- 14, 1, 1.4, 30.8, 30.8,
- tester.autoscale(application1, cluster1, capacity));
- assertEquals("Disk speed from min/max is used",
- NodeResources.DiskSpeed.any, scaledResources.nodeResources().diskSpeed());
- tester.deploy(application1, cluster1, scaledResources);
- assertTrue(tester.nodeRepository().nodes().list().owner(application1).stream()
- .allMatch(n -> n.allocation().get().requestedResources().diskSpeed() == NodeResources.DiskSpeed.any));
+ ClusterResources scaledResources = fixture.tester().assertResources("Scaling up",
+ 14, 1, 1.4, 30.8, 30.8,
+ fixture.autoscale(capacity));
+ assertEquals("Disk speed from new capacity is used",
+ DiskSpeed.any, scaledResources.nodeResources().diskSpeed());
+ fixture.deploy(Capacity.from(scaledResources));
+ assertTrue(fixture.nodes().stream()
+ .allMatch(n -> n.allocation().get().requestedResources().diskSpeed() == DiskSpeed.any));
}
@Test
public void autoscaling_target_preserves_any() {
- NodeResources hostResources = new NodeResources(3, 100, 100, 1);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- // Initial deployment
NodeResources resources = new NodeResources(1, 10, 10, 1);
- var min = new ClusterResources( 2, 1, resources.with(NodeResources.DiskSpeed.any));
- var max = new ClusterResources( 10, 1, resources.with(NodeResources.DiskSpeed.any));
- var capacity = Capacity.from(min, max);
- tester.deploy(application1, cluster1, Capacity.from(min, max));
+ var capacity = Capacity.from(new ClusterResources( 2, 1, resources.with(DiskSpeed.any)),
+ new ClusterResources( 10, 1, resources.with(DiskSpeed.any)));
+ var fixture = AutoscalingTester.fixture()
+ .capacity(capacity)
+ .initialResources(Optional.empty())
+ .build();
// Redeployment without target: Uses current resource numbers with *requested* non-numbers (i.e disk-speed any)
- assertTrue(tester.nodeRepository().applications().get(application1).get().cluster(cluster1.id()).get().targetResources().isEmpty());
- tester.deploy(application1, cluster1, Capacity.from(min, max));
- assertEquals(NodeResources.DiskSpeed.any,
- tester.nodeRepository().nodes().list().owner(application1).cluster(cluster1.id()).first().get()
- .allocation().get().requestedResources().diskSpeed());
+ assertTrue(fixture.tester().nodeRepository().applications().get(fixture.applicationId).get().cluster(fixture.clusterSpec.id()).get().targetResources().isEmpty());
+ fixture.deploy();
+ assertEquals(DiskSpeed.any, fixture.nodes().first().get().allocation().get().requestedResources().diskSpeed());
// Autoscaling: Uses disk-speed any as well
- tester.clock().advance(Duration.ofDays(2));
- tester.addCpuMeasurements(0.8f, 1f, 120, application1);
- Autoscaler.Advice advice = tester.autoscale(application1, cluster1, capacity);
- assertEquals(NodeResources.DiskSpeed.any, advice.target().get().nodeResources().diskSpeed());
-
-
+ fixture.deactivateRetired(capacity);
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ fixture.loader().applyCpuLoad(0.8, 120);
+ assertEquals(DiskSpeed.any, fixture.autoscale(capacity).target().get().nodeResources().diskSpeed());
}
@Test
public void autoscaling_respects_upper_limit() {
- NodeResources hostResources = new NodeResources(6, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources( 6, 1, new NodeResources(2.4, 78, 79, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 1,
- new NodeResources(1.9, 70, 70, 1));
- tester.addMeasurements(0.25f, 0.95f, 0.95f, 0, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up to limit since resource usage is too high",
- 6, 1, 2.4, 78.0, 70.0,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(5, 1, new NodeResources(1.9, 70, 70, 1));
+ var max = new ClusterResources( 6, 1, new NodeResources(2.4, 78, 79, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max)).build();
+
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ fixture.loader().applyLoad(0.25, 0.95, 0.95, 120);
+ fixture.tester().assertResources("Scaling up to limit since resource usage is too high",
+ 6, 1, 2.4, 78.0, 79.0,
+ fixture.autoscale());
}
@Test
public void autoscaling_respects_lower_limit() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 4, 1, new NodeResources(1.8, 7.4, 8.5, 1));
- ClusterResources max = new ClusterResources( 6, 1, new NodeResources(2.4, 78, 79, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
+ var min = new ClusterResources( 4, 1, new NodeResources(1.8, 7.4, 8.5, 1));
+ var max = new ClusterResources( 6, 1, new NodeResources(2.4, 78, 79, 1));
+ var fixture = AutoscalingTester.fixture().capacity(Capacity.from(min, max)).build();
// deploy
- tester.deploy(application1, cluster1, 5, 1, resources);
- tester.addMeasurements(0.05f, 0.05f, 0.05f, 0, 120, application1);
- tester.assertResources("Scaling down to limit since resource usage is low",
- 4, 1, 1.8, 7.7, 10.0,
- tester.autoscale(application1, cluster1, capacity));
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.05f, 0.05f, 0.05f, 120);
+ fixture.tester().assertResources("Scaling down to limit since resource usage is low",
+ 4, 1, 1.8, 7.4, 13.9,
+ fixture.autoscale());
}
@Test
public void autoscaling_with_unspecified_resources_use_defaults() {
- NodeResources hostResources = new NodeResources(6, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1, NodeResources.unspecified());
- ClusterResources max = new ClusterResources( 6, 1, NodeResources.unspecified());
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
+ var min = new ClusterResources( 2, 1, NodeResources.unspecified());
+ var max = new ClusterResources( 6, 1, NodeResources.unspecified());
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.empty())
+ .capacity(Capacity.from(min, max))
+ .build();
NodeResources defaultResources =
- new CapacityPolicies(tester.nodeRepository()).defaultNodeResources(cluster1, application1, false);
-
- // deploy
- tester.deploy(application1, cluster1, Capacity.from(min, max));
- tester.assertResources("Min number of nodes and default resources",
- 2, 1, defaultResources,
- tester.nodeRepository().nodes().list().owner(application1).toResources());
- tester.addMeasurements(0.25f, 0.95f, 0.95f, 0, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up to limit since resource usage is too high",
- 4, 1,
- defaultResources.vcpu(), defaultResources.memoryGb(), defaultResources.diskGb(),
- tester.autoscale(application1, cluster1, capacity));
+ new CapacityPolicies(fixture.tester().nodeRepository()).defaultNodeResources(fixture.clusterSpec, fixture.applicationId, false);
+
+ fixture.tester().assertResources("Min number of nodes and default resources",
+ 2, 1, defaultResources,
+ fixture.nodes().toResources());
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.25, 0.95, 0.95, 120);
+ fixture.tester().assertResources("Scaling up",
+ 5, 1,
+ defaultResources.vcpu(), defaultResources.memoryGb(), defaultResources.diskGb(),
+ fixture.autoscale());
}
@Test
public void autoscaling_respects_group_limit() {
- NodeResources hostResources = new NodeResources(30.0, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(18, 6, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 5, new NodeResources(3.0, 10, 10, 1));
- tester.addCpuMeasurements( 0.3f, 1f, 240, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up since resource usage is too high",
- 6, 6, 3.6, 8.0, 10.0,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(5, 5, new NodeResources(3.0, 10, 10, 1));
+ var max = new ClusterResources(18, 6, new NodeResources(100, 1000, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyCpuLoad(0.3, 240);
+ fixture.tester().assertResources("Scaling up",
+ 6, 6, 3.8, 8.0, 10.0,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_limits_when_min_equals_max() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = min;
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
+ var fixture = AutoscalingTester.fixture().capacity(Capacity.from(min, min)).build();
// deploy
- tester.deploy(application1, cluster1, 5, 1, resources);
- tester.clock().advance(Duration.ofDays(1));
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- assertTrue(tester.autoscale(application1, cluster1, capacity).isEmpty());
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ fixture.loader().applyCpuLoad(0.25, 120);
+ assertTrue(fixture.autoscale().isEmpty());
}
@Test
- public void prefers_remote_disk_when_no_local_match() {
- NodeResources resources = new NodeResources(3, 100, 50, 1);
- ClusterResources min = new ClusterResources( 2, 1, resources);
- ClusterResources max = min;
- // AutoscalingTester hardcodes 3Gb memory overhead:
- Flavor localFlavor = new Flavor("local", new NodeResources(3, 97, 75, 1, DiskSpeed.fast, StorageType.local));
- Flavor remoteFlavor = new Flavor("remote", new NodeResources(3, 97, 50, 1, DiskSpeed.fast, StorageType.remote));
-
- var tester = new AutoscalingTester(new Zone(new Cloud.Builder().dynamicProvisioning(true).build(),
- SystemName.defaultSystem(), Environment.prod, RegionName.defaultName()),
- List.of(localFlavor, remoteFlavor));
- tester.provisioning().makeReadyNodes(5, localFlavor.name(), NodeType.host, 8);
- tester.provisioning().makeReadyNodes(5, remoteFlavor.name(), NodeType.host, 8);
- tester.provisioning().activateTenantHosts();
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 3, 1, min.nodeResources());
- Duration timeAdded = tester.addDiskMeasurements(0.01f, 1f, 120, application1);
- tester.clock().advance(timeAdded.negated());
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> 10.0); // Query traffic only
- Autoscaler.Advice suggestion = tester.suggest(application1, cluster1.id(), min, max);
- tester.assertResources("Choosing the remote disk flavor as it has less disk",
- 6, 1, 3.0, 100.0, 10.0,
- suggestion);
+ public void container_prefers_remote_disk_when_no_local_match() {
+ var resources = new ClusterResources( 2, 1, new NodeResources(3, 100, 50, 1));
+ var local = new NodeResources(3, 100, 75, 1, fast, StorageType.local);
+ var remote = new NodeResources(3, 100, 50, 1, fast, StorageType.remote);
+ var fixture = AutoscalingTester.fixture()
+ .dynamicProvisioning(true)
+ .clusterType(ClusterSpec.Type.container)
+ .hostResources(local, remote)
+ .capacity(Capacity.from(resources))
+ .initialResources(Optional.of(new ClusterResources(3, 1, resources.nodeResources())))
+ .build();
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.01, 0.01, 0.01, 120);
+ Autoscaler.Advice suggestion = fixture.suggest();
+ fixture.tester().assertResources("Choosing the remote disk flavor as it has less disk",
+ 2, 1, 3.0, 100.0, 10.0,
+ suggestion);
assertEquals("Choosing the remote disk flavor as it has less disk",
StorageType.remote, suggestion.target().get().nodeResources().storageType());
}
@Test
+ public void content_prefers_local_disk_when_no_local_match() {
+ var resources = new ClusterResources( 2, 1, new NodeResources(3, 100, 50, 1));
+ var local = new NodeResources(3, 100, 75, 1, fast, StorageType.local);
+ var remote = new NodeResources(3, 100, 50, 1, fast, StorageType.remote);
+ var fixture = AutoscalingTester.fixture()
+ .dynamicProvisioning(true)
+ .clusterType(ClusterSpec.Type.content)
+ .hostResources(local, remote)
+ .capacity(Capacity.from(resources))
+ .initialResources(Optional.of(new ClusterResources(3, 1, resources.nodeResources())))
+ .build();
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.01, 0.01, 0.01, 120);
+ Autoscaler.Advice suggestion = fixture.suggest();
+ fixture.tester().assertResources("Always prefers local disk for content",
+ 2, 1, 3.0, 100.0, 75.0,
+ suggestion);
+ assertEquals("Always prefers local disk for content",
+ StorageType.local, suggestion.target().get().nodeResources().storageType());
+ }
+
+ @Test
public void suggestions_ignores_limits() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = min;
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 1, resources);
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up since resource usage is too high",
- 7, 1, 2.5, 80.0, 50.5,
- tester.suggest(application1, cluster1.id(), min, max));
+ var fixture = AutoscalingTester.fixture().capacity(Capacity.from(min, min)).build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyCpuLoad(1.0, 120);
+ fixture.tester().assertResources("Suggesting above capacity limit",
+ 8, 1, 9.3, 5.7, 57.1,
+ fixture.tester().suggest(fixture.applicationId, fixture.clusterSpec.id(), min, min));
}
@Test
public void not_using_out_of_service_measurements() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources(2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(5, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 2, 1, resources);
- tester.addMeasurements(0.5f, 0.6f, 0.7f, 1, false, true, 120, application1);
- assertTrue("Not scaling up since nodes were measured while cluster was unstable",
- tester.autoscale(application1, cluster1, capacity).isEmpty());
+ var fixture = AutoscalingTester.fixture().build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.9, 0.6, 0.7, 1, false, true, 120);
+ assertTrue("Not scaling up since nodes were measured while cluster was out of service",
+ fixture.autoscale().isEmpty());
}
@Test
public void not_using_unstable_measurements() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources(2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(5, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 2, 1, resources);
- tester.addMeasurements(0.5f, 0.6f, 0.7f, 1, true, false, 120, application1);
- assertTrue("Not scaling up since nodes were measured while cluster was unstable",
- tester.autoscale(application1, cluster1, capacity).isEmpty());
+ var fixture = AutoscalingTester.fixture().build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(0.9, 0.6, 0.7, 1, true, false, 120);
+ assertTrue("Not scaling up since nodes were measured while cluster was out of service",
+ fixture.autoscale().isEmpty());
}
@Test
public void test_autoscaling_group_size_1() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(20, 20, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 5, 5, resources);
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up since resource usage is too high",
- 7, 7, 2.5, 80.0, 50.5,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(5, 5, new NodeResources(3, 100, 100, 1));
+ var max = new ClusterResources(20, 20, new NodeResources(10, 1000, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyCpuLoad(0.9, 120);
+ fixture.tester().assertResources("Scaling the number of groups, but nothing requires us to stay with 1 node per group",
+ 10, 5, 7.7, 40.0, 40.0,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_groupsize_by_cpu_read_dominated() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 3, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(21, 7, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 6, 2, resources);
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 10,
- t -> t == 0 ? 20.0 : 10.0,
- t -> 1.0);
- tester.assertResources("Scaling up since resource usage is too high, changing to 1 group is cheaper",
- 8, 1, 2.6, 83.3, 52.6,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 3, 1, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(6, 2, new NodeResources(3, 100, 100, 1));
+ var max = new ClusterResources(21, 7, new NodeResources(100, 1000, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ Duration timePassed = fixture.loader().addCpuMeasurements(0.25, 120);
+ fixture.tester().clock().advance(timePassed.negated());
+ fixture.loader().addLoadMeasurements(10, t -> t == 0 ? 20.0 : 10.0, t -> 1.0);
+ fixture.tester().assertResources("Scaling up since resource usage is too high, changing to 1 group is cheaper",
+ 10, 1, 2.3, 27.8, 27.8,
+ fixture.autoscale());
}
/** Same as above but mostly write traffic, which favors smaller groups */
@Test
public void test_autoscaling_groupsize_by_cpu_write_dominated() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 3, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(21, 7, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 6, 2, resources);
- tester.addCpuMeasurements(0.25f, 1f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 10,
- t -> t == 0 ? 20.0 : 10.0,
- t -> 100.0);
- tester.assertResources("Scaling down since resource usage is too high, changing to 1 group is cheaper",
- 4, 1, 2.1, 83.3, 52.6,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 3, 1, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(6, 2, new NodeResources(3, 100, 100, 1));
+ var max = new ClusterResources(21, 7, new NodeResources(100, 1000, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ Duration timePassed = fixture.loader().addCpuMeasurements(0.25, 120);
+ fixture.tester().clock().advance(timePassed.negated());
+ fixture.loader().addLoadMeasurements(10, t -> t == 0 ? 20.0 : 10.0, t -> 100.0);
+ fixture.tester().assertResources("Scaling down since resource usage is too high, changing to 1 group is cheaper",
+ 6, 1, 1.0, 50.0, 50.0,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_group_size() {
- NodeResources hostResources = new NodeResources(100, 1000, 1000, 100);
- ClusterResources min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(30, 30, new NodeResources(100, 100, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 6, 2, new NodeResources(10, 100, 100, 1));
- tester.clock().advance(Duration.ofDays(1));
- tester.addMemMeasurements(1.0f, 1f, 1000, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Increase group size to reduce memory load",
- 8, 2, 12.4, 96.2, 62.5,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 2, 2, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(6, 2, new NodeResources(10, 100, 100, 1));
+ var max = new ClusterResources(30, 30, new NodeResources(100, 100, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(1));
+ fixture.loader().applyMemLoad(1.0, 1000);
+ fixture.tester().assertResources("Increase group size to reduce memory load",
+ 8, 2, 6.5, 96.2, 62.5,
+ fixture.autoscale());
}
@Test
public void autoscaling_avoids_illegal_configurations() {
- NodeResources hostResources = new NodeResources(6, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(20, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- // deploy
- tester.deploy(application1, cluster1, 6, 1, hostResources.withVcpu(hostResources.vcpu() / 2));
- tester.clock().advance(Duration.ofDays(2));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.addMemMeasurements(0.02f, 0.95f, 120, application1);
- tester.assertResources("Scaling down",
- 6, 1, 2.9, 4.0, 95.0,
- tester.autoscale(application1, cluster1, capacity));
+ var min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
+ var now = new ClusterResources(6, 1, new NodeResources(3, 100, 100, 1));
+ var max = new ClusterResources(20, 1, new NodeResources(100, 1000, 1000, 1));
+ var fixture = AutoscalingTester.fixture()
+ .initialResources(Optional.of(now))
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyMemLoad(0.02, 120);
+ fixture.tester().assertResources("Scaling down",
+ 6, 1, 3.1, 4.0, 100.0,
+ fixture.autoscale());
}
@Test
public void scaling_down_only_after_delay() {
- NodeResources hostResources = new NodeResources(6, 100, 100, 1);
- ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
- ClusterResources max = new ClusterResources(20, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(hostResources);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- tester.deploy(application1, cluster1, 6, 1, hostResources.withVcpu(hostResources.vcpu() / 2));
-
- // No autoscaling as it is too soon to scale down after initial deploy (counting as a scaling event)
- tester.addMemMeasurements(0.02f, 0.95f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- assertTrue(tester.autoscale(application1, cluster1, capacity).target().isEmpty());
-
- // Trying the same later causes autoscaling
- tester.clock().advance(Duration.ofDays(2));
- tester.addMemMeasurements(0.02f, 0.95f, 120, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling down",
- 6, 1, 1.4, 4.0, 95.0,
- tester.autoscale(application1, cluster1, capacity));
+ var fixture = AutoscalingTester.fixture().build();
+ fixture.loader().applyMemLoad(0.02, 120);
+ assertTrue("Too soon after initial deployment", fixture.autoscale().target().isEmpty());
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyMemLoad(0.02, 120);
+ fixture.tester().assertResources("Scaling down since enough time has passed",
+ 6, 1, 1.2, 4.0, 80.0,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_considers_real_resources() {
- NodeResources hostResources = new NodeResources(60, 100, 1000, 10);
- ClusterResources min = new ClusterResources(2, 1, new NodeResources( 2, 20, 200, 1));
- ClusterResources max = new ClusterResources(4, 1, new NodeResources(60, 100, 1000, 1));
- var capacity = Capacity.from(min, max);
-
{ // No memory tax
- AutoscalingTester tester = new AutoscalingTester(new Zone(Environment.prod, RegionName.from("us-east")),
- hostResources,
- new OnlySubtractingWhenForecastingCalculator(0));
-
- ApplicationId application1 = tester.applicationId("app1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- tester.deploy(application1, cluster1, min);
- tester.addMeasurements(1.0f, 1.0f, 0.7f, 0, 1000, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up",
- 4, 1, 6.7, 20.5, 200,
- tester.autoscale(application1, cluster1, capacity));
+ var fixture = AutoscalingTester.fixture()
+ .resourceCalculator(new OnlySubtractingWhenForecastingCalculator(0))
+ .build();
+ fixture.loader().applyLoad(1.0, 1.0, 0.7, 1000);
+ fixture.tester().assertResources("Scaling up",
+ 9, 1, 5.0, 9.6, 72.9,
+ fixture.autoscale());
}
- { // 15 Gb memory tax
- AutoscalingTester tester = new AutoscalingTester(new Zone(Environment.prod, RegionName.from("us-east")),
- hostResources,
- new OnlySubtractingWhenForecastingCalculator(15));
-
- ApplicationId application1 = tester.applicationId("app1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- tester.deploy(application1, cluster1, min);
- tester.addMeasurements(1.0f, 1.0f, 0.7f, 0, 1000, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling up",
- 4, 1, 6.7, 35.5, 200,
- tester.autoscale(application1, cluster1, capacity));
+ {
+ var fixture = AutoscalingTester.fixture()
+ .resourceCalculator(new OnlySubtractingWhenForecastingCalculator(3))
+ .build();
+ fixture.loader().applyLoad(1.0, 1.0, 0.7, 1000);
+ fixture.tester().assertResources("With 3Gb memory tax, we scale up memory more",
+ 7, 1, 6.4, 15.8, 97.2,
+ fixture.autoscale());
}
}
@@ -568,235 +434,193 @@ public class AutoscalingTest {
public void test_autoscaling_with_dynamic_provisioning() {
ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
ClusterResources max = new ClusterResources(20, 1, new NodeResources(100, 1000, 1000, 1));
- var capacity = Capacity.from(min, max);
- List<Flavor> flavors = new ArrayList<>();
- flavors.add(new Flavor("aws-xlarge", new NodeResources(3, 200, 100, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.remote)));
- flavors.add(new Flavor("aws-large", new NodeResources(3, 150, 100, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.remote)));
- flavors.add(new Flavor("aws-medium", new NodeResources(3, 100, 100, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.remote)));
- flavors.add(new Flavor("aws-small", new NodeResources(3, 80, 100, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.remote)));
- AutoscalingTester tester = new AutoscalingTester(new Zone(Cloud.builder()
- .dynamicProvisioning(true)
- .build(),
- SystemName.main,
- Environment.prod, RegionName.from("us-east")),
- flavors);
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.content, "cluster1");
-
- // deploy (Why 103 Gb memory? See AutoscalingTester.MockHostResourcesCalculator
- tester.deploy(application1, cluster1, 5, 1, new NodeResources(3, 103, 100, 1));
-
- tester.clock().advance(Duration.ofDays(2));
- tester.addMemMeasurements(0.9f, 0.6f, 120, application1);
- ClusterResources scaledResources = tester.assertResources("Scaling up since resource usage is too high.",
- 8, 1, 3, 83, 34.3,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.deploy(application1, cluster1, scaledResources);
- tester.deactivateRetired(application1, cluster1, scaledResources);
-
- tester.clock().advance(Duration.ofDays(2));
- tester.addMemMeasurements(0.3f, 0.6f, 1000, application1);
- tester.clock().advance(Duration.ofMinutes(-10 * 5));
- tester.addQueryRateMeasurements(application1, cluster1.id(), 10, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.assertResources("Scaling down since resource usage has gone down",
- 5, 1, 3, 83, 36.0,
- tester.autoscale(application1, cluster1, capacity));
+ var fixture = AutoscalingTester.fixture()
+ .dynamicProvisioning(true)
+ .hostResources(new NodeResources(3, 200, 100, 1, fast, remote),
+ new NodeResources(3, 150, 100, 1, fast, remote),
+ new NodeResources(3, 100, 100, 1, fast, remote),
+ new NodeResources(3, 80, 100, 1, fast, remote))
+ .capacity(Capacity.from(min, max))
+ .initialResources(Optional.of(new ClusterResources(5, 1,
+ new NodeResources(3, 100, 100, 1))))
+ .build();
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyMemLoad(0.9, 120);
+ var scaledResources = fixture.tester().assertResources("Scaling up since resource usage is too high.",
+ 8, 1, 3, 80, 57.1,
+ fixture.autoscale());
+ fixture.deploy(Capacity.from(scaledResources));
+ fixture.deactivateRetired(Capacity.from(scaledResources));
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyMemLoad(0.3, 1000);
+ fixture.tester().assertResources("Scaling down since resource usage has gone down",
+ 5, 1, 3, 80, 100.0,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_considers_read_share() {
- NodeResources resources = new NodeResources(3, 100, 100, 1);
- ClusterResources min = new ClusterResources( 1, 1, resources);
- ClusterResources max = new ClusterResources(10, 1, resources);
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(resources.withVcpu(resources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- tester.deploy(application1, cluster1, 5, 1, resources);
- tester.addQueryRateMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addCpuMeasurements(0.25f, 1f, 100, application1);
+ var min = new ClusterResources( 1, 1, new NodeResources(3, 100, 100, 1));
+ var max = new ClusterResources(10, 1, new NodeResources(3, 100, 100, 1));
+ var fixture = AutoscalingTester.fixture()
+ .capacity(Capacity.from(min, max))
+ .build();
+ fixture.tester.clock().advance(Duration.ofDays(1));
+ fixture.loader().applyCpuLoad(0.25, 120);
// (no read share stored)
- tester.assertResources("Advice to scale up since we set aside for bcp by default",
- 7, 1, 3, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.storeReadShare(0.25, 0.5, application1);
- tester.assertResources("Half of global share is the same as the default assumption used above",
- 7, 1, 3, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.storeReadShare(0.5, 0.5, application1);
- tester.assertResources("Advice to scale down since we don't need room for bcp",
- 4, 1, 3, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
+ fixture.tester().assertResources("Advice to scale up since we set aside for bcp by default",
+ 7, 1, 3, 100, 100,
+ fixture.autoscale());
+
+ fixture.storeReadShare(0.25, 0.5);
+ fixture.tester().assertResources("Half of global share is the same as the default assumption used above",
+ 7, 1, 3, 100, 100,
+ fixture.autoscale());
+
+ fixture.storeReadShare(0.5, 0.5);
+ fixture.tester().assertResources("Advice to scale down since we don't need room for bcp",
+ 6, 1, 3, 100, 100,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_considers_growth_rate() {
- NodeResources minResources = new NodeResources( 1, 100, 100, 1);
- NodeResources midResources = new NodeResources( 5, 100, 100, 1);
- NodeResources maxResources = new NodeResources(10, 100, 100, 1);
- ClusterResources min = new ClusterResources(5, 1, minResources);
- ClusterResources max = new ClusterResources(5, 1, maxResources);
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(maxResources.withVcpu(maxResources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- tester.deploy(application1, cluster1, 5, 1, midResources);
- Duration timeAdded = tester.addQueryRateMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0);
- tester.clock().advance(timeAdded.negated());
- tester.addCpuMeasurements(0.25f, 1f, 200, application1);
-
- // (no query rate data)
- tester.assertResources("Scale up since we assume we need 2x cpu for growth when no data scaling time data",
- 5, 1, 6.3, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.setScalingDuration(application1, cluster1.id(), Duration.ofMinutes(5));
- timeAdded = tester.addQueryRateMeasurements(application1, cluster1.id(),
- 100,
- t -> 10.0 + (t < 50 ? t : 100 - t));
- tester.clock().advance(timeAdded.negated());
- tester.addCpuMeasurements(0.25f, 1f, 200, application1);
- tester.assertResources("Scale down since observed growth is slower than scaling time",
- 5, 1, 3.4, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.clearQueryRateMeasurements(application1, cluster1.id());
-
- tester.setScalingDuration(application1, cluster1.id(), Duration.ofMinutes(60));
- timeAdded = tester.addQueryRateMeasurements(application1, cluster1.id(),
- 100,
- t -> 10.0 + (t < 50 ? t * t * t : 125000 - (t - 49) * (t - 49) * (t - 49)));
- tester.clock().advance(timeAdded.negated());
- tester.addCpuMeasurements(0.25f, 1f, 200, application1);
- tester.assertResources("Scale up since observed growth is faster than scaling time",
- 5, 1, 10.0, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
+ var fixture = AutoscalingTester.fixture().build();
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ Duration timeAdded = fixture.loader().addLoadMeasurements(100, t -> t == 0 ? 20.0 : 10.0, t -> 0.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.25, 200);
+
+ fixture.tester().assertResources("Scale up since we assume we need 2x cpu for growth when no data scaling time data",
+ 9, 1, 2.1, 5, 50,
+ fixture.autoscale());
+
+ fixture.setScalingDuration(Duration.ofMinutes(5));
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100, t -> 10.0 + (t < 50 ? t : 100 - t), t -> 0.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.25, 200);
+ fixture.tester().assertResources("Scale down since observed growth is slower than scaling time",
+ 9, 1, 1.8, 5, 50,
+ fixture.autoscale());
+
+ fixture.setScalingDuration(Duration.ofMinutes(60));
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100,
+ t -> 10.0 + (t < 50 ? t * t * t : 125000 - (t - 49) * (t - 49) * (t - 49)),
+ t -> 0.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.25, 200);
+ fixture.tester().assertResources("Scale up since observed growth is faster than scaling time",
+ 9, 1, 2.1, 5, 50,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_considers_query_vs_write_rate() {
- NodeResources minResources = new NodeResources( 1, 100, 100, 1);
- NodeResources midResources = new NodeResources( 5, 100, 100, 1);
- NodeResources maxResources = new NodeResources(10, 100, 100, 1);
- ClusterResources min = new ClusterResources(5, 1, minResources);
- ClusterResources max = new ClusterResources(5, 1, maxResources);
- var capacity = Capacity.from(min, max);
- AutoscalingTester tester = new AutoscalingTester(maxResources.withVcpu(maxResources.vcpu() * 2));
-
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
+ var fixture = AutoscalingTester.fixture().build();
- tester.deploy(application1, cluster1, 5, 1, midResources);
- tester.addCpuMeasurements(0.4f, 1f, 120, application1);
+ fixture.loader().addCpuMeasurements(0.4, 220);
// Why twice the query rate at time = 0?
// This makes headroom for queries doubling, which we want to observe the effect of here
- tester.addCpuMeasurements(0.4f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0, t -> 10.0);
- tester.assertResources("Query and write load is equal -> scale up somewhat",
- 5, 1, 7.3, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.addCpuMeasurements(0.4f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 80.0 : 40.0, t -> 10.0);
- tester.assertResources("Query load is 4x write load -> scale up more",
- 5, 1, 9.5, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.addCpuMeasurements(0.3f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0, t -> 100.0);
- tester.assertResources("Write load is 10x query load -> scale down",
- 5, 1, 2.9, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.addCpuMeasurements(0.4f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 100, t -> t == 0 ? 20.0 : 10.0, t-> 0.0);
- tester.assertResources("Query only -> largest possible",
- 5, 1, 10.0, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
-
- tester.addCpuMeasurements(0.4f, 1f, 100, application1);
- tester.clock().advance(Duration.ofMinutes(-100 * 5));
- tester.addLoadMeasurements(application1, cluster1.id(), 100, t -> 0.0, t -> 10.0);
- tester.assertResources("Write only -> smallest possible",
- 5, 1, 2.1, 100, 100,
- tester.autoscale(application1, cluster1, capacity));
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ var timeAdded = fixture.loader().addLoadMeasurements(100, t -> t == 0 ? 20.0 : 10.0, t -> 10.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.4, 200);
+ fixture.tester.assertResources("Query and write load is equal -> scale up somewhat",
+ 9, 1, 2.4, 5, 50,
+ fixture.autoscale());
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100, t -> t == 0 ? 80.0 : 40.0, t -> 10.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.4, 200);
+ // TODO: Ackhually, we scale down here - why?
+ fixture.tester().assertResources("Query load is 4x write load -> scale up more",
+ 9, 1, 2.1, 5, 50,
+ fixture.autoscale());
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100, t -> t == 0 ? 20.0 : 10.0, t -> 100.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.4, 200);
+ fixture.tester().assertResources("Write load is 10x query load -> scale down",
+ 9, 1, 1.1, 5, 50,
+ fixture.autoscale());
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100, t -> t == 0 ? 20.0 : 10.0, t-> 0.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.4, 200);
+ fixture.tester().assertResources("Query only -> largest possible",
+ 8, 1, 4.9, 5.7, 57.1,
+ fixture.autoscale());
+
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ timeAdded = fixture.loader().addLoadMeasurements(100, t -> 0.0, t -> 10.0);
+ fixture.tester.clock().advance(timeAdded.negated());
+ fixture.loader().addCpuMeasurements(0.4, 200);
+ fixture.tester().assertResources("Write only -> smallest possible",
+ 6, 1, 1.0, 8, 80,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_in_dev() {
- NodeResources resources = new NodeResources(1, 4, 50, 1);
- ClusterResources min = new ClusterResources( 1, 1, resources);
- ClusterResources max = new ClusterResources(3, 1, resources);
- Capacity capacity = Capacity.from(min, max, false, true);
-
- AutoscalingTester tester = new AutoscalingTester(Environment.dev, resources.withVcpu(resources.vcpu() * 2));
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- tester.deploy(application1, cluster1, capacity);
- tester.addQueryRateMeasurements(application1, cluster1.id(),
- 500, t -> 100.0);
- tester.addCpuMeasurements(1.0f, 1f, 10, application1);
+ var fixture = AutoscalingTester.fixture()
+ .zone(new Zone(Environment.dev, RegionName.from("us-east")))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(1.0, 1.0, 1.0, 200);
assertTrue("Not attempting to scale up because policies dictate we'll only get one node",
- tester.autoscale(application1, cluster1, capacity).target().isEmpty());
+ fixture.autoscale().target().isEmpty());
}
/** Same setup as test_autoscaling_in_dev(), just with required = true */
@Test
public void test_autoscaling_in_dev_with_required_resources() {
- NodeResources resources = new NodeResources(1, 4, 50, 1);
- ClusterResources min = new ClusterResources( 1, 1, resources);
- ClusterResources max = new ClusterResources(3, 1, resources);
- Capacity capacity = Capacity.from(min, max, true, true);
-
- AutoscalingTester tester = new AutoscalingTester(Environment.dev, resources.withVcpu(resources.vcpu() * 2));
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- tester.deploy(application1, cluster1, capacity);
- tester.addQueryRateMeasurements(application1, cluster1.id(),
- 500, t -> 100.0);
- tester.addCpuMeasurements(1.0f, 1f, 10, application1);
- tester.assertResources("We scale up even in dev because resources are required",
- 3, 1, 1.0, 4, 50,
- tester.autoscale(application1, cluster1, capacity));
+ var requiredCapacity =
+ Capacity.from(new ClusterResources(2, 1,
+ new NodeResources(1, 1, 1, 1, NodeResources.DiskSpeed.any)),
+ new ClusterResources(20, 1,
+ new NodeResources(100, 1000, 1000, 1, NodeResources.DiskSpeed.any)),
+ true,
+ true);
+
+ var fixture = AutoscalingTester.fixture()
+ .capacity(requiredCapacity)
+ .zone(new Zone(Environment.dev, RegionName.from("us-east")))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(1.0, 1.0, 1.0, 200);
+ fixture.tester().assertResources("We scale even in dev because resources are required",
+ 3, 1, 1.0, 7.7, 83.3,
+ fixture.autoscale());
}
@Test
public void test_autoscaling_in_dev_with_required_unspecified_resources() {
- NodeResources resources = NodeResources.unspecified();
- ClusterResources min = new ClusterResources( 1, 1, resources);
- ClusterResources max = new ClusterResources(3, 1, resources);
- Capacity capacity = Capacity.from(min, max, true, true);
-
- AutoscalingTester tester = new AutoscalingTester(Environment.dev,
- new NodeResources(10, 16, 100, 2));
- ApplicationId application1 = tester.applicationId("application1");
- ClusterSpec cluster1 = tester.clusterSpec(ClusterSpec.Type.container, "cluster1");
-
- tester.deploy(application1, cluster1, capacity);
- tester.addQueryRateMeasurements(application1, cluster1.id(),
- 500, t -> 100.0);
- tester.addCpuMeasurements(1.0f, 1f, 10, application1);
- tester.assertResources("We scale up even in dev because resources are required",
- 3, 1, 1.5, 8, 50,
- tester.autoscale(application1, cluster1, capacity));
+ var requiredCapacity =
+ Capacity.from(new ClusterResources(1, 1, NodeResources.unspecified()),
+ new ClusterResources(3, 1, NodeResources.unspecified()),
+ true,
+ true);
+
+ var fixture = AutoscalingTester.fixture()
+ .capacity(requiredCapacity)
+ .zone(new Zone(Environment.dev, RegionName.from("us-east")))
+ .build();
+ fixture.tester().clock().advance(Duration.ofDays(2));
+ fixture.loader().applyLoad(1.0, 1.0, 1.0, 200);
+ fixture.tester().assertResources("We scale even in dev because resources are required",
+ 3, 1, 1.5, 8, 50,
+ fixture.autoscale());
}
/**
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTester.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTester.java
index 94b938fc886..e21c57b3ef5 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTester.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/AutoscalingTester.java
@@ -1,22 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.autoscale;
-import com.yahoo.collections.Pair;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Capacity;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
-import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
-import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.Zone;
import com.yahoo.test.ManualClock;
import com.yahoo.transaction.Mutex;
import com.yahoo.vespa.hosted.provision.Node;
-import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.Nodelike;
import com.yahoo.vespa.hosted.provision.applications.Application;
@@ -29,11 +25,9 @@ import com.yahoo.vespa.hosted.provision.provisioning.HostResourcesCalculator;
import com.yahoo.vespa.hosted.provision.provisioning.ProvisioningTester;
import java.time.Duration;
-import java.time.Instant;
+import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
import java.util.Set;
-import java.util.function.IntFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -45,52 +39,48 @@ class AutoscalingTester {
private final ProvisioningTester provisioningTester;
private final Autoscaler autoscaler;
- private final MockHostResourcesCalculator hostResourcesCalculator;
+ private final HostResourcesCalculator hostResourcesCalculator;
private final CapacityPolicies capacityPolicies;
- /** Creates an autoscaling tester with a single host type ready */
- public AutoscalingTester(NodeResources hostResources) {
- this(Environment.prod, hostResources);
+ public AutoscalingTester(Zone zone, HostResourcesCalculator resourcesCalculator, List<NodeResources> hostResources) {
+ this(zone, hostResources, resourcesCalculator, 20);
}
- public AutoscalingTester(Environment environment, NodeResources hostResources) {
- this(new Zone(environment, RegionName.from("us-east")), hostResources, null);
- }
-
- public AutoscalingTester(Zone zone, NodeResources hostResources) {
- this(zone, hostResources, null);
- }
-
- public AutoscalingTester(Zone zone, NodeResources hostResources, HostResourcesCalculator resourcesCalculator) {
- this(zone, List.of(new Flavor("hostFlavor", hostResources)), resourcesCalculator);
- provisioningTester.makeReadyNodes(20, "hostFlavor", NodeType.host, 8);
+ private AutoscalingTester(Zone zone, List<NodeResources> hostResources, HostResourcesCalculator resourcesCalculator, int hostCount) {
+ this(zone, toFlavors(hostResources), resourcesCalculator);
+ for (Flavor flavor : toFlavors(hostResources))
+ provisioningTester.makeReadyNodes(hostCount, flavor.name(), NodeType.host, 8);
provisioningTester.activateTenantHosts();
}
- public AutoscalingTester(Zone zone, List<Flavor> flavors) {
- this(zone, flavors, new MockHostResourcesCalculator(zone));
- }
-
- private AutoscalingTester(Zone zone, List<Flavor> flavors,
- HostResourcesCalculator resourcesCalculator) {
+ private AutoscalingTester(Zone zone, List<Flavor> flavors, HostResourcesCalculator resourcesCalculator) {
provisioningTester = new ProvisioningTester.Builder().zone(zone)
.flavors(flavors)
.resourcesCalculator(resourcesCalculator)
.hostProvisioner(zone.getCloud().dynamicProvisioning() ? new MockHostProvisioner(flavors) : null)
.build();
- hostResourcesCalculator = new MockHostResourcesCalculator(zone);
+ hostResourcesCalculator = resourcesCalculator;
autoscaler = new Autoscaler(nodeRepository());
capacityPolicies = new CapacityPolicies(provisioningTester.nodeRepository());
}
+ private static List<Flavor> toFlavors(List<NodeResources> resources) {
+ List<Flavor> flavors = new ArrayList<>();
+ for (int i = 0; i < resources.size(); i++)
+ flavors.add(new Flavor("flavor" + i, resources.get(i)));
+ return flavors;
+ }
+
+ public static Fixture.Builder fixture() { return new Fixture.Builder(); }
+
public ProvisioningTester provisioning() { return provisioningTester; }
- public ApplicationId applicationId(String applicationName) {
+ public static ApplicationId applicationId(String applicationName) {
return ApplicationId.from("tenant1", applicationName, "instance1");
}
- public ClusterSpec clusterSpec(ClusterSpec.Type type, String clusterId) {
+ public static ClusterSpec clusterSpec(ClusterSpec.Type type, String clusterId) {
return ClusterSpec.request(type, ClusterSpec.Id.from(clusterId)).vespaVersion("7").build();
}
@@ -120,141 +110,14 @@ class AutoscalingTester {
nodeRepository().nodes().setReady(List.of(host), Agent.system, getClass().getSimpleName());
}
- public void deactivateRetired(ApplicationId application, ClusterSpec cluster, ClusterResources resources) {
- try (Mutex lock = nodeRepository().nodes().lock(application)){
+ public void deactivateRetired(ApplicationId application, ClusterSpec cluster, Capacity capacity) {
+ try (Mutex lock = nodeRepository().nodes().lock(application)) {
for (Node node : nodeRepository().nodes().list(Node.State.active).owner(application)) {
if (node.allocation().get().membership().retired())
nodeRepository().nodes().write(node.with(node.allocation().get().removable(true, true)), lock);
}
}
- deploy(application, cluster, resources);
- }
-
- /**
- * Adds measurements with the given resource value and ideal values for the other resources,
- * scaled to take one node redundancy into account.
- * (I.e we adjust to measure a bit lower load than "naively" wanted to offset for the autoscaler
- * wanting to see the ideal load with one node missing.)
- *
- * @param otherResourcesLoad the load factor relative to ideal to use for other resources
- * @param count the number of measurements
- * @param applicationId the application we're adding measurements for all nodes of
- */
- public void addCpuMeasurements(float value, float otherResourcesLoad,
- int count, ApplicationId applicationId) {
- NodeList nodes = nodeRepository().nodes().list(Node.State.active).owner(applicationId);
- float oneExtraNodeFactor = (float)(nodes.size() - 1.0) / (nodes.size());
- for (int i = 0; i < count; i++) {
- clock().advance(Duration.ofSeconds(150));
- for (Node node : nodes) {
- Load load = new Load(value,
- ClusterModel.idealMemoryLoad * otherResourcesLoad,
- ClusterModel.idealContentDiskLoad * otherResourcesLoad).multiply(oneExtraNodeFactor);
- nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
- new NodeMetricSnapshot(clock().instant(),
- load,
- 0,
- true,
- true,
- 0.0))));
- }
- }
- }
-
- /**
- * Adds measurements with the given resource value and ideal values for the other resources,
- * scaled to take one node redundancy into account.
- * (I.e we adjust to measure a bit lower load than "naively" wanted to offset for the autoscaler
- * wanting to see the ideal load with one node missing.)
- *
- * @param otherResourcesLoad the load factor relative to ideal to use for other resources
- * @param count the number of measurements
- * @param applicationId the application we're adding measurements for all nodes of
- * @return the duration added to the current time by this
- */
- public Duration addDiskMeasurements(float value, float otherResourcesLoad,
- int count, ApplicationId applicationId) {
- NodeList nodes = nodeRepository().nodes().list(Node.State.active).owner(applicationId);
- float oneExtraNodeFactor = (float)(nodes.size() - 1.0) / (nodes.size());
- Instant initialTime = clock().instant();
- for (int i = 0; i < count; i++) {
- clock().advance(Duration.ofSeconds(150));
- for (Node node : nodes) {
- Load load = new Load(ClusterModel.idealQueryCpuLoad * otherResourcesLoad,
- ClusterModel.idealContentDiskLoad * otherResourcesLoad,
- value).multiply(oneExtraNodeFactor);
- nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
- new NodeMetricSnapshot(clock().instant(),
- load,
- 0,
- true,
- true,
- 0.0))));
- }
- }
- return Duration.between(initialTime, clock().instant());
- }
-
- /**
- * Adds measurements with the given resource value and ideal values for the other resources,
- * scaled to take one node redundancy into account.
- * (I.e we adjust to measure a bit lower load than "naively" wanted to offset for the autoscaler
- * wanting to see the ideal load with one node missing.)
- *
- * @param otherResourcesLoad the load factor relative to ideal to use for other resources
- * @param count the number of measurements
- * @param applicationId the application we're adding measurements for all nodes of
- */
- public void addMemMeasurements(float value, float otherResourcesLoad,
- int count, ApplicationId applicationId) {
- NodeList nodes = nodeRepository().nodes().list(Node.State.active).owner(applicationId);
- float oneExtraNodeFactor = (float)(nodes.size() - 1.0) / (nodes.size());
- for (int i = 0; i < count; i++) {
- clock().advance(Duration.ofMinutes(1));
- for (Node node : nodes) {
- float cpu = (float) 0.2 * otherResourcesLoad * oneExtraNodeFactor;
- float memory = value * oneExtraNodeFactor;
- float disk = (float) ClusterModel.idealContentDiskLoad * otherResourcesLoad * oneExtraNodeFactor;
- Load load = new Load(0.2 * otherResourcesLoad,
- value,
- ClusterModel.idealContentDiskLoad * otherResourcesLoad).multiply(oneExtraNodeFactor);
- nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
- new NodeMetricSnapshot(clock().instant(),
- load,
- 0,
- true,
- true,
- 0.0))));
- }
- }
- }
-
- public void addMeasurements(float cpu, float memory, float disk, int generation, int count, ApplicationId applicationId) {
- addMeasurements(cpu, memory, disk, generation, true, true, count, applicationId);
- }
-
- public void addMeasurements(float cpu, float memory, float disk, int generation, boolean inService, boolean stable,
- int count, ApplicationId applicationId) {
- NodeList nodes = nodeRepository().nodes().list(Node.State.active).owner(applicationId);
- for (int i = 0; i < count; i++) {
- clock().advance(Duration.ofMinutes(1));
- for (Node node : nodes) {
- nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
- new NodeMetricSnapshot(clock().instant(),
- new Load(cpu, memory, disk),
- generation,
- inService,
- stable,
- 0.0))));
- }
- }
- }
-
- public void storeReadShare(double currentReadShare, double maxReadShare, ApplicationId applicationId) {
- Application application = nodeRepository().applications().require(applicationId);
- application = application.with(application.status().withCurrentReadShare(currentReadShare)
- .withMaxReadShare(maxReadShare));
- nodeRepository().applications().put(application, nodeRepository().nodes().lock(applicationId));
+ deploy(application, cluster, capacity);
}
/** Creates a single redeployment event with bogus data except for the given duration */
@@ -277,41 +140,6 @@ class AutoscalingTester {
nodeRepository().applications().put(application, nodeRepository().nodes().lock(applicationId));
}
- /** Creates the given number of measurements, spaced 5 minutes between, using the given function */
- public void addLoadMeasurements(ApplicationId application,
- ClusterSpec.Id cluster,
- int measurements,
- IntFunction<Double> queryRate,
- IntFunction<Double> writeRate) {
- for (int i = 0; i < measurements; i++) {
- nodeMetricsDb().addClusterMetrics(application,
- Map.of(cluster, new ClusterMetricSnapshot(clock().instant(),
- queryRate.apply(i),
- writeRate.apply(i))));
- clock().advance(Duration.ofMinutes(5));
- }
- }
-
- /** Creates the given number of measurements, spaced 5 minutes between, using the given function */
- public Duration addQueryRateMeasurements(ApplicationId application,
- ClusterSpec.Id cluster,
- int measurements,
- IntFunction<Double> queryRate) {
- Instant initialTime = clock().instant();
- for (int i = 0; i < measurements; i++) {
- nodeMetricsDb().addClusterMetrics(application,
- Map.of(cluster, new ClusterMetricSnapshot(clock().instant(),
- queryRate.apply(i),
- 0.0)));
- clock().advance(Duration.ofMinutes(5));
- }
- return Duration.between(initialTime, clock().instant());
- }
-
- public void clearQueryRateMeasurements(ApplicationId application, ClusterSpec.Id cluster) {
- ((MemoryMetricsDb)nodeMetricsDb()).clearClusterMetrics(application, cluster);
- }
-
public Autoscaler.Advice autoscale(ApplicationId applicationId, ClusterSpec cluster, Capacity capacity) {
capacity = capacityPolicies.applyOn(capacity, applicationId, capacityPolicies.decideExclusivity(capacity, cluster.isExclusive()));
Application application = nodeRepository().applications().get(applicationId).orElse(Application.empty(applicationId))
@@ -377,18 +205,20 @@ class AutoscalingTester {
public MetricsDb nodeMetricsDb() { return nodeRepository().metricsDb(); }
- private static class MockHostResourcesCalculator implements HostResourcesCalculator {
+ public static class MockHostResourcesCalculator implements HostResourcesCalculator {
private final Zone zone;
+ private double memoryTax = 0;
- public MockHostResourcesCalculator(Zone zone) {
+ public MockHostResourcesCalculator(Zone zone, double memoryTax) {
this.zone = zone;
+ this.memoryTax = memoryTax;
}
@Override
public NodeResources realResourcesOf(Nodelike node, NodeRepository nodeRepository) {
if (zone.getCloud().dynamicProvisioning())
- return node.resources().withMemoryGb(node.resources().memoryGb() - 3);
+ return node.resources().withMemoryGb(node.resources().memoryGb() - memoryTax);
else
return node.resources();
}
@@ -396,19 +226,19 @@ class AutoscalingTester {
@Override
public NodeResources advertisedResourcesOf(Flavor flavor) {
if (zone.getCloud().dynamicProvisioning())
- return flavor.resources().withMemoryGb(flavor.resources().memoryGb() + 3);
+ return flavor.resources().withMemoryGb(flavor.resources().memoryGb() + memoryTax);
else
return flavor.resources();
}
@Override
public NodeResources requestToReal(NodeResources resources, boolean exclusive) {
- return resources.withMemoryGb(resources.memoryGb() - 3);
+ return resources.withMemoryGb(resources.memoryGb() - memoryTax);
}
@Override
public NodeResources realToRequest(NodeResources resources, boolean exclusive) {
- return resources.withMemoryGb(resources.memoryGb() + 3);
+ return resources.withMemoryGb(resources.memoryGb() + memoryTax);
}
@Override
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModelTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModelTest.java
index 516a7a92d04..0559a232065 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModelTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/ClusterModelTest.java
@@ -27,50 +27,60 @@ public class ClusterModelTest {
private static final double delta = 0.001;
@Test
- public void test_traffic_headroom() {
- ManualClock clock = new ManualClock();
- Application application = Application.empty(ApplicationId.from("t1", "a1", "i1"));
- ClusterSpec clusterSpec = clusterSpec();
- Cluster cluster = cluster(new NodeResources(1, 10, 100, 1));
- application = application.with(cluster);
+ public void unit_adjustment_should_cause_no_change() {
+ var model = clusterModelWithNoData(); // 5 nodes, 1 group
+ assertEquals(Load.one(), model.loadAdjustment());
+ var target = model.loadAdjustment().scaled(resources());
+ int testingNodes = 5 - 1;
+ int currentNodes = 5 - 1;
+ assertEquals(resources(), model.loadWith(testingNodes, 1).scaled(Load.one().divide(model.loadWith(currentNodes, 1)).scaled(target)));
+ }
+ @Test
+ public void test_traffic_headroom() {
// No current traffic share: Ideal load is low but capped
- var model1 = new ClusterModel(application.with(new Status(0.0, 1.0)),
- clusterSpec, cluster, clock, Duration.ofMinutes(10),
- timeseries(cluster,100, t -> t == 0 ? 10000.0 : 0.0, t -> 0.0, clock),
- ClusterNodesTimeseries.empty());
- assertEquals(0.131, model1.idealLoad().cpu(), delta);
+ var model1 = clusterModel(new Status(0.0, 1.0),
+ t -> t == 0 ? 10000.0 : 0.0, t -> 0.0);
+ assertEquals(0.10672097759674132, model1.idealLoad().cpu(), delta);
// Almost no current traffic share: Ideal load is low but capped
- var model2 = new ClusterModel(application.with(new Status(0.0001, 1.0)),
- clusterSpec, cluster, clock, Duration.ofMinutes(10),
- timeseries(cluster,100, t -> t == 0 ? 10000.0 : 0.0, t -> 0.0, clock),
- ClusterNodesTimeseries.empty());
- assertEquals(0.131, model2.idealLoad().cpu(), delta);
+ var model2 = clusterModel(new Status(0.0001, 1.0),
+ t -> t == 0 ? 10000.0 : 0.0, t -> 0.0);
+ assertEquals(0.10672097759674132, model2.idealLoad().cpu(), delta);
}
@Test
public void test_growth_headroom() {
- ManualClock clock = new ManualClock();
+ // No current traffic: Ideal load is low but capped
+ var model1 = clusterModel(new Status(0.0, 0.0),
+ t -> t == 0 ? 10000.0 : 0.0, t -> 0.0);
+ assertEquals(0.2240325865580448, model1.idealLoad().cpu(), delta);
+ // Almost no current traffic: Ideal load is low but capped
+ var model2 = clusterModel(new Status(0.0001, 1.0),
+ t -> t == 0 ? 10000.0 : 0.0001, t -> 0.0);
+ assertEquals(0.0326530612244898, model2.idealLoad().cpu(), delta);
+ }
+
+ private ClusterModel clusterModelWithNoData() {
+ return clusterModel(new Status(0.0, 1.0), t -> 0.0, t -> 0.0);
+ }
+
+ private ClusterModel clusterModel(Status status, IntFunction<Double> queryRate, IntFunction<Double> writeRate) {
+ ManualClock clock = new ManualClock();
Application application = Application.empty(ApplicationId.from("t1", "a1", "i1"));
ClusterSpec clusterSpec = clusterSpec();
- Cluster cluster = cluster(new NodeResources(1, 10, 100, 1));
+ Cluster cluster = cluster(resources());
application = application.with(cluster);
- // No current traffic: Ideal load is low but capped
- var model1 = new ClusterModel(application,
- clusterSpec, cluster, clock, Duration.ofMinutes(10),
- timeseries(cluster,100, t -> t == 0 ? 10000.0 : 0.0, t -> 0.0, clock),
- ClusterNodesTimeseries.empty());
- assertEquals(0.275, model1.idealLoad().cpu(), delta);
+ return new ClusterModel(application.with(status),
+ clusterSpec, cluster, clock, Duration.ofMinutes(10),
+ timeseries(cluster,100, queryRate, writeRate, clock),
+ ClusterNodesTimeseries.empty());
+ }
- // Almost no current traffic: Ideal load is low but capped
- var model2 = new ClusterModel(application.with(new Status(0.0001, 1.0)),
- clusterSpec, cluster, clock, Duration.ofMinutes(10),
- timeseries(cluster,100, t -> t == 0 ? 10000.0 : 0.0001, t -> 0.0, clock),
- ClusterNodesTimeseries.empty());
- assertEquals(0.040, model2.idealLoad().cpu(), delta);
+ private NodeResources resources() {
+ return new NodeResources(1, 10, 100, 1);
}
private ClusterSpec clusterSpec() {
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Fixture.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Fixture.java
new file mode 100644
index 00000000000..2edd797b78a
--- /dev/null
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Fixture.java
@@ -0,0 +1,181 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.provision.autoscale;
+
+import com.yahoo.config.provision.ApplicationId;
+import com.yahoo.config.provision.Capacity;
+import com.yahoo.config.provision.Cloud;
+import com.yahoo.config.provision.ClusterResources;
+import com.yahoo.config.provision.ClusterSpec;
+import com.yahoo.config.provision.Environment;
+import com.yahoo.config.provision.NodeResources;
+import com.yahoo.config.provision.RegionName;
+import com.yahoo.config.provision.Zone;
+import com.yahoo.vespa.hosted.provision.Node;
+import com.yahoo.vespa.hosted.provision.NodeList;
+import com.yahoo.vespa.hosted.provision.applications.Application;
+import com.yahoo.vespa.hosted.provision.applications.Cluster;
+import com.yahoo.vespa.hosted.provision.provisioning.HostResourcesCalculator;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Fixture for autoscaling tests.
+ *
+ * @author bratseth
+ */
+public class Fixture {
+
+ final AutoscalingTester tester;
+ final ApplicationId applicationId;
+ final ClusterSpec clusterSpec;
+ final Capacity capacity;
+ final Loader loader;
+
+ public Fixture(Fixture.Builder builder, Optional<ClusterResources> initialResources) {
+ applicationId = builder.application;
+ clusterSpec = builder.cluster;
+ capacity = builder.capacity;
+ tester = new AutoscalingTester(builder.zone, builder.resourceCalculator, builder.hostResources);
+ var deployCapacity = initialResources.isPresent() ? Capacity.from(initialResources.get()) : capacity;
+ tester.deploy(builder.application, builder.cluster, deployCapacity);
+ this.loader = new Loader(this);
+ }
+
+ public AutoscalingTester tester() { return tester; }
+
+ public ApplicationId applicationId() { return applicationId; }
+
+ public ClusterSpec.Id clusterId() { return clusterSpec.id(); }
+
+ public Application application() {
+ return tester().nodeRepository().applications().get(applicationId).orElse(Application.empty(applicationId));
+ }
+
+ public Cluster cluster() {
+ return application().cluster(clusterId()).get();
+ }
+
+ public ClusterModel clusterModel() {
+ return new ClusterModel(application(),
+ clusterSpec,
+ cluster(),
+ nodes(),
+ tester.nodeRepository().metricsDb(),
+ tester.nodeRepository().clock());
+ }
+
+ /** Returns the nodes allocated to the fixture application cluster */
+ public NodeList nodes() {
+ return tester().nodeRepository().nodes().list(Node.State.active).owner(applicationId).cluster(clusterSpec.id());
+ }
+
+ public Loader loader() { return loader; }
+
+ /** Autoscale within the deployed capacity of this. */
+ public Autoscaler.Advice autoscale() {
+ return autoscale(capacity);
+ }
+
+ /** Autoscale within the given capacity. */
+ public Autoscaler.Advice autoscale(Capacity capacity) {
+ return tester().autoscale(applicationId, clusterSpec, capacity);
+ }
+
+ /** Compute an autoscaling suggestion for this. */
+ public Autoscaler.Advice suggest() {
+ return tester().suggest(applicationId, clusterSpec.id(), capacity.minResources(), capacity.maxResources());
+ }
+
+ /** Redeploy with the deployed capacity of this. */
+ public void deploy() {
+ deploy(capacity);
+ }
+
+ /** Redeploy with the given capacity. */
+ public void deploy(Capacity capacity) {
+ tester().deploy(applicationId, clusterSpec, capacity);
+ }
+
+ public void deactivateRetired(Capacity capacity) {
+ tester().deactivateRetired(applicationId, clusterSpec, capacity);
+ }
+
+ public void setScalingDuration(Duration duration) {
+ tester().setScalingDuration(applicationId, clusterSpec.id(), duration);
+ }
+
+ public void storeReadShare(double currentReadShare, double maxReadShare) {
+ var application = application();
+ application = application.with(application.status().withCurrentReadShare(currentReadShare)
+ .withMaxReadShare(maxReadShare));
+ tester.nodeRepository().applications().put(application, tester.nodeRepository().nodes().lock(applicationId));
+ }
+
+ public static class Builder {
+
+ ApplicationId application = AutoscalingTester.applicationId("application1");
+ ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster1")).vespaVersion("7").build();
+ Zone zone = new Zone(Environment.prod, RegionName.from("us-east"));
+ List<NodeResources> hostResources = List.of(new NodeResources(100, 100, 100, 1));
+ Optional<ClusterResources> initialResources = Optional.of(new ClusterResources(5, 1, new NodeResources(3, 10, 100, 1)));
+ Capacity capacity = Capacity.from(new ClusterResources(2, 1,
+ new NodeResources(1, 1, 1, 1, NodeResources.DiskSpeed.any)),
+ new ClusterResources(20, 1,
+ new NodeResources(100, 1000, 1000, 1, NodeResources.DiskSpeed.any)));
+ HostResourcesCalculator resourceCalculator = new AutoscalingTester.MockHostResourcesCalculator(zone, 0);
+
+ public Fixture.Builder zone(Zone zone) {
+ this.zone = zone;
+ return this;
+ }
+
+ /**
+ * Set to true to behave as if hosts are provisioned dynamically,
+ * and must therefore be allocated completely to one tenant node.
+ */
+ public Fixture. Builder dynamicProvisioning(boolean dynamic) {
+ this.zone = new Zone(Cloud.builder()
+ .dynamicProvisioning(dynamic)
+ .build(),
+ zone.system(),
+ zone.environment(),
+ zone.region());
+ return this;
+ }
+
+ public Fixture.Builder clusterType(ClusterSpec.Type type) {
+ cluster = ClusterSpec.request(type, cluster.id()).vespaVersion("7").build();
+ return this;
+ }
+
+ public Fixture.Builder hostResources(NodeResources ... hostResources) {
+ this.hostResources = Arrays.stream(hostResources).collect(Collectors.toList());
+ return this;
+ }
+
+ public Fixture.Builder initialResources(Optional<ClusterResources> initialResources) {
+ this.initialResources = initialResources;
+ return this;
+ }
+
+ public Fixture.Builder capacity(Capacity capacity) {
+ this.capacity = capacity;
+ return this;
+ }
+
+ public Fixture.Builder resourceCalculator(HostResourcesCalculator resourceCalculator) {
+ this.resourceCalculator = resourceCalculator;
+ return this;
+ }
+
+ public Fixture build() {
+ return new Fixture(this, initialResources);
+ }
+
+ }
+
+}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Loader.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Loader.java
new file mode 100644
index 00000000000..c0203f5f202
--- /dev/null
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/autoscale/Loader.java
@@ -0,0 +1,160 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.hosted.provision.autoscale;
+
+import com.yahoo.collections.Pair;
+import com.yahoo.vespa.hosted.provision.Node;
+import com.yahoo.vespa.hosted.provision.NodeList;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.function.IntFunction;
+
+/**
+ * A helper for applying load to an application represented by a fixture,
+ *
+ * @author bratseth
+ */
+public class Loader {
+
+ private final Fixture fixture;
+
+ public Loader(Fixture fixture) {
+ this.fixture = fixture;
+ }
+
+ /**
+ * Adds measurements with the given resource value and ideal values for the other resources,
+ * scaled to take one node redundancy into account.
+ * (I.e we adjust to measure a bit lower load than "naively" wanted to offset for the autoscaler
+ * wanting to see the ideal load with one node missing.)
+ *
+ * @param count the number of measurements
+ */
+ public Duration addCpuMeasurements(double value, int count) {
+ var idealLoad = fixture.clusterModel().idealLoad(); // TODO: Use this
+ NodeList nodes = fixture.nodes();
+ float oneExtraNodeFactor = (float)(nodes.size() - 1.0) / (nodes.size());
+ Instant initialTime = fixture.tester().clock().instant();
+ for (int i = 0; i < count; i++) {
+ fixture.tester().clock().advance(Duration.ofSeconds(150));
+ for (Node node : nodes) {
+ Load load = new Load(value,
+ ClusterModel.idealMemoryLoad,
+ ClusterModel.idealContentDiskLoad).multiply(oneExtraNodeFactor);
+ fixture.tester().nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
+ new NodeMetricSnapshot(fixture.tester().clock().instant(),
+ load,
+ 0,
+ true,
+ true,
+ 0.0))));
+ }
+ }
+ return Duration.between(initialTime, fixture.tester().clock().instant());
+ }
+
+ /** Creates the given number of measurements, spaced 5 minutes between, using the given function */
+ public Duration addLoadMeasurements(int measurements, IntFunction<Double> queryRate, IntFunction<Double> writeRate) {
+ Instant initialTime = fixture.tester().clock().instant();
+ for (int i = 0; i < measurements; i++) {
+ fixture.tester().nodeMetricsDb().addClusterMetrics(fixture.applicationId(),
+ Map.of(fixture.clusterId(), new ClusterMetricSnapshot(fixture.tester().clock().instant(),
+ queryRate.apply(i),
+ writeRate.apply(i))));
+ fixture.tester().clock().advance(Duration.ofMinutes(5));
+ }
+ return Duration.between(initialTime, fixture.tester().clock().instant());
+ }
+
+ public void applyCpuLoad(double cpuLoad, int measurements) {
+ Duration samplingInterval = Duration.ofSeconds(150L); // in addCpuMeasurements
+ addCpuMeasurements((float)cpuLoad, measurements);
+ fixture.tester().clock().advance(samplingInterval.negated().multipliedBy(measurements));
+ addQueryRateMeasurements(measurements, samplingInterval, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
+ }
+
+ public void applyMemLoad(double memLoad, int measurements) {
+ Duration samplingInterval = Duration.ofSeconds(150L); // in addMemMeasurements
+ addMemMeasurements(memLoad, measurements);
+ fixture.tester().clock().advance(samplingInterval.negated().multipliedBy(measurements));
+ addQueryRateMeasurements(measurements, samplingInterval, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
+ }
+
+ /**
+ * Adds measurements with the given resource value and ideal values for the other resources,
+ * scaled to take one node redundancy into account.
+ * (I.e we adjust to measure a bit lower load than "naively" wanted to offset for the autoscaler
+ * wanting to see the ideal load with one node missing.)
+ */
+ public void addMemMeasurements(double value, int count) {
+ var idealLoad = fixture.clusterModel().idealLoad(); // TODO: Use this
+ NodeList nodes = fixture.nodes();
+ float oneExtraNodeFactor = (float)(nodes.size() - 1.0) / (nodes.size());
+ for (int i = 0; i < count; i++) {
+ fixture.tester().clock().advance(Duration.ofMinutes(1));
+ for (Node node : nodes) {
+ Load load = new Load(0.2,
+ value,
+ ClusterModel.idealContentDiskLoad).multiply(oneExtraNodeFactor);
+ fixture.tester().nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
+ new NodeMetricSnapshot(fixture.tester().clock().instant(),
+ load,
+ 0,
+ true,
+ true,
+ 0.0))));
+ }
+ }
+ }
+
+ public Duration addMeasurements(double cpu, double memory, double disk, int count) {
+ return addMeasurements(cpu, memory, disk, 0, true, true, count);
+ }
+
+ public Duration addMeasurements(double cpu, double memory, double disk, int generation, boolean inService, boolean stable,
+ int count) {
+ Instant initialTime = fixture.tester().clock().instant();
+ for (int i = 0; i < count; i++) {
+ fixture.tester().clock().advance(Duration.ofMinutes(1));
+ for (Node node : fixture.nodes()) {
+ fixture.tester().nodeMetricsDb().addNodeMetrics(List.of(new Pair<>(node.hostname(),
+ new NodeMetricSnapshot(fixture.tester().clock().instant(),
+ new Load(cpu, memory, disk),
+ generation,
+ inService,
+ stable,
+ 0.0))));
+ }
+ }
+ return Duration.between(initialTime, fixture.tester().clock().instant());
+ }
+
+ public void applyLoad(double cpuLoad, double memoryLoad, double diskLoad, int measurements) {
+ Duration samplingInterval = Duration.ofSeconds(150L); // in addCpuMeasurements
+ addMeasurements(cpuLoad, memoryLoad, diskLoad, measurements);
+ fixture.tester().clock().advance(samplingInterval.negated().multipliedBy(measurements));
+ addQueryRateMeasurements(measurements, samplingInterval, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
+ }
+
+ public void applyLoad(double cpuLoad, double memoryLoad, double diskLoad, int generation, boolean inService, boolean stable, int measurements) {
+ Duration samplingInterval = Duration.ofSeconds(150L); // in addCpuMeasurements
+ addMeasurements(cpuLoad, memoryLoad, diskLoad, generation, inService, stable, measurements);
+ fixture.tester().clock().advance(samplingInterval.negated().multipliedBy(measurements));
+ addQueryRateMeasurements(measurements, samplingInterval, t -> t == 0 ? 20.0 : 10.0); // Query traffic only
+ }
+
+ public Duration addQueryRateMeasurements(int measurements, Duration samplingInterval, IntFunction<Double> queryRate) {
+ Instant initialTime = fixture.tester().clock().instant();
+ for (int i = 0; i < measurements; i++) {
+ fixture.tester().nodeMetricsDb().addClusterMetrics(fixture.applicationId(),
+ Map.of(fixture.clusterId(), new ClusterMetricSnapshot(fixture.tester().clock().instant(),
+ queryRate.apply(i),
+ 0.0)));
+ fixture.tester().clock().advance(samplingInterval);
+ }
+ return Duration.between(initialTime, fixture.tester().clock().instant());
+ }
+
+}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/AutoscalingMaintainerTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/AutoscalingMaintainerTest.java
index 5529f63211d..cee80459176 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/AutoscalingMaintainerTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/AutoscalingMaintainerTest.java
@@ -178,6 +178,9 @@ public class AutoscalingMaintainerTest {
}
assertEquals(Cluster.maxScalingEvents, tester.cluster(app1, cluster1).scalingEvents().size());
+ assertEquals("The latest rescaling is the last event stored",
+ tester.clock().instant(),
+ tester.cluster(app1, cluster1).scalingEvents().get(Cluster.maxScalingEvents - 1).at());
}
@Test
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainerTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainerTest.java
index 905fdc57813..e5e361da379 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainerTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/DynamicProvisioningMaintainerTest.java
@@ -570,6 +570,39 @@ public class DynamicProvisioningMaintainerTest {
assertEquals(2, provisioningTester.activate(applicationId, prepared).size());
}
+ @Test
+ public void deprovision_parked_node_with_allocation() {
+ var tester = new DynamicProvisioningTester();
+ tester.hostProvisioner.with(Behaviour.failProvisioning);
+ Node host4 = tester.addNode("host4", Optional.empty(), NodeType.host, Node.State.parked);
+ Node host41 = tester.addNode("host4-1", Optional.of("host4"), NodeType.tenant, Node.State.parked, DynamicProvisioningTester.tenantApp);
+ Node host42 = tester.addNode("host4-2", Optional.of("host4"), NodeType.tenant, Node.State.active, DynamicProvisioningTester.tenantApp);
+ Node host43 = tester.addNode("host4-3", Optional.of("host4"), NodeType.tenant, Node.State.failed, DynamicProvisioningTester.tenantApp);
+
+ // Host and children are marked for deprovisioning
+ tester.nodeRepository.nodes().deprovision("host4", Agent.operator, Instant.now());
+ for (var node : List.of(host4, host41, host42, host43)) {
+ assertTrue(tester.nodeRepository.nodes().node(node.hostname()).map(n -> n.status().wantToDeprovision()).get());
+ }
+
+ // Host and children remain parked because one child is still active
+ tester.maintainer.maintain();
+ for (var node : List.of(host4, host41)) {
+ assertEquals(Node.State.parked, tester.nodeRepository.nodes().node(node.hostname()).get().state());
+ }
+ assertEquals(Node.State.active, tester.nodeRepository.nodes().node(host42.hostname()).get().state());
+ assertEquals(Node.State.failed, tester.nodeRepository.nodes().node(host43.hostname()).get().state());
+
+ // Last child is parked
+ tester.nodeRepository.nodes().park(host42.hostname(), true, Agent.system, getClass().getSimpleName());
+
+ // Host and children can now be removed
+ tester.maintainer.maintain();
+ for (var node : List.of(host4, host41, host42, host43)) {
+ assertTrue(node.hostname() + " removed", tester.nodeRepository.nodes().node(node.hostname()).isEmpty());
+ }
+ }
+
private void assertCfghost3IsActive(DynamicProvisioningTester tester) {
assertEquals(5, tester.nodeRepository.nodes().list(Node.State.active).size());
assertEquals(3, tester.nodeRepository.nodes().list(Node.State.active).nodeType(NodeType.confighost).size());
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java
index 98d3ffa92f8..03a6a11d4bd 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/MetricsReporterTest.java
@@ -43,7 +43,6 @@ import java.util.TreeMap;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -162,11 +161,6 @@ public class MetricsReporterTest {
TestMetric metric = new TestMetric();
MetricsReporter metricsReporter = metricsReporter(metric, tester);
metricsReporter.maintain();
-
- // Only verify metrics that are set for hosts
- TreeMap<String, Number> metrics = new TreeMap<>(metric.values);
- assertTrue(metrics.containsKey("wantToEncrypt"));
- assertTrue(metrics.containsKey("diskEncrypted"));
}
private void verifyAndRemoveIntegerMetricSum(TestMetric metric, String key, int expected) {
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailerTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailerTest.java
index f7d29a116ed..3ba536ee4d7 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailerTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/maintenance/NodeFailerTest.java
@@ -457,6 +457,16 @@ public class NodeFailerTest {
tester.allNodesMakeAConfigRequestExcept();
tester.runMaintainers();
+ assertEquals(2, tester.deployer.redeployments);
+ assertEquals(3, tester.nodeRepository.nodes().list(Node.State.failed).nodeType(NodeType.tenant).size());
+ assertEquals(8, tester.nodeRepository.nodes().list(Node.State.active).nodeType(NodeType.tenant).size());
+ assertEquals(10, tester.nodeRepository.nodes().list(Node.State.ready).nodeType(NodeType.tenant).size());
+ assertEquals(7, tester.nodeRepository.nodes().list(Node.State.active).nodeType(NodeType.host).size());
+ assertEquals(0, tester.nodeRepository.nodes().list(Node.State.failed).nodeType(NodeType.host).size());
+
+ // The failing of the host is deferred to the next maintain
+ tester.runMaintainers();
+
assertEquals(2 + 1, tester.deployer.redeployments);
assertEquals(3, tester.nodeRepository.nodes().list(Node.State.failed).nodeType(NodeType.tenant).size());
assertEquals(8, tester.nodeRepository.nodes().list(Node.State.active).nodeType(NodeType.tenant).size());
@@ -495,6 +505,7 @@ public class NodeFailerTest {
tester.clock.advance(Duration.ofMinutes(90));
tester.allNodesMakeAConfigRequestExcept();
tester.runMaintainers();
+ tester.runMaintainers(); // The host is failed in the 2. maintain()
assertEquals(5 + 2, tester.deployer.redeployments);
assertEquals(7, tester.nodeRepository.nodes().list(Node.State.failed).nodeType(NodeType.tenant).size());
@@ -587,7 +598,7 @@ public class NodeFailerTest {
@Test
public void node_failing_throttle() {
- // Throttles based on a absolute number in small zone
+ // Throttles based on an absolute number in small zone
{
// 10 hosts with 3 tenant nodes each, total 40 nodes
NodeFailTester tester = NodeFailTester.withTwoApplications(10);
@@ -595,13 +606,12 @@ public class NodeFailerTest {
// 3 hosts fail. 2 of them and all of their children are allowed to fail
List<Node> failedHosts = hosts.asList().subList(0, 3);
- failedHosts.forEach(host -> {
- tester.serviceMonitor.setHostDown(host.hostname());
- });
+ failedHosts.forEach(host -> tester.serviceMonitor.setHostDown(host.hostname()));
tester.runMaintainers();
tester.clock.advance(Duration.ofMinutes(61));
tester.runMaintainers();
+ tester.runMaintainers(); // hosts are typically failed in the 2. maintain()
assertEquals(2 + /* hosts */
(2 * 3) /* containers per host */,
tester.nodeRepository.nodes().list(Node.State.failed).size());
@@ -620,6 +630,7 @@ public class NodeFailerTest {
// The final host and its containers are failed out
tester.clock.advance(Duration.ofMinutes(30));
tester.runMaintainers();
+ tester.runMaintainers(); // hosts are failed in the 2. maintain()
assertEquals(12, tester.nodeRepository.nodes().list(Node.State.failed).size());
assertEquals("Throttling is not indicated by the metric, as no throttled attempt is made", 0, tester.metric.values.get(NodeFailer.throttlingActiveMetric));
assertEquals("No throttled node failures", 0, tester.metric.values.get(NodeFailer.throttledNodeFailuresMetric));
@@ -724,7 +735,8 @@ public class NodeFailerTest {
.map(Map.Entry::getKey)
.flatMap(parentHost -> Stream.of(parentHost.get()))
.filter(node -> ! exceptSet.contains(node))
- .findFirst().get();
+ .findFirst()
+ .orElseThrow();
}
}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/os/OsVersionsTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/os/OsVersionsTest.java
index 97a8ac0d655..af2a215dae0 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/os/OsVersionsTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/os/OsVersionsTest.java
@@ -172,6 +172,7 @@ public class OsVersionsTest {
Supplier<NodeList> hostNodes = () -> tester.nodeRepository().nodes().list()
.hosts()
.not().state(Node.State.deprovisioned);
+ tester.clock().advance(RetiringOsUpgrader.GRACE_PERIOD.plusDays(1));
// Target is set and upgrade started
var version1 = Version.fromString("7.1");
@@ -233,6 +234,7 @@ public class OsVersionsTest {
Supplier<NodeList> hostNodes = () -> tester.nodeRepository().nodes().list()
.nodeType(NodeType.confighost)
.not().state(Node.State.deprovisioned);
+ tester.clock().advance(RetiringOsUpgrader.GRACE_PERIOD.plusDays(1));
// Target is set with zero budget and upgrade started
var version1 = Version.fromString("7.1");
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/ProvisioningTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/ProvisioningTest.java
index 34219a15caa..8c9c8939616 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/ProvisioningTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/ProvisioningTest.java
@@ -546,14 +546,14 @@ public class ProvisioningTest {
tester.activate(app1, cluster1, Capacity.from(resources(6, 3, 8, 25, 10),
resources(9, 3, 12, 35, 15)));
tester.assertNodes("Groups changed",
- 9, 3, 8, 35, 15,
+ 9, 3, 8, 30, 13,
app1, cluster1);
// Stop specifying node resources
tester.activate(app1, cluster1, Capacity.from(new ClusterResources(6, 3, NodeResources.unspecified()),
new ClusterResources(9, 3, NodeResources.unspecified())));
tester.assertNodes("No change",
- 9, 3, 8, 35, 15,
+ 9, 3, 8, 30, 13,
app1, cluster1);
}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningCompleteHostCalculatorTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningCompleteHostCalculatorTest.java
index 2f0caf8092f..d703ecf44e8 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningCompleteHostCalculatorTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningCompleteHostCalculatorTest.java
@@ -37,24 +37,23 @@ public class VirtualNodeProvisioningCompleteHostCalculatorTest {
ClusterSpec cluster1 = ClusterSpec.request(ClusterSpec.Type.content, new ClusterSpec.Id("cluster1")).vespaVersion("7").build();
var initialResources = new NodeResources(20, 16, 50, 1);
- tester.activate(app1, cluster1, Capacity.from(new ClusterResources(2, 1, initialResources),
- new ClusterResources(2, 1, initialResources)));
+ tester.activate(app1, cluster1, Capacity.from(new ClusterResources(2, 1, initialResources)));
tester.assertNodes("Initial allocation",
2, 1, 20, 16, 50, 1.0,
app1, cluster1);
var newMinResources = new NodeResources( 5, 4, 11, 1);
var newMaxResources = new NodeResources(20, 10, 30, 1);
+
tester.activate(app1, cluster1, Capacity.from(new ClusterResources(7, 1, newMinResources),
new ClusterResources(7, 1, newMaxResources)));
- tester.assertNodes("New allocation preserves total resources",
- 7, 1, 7, 4.6, 14.3, 1.0,
+ tester.assertNodes("New allocation preserves (redundancy adjusted) total resources",
+ 7, 1, 5, 4.0, 11, 1.0,
app1, cluster1);
-
tester.activate(app1, cluster1, Capacity.from(new ClusterResources(7, 1, newMinResources),
new ClusterResources(7, 1, newMaxResources)));
tester.assertNodes("Redeploying the same ranges does not cause changes",
- 7, 1, 7, 4.6, 14.3, 1.0,
+ 7, 1, 5, 4.0, 11, 1.0,
app1, cluster1);
}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningTest.java
index a1c55833862..7728e0ac9c8 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/provisioning/VirtualNodeProvisioningTest.java
@@ -522,14 +522,14 @@ public class VirtualNodeProvisioningTest {
var newMaxResources = new NodeResources(20, 10, 30, 1);
tester.activate(app1, cluster1, Capacity.from(new ClusterResources(7, 1, newMinResources),
new ClusterResources(7, 1, newMaxResources)));
- tester.assertNodes("New allocation preserves total resources",
- 7, 1, 7, 6.7, 14.3, 1.0,
+ tester.assertNodes("New allocation preserves total (redundancy adjusted) resources",
+ 7, 1, 5, 6.0, 11, 1.0,
app1, cluster1);
tester.activate(app1, cluster1, Capacity.from(new ClusterResources(7, 1, newMinResources),
new ClusterResources(7, 1, newMaxResources)));
tester.assertNodes("Redeploying does not cause changes",
- 7, 1, 7, 6.7, 14.3, 1.0,
+ 7, 1, 5, 6.0, 11, 1.0,
app1, cluster1);
}
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiTest.java b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiTest.java
index 6b1853b3893..19af4d00e54 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiTest.java
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/NodesV2ApiTest.java
@@ -770,8 +770,9 @@ public class NodesV2ApiTest {
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2, upgradeBudget to PT0S for nodes of type host\"}");
+ var nodeRepository = (NodeRepository) tester.container().components().getComponent(MockNodeRepository.class.getName());
+
// Activate target
- var nodeRepository = (NodeRepository)tester.container().components().getComponent(MockNodeRepository.class.getName());
var osUpgradeActivator = new OsUpgradeActivator(nodeRepository, Duration.ofDays(1), new TestMetric());
osUpgradeActivator.run();
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application1.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application1.json
index 63a604bf4eb..40719153b9e 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application1.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application1.json
@@ -71,7 +71,7 @@
},
"utilization" : {
"cpu" : 0.0,
- "idealCpu": 0.275,
+ "idealCpu": 0.1375,
"currentCpu": 0.0,
"memory" : 0.0,
"idealMemory": 0.65,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application2.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application2.json
index eddf9b957a7..41aa4257c00 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application2.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/application2.json
@@ -45,13 +45,13 @@
},
"utilization" : {
"cpu" : 0.0,
- "idealCpu": 0.2664285714285714,
+ "idealCpu": 0.1394913986537023,
"currentCpu": 0.0,
"memory" : 0.0,
- "idealMemory": 0.65,
+ "idealMemory": 0.325,
"currentMemory": 0.0,
"disk" : 0.0,
- "idealDisk": 0.6,
+ "idealDisk": 0.3,
"currentDisk": 0.0
},
"scalingEvents" : [
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-os-upgrade-complete.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-os-upgrade-complete.json
index b885f7bd7fc..287db73faf6 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-os-upgrade-complete.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-os-upgrade-complete.json
@@ -30,6 +30,7 @@
"currentRebootGeneration": 0,
"currentOsVersion": "7.5.2",
"wantedOsVersion": "7.5.2",
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-2.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-2.json
index 9c413cf3d82..4f598d1b592 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-2.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-2.json
@@ -36,6 +36,7 @@
},
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": true,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-3.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-3.json
index 77d701904a6..cc779e78cfd 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-3.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-3.json
@@ -36,6 +36,7 @@
},
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-4.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-4.json
index 8d00444bb1b..222b0d06592 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-4.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports-4.json
@@ -36,6 +36,7 @@
},
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports.json
index 051b1799324..a004375f18c 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1-reports.json
@@ -36,6 +36,7 @@
},
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": true,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1.json
index 14a0662a470..9ee16086472 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node1.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node2.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node2.json
index 6bde9d15fb2..b829fb2b4b4 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node2.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node2.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node3.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node3.json
index d1dc2375e1e..77c4675c359 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node3.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node3.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node4.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node4.json
index c4163f32d7a..0220b39fb4c 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node4.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node4.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node5.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node5.json
index 1964a2bac07..d25c68ad5a2 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node5.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/docker-node5.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost1-with-firmware-data.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost1-with-firmware-data.json
index d2e1c88236b..9fbf9bd4b8a 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost1-with-firmware-data.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost1-with-firmware-data.json
@@ -28,6 +28,7 @@
"requestedResources": { "vcpu":4.0, "memoryGb":32.0, "diskGb":1600.0, "bandwidthGbps":20.0, "diskSpeed":"fast", "storageType":"remote","architecture":"x86_64" },
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"currentFirmwareCheck": 100,
"wantedFirmwareCheck": 123,
"failCount": 0,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost6.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost6.json
index 54f29ee26a4..4dcfae18f79 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost6.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/dockerhost6.json
@@ -11,6 +11,7 @@
"environment": "BARE_METAL",
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 1,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/node9.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/node9.json
index 249cd77f780..e76a364e1bb 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/node9.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/node9.json
@@ -11,6 +11,7 @@
"environment": "BARE_METAL",
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/parent2.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/parent2.json
index e06ef551e74..58b96b51efa 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/parent2.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/parent2.json
@@ -13,6 +13,7 @@
"environment": "BARE_METAL",
"rebootGeneration": 0,
"currentRebootGeneration": 0,
+ "deferOsUpgrade": false,
"failCount": 0,
"wantToRetire": false,
"preferToRetire": false,
diff --git a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/stats.json b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/stats.json
index 8a46f8115be..38505726def 100644
--- a/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/stats.json
+++ b/node-repository/src/test/java/com/yahoo/vespa/hosted/provision/restapi/responses/stats.json
@@ -1,4 +1,6 @@
{
+ "totalCost": 8.591999999999999,
+ "totalAllocatedCost": 5.356,
"load": {
"cpu": 0.0,
"memory": 0.0,
@@ -51,4 +53,4 @@
"unutilizedCost": 0.0
}
]
-} \ No newline at end of file
+}
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorContext.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorContext.java
index aa218755792..f798cea3572 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorContext.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorContext.java
@@ -47,7 +47,7 @@ public class OrchestratorContext implements AutoCloseable {
/** Create an OrchestratorContext for an operation on a single application. */
public static OrchestratorContext createContextForSingleAppOp(Clock clock) {
return new OrchestratorContext(null, clock, TimeBudget.fromNow(clock, DEFAULT_TIMEOUT_FOR_SINGLE_OP),
- false, false);
+ false, false);
}
public static OrchestratorContext createContextForAdminOp(Clock clock) {
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorImpl.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorImpl.java
index b3244c1ac74..587875363d5 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorImpl.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/OrchestratorImpl.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.orchestrator;
-import com.yahoo.component.annotation.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
+import com.yahoo.component.annotation.Inject;
import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Zone;
@@ -19,6 +19,7 @@ import com.yahoo.vespa.orchestrator.controller.ClusterControllerClientFactory;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerNodeState;
import com.yahoo.vespa.orchestrator.model.ApplicationApi;
import com.yahoo.vespa.orchestrator.model.ApplicationApiFactory;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.model.NodeGroup;
import com.yahoo.vespa.orchestrator.model.VespaModelUtil;
import com.yahoo.vespa.orchestrator.policy.BatchHostStateChangeDeniedException;
@@ -99,7 +100,8 @@ public class OrchestratorImpl implements Orchestrator {
{
this(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone),
clusterControllerClientFactory,
- applicationApiFactory),
+ applicationApiFactory,
+ flagSource),
clusterControllerClientFactory,
statusService,
serviceMonitor,
@@ -425,7 +427,7 @@ public class OrchestratorImpl implements Orchestrator {
ClusterControllerClient client = clusterControllerClientFactory.createClient(clusterControllers, cluster.clusterId().s());
for (ServiceInstance service : cluster.serviceInstances()) {
try {
- if ( ! client.trySetNodeState(context, service.hostName(), VespaModelUtil.getStorageNodeIndex(service.configId()), MAINTENANCE))
+ if ( ! client.trySetNodeState(context, service.hostName(), VespaModelUtil.getStorageNodeIndex(service.configId()), MAINTENANCE, ContentService.STORAGE_NODE, false))
return false;
}
catch (Exception e) {
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClient.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClient.java
index 98ca9f805b4..e563f36a488 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClient.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClient.java
@@ -5,6 +5,7 @@ import com.yahoo.vespa.applicationmodel.ApplicationInstanceId;
import com.yahoo.vespa.applicationmodel.HostName;
import com.yahoo.vespa.orchestrator.ApplicationStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
/**
@@ -19,7 +20,8 @@ public interface ClusterControllerClient {
* @throws HostStateChangeDeniedException if operation fails, or is otherwise disallowed.
*/
boolean trySetNodeState(OrchestratorContext context, HostName host, int storageNodeIndex,
- ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException;
+ ClusterControllerNodeState wantedState, ContentService contentService, boolean force)
+ throws HostStateChangeDeniedException;
/**
* Requests that a cluster controller sets the requested node to the requested state.
@@ -27,7 +29,8 @@ public interface ClusterControllerClient {
* @throws HostStateChangeDeniedException if operation fails, or is disallowed.
*/
void setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex,
- ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException;
+ ClusterControllerNodeState wantedState, ContentService contentService, boolean force)
+ throws HostStateChangeDeniedException;
/**
* Requests that a cluster controller sets all nodes in the cluster to the requested state.
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImpl.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImpl.java
index 28ba259d2ae..25567cb00a1 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImpl.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImpl.java
@@ -18,6 +18,7 @@ import com.yahoo.vespa.applicationmodel.ApplicationInstanceId;
import com.yahoo.vespa.applicationmodel.HostName;
import com.yahoo.vespa.orchestrator.ApplicationStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.policy.HostedVespaPolicy;
import com.yahoo.yolean.Exceptions;
@@ -53,14 +54,16 @@ public class ClusterControllerClientImpl implements ClusterControllerClient {
}
private boolean setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex,
- ClusterControllerNodeState wantedState, boolean throwOnFailure) {
+ ClusterControllerNodeState wantedState, ContentService contentService,
+ Condition condition, boolean throwOnFailure) {
try {
ClusterControllerClientTimeouts timeouts = context.getClusterControllerTimeouts();
Inspector response = client.send(strategy(hosts), Method.POST)
- .at("cluster", "v2", clusterName, "storage", Integer.toString(storageNodeIndex))
+ .at("cluster", "v2", clusterName, contentService.nameInClusterController(),
+ Integer.toString(storageNodeIndex))
.deadline(timeouts.readBudget())
.parameters(() -> deadline(timeouts))
- .body(stateChangeRequestBytes(wantedState, Condition.SAFE, context.isProbe()))
+ .body(stateChangeRequestBytes(wantedState, condition, context.isProbe()))
.throwing(retryOnRedirect)
.read(SlimeUtils::jsonToSlime).get();
if ( ! response.field("wasModified").asBool()) {
@@ -99,13 +102,17 @@ public class ClusterControllerClientImpl implements ClusterControllerClient {
}
@Override
- public boolean trySetNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException {
- return setNodeState(context, host, storageNodeIndex, wantedState, false);
+ public boolean trySetNodeState(OrchestratorContext context, HostName host, int storageNodeIndex,
+ ClusterControllerNodeState wantedState, ContentService contentService, boolean force)
+ throws HostStateChangeDeniedException {
+ return setNodeState(context, host, storageNodeIndex, wantedState, contentService, force ? Condition.FORCE : Condition.SAFE, false);
}
@Override
- public void setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException {
- setNodeState(context, host, storageNodeIndex, wantedState, true);
+ public void setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex,
+ ClusterControllerNodeState wantedState, ContentService contentService, boolean force)
+ throws HostStateChangeDeniedException {
+ setNodeState(context, host, storageNodeIndex, wantedState, contentService, force ? Condition.FORCE : Condition.SAFE, true);
}
@Override
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ContentService.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ContentService.java
new file mode 100644
index 00000000000..f611bada264
--- /dev/null
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ContentService.java
@@ -0,0 +1,14 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.vespa.orchestrator.model;
+
+public enum ContentService {
+ DISTRIBUTOR("distributor"), STORAGE_NODE("storage");
+
+ private final String nameInClusterController;
+
+ ContentService(String nameInClusterController) {
+ this.nameInClusterController = nameInClusterController;
+ }
+
+ public String nameInClusterController() { return nameInClusterController; }
+}
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNode.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNode.java
index 863c817fe6f..671bd351b3b 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNode.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNode.java
@@ -8,5 +8,6 @@ import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
public interface StorageNode extends Comparable<StorageNode> {
HostName hostName();
- void setNodeState(OrchestratorContext context, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException;
+ void setStorageNodeState(OrchestratorContext context, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException;
+ void forceDistributorState(OrchestratorContext context, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException;
}
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNodeImpl.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNodeImpl.java
index f3e3fd0e674..29f7700ef54 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNodeImpl.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/StorageNodeImpl.java
@@ -41,7 +41,17 @@ public class StorageNodeImpl implements StorageNode {
}
@Override
- public void setNodeState(OrchestratorContext context, ClusterControllerNodeState wantedNodeState)
+ public void setStorageNodeState(OrchestratorContext context, ClusterControllerNodeState wantedNodeState)
+ throws HostStateChangeDeniedException {
+ setNodeState(context, wantedNodeState, ContentService.STORAGE_NODE, false);
+ }
+
+ @Override
+ public void forceDistributorState(OrchestratorContext context, ClusterControllerNodeState wantedState) throws HostStateChangeDeniedException {
+ setNodeState(context, wantedState, ContentService.DISTRIBUTOR, true);
+ }
+
+ public void setNodeState(OrchestratorContext context, ClusterControllerNodeState wantedNodeState, ContentService contentService, boolean force)
throws HostStateChangeDeniedException {
// The "cluster name" used by the Cluster Controller IS the cluster ID.
String clusterId = this.clusterId.s();
@@ -52,17 +62,18 @@ public class StorageNodeImpl implements StorageNode {
clusterControllers,
clusterId);
- ConfigId configId = storageService.configId();
- int nodeIndex = VespaModelUtil.getStorageNodeIndex(configId);
+ int nodeIndex = VespaModelUtil.getStorageNodeIndex(storageService.configId());
- logger.log(Level.FINE, () -> "Setting cluster controller state for " +
- "application " + applicationInstance.reference().asString() +
- ", host " + hostName() +
- ", cluster name " + clusterId +
- ", node index " + nodeIndex +
- ", node state " + wantedNodeState);
+ logger.log(Level.FINE, () -> (force ? "Force" : "Safe") +
+ " setting cluster controller state for " +
+ "application " + applicationInstance.reference().asString() +
+ ", host " + hostName() +
+ ", cluster name " + clusterId +
+ ", service " + contentService.nameInClusterController() +
+ ", node index " + nodeIndex +
+ ", node state " + wantedNodeState);
- client.setNodeState(context, storageService.hostName(), nodeIndex, wantedNodeState);
+ client.setNodeState(context, storageService.hostName(), nodeIndex, wantedNodeState, contentService, force);
}
@Override
diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicy.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicy.java
index 2ce62081f51..3f23be5e514 100644
--- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicy.java
+++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicy.java
@@ -3,6 +3,10 @@ package com.yahoo.vespa.orchestrator.policy;
import com.yahoo.vespa.applicationmodel.ApplicationInstance;
import com.yahoo.vespa.applicationmodel.HostName;
+import com.yahoo.vespa.flags.BooleanFlag;
+import com.yahoo.vespa.flags.FetchVector;
+import com.yahoo.vespa.flags.FlagSource;
+import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerClientFactory;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerNodeState;
@@ -30,13 +34,16 @@ public class HostedVespaPolicy implements Policy {
private final HostedVespaClusterPolicy clusterPolicy;
private final ClusterControllerClientFactory clusterControllerClientFactory;
private final ApplicationApiFactory applicationApiFactory;
+ private final BooleanFlag keepStorageNodeUpFlag;
public HostedVespaPolicy(HostedVespaClusterPolicy clusterPolicy,
ClusterControllerClientFactory clusterControllerClientFactory,
- ApplicationApiFactory applicationApiFactory) {
+ ApplicationApiFactory applicationApiFactory,
+ FlagSource flagSource) {
this.clusterPolicy = clusterPolicy;
this.clusterControllerClientFactory = clusterControllerClientFactory;
this.applicationApiFactory = applicationApiFactory;
+ this.keepStorageNodeUpFlag = Flags.KEEP_STORAGE_NODE_UP.bindTo(flagSource);
}
@Override
@@ -52,7 +59,7 @@ public class HostedVespaPolicy implements Policy {
// Ask Cluster Controller to set storage nodes in maintenance, unless the node is already allowed
// to be down (or permanently down) in case they are guaranteed to be in maintenance already.
for (StorageNode storageNode : application.getNoRemarksStorageNodesInGroupInClusterOrder()) {
- storageNode.setNodeState(context, ClusterControllerNodeState.MAINTENANCE);
+ storageNode.setStorageNodeState(context, ClusterControllerNodeState.MAINTENANCE);
}
// Ensure all nodes in the group are marked as allowed to be down
@@ -68,7 +75,7 @@ public class HostedVespaPolicy implements Policy {
throws HostStateChangeDeniedException {
// Always defer to Cluster Controller whether it's OK to resume storage node
for (StorageNode storageNode : application.getSuspendedStorageNodesInGroupInReverseClusterOrder()) {
- storageNode.setNodeState(context, ClusterControllerNodeState.UP);
+ storageNode.setStorageNodeState(context, ClusterControllerNodeState.UP);
}
// In particular, we're not modifying the state of PERMANENTLY_DOWN nodes.
@@ -94,10 +101,18 @@ public class HostedVespaPolicy implements Policy {
clusterPolicy.verifyGroupGoingDownPermanentlyIsFine(cluster);
}
- // Ask Cluster Controller to set storage nodes to DOWN.
- // These storage nodes are guaranteed to be NO_REMARKS
+ boolean keepStorageNodeUp = keepStorageNodeUpFlag
+ .with(FetchVector.Dimension.APPLICATION_ID, applicationApi.applicationId().serializedForm())
+ .value();
+
+ // Get permission from the Cluster Controller to remove the content nodes.
for (StorageNode storageNode : applicationApi.getStorageNodesInGroupInClusterOrder()) {
- storageNode.setNodeState(context, ClusterControllerNodeState.DOWN);
+ if (keepStorageNodeUp) {
+ storageNode.setStorageNodeState(context.createSubcontextForSingleAppOp(true), ClusterControllerNodeState.DOWN);
+ storageNode.forceDistributorState(context, ClusterControllerNodeState.DOWN);
+ } else {
+ storageNode.setStorageNodeState(context, ClusterControllerNodeState.DOWN);
+ }
}
// Ensure all nodes in the group are marked as permanently down
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java
index f5b7771d5f4..9fd7b9dade9 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java
@@ -24,6 +24,7 @@ import com.yahoo.vespa.orchestrator.controller.ClusterControllerClientFactory;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerClientFactoryMock;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerNodeState;
import com.yahoo.vespa.orchestrator.model.ApplicationApiFactory;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.model.NodeGroup;
import com.yahoo.vespa.orchestrator.policy.BatchHostStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
@@ -104,7 +105,8 @@ public class OrchestratorImplTest {
clustercontroller = new ClusterControllerClientFactoryMock();
orchestrator = new OrchestratorImpl(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone),
clustercontroller,
- applicationApiFactory),
+ applicationApiFactory,
+ flagSource),
clustercontroller,
statusService,
new DummyServiceMonitor(),
@@ -450,7 +452,8 @@ public class OrchestratorImplTest {
orchestrator = new OrchestratorImpl(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone),
clusterControllerClientFactory,
- applicationApiFactory),
+ applicationApiFactory,
+ flagSource),
clusterControllerClientFactory,
statusService,
serviceMonitor,
@@ -459,16 +462,16 @@ public class OrchestratorImplTest {
applicationApiFactory,
flagSource);
- when(fooClient.trySetNodeState(any(), any(), eq(1), eq(ClusterControllerNodeState.MAINTENANCE))).thenReturn(true);
- when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE))).thenReturn(true);
- when(barClient.trySetNodeState(any(), any(), eq(0), eq(ClusterControllerNodeState.MAINTENANCE))).thenReturn(true);
- when(barClient.trySetNodeState(any(), any(), eq(3), eq(ClusterControllerNodeState.MAINTENANCE))).thenReturn(true);
+ when(fooClient.trySetNodeState(any(), any(), eq(1), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenReturn(true);
+ when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenReturn(true);
+ when(barClient.trySetNodeState(any(), any(), eq(0), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenReturn(true);
+ when(barClient.trySetNodeState(any(), any(), eq(3), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenReturn(true);
assertTrue(orchestrator.isQuiescent(id));
- when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE))).thenReturn(false);
+ when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenReturn(false);
assertFalse(orchestrator.isQuiescent(id));
- when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE))).thenThrow(new RuntimeException());
+ when(fooClient.trySetNodeState(any(), any(), eq(2), eq(ClusterControllerNodeState.MAINTENANCE), eq(ContentService.STORAGE_NODE), eq(false))).thenThrow(new RuntimeException());
assertFalse(orchestrator.isQuiescent(id));
}
@@ -509,7 +512,8 @@ public class OrchestratorImplTest {
orchestrator = new OrchestratorImpl(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone),
clusterControllerClientFactory,
- applicationApiFactory),
+ applicationApiFactory,
+ flagSource),
clusterControllerClientFactory,
statusService,
serviceMonitor,
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorTest.java
index 29d6463a7d7..323ae678b0b 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorTest.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorTest.java
@@ -57,7 +57,8 @@ public class OrchestratorTest {
var timer = new TestTimer();
var clustercontroller = new ClusterControllerClientFactoryMock();
var applicationApiFactory = new ApplicationApiFactory(3, 5, timer.toUtcClock());
- var policy = new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone), clustercontroller, applicationApiFactory);
+ var clusterPolicy = new HostedVespaClusterPolicy(flagSource, zone);
+ var policy = new HostedVespaPolicy(clusterPolicy, clustercontroller, applicationApiFactory, flagSource);
var zone = new Zone(SystemName.cd, Environment.prod, RegionName.from("cd-us-east-1"));
this.superModelManager = new MySuperModelProvider();
var duperModel = new DuperModel();
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientFactoryMock.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientFactoryMock.java
index 597487ccfc5..a5348ad3d07 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientFactoryMock.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientFactoryMock.java
@@ -5,11 +5,10 @@ import com.yahoo.vespa.applicationmodel.ApplicationInstance;
import com.yahoo.vespa.applicationmodel.ApplicationInstanceId;
import com.yahoo.vespa.applicationmodel.ClusterId;
import com.yahoo.vespa.applicationmodel.HostName;
-import com.yahoo.vespa.orchestrator.ApplicationStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.DummyServiceMonitor;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.model.VespaModelUtil;
-import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
import java.util.HashMap;
import java.util.List;
@@ -30,7 +29,7 @@ public class ClusterControllerClientFactoryMock implements ClusterControllerClie
try {
ClusterId clusterName = VespaModelUtil.getContentClusterName(appInstance, hostName);
int storageNodeIndex = VespaModelUtil.getStorageNodeIndex(appInstance, hostName);
- String globalMapKey = clusterName + "/" + storageNodeIndex;
+ String globalMapKey = clusterName + "/" + ContentService.STORAGE_NODE.nameInClusterController() + "/" + storageNodeIndex;
return nodes.getOrDefault(globalMapKey, ClusterControllerNodeState.UP) == ClusterControllerNodeState.MAINTENANCE;
} catch (Exception e) {
//Catch all - meant to catch cases where the node is not part of a storage cluster
@@ -44,7 +43,7 @@ public class ClusterControllerClientFactoryMock implements ClusterControllerClie
for (HostName host : hosts) {
ClusterId clusterName = VespaModelUtil.getContentClusterName(app, host);
int storageNodeIndex = VespaModelUtil.getStorageNodeIndex(app, host);
- String globalMapKey = clusterName + "/" + storageNodeIndex;
+ String globalMapKey = clusterName + "/" + ContentService.STORAGE_NODE.nameInClusterController() + "/" + storageNodeIndex;
nodes.put(globalMapKey, ClusterControllerNodeState.UP);
}
}
@@ -53,12 +52,12 @@ public class ClusterControllerClientFactoryMock implements ClusterControllerClie
@Override
public ClusterControllerClient createClient(List<HostName> clusterControllers, String clusterName) {
return new ClusterControllerClient() {
- @Override public boolean trySetNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState) {
- nodes.put(clusterName + "/" + storageNodeIndex, wantedState);
+ @Override public boolean trySetNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState, ContentService contentService, boolean force) {
+ nodes.put(clusterName + "/" + contentService.nameInClusterController() + "/" + storageNodeIndex, wantedState);
return true;
}
- @Override public void setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState) {
- trySetNodeState(context, host, storageNodeIndex, wantedState);
+ @Override public void setNodeState(OrchestratorContext context, HostName host, int storageNodeIndex, ClusterControllerNodeState wantedState, ContentService contentService, boolean force) {
+ trySetNodeState(context, host, storageNodeIndex, wantedState, contentService, false);
}
@Override public void setApplicationState(OrchestratorContext context, ApplicationInstanceId applicationId, ClusterControllerNodeState wantedState) {
nodes.replaceAll((key, state) -> key.startsWith(clusterName + "/") ? wantedState : state);
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImplTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImplTest.java
index b8e078c60d4..81615f59be9 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImplTest.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/controller/ClusterControllerClientImplTest.java
@@ -7,13 +7,13 @@ import com.yahoo.vespa.applicationmodel.ApplicationInstanceId;
import com.yahoo.vespa.applicationmodel.HostName;
import com.yahoo.vespa.orchestrator.ApplicationStateChangeDeniedException;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
+import com.yahoo.vespa.orchestrator.model.ContentService;
import com.yahoo.vespa.orchestrator.policy.HostStateChangeDeniedException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
-import java.time.Clock;
import java.time.Duration;
import java.util.List;
@@ -66,7 +66,7 @@ public class ClusterControllerClientImplTest {
return "{ \"wasModified\": true }";
},
200);
- client.setNodeState(context, host, 2, DOWN);
+ client.setNodeState(context, host, 2, DOWN, ContentService.STORAGE_NODE, false);
clock.advance(Duration.ofSeconds(9));
wire.expect((url, body) -> {
@@ -79,7 +79,7 @@ public class ClusterControllerClientImplTest {
200);
assertEquals("Changing the state of node would violate controller-set-node-state: Failed to set state to DOWN in cluster controller: because",
assertThrows(HostStateChangeDeniedException.class,
- () -> client.setNodeState(context, host, 1, DOWN))
+ () -> client.setNodeState(context, host, 1, DOWN, ContentService.STORAGE_NODE, false))
.getMessage());
}
@@ -93,7 +93,7 @@ public class ClusterControllerClientImplTest {
return "{ \"wasModified\": false, \"reason\": \"no reason\" }";
},
200);
- assertFalse(client.trySetNodeState(OrchestratorContext.createContextForBatchProbe(clock), host, 2, MAINTENANCE));
+ assertFalse(client.trySetNodeState(OrchestratorContext.createContextForBatchProbe(clock), host, 2, MAINTENANCE, ContentService.STORAGE_NODE, false));
}
@Test
@@ -134,7 +134,7 @@ public class ClusterControllerClientImplTest {
assertEquals("Changing the state of node would violate deadline: Timeout while waiting for setNodeState(2, UP) " +
"against [host1, host2, host3]: Timed out after PT10S",
assertThrows(HostStateChangeDeniedException.class,
- () -> client.setNodeState(context, host, 2, UP))
+ () -> client.setNodeState(context, host, 2, UP, ContentService.STORAGE_NODE, false))
.getMessage());
}
@@ -154,7 +154,7 @@ public class ClusterControllerClientImplTest {
assertEquals("Changing the state of node would violate controller-set-node-state: Failed setting node 2 in cluster cc to state UP: " +
"got status code 503 for POST http://host1:19050/cluster/v2/cc/storage/2?timeout=9.6",
assertThrows(HostStateChangeDeniedException.class,
- () -> client.setNodeState(context, host, 2, UP))
+ () -> client.setNodeState(context, host, 2, UP, ContentService.STORAGE_NODE, false))
.getMessage());
}
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ModelTestUtils.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ModelTestUtils.java
index 291f96e3dc3..f2e2972ae9f 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ModelTestUtils.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ModelTestUtils.java
@@ -80,9 +80,9 @@ class ModelTestUtils {
mock(Metric.class),
new TestTimer(),
new DummyAntiServiceMonitor());
- private final Orchestrator orchestrator = new OrchestratorImpl(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, Zone.defaultZone()),
- clusterControllerClientFactory,
- applicationApiFactory()),
+ private final HostedVespaClusterPolicy clusterPolicy = new HostedVespaClusterPolicy(flagSource, Zone.defaultZone());
+ private final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clusterControllerClientFactory, applicationApiFactory(), flagSource);
+ private final Orchestrator orchestrator = new OrchestratorImpl(policy,
clusterControllerClientFactory,
statusService,
serviceMonitor,
diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java
index f01ce5a2227..a622142b873 100644
--- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java
+++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java
@@ -5,6 +5,7 @@ package com.yahoo.vespa.orchestrator.policy;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.test.ManualClock;
import com.yahoo.vespa.applicationmodel.HostName;
+import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.orchestrator.OrchestrationException;
import com.yahoo.vespa.orchestrator.OrchestratorContext;
import com.yahoo.vespa.orchestrator.controller.ClusterControllerClient;
@@ -37,6 +38,7 @@ public class HostedVespaPolicyTest {
private final ClusterControllerClient client = mock(ClusterControllerClient.class);
private final ManualClock clock = new ManualClock();
private final ApplicationApiFactory applicationApiFactory = new ApplicationApiFactory(3, 5, clock);
+ private final InMemoryFlagSource flagSource = new InMemoryFlagSource();
@Before
public void setUp() {
@@ -47,7 +49,7 @@ public class HostedVespaPolicyTest {
public void testGrantSuspension() throws HostStateChangeDeniedException {
final HostedVespaClusterPolicy clusterPolicy = mock(HostedVespaClusterPolicy.class);
when(clusterPolicy.verifyGroupGoingDownIsFine(any())).thenReturn(SuspensionReasons.nothingNoteworthy());
- final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory);
+ final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory, flagSource);
final ApplicationApi applicationApi = mock(ApplicationApi.class);
when(applicationApi.applicationId()).thenReturn(ApplicationId.fromSerializedForm("tenant:app:default"));
@@ -85,8 +87,8 @@ public class HostedVespaPolicyTest {
order.verify(clusterPolicy).verifyGroupGoingDownIsFine(clusterApi3);
order.verify(applicationApi).getNoRemarksStorageNodesInGroupInClusterOrder();
- order.verify(storageNode1).setNodeState(context, ClusterControllerNodeState.MAINTENANCE);
- order.verify(storageNode3).setNodeState(context, ClusterControllerNodeState.MAINTENANCE);
+ order.verify(storageNode1).setStorageNodeState(context, ClusterControllerNodeState.MAINTENANCE);
+ order.verify(storageNode3).setStorageNodeState(context, ClusterControllerNodeState.MAINTENANCE);
order.verify(applicationApi).getNodesInGroupWithStatus(HostStatus.NO_REMARKS);
order.verify(applicationApi).setHostState(context, hostName1, HostStatus.ALLOWED_TO_BE_DOWN);
@@ -99,7 +101,7 @@ public class HostedVespaPolicyTest {
@Test
public void testAcquirePermissionToRemove() throws OrchestrationException {
final HostedVespaClusterPolicy clusterPolicy = mock(HostedVespaClusterPolicy.class);
- final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory);
+ final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory, flagSource);
final ApplicationApi applicationApi = mock(ApplicationApi.class);
when(applicationApi.applicationId()).thenReturn(ApplicationId.fromSerializedForm("tenant:app:default"));
@@ -128,6 +130,8 @@ public class HostedVespaPolicyTest {
InOrder order = inOrder(applicationApi, clusterPolicy, storageNode1, storageNode3);
OrchestratorContext context = mock(OrchestratorContext.class);
+ OrchestratorContext probeContext = mock(OrchestratorContext.class);
+ when(context.createSubcontextForSingleAppOp(true)).thenReturn(probeContext);
policy.acquirePermissionToRemove(context, applicationApi);
order.verify(applicationApi).getClusters();
@@ -136,8 +140,8 @@ public class HostedVespaPolicyTest {
order.verify(clusterPolicy).verifyGroupGoingDownPermanentlyIsFine(clusterApi3);
order.verify(applicationApi).getStorageNodesInGroupInClusterOrder();
- order.verify(storageNode1).setNodeState(context, ClusterControllerNodeState.DOWN);
- order.verify(storageNode3).setNodeState(context, ClusterControllerNodeState.DOWN);
+ order.verify(storageNode1).setStorageNodeState(probeContext, ClusterControllerNodeState.DOWN);
+ order.verify(storageNode3).setStorageNodeState(probeContext, ClusterControllerNodeState.DOWN);
order.verify(applicationApi).getNodesInGroupWith(any());
order.verify(applicationApi).setHostState(context, hostName1, HostStatus.PERMANENTLY_DOWN);
@@ -150,7 +154,7 @@ public class HostedVespaPolicyTest {
@Test
public void testAcquirePermissionToRemoveConfigServer() throws OrchestrationException {
final HostedVespaClusterPolicy clusterPolicy = mock(HostedVespaClusterPolicy.class);
- final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory);
+ final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory, flagSource);
final ApplicationApi applicationApi = mock(ApplicationApi.class);
when(applicationApi.applicationId()).thenReturn(ApplicationId.fromSerializedForm("tenant:app:default"));
@@ -179,6 +183,8 @@ public class HostedVespaPolicyTest {
InOrder order = inOrder(applicationApi, clusterPolicy, storageNode1, storageNode3);
OrchestratorContext context = mock(OrchestratorContext.class);
+ OrchestratorContext probeContext = mock(OrchestratorContext.class);
+ when(context.createSubcontextForSingleAppOp(true)).thenReturn(probeContext);
policy.acquirePermissionToRemove(context, applicationApi);
order.verify(applicationApi).getClusters();
@@ -187,8 +193,8 @@ public class HostedVespaPolicyTest {
order.verify(clusterPolicy).verifyGroupGoingDownPermanentlyIsFine(clusterApi3);
order.verify(applicationApi).getStorageNodesInGroupInClusterOrder();
- order.verify(storageNode1).setNodeState(context, ClusterControllerNodeState.DOWN);
- order.verify(storageNode3).setNodeState(context, ClusterControllerNodeState.DOWN);
+ order.verify(storageNode1).setStorageNodeState(probeContext, ClusterControllerNodeState.DOWN);
+ order.verify(storageNode3).setStorageNodeState(probeContext, ClusterControllerNodeState.DOWN);
order.verify(applicationApi).getNodesInGroupWith(any());
order.verify(applicationApi).setHostState(context, hostName1, HostStatus.PERMANENTLY_DOWN);
diff --git a/parent/pom.xml b/parent/pom.xml
index f152a39a576..a83c7f50960 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -301,6 +301,27 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <!--
+ Configure rewrite-maven-plugin to facilitate Junit4 to Junit5 conversion.
+ Run "mvn rewrite:run" to perform automated rewrite to Junit5.
+ -->
+ <groupId>org.openrewrite.maven</groupId>
+ <artifactId>rewrite-maven-plugin</artifactId>
+ <version>4.27.0</version>
+ <configuration>
+ <activeRecipes>
+ <recipe>org.openrewrite.java.testing.junit5.JUnit5BestPractices</recipe>
+ </activeRecipes>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.openrewrite.recipe</groupId>
+ <artifactId>rewrite-testing-frameworks</artifactId>
+ <version>1.24.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
</plugins>
</pluginManagement>
</build>
@@ -422,7 +443,6 @@
</profiles>
<dependencyManagement>
<dependencies>
-
<!-- Please keep this list lexically sorted by groupId, then artifactId.-->
<dependency>
@@ -474,6 +494,11 @@
<version>2.6.0</version>
</dependency>
<dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
+ <version>2.33.2</version>
+ </dependency>
+ <dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${findbugs.version}</version>
@@ -850,6 +875,11 @@
<version>${jetty.version}</version>
</dependency>
<dependency>
+ <groupId>org.eclipse.jetty</groupId>
+ <artifactId>jetty-util</artifactId>
+ <version>${jetty.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version> <!-- 2.3.3 has a BROKEN manifest -->
@@ -914,6 +944,15 @@
<scope>test</scope> <!-- TODO: remove scope from parent pom -->
</dependency>
<dependency>
+ <!-- Facilitates automated Junit4 to Junit5 conversion.
+ See pluginManagement of rewrite-maven-plugin for more details -->
+ <groupId>org.openrewrite.recipe</groupId>
+ <artifactId>rewrite-recipe-bom</artifactId>
+ <version>1.5.0</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
@@ -995,7 +1034,7 @@
xargs perl -pi -e 's/major = [0-9]+, minor = [0-9]+, micro = [0-9]+/major = 5, minor = 3, micro = 0/g'
-->
<bouncycastle.version>1.68</bouncycastle.version>
- <curator.version>5.2.1</curator.version>
+ <curator.version>5.3.0</curator.version>
<commons.codec.version>1.15</commons.codec.version>
<commons.math3.version>3.6.1</commons.math3.version>
<eclipse-collections.version>11.0.0</eclipse-collections.version>
@@ -1004,7 +1043,7 @@
<findbugs.version>3.0.2</findbugs.version> <!-- Should be kept in sync with guava -->
<gson.version>2.8.9</gson.version>
<hdrhistogram.version>2.1.12</hdrhistogram.version>
- <jetty.version>9.4.46.v20220331</jetty.version>
+ <jetty.version>9.4.48.v20220622</jetty.version>
<jetty-alpn.version>1.1.3.v20160715</jetty-alpn.version>
<jna.version>5.11.0</jna.version>
<junit.version>5.8.1</junit.version>
@@ -1027,13 +1066,14 @@
<maven-site-plugin.version>3.9.1</maven-site-plugin.version>
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
<mockito.version>4.0.0</mockito.version>
- <onnxruntime.version>1.8.0</onnxruntime.version> <!-- WARNING: sync cloud-tenant-base-dependencies-enforcer/pom.xml -->
+ <onnxruntime.version>1.11.0</onnxruntime.version> <!-- WARNING: sync cloud-tenant-base-dependencies-enforcer/pom.xml -->
+ <org.json.version>20220320</org.json.version>
<org.lz4.version>1.8.0</org.lz4.version>
<prometheus.client.version>0.6.0</prometheus.client.version>
<protobuf.version>3.19.2</protobuf.version>
<spifly.version>1.3.5</spifly.version>
<surefire.version>2.22.2</surefire.version>
- <zookeeper.client.version>3.7.0</zookeeper.client.version>
+ <zookeeper.client.version>3.7.1</zookeeper.client.version>
<doclint>all</doclint>
<test.hide>true</test.hide>
diff --git a/persistence/src/vespa/persistence/conformancetest/conformancetest.cpp b/persistence/src/vespa/persistence/conformancetest/conformancetest.cpp
index bf1c828e2e6..e03403f601d 100644
--- a/persistence/src/vespa/persistence/conformancetest/conformancetest.cpp
+++ b/persistence/src/vespa/persistence/conformancetest/conformancetest.cpp
@@ -765,11 +765,11 @@ TEST_F(ConformanceTest, testRemoveMulti)
docs.push_back(testDocMan.createRandomDocumentAtLocation(0x01, i));
}
- std::vector<PersistenceProvider::TimeStampAndDocumentId> ids;
+ std::vector<spi::IdAndTimestamp> ids;
for (size_t i(0); i < docs.size(); i++) {
spi->put(bucket1, Timestamp(i), docs[i]);
if (i & 0x1) {
- ids.emplace_back(Timestamp(i), docs[i]->getId());
+ ids.emplace_back(docs[i]->getId(), Timestamp(i));
}
}
diff --git a/persistence/src/vespa/persistence/dummyimpl/dummypersistence.cpp b/persistence/src/vespa/persistence/dummyimpl/dummypersistence.cpp
index 81bfdf7f9a3..6eabadc2f86 100644
--- a/persistence/src/vespa/persistence/dummyimpl/dummypersistence.cpp
+++ b/persistence/src/vespa/persistence/dummyimpl/dummypersistence.cpp
@@ -476,16 +476,16 @@ DummyPersistence::updateAsync(const Bucket& bucket, Timestamp ts, DocumentUpdate
}
void
-DummyPersistence::removeAsync(const Bucket& b, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP onComplete)
+DummyPersistence::removeAsync(const Bucket& b, std::vector<spi::IdAndTimestamp> ids, OperationComplete::UP onComplete)
{
DUMMYPERSISTENCE_VERIFY_INITIALIZED;
assert(b.getBucketSpace() == FixedBucketSpaces::default_space());
BucketContentGuard::UP bc(acquireBucketWithLock(b));
uint32_t numRemoves(0);
- for (const TimeStampAndDocumentId & stampedId : ids) {
- const DocumentId & id = stampedId.second;
- Timestamp t = stampedId.first;
+ for (const spi::IdAndTimestamp & stampedId : ids) {
+ const DocumentId & id = stampedId.id;
+ Timestamp t = stampedId.timestamp;
LOG(debug, "remove(%s, %" PRIu64 ", %s)", b.toString().c_str(), uint64_t(t), id.toString().c_str());
while (!bc) {
diff --git a/persistence/src/vespa/persistence/dummyimpl/dummypersistence.h b/persistence/src/vespa/persistence/dummyimpl/dummypersistence.h
index e015185e5b0..56602b3ab00 100644
--- a/persistence/src/vespa/persistence/dummyimpl/dummypersistence.h
+++ b/persistence/src/vespa/persistence/dummyimpl/dummypersistence.h
@@ -160,7 +160,7 @@ public:
BucketInfoResult getBucketInfo(const Bucket&) const override;
GetResult get(const Bucket&, const document::FieldSet&, const DocumentId&, Context&) const override;
void putAsync(const Bucket&, Timestamp, DocumentSP, OperationComplete::UP) override;
- void removeAsync(const Bucket& b, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP) override;
+ void removeAsync(const Bucket& b, std::vector<spi::IdAndTimestamp> ids, OperationComplete::UP) override;
void updateAsync(const Bucket&, Timestamp, DocumentUpdateSP, OperationComplete::UP) override;
CreateIteratorResult
diff --git a/persistence/src/vespa/persistence/spi/CMakeLists.txt b/persistence/src/vespa/persistence/spi/CMakeLists.txt
index e4bae1c7551..bc94020ae95 100644
--- a/persistence/src/vespa/persistence/spi/CMakeLists.txt
+++ b/persistence/src/vespa/persistence/spi/CMakeLists.txt
@@ -10,6 +10,7 @@ vespa_add_library(persistence_spi OBJECT
context.cpp
docentry.cpp
exceptions.cpp
+ id_and_timestamp.cpp
persistenceprovider.cpp
read_consistency.cpp
resource_usage.cpp
diff --git a/persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp b/persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp
index f301a9c5428..04d06235f59 100644
--- a/persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp
+++ b/persistence/src/vespa/persistence/spi/abstractpersistenceprovider.cpp
@@ -10,8 +10,8 @@ void
AbstractPersistenceProvider::removeIfFoundAsync(const Bucket& b, Timestamp timestamp,
const DocumentId& id, OperationComplete::UP onComplete)
{
- std::vector<TimeStampAndDocumentId> ids;
- ids.emplace_back(timestamp, id);
+ std::vector<IdAndTimestamp> ids;
+ ids.emplace_back(id, timestamp);
removeAsync(b, std::move(ids), std::move(onComplete));
}
diff --git a/persistence/src/vespa/persistence/spi/id_and_timestamp.cpp b/persistence/src/vespa/persistence/spi/id_and_timestamp.cpp
new file mode 100644
index 00000000000..fba45990744
--- /dev/null
+++ b/persistence/src/vespa/persistence/spi/id_and_timestamp.cpp
@@ -0,0 +1,17 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#include "id_and_timestamp.h"
+
+namespace storage::spi {
+
+IdAndTimestamp::IdAndTimestamp() : id(), timestamp(0) {}
+IdAndTimestamp::IdAndTimestamp(document::DocumentId id_, Timestamp timestamp_) noexcept
+ : id(std::move(id_)),
+ timestamp(timestamp_)
+{}
+
+IdAndTimestamp::IdAndTimestamp(const IdAndTimestamp&) = default;
+IdAndTimestamp& IdAndTimestamp::operator=(const IdAndTimestamp&) = default;
+IdAndTimestamp::IdAndTimestamp(IdAndTimestamp&&) noexcept = default;
+IdAndTimestamp& IdAndTimestamp::operator=(IdAndTimestamp&&) noexcept = default;
+
+}
diff --git a/persistence/src/vespa/persistence/spi/id_and_timestamp.h b/persistence/src/vespa/persistence/spi/id_and_timestamp.h
new file mode 100644
index 00000000000..d8cdba3d063
--- /dev/null
+++ b/persistence/src/vespa/persistence/spi/id_and_timestamp.h
@@ -0,0 +1,38 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
+#include "types.h"
+#include <vespa/document/base/documentid.h>
+
+namespace storage::spi {
+
+/**
+ * Convenience wrapper for referencing a document ID at a particular timestamp.
+ *
+ * Prefer this instead of a std::pair due to named fields and a pre-provided hash function.
+ */
+struct IdAndTimestamp {
+ document::DocumentId id;
+ Timestamp timestamp;
+
+ IdAndTimestamp();
+ IdAndTimestamp(document::DocumentId id_, Timestamp timestamp_) noexcept;
+
+ IdAndTimestamp(const IdAndTimestamp&);
+ IdAndTimestamp& operator=(const IdAndTimestamp&);
+ IdAndTimestamp(IdAndTimestamp&&) noexcept;
+ IdAndTimestamp& operator=(IdAndTimestamp&&) noexcept;
+
+ bool operator==(const IdAndTimestamp& rhs) const noexcept {
+ return ((id == rhs.id) && (timestamp == rhs.timestamp));
+ }
+
+ struct hash {
+ size_t operator()(const IdAndTimestamp& id_ts) const noexcept {
+ const size_t h = document::GlobalId::hash()(id_ts.id.getGlobalId());
+ return h ^ (id_ts.timestamp + 0x9e3779b9U + (h << 6U) + (h >> 2U)); // Basically boost::hash_combine
+ }
+ };
+};
+
+}
diff --git a/persistence/src/vespa/persistence/spi/persistenceprovider.cpp b/persistence/src/vespa/persistence/spi/persistenceprovider.cpp
index 03cefb8df89..911b3753b1f 100644
--- a/persistence/src/vespa/persistence/spi/persistenceprovider.cpp
+++ b/persistence/src/vespa/persistence/spi/persistenceprovider.cpp
@@ -44,8 +44,8 @@ RemoveResult
PersistenceProvider::remove(const Bucket& bucket, Timestamp timestamp, const DocumentId & docId) {
auto catcher = std::make_unique<CatchResult>();
auto future = catcher->future_result();
- std::vector<TimeStampAndDocumentId> ids;
- ids.emplace_back(timestamp, docId);
+ std::vector<IdAndTimestamp> ids;
+ ids.emplace_back(docId, timestamp);
removeAsync(bucket, std::move(ids), std::move(catcher));
return dynamic_cast<const RemoveResult &>(*future.get());
}
diff --git a/persistence/src/vespa/persistence/spi/persistenceprovider.h b/persistence/src/vespa/persistence/spi/persistenceprovider.h
index a90d39e8334..d3e1465e528 100644
--- a/persistence/src/vespa/persistence/spi/persistenceprovider.h
+++ b/persistence/src/vespa/persistence/spi/persistenceprovider.h
@@ -4,6 +4,7 @@
#include "bucket.h"
#include "bucketinfo.h"
#include "context.h"
+#include "id_and_timestamp.h"
#include "result.h"
#include "selection.h"
#include "clusterstate.h"
@@ -170,7 +171,7 @@ struct PersistenceProvider
* @param timestamp The timestamp for the new bucket entry.
* @param id The ID to remove
*/
- virtual void removeAsync(const Bucket&, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP) = 0;
+ virtual void removeAsync(const Bucket&, std::vector<IdAndTimestamp> ids, OperationComplete::UP) = 0;
/**
* @see remove()
diff --git a/pom.xml b/pom.xml
index 6cd49656180..388688d95b4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -142,7 +142,6 @@
<module>vespa-3party-bundles</module>
<module>vespajlib</module>
<module>vespalog</module>
- <module>yolean</module>
<module>zkfacade</module>
<module>zookeeper-client-common</module>
<module>zookeeper-command-line-client</module>
diff --git a/predicate-search-core/pom.xml b/predicate-search-core/pom.xml
index 4951b3d40f1..0862d76c5a1 100644
--- a/predicate-search-core/pom.xml
+++ b/predicate-search-core/pom.xml
@@ -15,13 +15,14 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -35,6 +36,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<scope>provided</scope>
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
index c37d6b246a5..0f15fcd656a 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
@@ -3,10 +3,10 @@ package com.yahoo.document.predicate;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Slime;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class BinaryFormatTest {
@Test
- public void requireThatEncodeNullThrows() {
+ void requireThatEncodeNullThrows() {
try {
BinaryFormat.encode(null);
fail();
@@ -24,7 +24,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatDecodeNullThrows() {
+ void requireThatDecodeNullThrows() {
try {
BinaryFormat.decode(null);
fail();
@@ -34,7 +34,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatDecodeEmptyThrows() {
+ void requireThatDecodeEmptyThrows() {
try {
BinaryFormat.decode(new byte[0]);
fail();
@@ -44,17 +44,17 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatConjunctionCanBeSerialized() {
+ void requireThatConjunctionCanBeSerialized() {
assertSerialize(new Conjunction(new FeatureSet("foo", "bar"), new FeatureSet("baz", "cox")));
}
@Test
- public void requireThatDisjunctionCanBeSerialized() {
+ void requireThatDisjunctionCanBeSerialized() {
assertSerialize(new Disjunction(new FeatureSet("foo", "bar"), new FeatureSet("baz", "cox")));
}
@Test
- public void requireThatFeatureRangeCanBeSerialized() {
+ void requireThatFeatureRangeCanBeSerialized() {
assertSerialize(new FeatureRange("foo", null, null));
assertSerialize(new FeatureRange("foo", null, 9L));
assertSerialize(new FeatureRange("foo", 6L, null));
@@ -62,7 +62,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatPartitionedFeatureRangeCanBeSerialized() {
+ void requireThatPartitionedFeatureRangeCanBeSerialized() {
FeatureRange expected = new FeatureRange("foo", 8L, 20L);
FeatureRange f = new FeatureRange("foo", 8L, 20L);
f.addPartition(new RangeEdgePartition("foo=0", 0, 8, -1));
@@ -87,25 +87,25 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatFeatureSetCanBeSerialized() {
+ void requireThatFeatureSetCanBeSerialized() {
assertSerialize(new FeatureSet("foo"));
assertSerialize(new FeatureSet("foo", "bar"));
assertSerialize(new FeatureSet("foo", "bar", "baz"));
}
@Test
- public void requireThatNegationCanBeSerialized() {
+ void requireThatNegationCanBeSerialized() {
assertSerialize(new Negation(new FeatureSet("foo", "bar")));
}
@Test
- public void requireThatBooleanCanBeSerialized() {
+ void requireThatBooleanCanBeSerialized() {
assertSerialize(new BooleanPredicate(true));
assertSerialize(new BooleanPredicate(false));
}
@Test
- public void requireThatUnknownNodeThrows() {
+ void requireThatUnknownNodeThrows() {
try {
BinaryFormat.encode(SimplePredicates.newString("foo"));
fail();
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
index 92c45520504..0dbfdb2559d 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
@@ -1,12 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,12 +11,12 @@ import static org.junit.Assert.assertTrue;
public class BooleanPredicateTest {
@Test
- public void requireThatFalseIsAValue() {
+ void requireThatFalseIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(BooleanPredicate.class));
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
BooleanPredicate node1 = new BooleanPredicate(true);
BooleanPredicate node2 = node1.clone();
assertEquals(node1, node2);
@@ -27,21 +24,21 @@ public class BooleanPredicateTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new BooleanPredicate(true).hashCode(), new BooleanPredicate(true).hashCode());
assertEquals(new BooleanPredicate(false).hashCode(), new BooleanPredicate(false).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
BooleanPredicate lhs = new BooleanPredicate(true);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
BooleanPredicate rhs = new BooleanPredicate(false);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setValue(true);
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
index cbcab2917e5..fa4872715f6 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +13,12 @@ import static org.junit.Assert.assertTrue;
public class ConjunctionTest {
@Test
- public void requireThatConjunctionIsAnOperator() {
+ void requireThatConjunctionIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Conjunction.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Conjunction node = new Conjunction();
Predicate a = SimplePredicates.newString("a");
node.addOperand(a);
@@ -40,7 +37,7 @@ public class ConjunctionTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Conjunction node = new Conjunction(foo, bar);
@@ -51,7 +48,7 @@ public class ConjunctionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Conjunction node1 = new Conjunction(SimplePredicates.newString("a"), SimplePredicates.newString("b"));
Conjunction node2 = node1.clone();
assertEquals(node1, node2);
@@ -60,27 +57,27 @@ public class ConjunctionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new Conjunction().hashCode(), new Conjunction().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Conjunction lhs = new Conjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ SimplePredicates.newString("bar"));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Conjunction rhs = new Conjunction();
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatNodeDelimiterIsAND() {
+ void requireThatNodeDelimiterIsAND() {
assertEquals("", newConjunction().toString());
assertEquals("foo", newConjunction("foo").toString());
assertEquals("foo and bar", newConjunction("foo", "bar").toString());
@@ -88,22 +85,22 @@ public class ConjunctionTest {
}
@Test
- public void requireThatSimpleConjunctionsArePrettyPrinted() {
+ void requireThatSimpleConjunctionsArePrettyPrinted() {
assertEquals("foo and bar",
- new Conjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar")).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ SimplePredicates.newString("bar")).toString());
}
@Test
- public void requireThatComplexConjunctionsArePrintedAsGroup() {
+ void requireThatComplexConjunctionsArePrintedAsGroup() {
assertEquals("foo and bar and baz",
- new Conjunction(SimplePredicates.newString("foo"),
- new Conjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ new Conjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
assertEquals("foo and (bar or baz)",
- new Conjunction(SimplePredicates.newString("foo"),
- new Disjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ new Disjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
}
private static Conjunction newConjunction(String... operands) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
index 1dab0dd80a2..d5640c7f0a2 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +13,12 @@ import static org.junit.Assert.assertTrue;
public class DisjunctionTest {
@Test
- public void requireThatDisjunctionIsAnOperator() {
+ void requireThatDisjunctionIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Disjunction.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Disjunction node = new Disjunction();
Predicate a = SimplePredicates.newString("a");
node.addOperand(a);
@@ -40,7 +37,7 @@ public class DisjunctionTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Disjunction node = new Disjunction(foo, bar);
@@ -51,7 +48,7 @@ public class DisjunctionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Disjunction node1 = new Disjunction(SimplePredicates.newString("a"), SimplePredicates.newString("b"));
Disjunction node2 = node1.clone();
assertEquals(node1, node2);
@@ -60,27 +57,27 @@ public class DisjunctionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new Disjunction().hashCode(), new Disjunction().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Disjunction lhs = new Disjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ SimplePredicates.newString("bar"));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Disjunction rhs = new Disjunction();
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatNodeDelimiterIsOR() {
+ void requireThatNodeDelimiterIsOR() {
assertEquals("", newDisjunction().toString());
assertEquals("foo", newDisjunction("foo").toString());
assertEquals("foo or bar", newDisjunction("foo", "bar").toString());
@@ -88,22 +85,22 @@ public class DisjunctionTest {
}
@Test
- public void requireThatSimpleDisjunctionsArePrettyPrinted() {
+ void requireThatSimpleDisjunctionsArePrettyPrinted() {
assertEquals("foo or bar",
- new Disjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar")).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ SimplePredicates.newString("bar")).toString());
}
@Test
- public void requireThatComplexDisjunctionsArePrintedAsGroup() {
+ void requireThatComplexDisjunctionsArePrintedAsGroup() {
assertEquals("foo or bar or baz",
- new Disjunction(SimplePredicates.newString("foo"),
- new Disjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ new Disjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
assertEquals("foo or (bar and baz)",
- new Disjunction(SimplePredicates.newString("foo"),
- new Conjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ new Conjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
}
private static Disjunction newDisjunction(String... operands) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
index 059022f87e8..e44fd0e0a78 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
@@ -15,38 +16,48 @@ import static com.yahoo.document.predicate.Predicates.not;
public class FeatureConjunctionTest {
@Test
- public void require_that_featureconjunction_with_valid_operands_can_be_constructed() {
+ void require_that_featureconjunction_with_valid_operands_can_be_constructed() {
new FeatureConjunction(Arrays.asList(
not(feature("a").inSet("1")),
feature("b").inSet("1")));
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_all_operands_are_not_featuresets() {
- new FeatureConjunction(Arrays.asList(
- not(feature("a").inSet("1")),
- feature("b").inRange(1, 2)));
+ @Test
+ void require_that_constructor_throws_exception_if_all_operands_are_not_featuresets() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(
+ not(feature("a").inSet("1")),
+ feature("b").inRange(1, 2)));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_single_operand() {
- new FeatureConjunction(Arrays.asList(feature("a").inSet("1")));
+ @Test
+ void require_that_constructor_throws_exception_if_single_operand() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(feature("a").inSet("1")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_no_operands() {
- new FeatureConjunction(Collections.emptyList());
+ @Test
+ void require_that_constructor_throws_exception_if_no_operands() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Collections.emptyList());
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_contructor_throws_exception_if_featuresets_contain_multiple_values() {
- new FeatureConjunction(Arrays.asList(feature("a").inSet("1"), feature("b").inSet("2", "3")));
+ @Test
+ void require_that_contructor_throws_exception_if_featuresets_contain_multiple_values() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(feature("a").inSet("1"), feature("b").inSet("2", "3")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_featureset_keys_are_not_unique() {
- new FeatureConjunction(Arrays.asList(
- not(feature("a").inSet("1")),
- feature("a").inSet("2")));
+ @Test
+ void require_that_constructor_throws_exception_if_featureset_keys_are_not_unique() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(
+ not(feature("a").inSet("1")),
+ feature("a").inSet("2")));
+ });
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java
index 0951ae3bbc6..8d31765cf1b 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java
@@ -1,11 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,12 +13,12 @@ import static org.junit.Assert.*;
public class FeatureRangeTest {
@Test
- public void requireThatFeatureRangeIsAValue() {
+ void requireThatFeatureRangeIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(FeatureRange.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FeatureRange node = new FeatureRange("foo");
assertEquals("foo", node.getKey());
node.setKey("bar");
@@ -36,7 +36,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
FeatureRange node = new FeatureRange("foo");
assertEquals("foo", node.getKey());
assertNull(node.getFromInclusive());
@@ -64,7 +64,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
FeatureRange node1 = new FeatureRange("foo", 6L, 9L);
FeatureRange node2 = node1.clone();
assertEquals(node1, node2);
@@ -72,36 +72,36 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new FeatureRange("key").hashCode(), new FeatureRange("key").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
FeatureRange lhs = new FeatureRange("foo", 6L, 9L);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
FeatureRange rhs = new FeatureRange("bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setKey("foo");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setFromInclusive(6L);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setToInclusive(9L);
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
rhs.addPartition(new RangePartition("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
lhs.addPartition(new RangePartition("foo"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
rhs.addPartition(new RangeEdgePartition("foo", 10, 0, 2));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
lhs.addPartition(new RangeEdgePartition("foo", 10, 0, 2));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatFeatureKeyIsMandatoryInConstructor() {
+ void requireThatFeatureKeyIsMandatoryInConstructor() {
try {
new FeatureRange(null);
fail();
@@ -111,7 +111,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFeatureKeyIsMandatoryInSetter() {
+ void requireThatFeatureKeyIsMandatoryInSetter() {
FeatureRange node = new FeatureRange("foo");
try {
node.setKey(null);
@@ -123,7 +123,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatRangeCanBeSingleValue() {
+ void requireThatRangeCanBeSingleValue() {
FeatureRange node = new FeatureRange("key", 6L, 6L);
assertEquals(6, node.getFromInclusive().intValue());
assertEquals(6, node.getToInclusive().intValue());
@@ -134,7 +134,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFromCanNotBeConstructedGreaterThanTo() {
+ void requireThatFromCanNotBeConstructedGreaterThanTo() {
try {
new FeatureRange("key", 9L, 6L);
fail();
@@ -144,7 +144,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFromCanNotBeSetGreaterThanTo() {
+ void requireThatFromCanNotBeSetGreaterThanTo() {
FeatureRange node = new FeatureRange("key", null, 6L);
try {
node.setFromInclusive(9L);
@@ -165,7 +165,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatToCanNotBeSetLessThanFrom() {
+ void requireThatToCanNotBeSetLessThanFrom() {
FeatureRange node = new FeatureRange("key", 9L, null);
try {
node.setToInclusive(6L);
@@ -186,49 +186,49 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo in [6..9]",
- new FeatureRange("foo", 6L, 9L).toString());
+ new FeatureRange("foo", 6L, 9L).toString());
assertEquals("'\\foo' in [6..9]",
- new FeatureRange("\foo", 6L, 9L).toString());
+ new FeatureRange("\foo", 6L, 9L).toString());
assertEquals("'\\x27foo\\x27' in [6..9]",
- new FeatureRange("'foo'", 6L, 9L).toString());
+ new FeatureRange("'foo'", 6L, 9L).toString());
}
@Test
- public void requireThatToStringIncludesLimits() {
+ void requireThatToStringIncludesLimits() {
assertEquals("foo in [6..9]", new FeatureRange("foo", 6L, 9L).toString());
}
@Test
- public void requireThatToStringAllowsNullLimits() {
+ void requireThatToStringAllowsNullLimits() {
assertEquals("foo in [..]", new FeatureRange("foo").toString());
}
@Test
- public void requireThatToStringAllowsNullFromLimit() {
+ void requireThatToStringAllowsNullFromLimit() {
assertEquals("foo in [..69]", new FeatureRange("foo", null, 69L).toString());
}
@Test
- public void requireThatToStringAllowsNullToLimit() {
+ void requireThatToStringAllowsNullToLimit() {
assertEquals("foo in [69..]", new FeatureRange("foo", 69L, null).toString());
}
@Test
- public void requireThatSimpleStringsArePrettyPrinted() {
+ void requireThatSimpleStringsArePrettyPrinted() {
assertEquals("foo in [6..9]",
- new FeatureRange("foo", 6L, 9L).toString());
+ new FeatureRange("foo", 6L, 9L).toString());
}
@Test
- public void requireThatComplexStringsAreEscaped() {
+ void requireThatComplexStringsAreEscaped() {
assertEquals("'\\foo' in [6..9]",
- new FeatureRange("\foo", 6L, 9L).toString());
+ new FeatureRange("\foo", 6L, 9L).toString());
}
@Test
- public void requireThatRangePartitionsCanBeAdded() {
+ void requireThatRangePartitionsCanBeAdded() {
FeatureRange range = new FeatureRange("foo", 10L, 22L);
range.addPartition(new RangePartition("foo=10-19"));
range.addPartition(new RangePartition("foo", 0, 0x8000000000000000L, true));
@@ -237,7 +237,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatRangePartitionsCanBeCleared() {
+ void requireThatRangePartitionsCanBeCleared() {
FeatureRange range = new FeatureRange("foo", 10L, 22L);
range.addPartition(new RangePartition("foo=10-19"));
range.addPartition(new RangeEdgePartition("foo=20", 20, 0, 2));
@@ -247,7 +247,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFeatureRangeCanBeBuiltFromMixedInNode() {
+ void requireThatFeatureRangeCanBeBuiltFromMixedInNode() {
assertEquals(new FeatureRange("foo", 10L, 19L),
FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10-19"), 10));
assertEquals(new FeatureRange("foo", -19L, -10L),
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java
index e0ed8da13c8..7068538a1e0 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -9,12 +9,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -22,12 +17,12 @@ import static org.junit.Assert.fail;
public class FeatureSetTest {
@Test
- public void requireThatFeatureSetIsAValue() {
+ void requireThatFeatureSetIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(FeatureSet.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FeatureSet node = new FeatureSet("key", "valueA", "valueB");
assertEquals("key", node.getKey());
assertValues(Arrays.asList("valueA", "valueB"), node);
@@ -40,7 +35,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatValueSetIsMutable() {
+ void requireThatValueSetIsMutable() {
FeatureSet node = new FeatureSet("key");
node.getValues().add("valueA");
assertValues(Arrays.asList("valueA"), node);
@@ -51,7 +46,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
FeatureSet node = new FeatureSet("key", "valueA", "valueB");
assertEquals("key", node.getKey());
assertValues(Arrays.asList("valueA", "valueB"), node);
@@ -62,7 +57,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
FeatureSet node1 = new FeatureSet("key", "valueA", "valueB");
FeatureSet node2 = node1.clone();
assertEquals(node1, node2);
@@ -71,28 +66,28 @@ public class FeatureSetTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new FeatureSet("key").hashCode(), new FeatureSet("key").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
FeatureSet lhs = new FeatureSet("keyA", "valueA", "valueB");
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
FeatureSet rhs = new FeatureSet("keyB");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setKey("keyA");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addValue("valueA");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addValue("valueB");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatkeyIsMandatoryInConstructor() {
+ void requireThatkeyIsMandatoryInConstructor() {
try {
new FeatureSet(null);
fail();
@@ -108,7 +103,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatkeyIsMandatoryInSetter() {
+ void requireThatkeyIsMandatoryInSetter() {
FeatureSet node = new FeatureSet("foo");
try {
node.setKey(null);
@@ -120,7 +115,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatValueIsMandatoryInSetter() {
+ void requireThatValueIsMandatoryInSetter() {
FeatureSet node = new FeatureSet("foo", "bar");
try {
node.addValue(null);
@@ -132,49 +127,49 @@ public class FeatureSetTest {
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo in [val]",
- new FeatureSet("foo", "val").toString());
+ new FeatureSet("foo", "val").toString());
assertEquals("'\\foo' in [val]",
- new FeatureSet("\foo", "val").toString());
+ new FeatureSet("\foo", "val").toString());
assertEquals("'\\x27foo\\x27' in [val]",
- new FeatureSet("'foo'", "val").toString());
+ new FeatureSet("'foo'", "val").toString());
}
@Test
- public void requireThatValuesAreEscapedInToString() {
+ void requireThatValuesAreEscapedInToString() {
assertEquals("key in [bar, foo]",
- new FeatureSet("key", "foo", "bar").toString());
+ new FeatureSet("key", "foo", "bar").toString());
assertEquals("key in ['\\foo', 'ba\\r']",
- new FeatureSet("key", "\foo", "ba\r").toString());
+ new FeatureSet("key", "\foo", "ba\r").toString());
assertEquals("key in ['\\x27bar\\x27', '\\x27foo\\x27']",
- new FeatureSet("key", "'foo'", "'bar'").toString());
+ new FeatureSet("key", "'foo'", "'bar'").toString());
}
@Test
- public void requireThatSimpleStringsArePrettyPrinted() {
+ void requireThatSimpleStringsArePrettyPrinted() {
assertEquals("foo in [bar]",
- new FeatureSet("foo", "bar").toString());
+ new FeatureSet("foo", "bar").toString());
}
@Test
- public void requireThatComplexStringsAreEscaped() {
+ void requireThatComplexStringsAreEscaped() {
assertEquals("'\\foo' in ['ba\\r']",
- new FeatureSet("\foo", "ba\r").toString());
+ new FeatureSet("\foo", "ba\r").toString());
}
@Test
- public void requireThatNegatedFeatureSetsArePrettyPrinted() {
+ void requireThatNegatedFeatureSetsArePrettyPrinted() {
assertEquals("country not in [no, se]",
- new Negation(new FeatureSet("country", "no", "se")).toString());
+ new Negation(new FeatureSet("country", "no", "se")).toString());
}
private static void assertValues(Collection<String> expected, FeatureSet actual) {
List<String> tmp = new ArrayList<>(expected);
for (String value : actual.getValues()) {
- assertNotNull(value, tmp.remove(value));
+ assertNotNull(tmp.remove(value), value);
}
- assertTrue(tmp.toString(), tmp.isEmpty());
+ assertTrue(tmp.isEmpty(), tmp.toString());
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
index 904dce795c3..2a86727c81a 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
@@ -1,14 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +11,12 @@ import static org.junit.Assert.fail;
public class NegationTest {
@Test
- public void requireThatNegationIsAnOperator() {
+ void requireThatNegationIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Negation.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Negation node = new Negation(foo);
assertSame(foo, node.getOperand());
@@ -32,7 +27,7 @@ public class NegationTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Negation node1 = new Negation(SimplePredicates.newString("a"));
Negation node2 = node1.clone();
assertEquals(node1, node2);
@@ -41,25 +36,25 @@ public class NegationTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
Predicate predicate = SimplePredicates.newPredicate();
assertEquals(new Negation(predicate).hashCode(), new Negation(predicate).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Negation lhs = new Negation(SimplePredicates.newString("foo"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Negation rhs = new Negation(SimplePredicates.newString("bar"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setOperand(SimplePredicates.newString("foo"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatChildIsMandatoryInConstructor() {
+ void requireThatChildIsMandatoryInConstructor() {
try {
new Negation(null);
fail();
@@ -69,7 +64,7 @@ public class NegationTest {
}
@Test
- public void requireThatChildIsMandatoryInSetter() {
+ void requireThatChildIsMandatoryInSetter() {
Predicate operand = SimplePredicates.newPredicate();
Negation negation = new Negation(operand);
try {
@@ -82,7 +77,7 @@ public class NegationTest {
}
@Test
- public void requireThatChildIsIncludedInToString() {
+ void requireThatChildIsIncludedInToString() {
assertEquals("not (foo)", new Negation(SimplePredicates.newString("foo")).toString());
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
index 7b1b6886aa0..2db73aff6fe 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class PredicateHashTest{
@Test
- public void requireThatShortStringsGetsHashes() {
+ void requireThatShortStringsGetsHashes() {
assertHashesTo(0x82af3d1de65ec252L, "abcdefg");
assertHashesTo(0xdc50d922fb0e91d6L, "雅虎");
assertHashesTo(0x709bd6ff1a84dc14L, "country=日本");
@@ -44,7 +44,7 @@ public class PredicateHashTest{
}
@Test
- public void requireThatLongStringsGetsHashes() {
+ void requireThatLongStringsGetsHashes() {
assertHashesTo(0x79fac97d13f4cc84L, "abcdefghijklmn1234567890");
assertHashesTo(0xd7af1798f1d5de44L, "abcdefghijklmn1234567890a");
assertHashesTo(0x5a259ad887478cccL, "abcdefghijklmn1234567890ab");
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
index 2bcc62b76e0..d1e36c2b117 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class PredicateOperatorTest {
@Test
- public void requireThatOperatorIsAPredicate() {
+ void requireThatOperatorIsAPredicate() {
assertTrue(Predicate.class.isAssignableFrom(PredicateOperator.class));
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java
index b4b45ab198e..96c774fe8ed 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -14,7 +12,7 @@ import static org.junit.Assert.fail;
public class PredicateParserTest {
@Test
- public void requireThatParseErrorThrowsException() {
+ void requireThatParseErrorThrowsException() {
try {
Predicate.fromString("a in b");
fail("Expected an exception");
@@ -24,7 +22,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatLexerErrorThrowsException() {
+ void requireThatLexerErrorThrowsException() {
try {
Predicate.fromString("a-b in [b]");
fail("Expected an exception");
@@ -34,7 +32,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatSingleValueLeafNodesParse() {
+ void requireThatSingleValueLeafNodesParse() {
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("0 in [1]", "0 in [1]");
assertParsesTo("in in [in]", "in in [in]");
@@ -44,17 +42,17 @@ public class PredicateParserTest {
assertParsesTo("string in ['!@#$%^&*()[]']", "'string' in ['!@#$%^&*()[]']");
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("string in ['foo\\\\_\"\\t\\n\\f\\rbar']",
- "string in ['foo\\\\_\\x22\\t\\n\\f\\rbar']");
+ "string in ['foo\\\\_\\x22\\t\\n\\f\\rbar']");
assertParsesTo("'\\xC3\\xB8' in [b]", "'ø' in [b]");
assertParsesTo("'\\xEF\\xBF\\xBD' in [b]", "'\\xf8' in [b]");
assertParsesTo("'\\xEF\\xBF\\xBD' in [b]", "'\\xef\\xbf\\xbd' in ['b']");
assertParsesTo("'\\xE4\\xB8\\x9C\\xE8\\xA5\\xBF' in ['\\xE8\\x87\\xAA\\xE8\\xA1\\x8C\\xE8\\xBD\\xA6']",
- "'东西' in ['自行车']");
+ "'东西' in ['自行车']");
assertParsesTo("true in [false]", "true in [false]");
}
@Test
- public void requireThatMultiValueLeafNodesParse() {
+ void requireThatMultiValueLeafNodesParse() {
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("0 in [1]", "0 in [1]");
assertParsesTo("in in [and, in]", "in in [in, and]");
@@ -62,7 +60,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatBothSingleAndDoubleQuotesWork() {
+ void requireThatBothSingleAndDoubleQuotesWork() {
assertParsesTo("a in [b]", "'a' in ['b']");
assertParsesTo("a in [b]", "\"a\" in [\"b\"]");
assertParsesTo("'a\\x27' in [b]", "'a\\'' in ['b']");
@@ -70,7 +68,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatRangeLeafNodesParse() {
+ void requireThatRangeLeafNodesParse() {
assertParsesTo("a in [0..100]", "a in [0..100]");
assertParsesTo("0 in [..100]", "0 in [..100]");
assertParsesTo("0 in [0..]", "0 in [0..]");
@@ -81,7 +79,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatRangePartitionsAreIgnored() {
+ void requireThatRangePartitionsAreIgnored() {
assertParsesTo("a in [0..100]", "a in [0..100 (a=0-99,a=100+[..0])]");
assertParsesTo("a in [-100..0]", "a in [-100..0 (a=-0-99,a=-100+[..0])]");
assertParsesTo("a in [-9223372036854775808..0]", "a in [-9223372036854775808..0 (a=-0-9223372036854775808)]");
@@ -91,57 +89,57 @@ public class PredicateParserTest {
}
@Test
- public void requireThatNotInSetWorks() {
+ void requireThatNotInSetWorks() {
assertParsesTo("a not in [b]", "a not in [b]");
}
@Test
- public void requireThatConjunctionWorks() {
+ void requireThatConjunctionWorks() {
assertParsesTo("a in [b] and c in [d]", "a in [b] and c in [d]");
assertParsesTo("a in [b] and c in [d] and e in [f]", "a in [b] and c in [d] and e in [f]");
}
@Test
- public void requireThatDisjunctionWorks() {
+ void requireThatDisjunctionWorks() {
assertParsesTo("a in [b] or c in [d]", "a in [b] or c in [d]");
assertParsesTo("a in [b] or c in [d] or e in [f]", "a in [b] or c in [d] or e in [f]");
}
@Test
- public void requireThatParenthesesWorks() {
+ void requireThatParenthesesWorks() {
assertParsesTo("a in [b] or c in [d]",
- "(a in [b]) or (c in [d])");
+ "(a in [b]) or (c in [d])");
assertParsesTo("a in [b] or c in [d] or e in [f]",
- "(((a in [b]) or c in [d]) or e in [f])");
+ "(((a in [b]) or c in [d]) or e in [f])");
assertParsesTo("(a in [b] and c in [d]) or e in [f]",
- "a in [b] and c in [d] or e in [f]");
+ "a in [b] and c in [d] or e in [f]");
assertParsesTo("a in [b] and (c in [d] or e in [f])",
- "a in [b] and (c in [d] or e in [f])");
+ "a in [b] and (c in [d] or e in [f])");
assertParsesTo("a in [b] and (c in [d] or e in [f]) and g in [h]",
- "a in [b] and (c in [d] or e in [f]) and g in [h]");
+ "a in [b] and (c in [d] or e in [f]) and g in [h]");
}
@Test
- public void requireThatNotOutsideParenthesesWorks() {
+ void requireThatNotOutsideParenthesesWorks() {
assertParsesTo("a not in [b]", "not (a in [b])");
}
@Test
- public void requireThatConjunctionsCanGetMoreThanTwoChildren() {
+ void requireThatConjunctionsCanGetMoreThanTwoChildren() {
Predicate p = Predicate.fromString("a in [b] and c in [d] and e in [f] and g in [h]");
assertTrue(p instanceof Conjunction);
- assertEquals(4, ((Conjunction)p).getOperands().size());
+ assertEquals(4, ((Conjunction) p).getOperands().size());
}
@Test
- public void requireThatDisjunctionsCanGetMoreThanTwoChildren() {
+ void requireThatDisjunctionsCanGetMoreThanTwoChildren() {
Predicate p = Predicate.fromString("a in [b] or c in [d] or e in [f] or g in [h]");
assertTrue(p instanceof Disjunction);
- assertEquals(4, ((Disjunction)p).getOperands().size());
+ assertEquals(4, ((Disjunction) p).getOperands().size());
}
@Test
- public void requireThatBooleanCanBeParsed() {
+ void requireThatBooleanCanBeParsed() {
assertParsesTo("true", "true");
assertParsesTo("false", "false");
assertParsesTo("true or false", "true or false");
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java
index 10de465f342..544403f6c9f 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertTrue;
public class PredicateTest {
@Test
- public void requireThatPredicateIsCloneable() {
+ void requireThatPredicateIsCloneable() {
assertTrue(Cloneable.class.isAssignableFrom(Predicate.class));
}
@Test
- public void requireThatANDConstructsAConjunction() {
+ void requireThatANDConstructsAConjunction() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Predicate predicate = and(foo, bar);
@@ -30,7 +30,7 @@ public class PredicateTest {
}
@Test
- public void requireThatORConstructsADisjunction() {
+ void requireThatORConstructsADisjunction() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Predicate predicate = or(foo, bar);
@@ -39,7 +39,7 @@ public class PredicateTest {
}
@Test
- public void requireThatNOTConstructsANegation() {
+ void requireThatNOTConstructsANegation() {
Predicate foo = SimplePredicates.newString("foo");
Predicate predicate = not(foo);
assertEquals(Negation.class, predicate.getClass());
@@ -47,52 +47,52 @@ public class PredicateTest {
}
@Test
- public void requireThatFeatureBuilderCanConstructFeatureRange() {
+ void requireThatFeatureBuilderCanConstructFeatureRange() {
assertEquals(new FeatureRange("key", 6L, 9L),
- feature("key").inRange(6, 9));
+ feature("key").inRange(6, 9));
assertEquals(new Negation(new FeatureRange("key", 6L, 9L)),
- feature("key").notInRange(6, 9));
+ feature("key").notInRange(6, 9));
assertEquals(new FeatureRange("key", 7L, null),
- feature("key").greaterThan(6));
+ feature("key").greaterThan(6));
assertEquals(new FeatureRange("key", 6L, null),
- feature("key").greaterThanOrEqualTo(6));
+ feature("key").greaterThanOrEqualTo(6));
assertEquals(new FeatureRange("key", null, 5L),
- feature("key").lessThan(6));
+ feature("key").lessThan(6));
assertEquals(new FeatureRange("key", null, 9L),
- feature("key").lessThanOrEqualTo(9));
+ feature("key").lessThanOrEqualTo(9));
}
@Test
- public void requireThatFeatureBuilderCanConstructFeatureSet() {
+ void requireThatFeatureBuilderCanConstructFeatureSet() {
assertEquals(new FeatureSet("key", "valueA", "valueB"),
- feature("key").inSet("valueA", "valueB"));
+ feature("key").inSet("valueA", "valueB"));
assertEquals(new Negation(new FeatureSet("key", "valueA", "valueB")),
- feature("key").notInSet("valueA", "valueB"));
+ feature("key").notInSet("valueA", "valueB"));
}
@Test
- public void requireThatPredicatesCanBeConstructedUsingConstructors() {
+ void requireThatPredicatesCanBeConstructedUsingConstructors() {
assertEquals("country in [no, se] and age in [20..30]",
- new Conjunction(new FeatureSet("country", "no", "se"),
- new FeatureRange("age", 20L, 30L)).toString());
+ new Conjunction(new FeatureSet("country", "no", "se"),
+ new FeatureRange("age", 20L, 30L)).toString());
assertEquals("country not in [no, se] or age in [20..] or height in [..160]",
- new Disjunction(new Negation(new FeatureSet("country", "no", "se")),
- new FeatureRange("age", 20L, null),
- new FeatureRange("height", null, 160L)).toString());
+ new Disjunction(new Negation(new FeatureSet("country", "no", "se")),
+ new FeatureRange("age", 20L, null),
+ new FeatureRange("height", null, 160L)).toString());
}
@Test
- public void requireThatPredicatesCanBeBuiltUsingChainedMethodCalls() {
+ void requireThatPredicatesCanBeBuiltUsingChainedMethodCalls() {
assertEquals("country not in [no, se] or age in [20..] or height in [..160]",
- new Disjunction()
- .addOperand(new Negation(new FeatureSet("country").addValue("no").addValue("se")))
- .addOperand(new FeatureRange("age").setFromInclusive(20L))
- .addOperand(new FeatureRange("height").setToInclusive(160L))
- .toString());
+ new Disjunction()
+ .addOperand(new Negation(new FeatureSet("country").addValue("no").addValue("se")))
+ .addOperand(new FeatureRange("age").setFromInclusive(20L))
+ .addOperand(new FeatureRange("height").setToInclusive(160L))
+ .toString());
}
@Test
- public void requireThatPredicatesCanBeBuiltUsingSeparateMethodCalls() {
+ void requireThatPredicatesCanBeBuiltUsingSeparateMethodCalls() {
Conjunction conjunction = new Conjunction();
FeatureSet countrySet = new FeatureSet("country");
countrySet.addValue("no");
@@ -105,6 +105,6 @@ public class PredicateTest {
heightRange.setToInclusive(160L);
conjunction.addOperand(heightRange);
assertEquals("country in [no, se] and age in [20..] and height in [..160]",
- conjunction.toString());
+ conjunction.toString());
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
index fe5f6db1cfa..c32a36f153b 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class PredicateValueTest {
@Test
- public void requireThatValueIsAPredicate() {
+ void requireThatValueIsAPredicate() {
assertTrue(Predicate.class.isAssignableFrom(PredicateValue.class));
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java
index c8cd3f776c8..a40e577fae5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java
@@ -1,14 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
import static com.yahoo.document.predicate.Predicates.value;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -16,21 +16,21 @@ import static org.junit.Assert.assertEquals;
public class PredicatesTest {
@Test
- public void requireThatApiIsUsable() {
+ void requireThatApiIsUsable() {
assertEquals(
new Disjunction(
new Conjunction(new FeatureSet("country", "de", "no"),
- new Negation(new FeatureSet("gender", "female")),
- new FeatureRange("age", 6L, 9L)),
+ new Negation(new FeatureSet("gender", "female")),
+ new FeatureRange("age", 6L, 9L)),
new Conjunction(new Negation(new FeatureSet("country", "se")),
- new FeatureSet("gender", "female"),
- new FeatureRange("age", 69L, null))),
+ new FeatureSet("gender", "female"),
+ new FeatureRange("age", 69L, null))),
or(and(feature("country").inSet("de", "no"),
- feature("gender").notInSet("female"),
- feature("age").inRange(6, 9)),
- and(not(feature("country").inSet("se")),
- feature("gender").inSet("female"),
- feature("age").greaterThanOrEqualTo(69))));
+ feature("gender").notInSet("female"),
+ feature("age").inRange(6, 9)),
+ and(not(feature("country").inSet("se")),
+ feature("gender").inSet("female"),
+ feature("age").greaterThanOrEqualTo(69))));
assertEquals(new BooleanPredicate(true), value(true));
assertEquals(new BooleanPredicate(false), value(false));
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
index be01b1cd842..00a25e4dc49 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -12,12 +11,12 @@ import static org.junit.Assert.assertEquals;
public class RangeEdgePartitionTest {
@Test
- public void requireThatRangeEdgePartitionIsAValue() {
+ void requireThatRangeEdgePartitionIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(RangeEdgePartition.class));
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
RangeEdgePartition part = new RangeEdgePartition("foo=10", 10, 0, -1);
assertEquals("foo=10", part.getLabel());
assertEquals(0, part.getLowerBound());
@@ -25,7 +24,7 @@ public class RangeEdgePartitionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
RangeEdgePartition node1 = new RangeEdgePartition("foo=10", 10, 0, 0);
RangeEdgePartition node2 = node1.clone();
assertEquals(node1, node2);
@@ -33,29 +32,29 @@ public class RangeEdgePartitionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode(),
new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
RangeEdgePartition lhs = new RangeEdgePartition("foo=10", 10, 5, 10);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
RangeEdgePartition rhs = new RangeEdgePartition("foo=20", 20, 0, 0);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs = new RangeEdgePartition("foo=10", 10, 5, 10);
- assertTrue(lhs.equals(rhs));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 10, 5, 11)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 10, 6, 10)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 11, 5, 10)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=11", 10, 5, 10)));
+ assertEquals(lhs, rhs);
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 10, 5, 11));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 10, 6, 10));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 11, 5, 10));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=11", 10, 5, 10));
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo=10+[2..3]", new RangeEdgePartition("foo=10", 10, 2, 3).toString());
assertEquals("'\\foo=10'+[2..3]", new RangeEdgePartition("\foo=10", 10, 2, 3).toString());
assertEquals("'\\x27foo\\x27=10'+[2..3]", new RangeEdgePartition("'foo'=10", 10, 2, 3).toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
index c11a7fb433f..ea191c705a5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -12,12 +11,12 @@ import static org.junit.Assert.assertEquals;
public class RangePartitionTest {
@Test
- public void requireThatRangePartitionIsAValue() {
+ void requireThatRangePartitionIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(RangePartition.class));
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
RangePartition part = new RangePartition("foo=10-19");
assertEquals("foo=10-19", part.getLabel());
part = new RangePartition("foo", 10, 19, false);
@@ -27,7 +26,7 @@ public class RangePartitionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
RangePartition node1 = new RangePartition("foo=300-399");
RangePartition node2 = node1.clone();
assertEquals(node1, node2);
@@ -35,24 +34,24 @@ public class RangePartitionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new RangePartition("foo=0-9").hashCode(), new RangePartition("foo=0-9").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
RangePartition lhs = new RangePartition("foo=10-19");
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
RangePartition rhs = new RangePartition("bar=1000-1999");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs = new RangePartition("foo=10-19");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo=10-19", new RangePartition("foo=10-19").toString());
assertEquals("'\\foo=10-19'", new RangePartition("\foo=10-19").toString());
assertEquals("'\\x27foo\\x27=10-19'", new RangePartition("'foo'=10-19").toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
index bd580ac232e..8e8a4f45562 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -15,17 +15,17 @@ import static org.junit.Assert.assertEquals;
public class PredicateQueryParserTest {
@Test
- public void require_that_json_is_correctly_parsed() {
+ void require_that_json_is_correctly_parsed() {
String json =
"{" +
- " \"features\":[" +
- " {\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
- " {\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
- " ],\"rangeFeatures\":[" +
- " {\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
- " {\"k\":\"range2\",\"v\":0,\"s\":\"0xffffffffffffffff\"}" +
- " ]" +
- "}";
+ " \"features\":[" +
+ " {\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
+ " {\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
+ " ],\"rangeFeatures\":[" +
+ " {\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
+ " {\"k\":\"range2\",\"v\":0,\"s\":\"0xffffffffffffffff\"}" +
+ " ]" +
+ "}";
PredicateQueryParser parser = new PredicateQueryParser();
List<String> result = new ArrayList<>();
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
index 2725132e68a..497c490b844 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -16,93 +16,93 @@ import static org.junit.Assert.assertEquals;
public class AndOrSimplifierTest {
@Test
- public void requireThatNestedConjunctionsAreCollapsed() {
+ void requireThatNestedConjunctionsAreCollapsed() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d")),
- and(and(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d")),
+ and(and(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNestedConjuctionsAreCollapsedInPlace() {
+ void requireThatNestedConjuctionsAreCollapsedInPlace() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f")),
- and(feature("a").inSet("b"),
- and(feature("c").inSet("d")),
- feature("e").inSet("f")));
+ feature("c").inSet("d"),
+ feature("e").inSet("f")),
+ and(feature("a").inSet("b"),
+ and(feature("c").inSet("d")),
+ feature("e").inSet("f")));
}
@Test
- public void requireThatDeeplyNestedConjunctionsAreCollapsed() {
+ void requireThatDeeplyNestedConjunctionsAreCollapsed() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f"),
- feature("g").inSet("h"),
- feature("i").inSet("j")),
- and(feature("a").inSet("b"),
- and(feature("c").inSet("d")),
- feature("e").inSet("f"),
- and(and(feature("g").inSet("h"),
- feature("i").inSet("j")))));
+ feature("c").inSet("d"),
+ feature("e").inSet("f"),
+ feature("g").inSet("h"),
+ feature("i").inSet("j")),
+ and(feature("a").inSet("b"),
+ and(feature("c").inSet("d")),
+ feature("e").inSet("f"),
+ and(and(feature("g").inSet("h"),
+ feature("i").inSet("j")))));
}
@Test
- public void requireThatNestedDisjunctionsAreCollapsed() {
+ void requireThatNestedDisjunctionsAreCollapsed() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d")),
- or(or(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d")),
+ or(or(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNestedDisjuctionsAreCollapsedInPlace() {
+ void requireThatNestedDisjuctionsAreCollapsedInPlace() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f")),
- or(feature("a").inSet("b"),
- or(feature("c").inSet("d")),
- feature("e").inSet("f")));
+ feature("c").inSet("d"),
+ feature("e").inSet("f")),
+ or(feature("a").inSet("b"),
+ or(feature("c").inSet("d")),
+ feature("e").inSet("f")));
}
@Test
- public void requireThatDeeplyNestedDisjunctionsAreCollapsed() {
+ void requireThatDeeplyNestedDisjunctionsAreCollapsed() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f"),
- feature("g").inSet("h"),
- feature("i").inSet("j")),
- or(feature("a").inSet("b"),
- or(feature("c").inSet("d")),
- feature("e").inSet("f"),
- or(or(feature("g").inSet("h"),
- feature("i").inSet("j")))));
+ feature("c").inSet("d"),
+ feature("e").inSet("f"),
+ feature("g").inSet("h"),
+ feature("i").inSet("j")),
+ or(feature("a").inSet("b"),
+ or(feature("c").inSet("d")),
+ feature("e").inSet("f"),
+ or(or(feature("g").inSet("h"),
+ feature("i").inSet("j")))));
}
@Test
- public void requireThatConjunctionsAndDisjunctionsAreNotCollapsed() {
+ void requireThatConjunctionsAndDisjunctionsAreNotCollapsed() {
assertSimplified(and(or(feature("a").inSet("b"),
- feature("c").inSet("d"))),
- and(or(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d"))),
+ and(or(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNotOrIsTranslatedToAndNot() {
+ void requireThatNotOrIsTranslatedToAndNot() {
assertSimplified(
and(feature("a").notInSet("b"), feature("c").inSet("d")),
not(or(feature("a").inSet("b"), feature("c").notInSet("d"))));
}
@Test
- public void requireThatNotAndIsTranslatedToOrNot() {
+ void requireThatNotAndIsTranslatedToOrNot() {
assertSimplified(
or(feature("a").notInSet("b"), feature("c").inSet("d")),
not(and(feature("a").inSet("b"), feature("c").notInSet("d"))));
}
@Test
- public void requireThatTreeWithoutNotIsNotAffected() {
+ void requireThatTreeWithoutNotIsNotAffected() {
assertSimplified(
and(feature("a").inSet("b"), feature("c").notInSet("d")),
and(feature("a").inSet("b"), feature("c").notInSet("d")));
@@ -113,14 +113,14 @@ public class AndOrSimplifierTest {
}
@Test
- public void requireThatNotOfNotIsRemoved() {
+ void requireThatNotOfNotIsRemoved() {
assertSimplified(feature("a").inSet("b"), not(not(feature("a").inSet("b"))));
assertSimplified(feature("a").inSet("b"), not(feature("a").notInSet("b")));
assertSimplified(feature("a").notInSet("b"), not(not(feature("a").notInSet("b"))));
}
@Test
- public void requireThatNotBeneathAndIsTranslated() {
+ void requireThatNotBeneathAndIsTranslated() {
assertSimplified(
and(feature("a").notInSet("b"), feature("c").inSet("d"), feature("b").inSet("c")),
and(not(or(feature("a").inSet("b"), feature("c").notInSet("d"))), feature("b").inSet("c")));
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
index 54031d36b47..e03a01d3996 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
@@ -2,10 +2,10 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -13,32 +13,32 @@ import static org.junit.Assert.assertEquals;
public class BooleanSimplifierTest {
@Test
- public void requireThatOrOfTrueIsTrue() {
+ void requireThatOrOfTrueIsTrue() {
assertSimplifiedTo(value(true), or(feature("a").inSet("b"), value(true)));
}
@Test
- public void requireThatFalseChildrenOfOrAreRemoved() {
+ void requireThatFalseChildrenOfOrAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), or(feature("a").inSet("b"), value(false)));
}
@Test
- public void requireThatAndOfFalseIsFalse() {
+ void requireThatAndOfFalseIsFalse() {
assertSimplifiedTo(value(false), and(feature("a").inSet("b"), value(false)));
}
@Test
- public void requireThatTrueChildrenOfAndAreRemoved() {
+ void requireThatTrueChildrenOfAndAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), and(feature("a").inSet("b"), value(true)));
}
@Test
- public void requireThatSingleChildAndOrAreRemoved() {
+ void requireThatSingleChildAndOrAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), and(or(and(feature("a").inSet("b")))));
}
@Test
- public void requireThatValueChildrenOfNotAreInverted() {
+ void requireThatValueChildrenOfNotAreInverted() {
assertSimplifiedTo(value(true), not(value(false)));
assertSimplifiedTo(value(false), not(value(true)));
assertSimplifiedTo(value(true), not(not(not(value(false)))));
@@ -46,7 +46,7 @@ public class BooleanSimplifierTest {
}
@Test
- public void requireThatComplexExpressionIsSimplified() {
+ void requireThatComplexExpressionIsSimplified() {
assertSimplifiedTo(
Predicate.fromString("'pub_entity' not in [301951]"),
Predicate.fromString("true and true and true and true and true and 'pub_entity' not in [301951] and ((true and true and true and true) or (true and true and true and true) or (true and true and true and true and 'pub_entity' in [86271]))"));
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
index ac491d57ecd..596b28e8395 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
@@ -4,9 +4,9 @@ package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.FeatureRange;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.document.predicate.RangePartition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -29,7 +29,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatSingleValueRangesAreConverted() {
+ void requireThatSingleValueRangesAreConverted() {
testConvert("foo in [0..0]", "foo in [0..0 (foo=0+[..0])]");
testConvert("foo in [5..5]", "foo in [5..5 (foo=0+[5..5])]");
testConvert("foo in [9..9]", "foo in [9..9 (foo=0+[9..])]");
@@ -40,7 +40,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatVeryShortRangesAreConverted() {
+ void requireThatVeryShortRangesAreConverted() {
testConvert("foo in [10..17]", "foo in [10..17 (foo=10+[..7])]");
testConvert("foo in [12..19]", "foo in [12..19 (foo=10+[2..])]");
testConvert("foo in [11..18]", "foo in [11..18 (foo=10+[1..8])]");
@@ -53,7 +53,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatShortRangeIsConverted() {
+ void requireThatShortRangeIsConverted() {
testConvert("foo in [9..19]", "foo in [9..19 (foo=0+[9..],foo=10-19)]");
testConvert("foo in [10..19]", "foo in [10..19 (foo=10-19)]");
testConvert("foo in [10..20]", "foo in [10..20 (foo=20+[..0],foo=10-19)]");
@@ -67,7 +67,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatMediumRangeIsConverted() {
+ void requireThatMediumRangeIsConverted() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=10-19,foo=20-29,foo=30-39)]");
testConvert("foo in [10..38]", "foo in [10..38 (foo=30+[..8],foo=10-19,foo=20-29)]");
testConvert("foo in [18..39]", "foo in [18..39 (foo=10+[8..],foo=20-29,foo=30-39)]");
@@ -80,7 +80,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLargeRangeIsConverted() {
+ void requireThatLargeRangeIsConverted() {
testConvert("foo in [10..199]", "foo in [10..199 (foo=10-19,foo=20-29,foo=30-39,foo=40-49,foo=50-59,foo=60-69,foo=70-79,foo=80-89,foo=90-99,foo=100-199)]");
testConvert("foo in [8..207]", "foo in [8..207 (foo=0+[8..],foo=200+[..7],foo=10-19,foo=20-29,foo=30-39,foo=40-49,foo=50-59,foo=60-69,foo=70-79,foo=80-89,foo=90-99,foo=100-199)]");
testConvert("foo in [999..2001]", "foo in [999..2001 (foo=990+[9..],foo=2000+[..1],foo=1000-1999)]");
@@ -94,7 +94,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLongMaxIsConverted() {
+ void requireThatLongMaxIsConverted() {
testConvert("foo in [0..9223372036854775807]",
"foo in [0..9223372036854775807 (" +
"foo=9223372036854775800+[..7]," +
@@ -184,7 +184,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLongMinIsConverted() {
+ void requireThatLongMinIsConverted() {
testConvert("foo in [-9223372036854775808..-1]",
"foo in [-9223372036854775808..-1 (" +
"foo=-9223372036854775800+[..8]," +
@@ -273,7 +273,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLowAritiesWork() {
+ void requireThatLowAritiesWork() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=10-11,foo=12-15,foo=32-39,foo=16-31)]", 2);
testConvert("foo in [2..32]", "foo in [2..32 (foo=32+[..0],foo=2-3,foo=4-7,foo=8-15,foo=16-31)]", 2);
testConvert("foo in [-31..63]", "foo in [-31..63 (foo=-31-0,foo=0-63)]", 2);
@@ -327,7 +327,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatHighAritiesWork() {
+ void requireThatHighAritiesWork() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=0+[10..39])]", 1000);
testConvert("foo in [9000..11000]", "foo in [9000..11000 (foo=0+[9000..],foo=10000+[..1000])]", 10000);
testConvert("foo in [10..39]", "foo in [10..39 (foo=0+[10..39])]", 16384);
@@ -338,13 +338,13 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatOpenRangesWork() {
+ void requireThatOpenRangesWork() {
testConvert("foo in [-7..]", "foo in [-7.. (foo=-7-0,foo=0-9223372036854775807)]", 2);
testConvert("foo in [..7]", "foo in [..7 (foo=-9223372036854775808+[..0],foo=-9223372036854775807-0,foo=0-7)]", 2);
}
@Test
- public void requireThatUpperAndLowerBoundsWork() {
+ void requireThatUpperAndLowerBoundsWork() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [-9..]", "foo in [-9.. (foo=-9-0,foo=0-999)]", 10);
@@ -353,7 +353,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatUpperAndLowerBoundsPruneClosedRanges() {
+ void requireThatUpperAndLowerBoundsPruneClosedRanges() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [0..10000]", "foo in [0..10000 (foo=0-999)]", 10);
@@ -364,7 +364,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatRangesOutsideBoundsAreSimplifiedToOneImpossibleRange() {
+ void requireThatRangesOutsideBoundsAreSimplifiedToOneImpossibleRange() {
lowerBound = 900;
upperBound = 999;
testConvert("foo in [0..100]", "foo in [0..100 (foo=-9223372036854775799-9223372036854775790)]", 10);
@@ -380,7 +380,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatUpperAndLowerBoundsAreAdjustedWithArity() {
+ void requireThatUpperAndLowerBoundsAreAdjustedWithArity() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [0..10000]", "foo in [0..10000 (foo=0-999)]", 10);
@@ -592,10 +592,10 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatExistingPartitionsAreCleared() {
+ void requireThatExistingPartitionsAreCleared() {
testConvert("foo in [10..19]", "foo in [10..19 (foo=10-19)]");
Predicate p = Predicate.fromString("foo in [10..19]");
- ((FeatureRange)p).addPartition(new RangePartition("foo", 10000L, 20000L, false));
+ ((FeatureRange) p).addPartition(new RangePartition("foo", 10000L, 20000L, false));
ComplexNodeTransformer tranformer = new ComplexNodeTransformer();
Predicate converted = tranformer.process(p, new PredicateOptions(10, lowerBound, upperBound));
assertEquals("foo in [10..19 (foo=10-19)]", converted.toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
index b1a0be796ab..665b88d3af5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
@@ -2,19 +2,19 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class NotNodeReordererTest {
@Test
- public void requireThatNotChildrenAreMovedAwayFromLastAndChild() {
+ void requireThatNotChildrenAreMovedAwayFromLastAndChild() {
checkReorder(
and(feature("a").inSet("b"), feature("c").notInSet("d")),
and(feature("c").notInSet("d"), feature("a").inSet("b")));
@@ -25,7 +25,7 @@ public class NotNodeReordererTest {
}
@Test
- public void requireThatNotChildrenAreMovedToLastOrChild() {
+ void requireThatNotChildrenAreMovedToLastOrChild() {
checkReorder(
or(feature("c").notInSet("d"), feature("a").inSet("b")),
or(feature("a").inSet("b"), feature("c").notInSet("d")));
@@ -36,15 +36,15 @@ public class NotNodeReordererTest {
}
@Test
- public void requireThatComplexReorderingWork() {
+ void requireThatComplexReorderingWork() {
checkReorder(and(feature("g").inSet("h"),
- or(and(feature("a").notInSet("b"),
- feature("c").notInSet("d")),
- feature("e").inSet("f"))),
+ or(and(feature("a").notInSet("b"),
+ feature("c").notInSet("d")),
+ feature("e").inSet("f"))),
and(or(feature("e").inSet("f"),
- and(feature("a").notInSet("b"),
- feature("c").notInSet("d"))),
- feature("g").inSet("h")));
+ and(feature("a").notInSet("b"),
+ feature("c").notInSet("d"))),
+ feature("g").inSet("h")));
}
private static void checkReorder(Predicate input, Predicate expected) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
index 90487b761db..e51e3d29ac2 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
@@ -2,18 +2,18 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class OrSimplifierTest {
@Test
- public void require_that_or_with_feature_sets_of_same_key_is_simplified_to_single_feature_set() {
+ void require_that_or_with_feature_sets_of_same_key_is_simplified_to_single_feature_set() {
Predicate p =
or(
feature("key1").inSet("value1", "value4"),
@@ -24,7 +24,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_with_feature_sets_of_different_keys_is_simplified() {
+ void require_that_or_with_feature_sets_of_different_keys_is_simplified() {
Predicate p =
or(
feature("key1").inSet("value1", "value3"),
@@ -39,7 +39,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_conversion_is_recursive_and_cascades() {
+ void require_that_conversion_is_recursive_and_cascades() {
Predicate p =
or(
feature("key1").inSet("value1", "value4"),
@@ -52,7 +52,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_below_and_is_converted() {
+ void require_that_or_below_and_is_converted() {
Predicate p =
and(
or(
@@ -67,7 +67,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_below_not_is_converted() {
+ void require_that_or_below_not_is_converted() {
Predicate p =
not(
or(
@@ -78,7 +78,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_non_feature_set_nodes_are_left_untouched() {
+ void require_that_non_feature_set_nodes_are_left_untouched() {
Predicate p =
or(
feature("key1").inSet("value1"),
diff --git a/predicate-search/pom.xml b/predicate-search/pom.xml
index 75c9350707c..a41c72b0211 100644
--- a/predicate-search/pom.xml
+++ b/predicate-search/pom.xml
@@ -15,11 +15,6 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -36,6 +31,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
index bed1228c8b8..b6e4de3a6b8 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
@@ -3,24 +3,27 @@ package com.yahoo.search.predicate;
import com.yahoo.document.predicate.BooleanPredicate;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
*/
public class PredicateIndexBuilderTest {
- @Test(expected = IllegalArgumentException.class)
- public void requireThatIndexingMultiDocumentsWithSameIdThrowsException() {
- PredicateIndexBuilder builder = new PredicateIndexBuilder(2);
- builder.indexDocument(1, Predicate.fromString("a in ['b']"));
- builder.indexDocument(1, Predicate.fromString("c in ['d']"));
+ @Test
+ void requireThatIndexingMultiDocumentsWithSameIdThrowsException() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PredicateIndexBuilder builder = new PredicateIndexBuilder(2);
+ builder.indexDocument(1, Predicate.fromString("a in ['b']"));
+ builder.indexDocument(1, Predicate.fromString("c in ['d']"));
+ });
}
@Test
- public void requireThatEmptyDocumentsCanBeIndexed() {
+ void requireThatEmptyDocumentsCanBeIndexed() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
assertEquals(0, builder.getZeroConstraintDocCount());
builder.indexDocument(2, new BooleanPredicate(true));
@@ -29,7 +32,7 @@ public class PredicateIndexBuilderTest {
}
@Test
- public void requireThatMultipleDocumentsCanBeIndexed() {
+ void requireThatMultipleDocumentsCanBeIndexed() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("a in ['b']"));
builder.indexDocument(2, Predicate.fromString("a in ['b']"));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
index 5ed04418664..a8aef273f3c 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.predicate;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,7 +19,7 @@ public class PredicateIndexTest {
private static final int DOC_ID = 42;
@Test
- public void requireThatPredicateIndexCanSearch() {
+ void requireThatPredicateIndexCanSearch() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no', 'se'] and gender in ['male']"));
builder.indexDocument(0x3fffffe, Predicate.fromString("country in ['no'] and gender in ['female']"));
@@ -34,7 +34,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithNotExpression() {
+ void requireThatPredicateIndexCanSearchWithNotExpression() {
{
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no'] and gender not in ['male']"));
@@ -77,7 +77,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatSearchesCanUseSubqueries() {
+ void requireThatSearchesCanUseSubqueries() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(DOC_ID, Predicate.fromString("country in [no] and gender in [male]"));
PredicateIndex index = builder.build();
@@ -91,7 +91,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithRange() {
+ void requireThatPredicateIndexCanSearchWithRange() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("gender in ['male'] and age in [20..40]"));
builder.indexDocument(2, Predicate.fromString("gender in ['female'] and age in [20..40]"));
@@ -106,7 +106,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithEmptyDocuments() {
+ void requireThatPredicateIndexCanSearchWithEmptyDocuments() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("true"));
builder.indexDocument(2, Predicate.fromString("false"));
@@ -117,7 +117,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicatesHavingMultipleIdenticalConjunctionsAreSupported() {
+ void requireThatPredicatesHavingMultipleIdenticalConjunctionsAreSupported() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(DOC_ID, Predicate.fromString(
"((a in ['b'] and c in ['d']) or x in ['y']) and ((a in ['b'] and c in ['d']) or z in ['w'])"));
@@ -130,7 +130,7 @@ public class PredicateIndexTest {
}
@Test
- public void require_that_serialization_and_deserialization_retain_data() throws IOException {
+ void require_that_serialization_and_deserialization_retain_data() throws IOException {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no', 'se'] and gender in ['male']"));
builder.indexDocument(0x3fffffe, Predicate.fromString("country in ['no'] and gender in ['female']"));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
index 789a8e0a7f4..bde9891895b 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
@@ -4,7 +4,7 @@ package com.yahoo.search.predicate.annotator;
import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.document.predicate.PredicateOperator;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
@@ -12,14 +12,12 @@ import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class PredicateTreeAnalyzerTest {
@Test
- public void require_that_minfeature_is_1_for_simple_term() {
+ void require_that_minfeature_is_1_for_simple_term() {
Predicate p = feature("foo").inSet("bar");
PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p);
assertEquals(1, r.minFeature);
@@ -28,14 +26,14 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_is_1_for_simple_negative_term() {
+ void require_that_minfeature_is_1_for_simple_negative_term() {
Predicate p = not(feature("foo").inSet("bar"));
PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p);
assertEquals(1, r.minFeature);
}
@Test
- public void require_that_minfeature_is_sum_for_and() {
+ void require_that_minfeature_is_sum_for_and() {
Predicate p =
and(
feature("foo").inSet("bar"),
@@ -51,7 +49,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_is_min_for_or() {
+ void require_that_minfeature_is_min_for_or() {
Predicate p =
or(
and(
@@ -73,7 +71,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_rounds_up() {
+ void require_that_minfeature_rounds_up() {
Predicate p =
or(
feature("foo").inSet("bar"),
@@ -85,7 +83,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minvalue_feature_set_considers_all_values() {
+ void require_that_minvalue_feature_set_considers_all_values() {
{
Predicate p =
and(
@@ -107,7 +105,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_not_features_dont_count_towards_minfeature_calculation() {
+ void require_that_not_features_dont_count_towards_minfeature_calculation() {
Predicate p =
and(
feature("foo").inSet("A"),
@@ -120,7 +118,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_multilevel_and_stores_size() {
+ void require_that_multilevel_and_stores_size() {
Predicate p =
and(
and(
@@ -144,7 +142,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_not_ranges_dont_count_towards_minfeature_calculation() {
+ void require_that_not_ranges_dont_count_towards_minfeature_calculation() {
Predicate p =
and(
feature("foo").inRange(0, 10),
@@ -157,7 +155,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_featureconjunctions_contribute_as_one_feature() {
+ void require_that_featureconjunctions_contribute_as_one_feature() {
Predicate p =
conj(
feature("foo").inSet("bar"),
@@ -168,7 +166,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_featureconjunctions_count_as_leaf_in_subtree_calculation() {
+ void require_that_featureconjunctions_count_as_leaf_in_subtree_calculation() {
Predicate p =
and(
and(
@@ -189,7 +187,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_multiple_indentical_feature_conjunctions_does_not_contribute_more_than_one() {
+ void require_that_multiple_indentical_feature_conjunctions_does_not_contribute_more_than_one() {
Predicate p =
and(
or(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
index 6414104f996..2ab5ec6505b 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
@@ -11,7 +11,7 @@ import com.yahoo.document.predicate.RangePartition;
import com.yahoo.search.predicate.index.Feature;
import com.yahoo.search.predicate.index.IntervalWithBounds;
import com.yahoo.search.predicate.index.conjunction.IndexableFeatureConjunction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
@@ -21,14 +21,12 @@ import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
public class PredicateTreeAnnotatorTest {
@Test
- public void require_that_or_intervals_are_the_same() {
+ void require_that_or_intervals_are_the_same() {
Predicate p =
or(
feature("key1").inSet("value1"),
@@ -42,7 +40,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_ands_below_ors_get_different_intervals() {
+ void require_that_ands_below_ors_get_different_intervals() {
Predicate p =
or(
and(
@@ -62,7 +60,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_nots_get_correct_intervals() {
+ void require_that_nots_get_correct_intervals() {
Predicate p =
and(
feature("key").inSet("value"),
@@ -78,7 +76,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_final_first_not_interval_is_extended() {
+ void require_that_final_first_not_interval_is_extended() {
Predicate p = not(feature("key").inSet("A"));
PredicateTreeAnnotations r = PredicateTreeAnnotator.createPredicateTreeAnnotations(p);
assertEquals(1, r.minFeature);
@@ -89,7 +87,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void show_different_types_of_not_intervals() {
+ void show_different_types_of_not_intervals() {
{
Predicate p =
and(
@@ -151,7 +149,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_hashed_ranges_get_correct_intervals() {
+ void require_that_hashed_ranges_get_correct_intervals() {
Predicate p =
and(
range("key",
@@ -183,7 +181,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_extreme_ranges_works() {
+ void require_that_extreme_ranges_works() {
Predicate p =
and(
range("max range", partition("max range=9223372036854775806-9223372036854775807")),
@@ -202,7 +200,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_featureconjunctions_are_registered_and_given_an_interval() {
+ void require_that_featureconjunctions_are_registered_and_given_an_interval() {
Predicate p =
and(
or(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
index ad9f5b8cdd1..2bde0401c51 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
@@ -2,15 +2,13 @@
package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* This test lies in com.yahoo.search.predicate to get access to some methods of PredicateIndex.
@@ -20,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class BoundsPostingListTest {
@Test
- public void requireThatPostingListChecksBounds() {
+ void requireThatPostingListChecksBounds() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
List<Integer> docIds = new ArrayList<>();
List<Integer> dataRefs = new ArrayList<>();
@@ -72,13 +70,13 @@ public class BoundsPostingListTest {
}
private void checkNext(BoundsPostingList postingList, int movePast, int docId, int intervalCount) {
- assertTrue("Unable to move past " + movePast, postingList.nextDocument(movePast));
+ assertTrue(postingList.nextDocument(movePast), "Unable to move past " + movePast);
assertEquals(intervalCount > 0, postingList.prepareIntervals());
assertEquals(docId, postingList.getDocId());
for (int i = 0; i < intervalCount - 1; ++i) {
- assertTrue("Too few intervals, expected " + intervalCount, postingList.nextInterval());
+ assertTrue(postingList.nextInterval(), "Too few intervals, expected " + intervalCount);
}
- assertFalse("Too many intervals, expected " + intervalCount, postingList.nextInterval());
+ assertFalse(postingList.nextInterval(), "Too many intervals, expected " + intervalCount);
}
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
index 21691a47f3e..71cbff6ab3f 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
@@ -3,14 +3,14 @@ package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
import org.eclipse.collections.impl.map.mutable.primitive.ObjectIntHashMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
public class CachedPostingListCounterTest {
@Test
- public void require_that_docids_are_counted_correctly() {
+ void require_that_docids_are_counted_correctly() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
@@ -35,7 +35,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_most_costly_posting_lists_are_first_in_bit_vector() {
+ void require_that_most_costly_posting_lists_are_first_in_bit_vector() {
int nDocuments = 5;
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
List<PostingList> list = new ArrayList<>();
@@ -43,7 +43,10 @@ public class CachedPostingListCounterTest {
PostingList p2 = postingList(0, 1, 2, 3, 4);
PostingList p3 = postingList(1, 2, 3, 4);
PostingList p4 = postingList(3, 4);
- list.add(p1); list.add(p2); list.add(p3); list.add(p4);
+ list.add(p1);
+ list.add(p2);
+ list.add(p3);
+ list.add(p4);
for (int i = 0; i < 100; i++) {
list.add(postingList(0));
}
@@ -64,7 +67,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_cached_docids_are_counted_correctly() {
+ void require_that_cached_docids_are_counted_correctly() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
@@ -82,7 +85,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_cache_rebuilding_behaves_correctly_for_large_amount_of_posting_lists() {
+ void require_that_cache_rebuilding_behaves_correctly_for_large_amount_of_posting_lists() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
index 6cf8821c5f4..755cf39afff 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
@@ -2,24 +2,22 @@
package com.yahoo.search.predicate.index;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class IntervalPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
int ref1 = builder.insert(Arrays.asList(0x1ffff));
int ref2 = builder.insert(Arrays.asList(0x1ffff));
int ref3 = builder.insert(Arrays.asList(0x10001, 0x2ffff));
IntervalPostingList postingList = new IntervalPostingList(
- builder.build(), new int[]{2, 4, 6}, new int[] {ref1, ref2, ref3}, SubqueryBitmap.ALL_SUBQUERIES);
+ builder.build(), new int[]{2, 4, 6}, new int[]{ref1, ref2, ref3}, SubqueryBitmap.ALL_SUBQUERIES);
assertEquals(-1, postingList.getDocId());
assertEquals(0, postingList.getInterval());
assertEquals(0xffffffffffffffffL, postingList.getSubquery());
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
index c12817fbcf6..95ce3116fdf 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
@@ -2,7 +2,7 @@
package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@@ -10,44 +10,44 @@ import java.util.Arrays;
import java.util.List;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
*/
public class PredicateIntervalStoreTest {
- @Test(expected = IllegalArgumentException.class)
- public void requireThatEmptyIntervalListThrows() {
- PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
- builder.insert(new ArrayList<>());
+ @Test
+ void requireThatEmptyIntervalListThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
+ builder.insert(new ArrayList<>());
+ });
}
@Test
- public void requireThatSingleIntervalCanBeInserted() {
+ void requireThatSingleIntervalCanBeInserted() {
testInsertAndRetrieve(0x0001ffff);
}
@Test
- public void requireThatMultiIntervalEntriesCanBeInserted() {
+ void requireThatMultiIntervalEntriesCanBeInserted() {
testInsertAndRetrieve(0x00010001, 0x00020002, 0x0003ffff);
testInsertAndRetrieve(0x00010001, 0x00020002, 0x00030003, 0x00040004, 0x00050005, 0x00060006,
0x00070007, 0x00080008, 0x00090009, 0x000a000a);
}
@Test
- public void requireThatDifferentSizeIntervalArraysCanBeInserted() {
+ void requireThatDifferentSizeIntervalArraysCanBeInserted() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
- int intervals1[] = new int[] {0x00010001, 0x00020002};
- int intervals2[] = new int[] {0x00010001, 0x00020002, 0x00030003};
+ int intervals1[] = new int[]{0x00010001, 0x00020002};
+ int intervals2[] = new int[]{0x00010001, 0x00020002, 0x00030003};
assertEquals(0, builder.insert(Ints.asList(intervals1)));
assertEquals(1, builder.insert(Ints.asList(intervals2)));
}
@Test
- public void requireThatSerializationAndDeserializationRetainIntervals() throws IOException {
+ void requireThatSerializationAndDeserializationRetainIntervals() throws IOException {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
builder.insert(Arrays.asList(0x00010001, 0x00020002));
builder.insert(Arrays.asList(0x00010001, 0x00020002, 0x00030003));
@@ -58,7 +58,7 @@ public class PredicateIntervalStoreTest {
}
@Test
- public void requireThatEqualIntervalListsReturnsSameReference() {
+ void requireThatEqualIntervalListsReturnsSameReference() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
List<Integer> intervals1 = Arrays.asList(0x00010001, 0x00020002);
List<Integer> intervals2 = Arrays.asList(0x00010001, 0x00020002);
@@ -67,7 +67,7 @@ public class PredicateIntervalStoreTest {
PredicateIntervalStore store = builder.build();
int[] a1 = store.get(ref1);
int[] a2 = store.get(ref2);
- assertTrue(a1 == a2);
+ assertEquals(a1, a2);
}
private static void testInsertAndRetrieve(int... intervals) {
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
index 90db2aea89b..9d43893864d 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
@@ -2,21 +2,19 @@
package com.yahoo.search.predicate.index;
import com.yahoo.document.predicate.PredicateHash;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class PredicateRangeTermExpanderTest {
@Test
- public void requireThatSmallRangeIsExpanded() {
+ void requireThatSmallRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -38,12 +36,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-99999999999999999",
"key=0-999999999999999999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatLargeRangeIsExpanded() {
+ void requireThatLargeRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=123456789012345670-123456789012345679",
@@ -65,12 +66,15 @@ public class PredicateRangeTermExpanderTest {
"key=100000000000000000-199999999999999999",
"key=0-999999999999999999").iterator();
expander.expand("key", 123456789012345678L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=123456789012345670"), edge); assertEquals(8, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=123456789012345670"), edge);
+ assertEquals(8, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMaxRangeIsExpanded() {
+ void requireThatMaxRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
expander.expand("key", 9223372036854775807L, range -> fail(),
(edge, value) -> {
@@ -80,7 +84,7 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatSmallNegativeRangeIsExpanded() {
+ void requireThatSmallNegativeRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=-49-40",
@@ -102,12 +106,15 @@ public class PredicateRangeTermExpanderTest {
"key=-99999999999999999-0",
"key=-999999999999999999-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMinRangeIsExpanded() {
+ void requireThatMinRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
expander.expand("key", -9223372036854775808L, range -> fail(),
(edge, value) -> {
@@ -117,18 +124,21 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatMinRangeMinus9IsExpanded() {
+ void requireThatMinRangeMinus9IsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=-9223372036854775799-9223372036854775790",
"key=-9223372036854775799-9223372036854775700").iterator();
expander.expand("key", -9223372036854775799L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-9223372036854775790"), edge); assertEquals(9, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-9223372036854775790"), edge);
+ assertEquals(9, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMinRangeIsExpandedWithArity8() {
+ void requireThatMinRangeIsExpandedWithArity8() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(8);
expander.expand("key", -9223372036854775808L, range -> fail(),
(edge, value) -> {
@@ -138,7 +148,7 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatSmallRangeIsExpandedInArity2() {
+ void requireThatSmallRangeIsExpandedInArity2() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2);
Iterator<String> expectedLabels = Arrays.asList(
"key=42-43",
@@ -205,12 +215,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-4611686018427387903",
"key=0-9223372036854775807").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=42"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=42"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSmallNegativeRangeIsExpandedInArity2() {
+ void requireThatSmallNegativeRangeIsExpandedInArity2() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2);
Iterator<String> expectedLabels = Arrays.asList(
"key=-43-42",
@@ -277,12 +290,15 @@ public class PredicateRangeTermExpanderTest {
"key=-4611686018427387903-0",
"key=-9223372036854775807-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-42"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-42"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatUpperBoundIsUsed() {
+ void requireThatUpperBoundIsUsed() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 9999);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -290,12 +306,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatLowerBoundIsUsed() {
+ void requireThatLowerBoundIsUsed() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -9999, 99);
Iterator<String> expectedLabels = Arrays.asList(
"key=-49-40",
@@ -303,19 +322,22 @@ public class PredicateRangeTermExpanderTest {
"key=-999-0",
"key=-9999-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchesOutsideBoundsGenerateNoLabels() {
+ void requireThatSearchesOutsideBoundsGenerateNoLabels() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 0, 200);
- expander.expand("key", -10, x -> fail(), (x,y) -> fail());
+ expander.expand("key", -10, x -> fail(), (x, y) -> fail());
expander.expand("key", 210, x -> fail(), (x, y) -> fail());
}
@Test
- public void requireThatUpperAndLowerBoundGreaterThan0Works() {
+ void requireThatUpperAndLowerBoundGreaterThan0Works() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 100, 9999);
Iterator<String> expectedLabels = Arrays.asList(
"key=140-149",
@@ -323,12 +345,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 142, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=140"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=140"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchCloseToUnevenUpperBoundIsSensible() {
+ void requireThatSearchCloseToUnevenUpperBoundIsSensible() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 1234);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -336,19 +361,25 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchCloseToMaxUnevenUpperBoundIsSensible() {
+ void requireThatSearchCloseToMaxUnevenUpperBoundIsSensible() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 0, 9223372036854771234L);
Iterator<String> expectedLabels = Arrays.asList(
"key=9223372036854770000-9223372036854770009",
"key=9223372036854770000-9223372036854770099",
"key=9223372036854770000-9223372036854770999").iterator();
expander.expand("key", 9223372036854770000L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=9223372036854770000"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=9223372036854770000"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
index 654b944fb3f..433d69e88a2 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
@@ -3,14 +3,14 @@ package com.yahoo.search.predicate.index;
import com.yahoo.search.predicate.Hit;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,13 +19,13 @@ import static org.junit.Assert.assertEquals;
public class PredicateSearchTest {
@Test
- public void requireThatNoStreamsReturnNoResults() {
+ void requireThatNoStreamsReturnNoResults() {
PredicateSearch search = new PredicateSearch(new ArrayList<>(), new byte[0], new byte[0], new short[0], 1);
assertEquals(0, search.stream().count());
}
@Test
- public void requireThatSingleStreamFiltersOnConstructedCompleteIntervals() {
+ void requireThatSingleStreamFiltersOnConstructedCompleteIntervals() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1, 1},
postingList(
@@ -37,7 +37,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatMinFeatureIsUsedToPruneResults() {
+ void requireThatMinFeatureIsUsedToPruneResults() {
PredicateSearch search = createPredicateSearch(
new byte[]{3, 1},
postingList(
@@ -48,7 +48,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatAHighKCanYieldResults() {
+ void requireThatAHighKCanYieldResults() {
PredicateSearch search = createPredicateSearch(
new byte[]{2},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -59,9 +59,9 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatPostingListsAreSortedAfterAdvancing() {
+ void requireThatPostingListsAreSortedAfterAdvancing() {
PredicateSearch search = createPredicateSearch(
- new byte[] {2, 1, 1, 1},
+ new byte[]{2, 1, 1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(0, 0x000100ff),
entry(3, 0x000100ff)),
@@ -72,7 +72,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatEmptyPostingListsWork() {
+ void requireThatEmptyPostingListsWork() {
PredicateSearch search = createPredicateSearch(
new byte[0],
postingList(SubqueryBitmap.ALL_SUBQUERIES));
@@ -80,7 +80,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatShorterPostingListEndingIsOk() {
+ void requireThatShorterPostingListEndingIsOk() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -92,7 +92,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatSortingWorksForManyPostingLists() {
+ void requireThatSortingWorksForManyPostingLists() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 5, 2, 2},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -116,7 +116,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatInsufficientIntervalCoveragePreventsMatch() {
+ void requireThatInsufficientIntervalCoveragePreventsMatch() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -126,7 +126,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatIntervalsAreSorted() {
+ void requireThatIntervalsAreSorted() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -139,7 +139,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatThereCanBeManyIntervals() {
+ void requireThatThereCanBeManyIntervals() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -148,7 +148,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_NoMatch() {
+ void requireThatNotIsSupported_NoMatch() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -159,7 +159,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_Match() {
+ void requireThatNotIsSupported_Match() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -168,7 +168,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_NoMatchBecauseOfPreviousTerm() {
+ void requireThatNotIsSupported_NoMatchBecauseOfPreviousTerm() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -177,7 +177,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatIntervalSortingWorksAsUnsigned() {
+ void requireThatIntervalSortingWorksAsUnsigned() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -188,7 +188,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatMatchCanRequireMultiplePostingLists() {
+ void requireThatMatchCanRequireMultiplePostingLists() {
PredicateSearch search = createPredicateSearch(
new byte[]{6},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
index b0ff62e33fb..6d416eade9f 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.index;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,7 +19,7 @@ public class SimpleIndexTest {
private static final int DOC_ID = 42;
@Test
- public void requireThatValuesCanBeInserted() {
+ void requireThatValuesCanBeInserted() {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
SimpleIndex index = builder.build();
@@ -38,7 +38,7 @@ public class SimpleIndexTest {
}
@Test
- public void requireThatEntriesAreSortedOnId() {
+ void requireThatEntriesAreSortedOnId() {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
builder.insert(KEY, new Posting(DOC_ID - 1, 20)); // Out of order
@@ -52,7 +52,7 @@ public class SimpleIndexTest {
}
@Test
- public void requireThatSerializationAndDeserializationRetainDictionary() throws IOException {
+ void requireThatSerializationAndDeserializationRetainDictionary() throws IOException {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
builder.insert(KEY, new Posting(DOC_ID + 1, 20));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java
index bade49aaeca..c218e9e5474 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java
@@ -1,11 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.index;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -13,9 +11,9 @@ import static org.junit.Assert.assertTrue;
public class ZeroConstraintPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
ZeroConstraintPostingList postingList =
- new ZeroConstraintPostingList(new int[] {2, 4, 6, 8});
+ new ZeroConstraintPostingList(new int[]{2, 4, 6, 8});
assertEquals(-1, postingList.getDocId());
assertEquals(Interval.fromBoundaries(1, Interval.ZERO_CONSTRAINT_RANGE), postingList.getInterval());
assertEquals(0xffffffffffffffffL, postingList.getSubquery());
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
index e0378bdb7e9..f1d7d0b308a 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
@@ -1,20 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.index;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class ZstarCompressedPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
int ref1 = builder.insert(Arrays.asList(0x10000));
int ref2 = builder.insert(Arrays.asList(0x10000, 0x0ffff));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
index 56c6721fe76..23068097f83 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
@@ -2,11 +2,9 @@
package com.yahoo.search.predicate.index.conjunction;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -15,7 +13,7 @@ public class ConjunctionIdIteratorTest {
@SuppressWarnings("PointlessBitwiseExpression")
@Test
- public void require_that_next_returns_skips_to_correct_value() {
+ void require_that_next_returns_skips_to_correct_value() {
// NOTE: LST bit represents the conjunction sign: 0 => negative, 1 => positive.
int[] conjunctionIds = new int[]{
0 | 1,
@@ -49,7 +47,7 @@ public class ConjunctionIdIteratorTest {
}
@Test
- public void require_that_subquery_is_correct() {
+ void require_that_subquery_is_correct() {
ConjunctionIdIterator iterator = new ConjunctionIdIterator(0b1111, new int[]{1});
assertEquals(0b1111, iterator.getSubqueryBitmap());
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
index 07bcf83776a..9f040553a83 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
@@ -4,7 +4,7 @@ package com.yahoo.search.predicate.index.conjunction;
import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.search.predicate.PredicateQuery;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
@@ -14,14 +14,12 @@ import java.util.List;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class ConjunctionIndexTest {
@Test
- public void require_that_single_conjunction_can_be_indexed() {
+ void require_that_single_conjunction_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(conj(feature("a").inSet("1"), feature("b").inSet("2"))));
assertEquals(2, builder.calculateFeatureCount());
@@ -29,7 +27,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_large_conjunction_can_be_indexed() {
+ void require_that_large_conjunction_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -41,7 +39,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_multiple_conjunctions_can_be_indexed() {
+ void require_that_multiple_conjunctions_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -70,7 +68,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_search_for_simple_conjunctions_work() {
+ void require_that_search_for_simple_conjunctions_work() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
@@ -105,7 +103,7 @@ public class ConjunctionIndexTest {
@Test
- public void require_that_conjunction_with_not_is_indexed() {
+ void require_that_conjunction_with_not_is_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -121,7 +119,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_0() {
+ void require_that_not_works_when_k_is_0() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -161,7 +159,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_1() {
+ void require_that_not_works_when_k_is_1() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -197,7 +195,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_2() {
+ void require_that_not_works_when_k_is_2() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -236,7 +234,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_multi_term_queries_are_supported() {
+ void require_that_multi_term_queries_are_supported() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -255,7 +253,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_subqueries_are_supported() {
+ void require_that_subqueries_are_supported() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -328,7 +326,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_serialization_and_deserialization_retain_data() throws IOException {
+ void require_that_serialization_and_deserialization_retain_data() throws IOException {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
index 88b8bf005a4..6bdb3d1e415 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
@@ -5,14 +5,14 @@ import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.FeatureRange;
import com.yahoo.document.predicate.FeatureSet;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -21,7 +21,7 @@ public class FeatureConjunctionTransformerTest {
private static final FeatureConjunctionTransformer transformer = new FeatureConjunctionTransformer(true);
@Test
- public void require_that_simple_ands_are_converted() {
+ void require_that_simple_ands_are_converted() {
assertConvertedPredicateEquals(
conj(not(featureSet(1)), featureSet(2)),
and(not(featureSet(1)), featureSet(2))
@@ -29,7 +29,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featureranges_are_split_into_separate_and() {
+ void require_that_featureranges_are_split_into_separate_and() {
assertConvertedPredicateEquals(
and(featureRange(2), conj(not(featureSet(1)), featureSet(3))),
and(not(featureSet(1)), featureRange(2), featureSet(3))
@@ -37,7 +37,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ors_are_split_into_separate_and() {
+ void require_that_ors_are_split_into_separate_and() {
assertConvertedPredicateEquals(
and(or(featureSet(1), featureSet(2)), conj(featureSet(3), featureSet(4))),
and(or(featureSet(1), featureSet(2)), featureSet(3), featureSet(4))
@@ -45,7 +45,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ands_must_have_more_than_one_featureset_to_be_converted() {
+ void require_that_ands_must_have_more_than_one_featureset_to_be_converted() {
assertConvertedPredicateEquals(
and(featureSet(1), featureRange(2)),
and(featureSet(1), featureRange(2))
@@ -53,7 +53,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ordering_of_and_operands_are_preserved() {
+ void require_that_ordering_of_and_operands_are_preserved() {
assertConvertedPredicateEquals(
and(not(featureRange(1)), featureRange(4), conj(not(featureSet(2)), featureSet(3))),
and(not(featureRange(1)), not(featureSet(2)), featureSet(3), featureRange(4))
@@ -61,7 +61,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_nested_ands_are_converted() {
+ void require_that_nested_ands_are_converted() {
assertConvertedPredicateEquals(
and(conj(featureSet(1), featureSet(2)), conj(featureSet(3), featureSet(4))),
and(and(featureSet(1), featureSet(2)), and(featureSet(3), featureSet(4)))
@@ -69,7 +69,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featureset_with_common_key_is_not_converted() {
+ void require_that_featureset_with_common_key_is_not_converted() {
assertConvertedPredicateEquals(
and(not(featureSet(1)), featureSet(1)),
and(not(featureSet(1)), featureSet(1))
@@ -77,7 +77,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_nonunique_featureset_are_split_into_separate_conjunctions() {
+ void require_that_nonunique_featureset_are_split_into_separate_conjunctions() {
assertConvertedPredicateEquals(
and(conj(not(featureSet(1)), featureSet(2)), featureSet(1)),
and(not(featureSet(1)), featureSet(1), featureSet(2))
@@ -93,7 +93,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featuresets_in_conjunction_may_only_have_a_single_value() {
+ void require_that_featuresets_in_conjunction_may_only_have_a_single_value() {
assertConvertedPredicateEquals(
and(featureSet(1, "a", "b"), featureSet(4, "c", "d"), conj(featureSet(2), featureSet(3))),
and(featureSet(1, "a", "b"), featureSet(2), featureSet(3), featureSet(4, "c", "d"))
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
index 0bd9a1cda01..f6a44caf130 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.search.predicate.serialization;
import com.yahoo.search.predicate.PredicateQuery;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -15,15 +15,15 @@ import static org.junit.Assert.assertEquals;
public class PredicateQuerySerializerTest {
@Test
- public void require_that_query_is_correctly_parsed_and_written_back_to_json() throws Exception {
+ void require_that_query_is_correctly_parsed_and_written_back_to_json() throws Exception {
String json =
"{\"features\":[" +
- "{\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
- "{\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
- "],\"rangeFeatures\":[" +
- "{\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
- "{\"k\":\"range2\",\"v\":0}" +
- "]}";
+ "{\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
+ "{\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
+ "],\"rangeFeatures\":[" +
+ "{\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
+ "{\"k\":\"range2\",\"v\":0}" +
+ "]}";
PredicateQuerySerializer serializer = new PredicateQuerySerializer();
PredicateQuery query = serializer.fromJSON(json);
List<PredicateQuery.Feature> features = query.getFeatures();
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java
index fa8fbb1e77d..1a2df01b248 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.serialization;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -13,28 +13,28 @@ import static com.yahoo.search.predicate.serialization.SerializationTestHelper.*
public class SerializationHelperTest {
@Test
- public void require_that_long_serialization_works() throws IOException {
+ void require_that_long_serialization_works() throws IOException {
long[] longs = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
longs, SerializationHelper::writeLongArray, SerializationHelper::readLongArray);
}
@Test
- public void require_that_int_serialization_works() throws IOException {
+ void require_that_int_serialization_works() throws IOException {
int[] ints = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
ints, SerializationHelper::writeIntArray, SerializationHelper::readIntArray);
}
@Test
- public void require_that_byte_serialization_works() throws IOException {
+ void require_that_byte_serialization_works() throws IOException {
byte[] bytes = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
bytes, SerializationHelper::writeByteArray, SerializationHelper::readByteArray);
}
@Test
- public void require_that_short_serialization_works() throws IOException {
+ void require_that_short_serialization_works() throws IOException {
short[] shorts = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
shorts, SerializationHelper::writeShortArray, SerializationHelper::readShortArray);
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
index 42cfa861f34..608ed0b1a52 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
@@ -7,7 +7,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* @author bjorncs
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
index a1bb225fb9f..2b452ad6536 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.utils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class PostingListSearchTest {
@Test
- public void require_that_search_find_index_of_first_element_higher() {
+ void require_that_search_find_index_of_first_element_higher() {
int[] values = {2, 8, 4000, 4001, 4100, 10000, 10000000};
int length = values.length;
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, length, 1));
@@ -24,7 +24,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_one_size_arrays() {
+ void require_that_search_is_correct_for_one_size_arrays() {
int[] values = {100};
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, 1, 0));
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, 1, 99));
@@ -34,7 +34,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_sub_arrays() {
+ void require_that_search_is_correct_for_sub_arrays() {
int[] values = {0, 2, 8, 4000, 4001, 4100};
assertEquals(1, PostingListSearch.interpolationSearch(values, 1, 2, 1));
assertEquals(2, PostingListSearch.interpolationSearch(values, 1, 2, 2));
@@ -45,7 +45,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_large_arrays() {
+ void require_that_search_is_correct_for_large_arrays() {
int length = 10000;
int[] values = new int[length];
for (int i = 0; i < length; i++) {
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
index eb641b6fa05..692fb9ab696 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
@@ -1,33 +1,30 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.utils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Random;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class PrimitiveArraySorterTest {
@Test
- public void sorting_empty_array_should_not_throw_exception() {
+ void sorting_empty_array_should_not_throw_exception() {
short[] array = {};
PrimitiveArraySorter.sort(array, Short::compare);
}
@Test
- public void test_sorting_single_item_array() {
+ void test_sorting_single_item_array() {
short[] array = {42};
PrimitiveArraySorter.sort(array, Short::compare);
assertEquals(42, array[0]);
}
@Test
- public void test_sorting_custom_comparator() {
+ void test_sorting_custom_comparator() {
short[] array = {4, 2, 5};
PrimitiveArraySorter.sort(array, (a, b) -> Short.compare(b, a)); // Sort using inverse ordering.
short[] expected = {5, 4, 2};
@@ -35,7 +32,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_complicated_array() {
+ void test_complicated_array() {
short[] array = {20381, -28785, -19398, 17307, -12612, 11459, -30164, -16597, -4267, 30838, 8918, 9014, -26444,
-1232, -14620, 12636, -12389, -4931, 32108, 19854, -12681, 14933, 319, 27348, -4907, 19196, 14209,
-32694, 2579, 9771, -1157, -13717, 28506, -8016, 21423, 23697, 23755, 29650, 25644, -14660, -18952,
@@ -48,7 +45,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void sorting_random_arrays_should_produce_identical_result_as_java_sort() {
+ void sorting_random_arrays_should_produce_identical_result_as_java_sort() {
Random r = new Random(4234);
for (int i = 0; i < 10000; i++) {
short[] original = makeRandomArray(r);
@@ -57,12 +54,12 @@ public class PrimitiveArraySorterTest {
PrimitiveArraySorter.sort(customSorted, Short::compare);
Arrays.sort(javaSorted);
String errorMsg = String.format("%s != %s (before sorting: %s)", Arrays.toString(customSorted), Arrays.toString(javaSorted), Arrays.toString(original));
- assertArrayEquals(errorMsg, customSorted, javaSorted);
+ assertArrayEquals(customSorted, javaSorted, errorMsg);
}
}
@Test
- public void test_merging_simple_array() {
+ void test_merging_simple_array() {
short[] array = {-20, -12, 2, -22, -11, 33, 44};
short[] expected = {-22, -20, -12, -11, 2, 33, 44};
short[] result = new short[array.length];
@@ -71,7 +68,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_merging_of_random_generated_arrays() {
+ void test_merging_of_random_generated_arrays() {
Random r = new Random(4234);
for (int i = 0; i < 10000; i++) {
short[] array = makeRandomArray(r);
@@ -89,7 +86,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_sortandmerge_returns_false_when_sort_is_in_place() {
+ void test_sortandmerge_returns_false_when_sort_is_in_place() {
short[] array = {3, 2, 1, 0, 4, 5, 6};
short[] mergeArray = new short[array.length];
assertFalse(PrimitiveArraySorter.sortAndMerge(array, mergeArray, 4, 7, Short::compare));
diff --git a/screwdriver/build-vespa.sh b/screwdriver/build-vespa.sh
index ca9ada81205..6a93474c620 100755
--- a/screwdriver/build-vespa.sh
+++ b/screwdriver/build-vespa.sh
@@ -53,23 +53,6 @@ case $SHOULD_BUILD in
esac
if [[ $SHOULD_BUILD == systemtest ]]; then
- dnf module enable -y ruby:2.7
- dnf install -y \
- gcc-toolset-11-annobin \
- gcc-toolset-11-annobin-plugin-gcc \
- gcc-toolset-11-binutils \
- gcc-toolset-11-gcc-c++ \
- gcc-toolset-11-libatomic-devel \
- libxml2-devel \
- ruby \
- ruby-devel \
- rubygems-devel \
- rubygem-net-telnet \
- zstd
-
- source /opt/rh/gcc-toolset-11/enable
- gem install libxml-ruby gnuplot distribution test-unit builder concurrent-ruby bigdecimal ffi parallel
-
cd $HOME
git clone https://github.com/vespa-engine/system-test
export SYSTEM_TEST_DIR=$(pwd)/system-test
diff --git a/screwdriver/delete-old-artifactory-artifacts.sh b/screwdriver/delete-old-artifactory-artifacts.sh
index 80cee37bd72..3bb968f3995 100755
--- a/screwdriver/delete-old-artifactory-artifacts.sh
+++ b/screwdriver/delete-old-artifactory-artifacts.sh
@@ -10,15 +10,20 @@ ARTIFACTORY_URL="https://artifactory.yahooinc.com/artifactory"
# JFrog Cloud repo file
if [[ ! -f /etc/yum.repos.d/vespa.repo ]]; then
cat << EOF > /etc/yum.repos.d/vespa.repo
-[vespa-release]
+[vespa-release-el8]
name=Vespa releases
baseurl=$ARTIFACTORY_URL/vespa/centos/8/release/\$basearch
gpgcheck=0
enabled=1
+[vespa-release-el7]
+name=Vespa releases
+baseurl=$ARTIFACTORY_URL/vespa/centos/7/release/\$basearch
+gpgcheck=0
+enabled=1
EOF
fi
-VERSIONS_TO_DELETE=$(dnf list --quiet --showduplicates --disablerepo='*' --enablerepo=vespa-release vespa | awk '/[0-9].*\.[0-9].*\.[0-9].*/{print $2}' | sort -V | head -n -200)
+VERSIONS_TO_DELETE=$(dnf list --quiet --showduplicates --disablerepo='*' --enablerepo=vespa-release-el7,vespa-release-el8 vespa | awk '/[0-9].*\.[0-9].*\.[0-9].*/{print $2}' | sort -V | head -n -200 | grep -v "7.594.36")
RPMS_TO_DELETE=$(mktemp)
trap "rm -f $RPMS_TO_DELETE" EXIT
diff --git a/screwdriver/release-rpms.sh b/screwdriver/release-rpms.sh
index c6206fd662e..5de292eb9c5 100755
--- a/screwdriver/release-rpms.sh
+++ b/screwdriver/release-rpms.sh
@@ -12,7 +12,7 @@ fi
readonly VESPA_RELEASE="$1"
readonly VESPA_REF="$2"
-VESPA_RPM=$(dnf repoquery --repofrompath=vespa,https://copr-be.cloud.fedoraproject.org/results/@vespa/vespa/centos-stream-8-x86_64 --repoid=vespa -q vespa | tail -1 | cut -d: -f2 | cut -d- -f1)
+VESPA_RPM=$(dnf repoquery --repofrompath=vespa,https://copr-be.cloud.fedoraproject.org/results/@vespa/vespa/centos-stream-8-x86_64 --repoid=vespa -q vespa | cut -d: -f2 | cut -d- -f1 | sort -V | tail -1)
echo "Latest RPM on Copr: $VESPA_RPM"
if [ "$VESPA_RELEASE" == "$VESPA_RPM" ]; then
@@ -33,7 +33,7 @@ dist/release-vespa-rpm.sh $VESPA_RELEASE $VESPA_REF
while [ "$VESPA_RELEASE" != "$VESPA_RPM" ]; do
dnf clean --repofrompath=vespa,https://copr-be.cloud.fedoraproject.org/results/@vespa/vespa/centos-stream-8-x86_64 --repoid=vespa metadata
- VESPA_RPM=$(dnf repoquery --repofrompath=vespa,https://copr-be.cloud.fedoraproject.org/results/@vespa/vespa/centos-stream-8-x86_64 --repoid=vespa -q vespa | tail -1 | cut -d: -f2 | cut -d- -f1)
+ VESPA_RPM=$(dnf repoquery --repofrompath=vespa,https://copr-be.cloud.fedoraproject.org/results/@vespa/vespa/centos-stream-8-x86_64 --repoid=vespa -q vespa | cut -d: -f2 | cut -d- -f1 | sort -V | tail -1)
echo "RPM: $VESPA_RPM"
sleep 150
done
diff --git a/screwdriver/update-vespa-version-in-sample-apps.sh b/screwdriver/update-vespa-version-in-sample-apps.sh
index ca163de347c..22a55b0ce20 100755
--- a/screwdriver/update-vespa-version-in-sample-apps.sh
+++ b/screwdriver/update-vespa-version-in-sample-apps.sh
@@ -17,9 +17,9 @@ function is_published {
echo $TMP_MVN_REPO
mkdir -p $TMP_MVN_REPO
rm -rf $TMP_MVN_REPO/com/yahoo/vespa
- # Because the transfer of artifacts to Maven Central is not atomic we can't just check a simple pom or jar to be available. Because of this we
+ # Because the transfer of artifacts to Maven Central is not atomic we can't just check a simple pom or jar to be available. Because of this we
# check that the publication is complete enough to compile a Java sample app
- if mvn -V -B -pl ai.vespa.example:albums -Dmaven.repo.local=$TMP_MVN_REPO -Dmaven.javadoc.skip=true -Dmaven.source.skip=true -DskipTests clean package; then
+ if mvn -V -B -pl ai.vespa.examples:album-recommendation-java -Dmaven.repo.local=$TMP_MVN_REPO -Dmaven.javadoc.skip=true -Dmaven.source.skip=true -DskipTests clean package; then
return 0
else
return 1
diff --git a/searchcore/src/apps/vespa-feed-bm/vespa_feed_bm.cpp b/searchcore/src/apps/vespa-feed-bm/vespa_feed_bm.cpp
index df0827e78c9..95c63f56bac 100644
--- a/searchcore/src/apps/vespa-feed-bm/vespa_feed_bm.cpp
+++ b/searchcore/src/apps/vespa-feed-bm/vespa_feed_bm.cpp
@@ -21,14 +21,11 @@
#include <vespa/searchcore/bmcluster/spi_bm_feed_handler.h>
#include <vespa/searchlib/index/dummyfileheadercontext.h>
#include <vespa/vespalib/objects/nbostream.h>
-#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <getopt.h>
#include <filesystem>
#include <iostream>
-#include <thread>
-#include <unistd.h>
#include <vespa/log/log.h>
LOG_SETUP("vespa-feed-bm");
@@ -229,7 +226,6 @@ App::usage()
"[--rpc-events-before-wakeup events]\n"
"[--rpc-network-threads threads]\n"
"[--rpc-targets-per-node targets]\n"
- "[--skip-communicationmanager-thread]\n"
"[--skip-get-spi-bucket-info]\n"
"[--update-passes update-passes]\n"
"[--use-async-message-handling]\n"
@@ -261,7 +257,6 @@ App::get_options(int argc, char **argv)
{ "rpc-events-before-wakeup", 1, nullptr, 0 },
{ "rpc-network-threads", 1, nullptr, 0 },
{ "rpc-targets-per-node", 1, nullptr, 0 },
- { "skip-communicationmanager-thread", 0, nullptr, 0 },
{ "skip-get-spi-bucket-info", 0, nullptr, 0 },
{ "update-passes", 1, nullptr, 0 },
{ "use-async-message-handling", 0, nullptr, 0 },
@@ -288,7 +283,6 @@ App::get_options(int argc, char **argv)
LONGOPT_RPC_EVENTS_BEFORE_WAKEUP,
LONGOPT_RPC_NETWORK_THREADS,
LONGOPT_RPC_TARGETS_PER_NODE,
- LONGOPT_SKIP_COMMUNICATIONMANAGER_THREAD,
LONGOPT_SKIP_GET_SPI_BUCKET_INFO,
LONGOPT_UPDATE_PASSES,
LONGOPT_USE_ASYNC_MESSAGE_HANDLING,
@@ -355,9 +349,6 @@ App::get_options(int argc, char **argv)
case LONGOPT_RPC_TARGETS_PER_NODE:
_bm_params.set_rpc_targets_per_node(atoi(optarg));
break;
- case LONGOPT_SKIP_COMMUNICATIONMANAGER_THREAD:
- _bm_params.set_skip_communicationmanager_thread(true);
- break;
case LONGOPT_SKIP_GET_SPI_BUCKET_INFO:
_bm_params.set_skip_get_spi_bucket_info(true);
break;
diff --git a/searchcore/src/apps/vespa-redistribute-bm/vespa_redistribute_bm.cpp b/searchcore/src/apps/vespa-redistribute-bm/vespa_redistribute_bm.cpp
index f22e817b72c..7d190a81087 100644
--- a/searchcore/src/apps/vespa-redistribute-bm/vespa_redistribute_bm.cpp
+++ b/searchcore/src/apps/vespa-redistribute-bm/vespa_redistribute_bm.cpp
@@ -23,7 +23,6 @@
#include <vespa/searchcore/bmcluster/spi_bm_feed_handler.h>
#include <vespa/searchlib/index/dummyfileheadercontext.h>
#include <vespa/vespalib/objects/nbostream.h>
-#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
@@ -31,7 +30,6 @@
#include <filesystem>
#include <iostream>
#include <thread>
-#include <unistd.h>
#include <vespa/log/log.h>
LOG_SETUP("vespa-redistribute-bm");
@@ -491,7 +489,6 @@ App::usage()
"[--rpc-network-threads threads]\n"
"[--rpc-targets-per-node targets]\n"
"[--response-threads threads]\n"
- "[--skip-communicationmanager-thread]\n"
"[--use-async-message-handling]\n"
"[--use-feed-settle]" << std::endl;
}
@@ -526,7 +523,6 @@ App::get_options(int argc, char **argv)
{ "rpc-events-before-wakeup", 1, nullptr, 0 },
{ "rpc-network-threads", 1, nullptr, 0 },
{ "rpc-targets-per-node", 1, nullptr, 0 },
- { "skip-communicationmanager-thread", 0, nullptr, 0 },
{ "use-async-message-handling", 0, nullptr, 0 },
{ "use-feed-settle", 0, nullptr, 0 },
{ nullptr, 0, nullptr, 0 }
@@ -556,7 +552,6 @@ App::get_options(int argc, char **argv)
LONGOPT_RPC_EVENTS_BEFORE_WAKEUP,
LONGOPT_RPC_NETWORK_THREADS,
LONGOPT_RPC_TARGETS_PER_NODE,
- LONGOPT_SKIP_COMMUNICATIONMANAGER_THREAD,
LONGOPT_USE_ASYNC_MESSAGE_HANDLING,
LONGOPT_USE_FEED_SETTLE
};
@@ -643,9 +638,6 @@ App::get_options(int argc, char **argv)
case LONGOPT_RPC_TARGETS_PER_NODE:
_bm_params.set_rpc_targets_per_node(atoi(optarg));
break;
- case LONGOPT_SKIP_COMMUNICATIONMANAGER_THREAD:
- _bm_params.set_skip_communicationmanager_thread(true);
- break;
case LONGOPT_USE_ASYNC_MESSAGE_HANDLING:
_bm_params.set_use_async_message_handling_on_schedule(true);
break;
diff --git a/searchcore/src/tests/proton/docsummary/CMakeLists.txt b/searchcore/src/tests/proton/docsummary/CMakeLists.txt
index 274c1e302da..6c94e7fd38a 100644
--- a/searchcore/src/tests/proton/docsummary/CMakeLists.txt
+++ b/searchcore/src/tests/proton/docsummary/CMakeLists.txt
@@ -23,11 +23,5 @@ vespa_add_executable(searchcore_docsummary_test_app TEST
searchcore_proton_metrics
searchcore_fconfig
)
-vespa_add_executable(searchcore_summaryfieldconverter_test_app
- SOURCES
- summaryfieldconverter_test.cpp
- DEPENDS
- searchcore_docsummary
-)
vespa_add_test(NAME searchcore_docsummary_test_app COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/docsummary_test.sh
- DEPENDS searchcore_docsummary_test_app searchcore_summaryfieldconverter_test_app)
+ DEPENDS searchcore_docsummary_test_app)
diff --git a/searchcore/src/tests/proton/docsummary/docsummary.cpp b/searchcore/src/tests/proton/docsummary/docsummary.cpp
index 49fd82c3a36..4ede2aeb4cf 100644
--- a/searchcore/src/tests/proton/docsummary/docsummary.cpp
+++ b/searchcore/src/tests/proton/docsummary/docsummary.cpp
@@ -322,8 +322,8 @@ assertString(const std::string & exp, const std::string & fieldName,
DocumentStoreAdapter &dsa, uint32_t id)
{
GeneralResultPtr res = getResult(dsa, id);
- return EXPECT_EQUAL(exp, std::string(res->GetEntry(fieldName.c_str())->_stringval,
- res->GetEntry(fieldName.c_str())->_stringlen));
+ return EXPECT_EQUAL(exp, std::string(res->GetPresentEntry(fieldName.c_str())->_stringval,
+ res->GetPresentEntry(fieldName.c_str())->_stringlen));
}
void
@@ -392,24 +392,24 @@ TEST_F("requireThatAdapterHandlesAllFieldTypes", Fixture)
bc.createFieldCacheRepo(f.getResultConfig())->getFieldCache("class0"),
f.getMarkupFields());
GeneralResultPtr res = getResult(dsa, 0);
- EXPECT_EQUAL(255u, res->GetEntry("a")->_intval);
- EXPECT_EQUAL(32767u, res->GetEntry("b")->_intval);
- EXPECT_EQUAL(2147483647u, res->GetEntry("c")->_intval);
- EXPECT_EQUAL(2147483648u, res->GetEntry("d")->_int64val);
- EXPECT_APPROX(1234.56, res->GetEntry("e")->_doubleval, 10e-5);
- EXPECT_APPROX(9876.54, res->GetEntry("f")->_doubleval, 10e-5);
- EXPECT_EQUAL("foo", std::string(res->GetEntry("g")->_stringval,
- res->GetEntry("g")->_stringlen));
- EXPECT_EQUAL("bar", std::string(res->GetEntry("h")->_stringval,
- res->GetEntry("h")->_stringlen));
- EXPECT_EQUAL("baz", std::string(res->GetEntry("i")->_dataval,
- res->GetEntry("i")->_datalen));
- EXPECT_EQUAL("qux", std::string(res->GetEntry("j")->_dataval,
- res->GetEntry("j")->_datalen));
- EXPECT_EQUAL("<foo>", std::string(res->GetEntry("k")->_stringval,
- res->GetEntry("k")->_stringlen));
- EXPECT_EQUAL("{foo:10}", std::string(res->GetEntry("l")->_stringval,
- res->GetEntry("l")->_stringlen));
+ EXPECT_EQUAL(255u, res->GetPresentEntry("a")->_intval);
+ EXPECT_EQUAL(32767u, res->GetPresentEntry("b")->_intval);
+ EXPECT_EQUAL(2147483647u, res->GetPresentEntry("c")->_intval);
+ EXPECT_EQUAL(2147483648u, res->GetPresentEntry("d")->_int64val);
+ EXPECT_APPROX(1234.56, res->GetPresentEntry("e")->_doubleval, 10e-5);
+ EXPECT_APPROX(9876.54, res->GetPresentEntry("f")->_doubleval, 10e-5);
+ EXPECT_EQUAL("foo", std::string(res->GetPresentEntry("g")->_stringval,
+ res->GetPresentEntry("g")->_stringlen));
+ EXPECT_EQUAL("bar", std::string(res->GetPresentEntry("h")->_stringval,
+ res->GetPresentEntry("h")->_stringlen));
+ EXPECT_EQUAL("baz", std::string(res->GetPresentEntry("i")->_dataval,
+ res->GetPresentEntry("i")->_datalen));
+ EXPECT_EQUAL("qux", std::string(res->GetPresentEntry("j")->_dataval,
+ res->GetPresentEntry("j")->_datalen));
+ EXPECT_EQUAL("<foo>", std::string(res->GetPresentEntry("k")->_stringval,
+ res->GetPresentEntry("k")->_stringlen));
+ EXPECT_EQUAL("{foo:10}", std::string(res->GetPresentEntry("l")->_stringval,
+ res->GetPresentEntry("l")->_stringlen));
}
TEST_F("requireThatAdapterHandlesMultipleDocuments", Fixture)
@@ -433,11 +433,11 @@ TEST_F("requireThatAdapterHandlesMultipleDocuments", Fixture)
f.getMarkupFields());
{ // doc 0
GeneralResultPtr res = getResult(dsa, 0);
- EXPECT_EQUAL(1000u, res->GetEntry("a")->_intval);
+ EXPECT_EQUAL(1000u, res->GetPresentEntry("a")->_intval);
}
{ // doc 1
GeneralResultPtr res = getResult(dsa, 1);
- EXPECT_EQUAL(2000u, res->GetEntry("a")->_intval);
+ EXPECT_EQUAL(2000u, res->GetPresentEntry("a")->_intval);
}
{ // doc 2
DocsumStoreValue docsum = dsa.getMappedDocsum(2);
@@ -445,7 +445,7 @@ TEST_F("requireThatAdapterHandlesMultipleDocuments", Fixture)
}
{ // doc 0 (again)
GeneralResultPtr res = getResult(dsa, 0);
- EXPECT_EQUAL(1000u, res->GetEntry("a")->_intval);
+ EXPECT_EQUAL(1000u, res->GetPresentEntry("a")->_intval);
}
EXPECT_EQUAL(0u, bc._str.lastSyncToken());
uint64_t flushToken = bc._str.initFlush(bc._serialNum - 1);
@@ -466,8 +466,8 @@ TEST_F("requireThatAdapterHandlesDocumentIdField", Fixture)
bc.createFieldCacheRepo(f.getResultConfig())->getFieldCache("class4"),
f.getMarkupFields());
GeneralResultPtr res = getResult(dsa, 0);
- EXPECT_EQUAL("id:ns:searchdocument::0", std::string(res->GetEntry("documentid")->_stringval,
- res->GetEntry("documentid")->_stringlen));
+ EXPECT_EQUAL("id:ns:searchdocument::0", std::string(res->GetPresentEntry("documentid")->_stringval,
+ res->GetPresentEntry("documentid")->_stringlen));
}
GlobalId gid1 = DocumentId("id:ns:searchdocument::1").getGlobalId(); // lid 1
@@ -960,14 +960,14 @@ TEST_F("requireThatUrisAreUsed", Fixture)
GeneralResultPtr res = getResult(dsa, 1);
{
vespalib::Slime slime;
- decode(res->GetEntry("uriarray"), slime);
+ decode(res->GetPresentEntry("uriarray"), slime);
EXPECT_TRUE(slime.get().valid());
EXPECT_EQUAL("http://www.example.com:82/fluke?ab=2#8", asVstring(slime.get()[0]));
EXPECT_EQUAL("http://www.flickr.com:82/fluke?ab=2#9", asVstring(slime.get()[1]));
}
{
vespalib::Slime slime;
- decode(res->GetEntry("uriwset"), slime);
+ decode(res->GetPresentEntry("uriwset"), slime);
EXPECT_TRUE(slime.get().valid());
EXPECT_EQUAL(4L, slime.get()[0]["weight"].asLong());
EXPECT_EQUAL(7L, slime.get()[1]["weight"].asLong());
@@ -1012,7 +1012,7 @@ TEST("requireThatPositionsAreUsed")
req.hits.push_back(DocsumRequest::Hit(gid1));
DocsumReply::UP rep = dc._ddb->getDocsums(req);
EXPECT_TRUE(assertSlime("{docsums:["
- "{docsum:{sp2:'1047758'"
+ "{docsum:{sp2:1047758"
",sp2x:{x:1002, y:1003, latlong:'N0.001003;E0.001002'}"
",ap2:[1047806,1048322]"
",ap2x:[{x:1006, y:1007, latlong:'N0.001007;E0.001006'},"
@@ -1089,14 +1089,14 @@ TEST_F("requireThatRawFieldsWorks", Fixture)
GeneralResultPtr res = getResult(dsa, 1);
{
vespalib::Slime slime;
- decode(res->GetEntry("araw"), slime);
+ decode(res->GetPresentEntry("araw"), slime);
EXPECT_TRUE(slime.get().valid());
EXPECT_EQUAL(vespalib::Base64::encode(raw1a0), b64encode(slime.get()[0]));
EXPECT_EQUAL(vespalib::Base64::encode(raw1a1), b64encode(slime.get()[1]));
}
{
vespalib::Slime slime;
- decode(res->GetEntry("wraw"), slime);
+ decode(res->GetPresentEntry("wraw"), slime);
EXPECT_TRUE(slime.get().valid());
EXPECT_EQUAL(46L, slime.get()[0]["weight"].asLong());
EXPECT_EQUAL(45L, slime.get()[1]["weight"].asLong());
diff --git a/searchcore/src/tests/proton/docsummary/docsummary_test.sh b/searchcore/src/tests/proton/docsummary/docsummary_test.sh
index 3722c967455..4f05e6ee6f3 100755
--- a/searchcore/src/tests/proton/docsummary/docsummary_test.sh
+++ b/searchcore/src/tests/proton/docsummary/docsummary_test.sh
@@ -14,4 +14,3 @@ rm -rf summary
rm -rf indexingdocument
rm -rf searchdocument
rm -rf *.dat
-$VALGRIND ./searchcore_summaryfieldconverter_test_app
diff --git a/searchcore/src/tests/proton/docsummary/summary.cfg b/searchcore/src/tests/proton/docsummary/summary.cfg
index 33fd90f4c82..db18babb03b 100644
--- a/searchcore/src/tests/proton/docsummary/summary.cfg
+++ b/searchcore/src/tests/proton/docsummary/summary.cfg
@@ -38,7 +38,7 @@ classes[0].fields[15].type "jsonstring"
classes[0].fields[16].name "sp1"
classes[0].fields[16].type "string"
classes[0].fields[17].name "sp2"
-classes[0].fields[17].type "string"
+classes[0].fields[17].type "int64"
classes[0].fields[18].name "ap1"
classes[0].fields[18].type "jsonstring"
classes[0].fields[19].name "ap2"
@@ -95,7 +95,7 @@ classes[5].id 5
classes[5].name "class5"
classes[5].fields[6]
classes[5].fields[0].name "sp2"
-classes[5].fields[0].type "string"
+classes[5].fields[0].type "int64"
classes[5].fields[1].name "sp2x"
classes[5].fields[1].type "xmlstring"
classes[5].fields[2].name "ap2"
diff --git a/searchcore/src/tests/proton/matching/request_context/request_context_test.cpp b/searchcore/src/tests/proton/matching/request_context/request_context_test.cpp
index 191c1718f61..3e74ed152b1 100644
--- a/searchcore/src/tests/proton/matching/request_context/request_context_test.cpp
+++ b/searchcore/src/tests/proton/matching/request_context/request_context_test.cpp
@@ -5,7 +5,8 @@
#include <vespa/eval/eval/tensor_spec.h>
#include <vespa/searchcore/proton/matching/requestcontext.h>
#include <vespa/searchlib/attribute/attribute_blueprint_params.h>
-#include <vespa/searchlib/fef/properties.h>
+#include <vespa/searchlib/fef/test/indexenvironment.h>
+#include <vespa/searchlib/fef/test/queryenvironment.h>
#include <vespa/vespalib/util/testclock.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/objects/nbostream.h>
@@ -14,11 +15,14 @@ using search::attribute::AttributeBlueprintParams;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeFunctor;
using search::attribute::IAttributeVector;
-using search::fef::Properties;
+using search::fef::test::IndexEnvironment;
+using search::fef::test::QueryEnvironment;
using vespalib::eval::SimpleValue;
using vespalib::eval::TensorSpec;
using vespalib::eval::Value;
+
using namespace proton;
+using namespace search::fef::indexproperties;
class MyAttributeContext : public search::attribute::IAttributeContext {
public:
@@ -33,14 +37,15 @@ private:
vespalib::TestClock _clock;
vespalib::Doom _doom;
MyAttributeContext _attr_ctx;
- Properties _props;
+ IndexEnvironment _index_env;
+ QueryEnvironment _query_env;
RequestContext _request_ctx;
Value::UP _query_tensor;
void insert_tensor_in_properties(const vespalib::string& tensor_name, const Value& tensor_value) {
vespalib::nbostream stream;
encode_value(tensor_value, stream);
- _props.add(tensor_name, vespalib::stringref(stream.data(), stream.size()));
+ _query_env.getProperties().add(tensor_name, vespalib::stringref(stream.data(), stream.size()));
}
public:
@@ -48,18 +53,20 @@ public:
: _clock(),
_doom(_clock.clock(), vespalib::steady_time(), vespalib::steady_time(), false),
_attr_ctx(),
- _props(),
- _request_ctx(_doom, _attr_ctx, _props, AttributeBlueprintParams()),
+ _index_env(),
+ _query_env(&_index_env),
+ _request_ctx(_doom, _attr_ctx, _query_env, _query_env.getObjectStore(), AttributeBlueprintParams()),
_query_tensor(SimpleValue::from_spec(TensorSpec("tensor(x[2])")
.add({{"x", 0}}, 3).add({{"x", 1}}, 5)))
{
+ type::QueryFeature::set(_index_env.getProperties(), "my_tensor", "tensor(x[2])");
insert_tensor_in_properties("my_tensor", *_query_tensor);
- _props.add("my_string", "foo bar");
+ _query_env.getProperties().add("my_string", "foo bar");
}
TensorSpec expected_query_tensor() const {
return spec_from_value(*_query_tensor);
}
- Value::UP get_query_tensor(const vespalib::string& tensor_name) const {
+ const Value* get_query_tensor(const vespalib::string& tensor_name) const {
return _request_ctx.get_query_tensor(tensor_name);
}
};
diff --git a/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.cpp b/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.cpp
index 3ff10b19164..23118aab630 100644
--- a/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.cpp
+++ b/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.cpp
@@ -27,7 +27,6 @@ BmClusterParams::BmClusterParams()
_rpc_events_before_wakeup(1), // Same default as in stor-communicationmanager.def
_rpc_network_threads(1), // Same default as previous in stor-communicationmanager.def
_rpc_targets_per_node(1), // Same default as in stor-communicationmanager.def
- _skip_communicationmanager_thread(false), // Same default as in stor-communicationmanager.def
_skip_get_spi_bucket_info(false),
_use_async_message_handling_on_schedule(false),
_use_document_api(false),
diff --git a/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.h b/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.h
index d365a28b0b6..06734e3ee86 100644
--- a/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.h
+++ b/searchcore/src/vespa/searchcore/bmcluster/bm_cluster_params.h
@@ -34,7 +34,6 @@ class BmClusterParams
uint32_t _rpc_events_before_wakeup;
uint32_t _rpc_network_threads;
uint32_t _rpc_targets_per_node;
- bool _skip_communicationmanager_thread;
bool _skip_get_spi_bucket_info;
bool _use_async_message_handling_on_schedule;
bool _use_document_api;
@@ -64,7 +63,6 @@ public:
uint32_t get_rpc_events_before_wakeup() const { return _rpc_events_before_wakeup; }
uint32_t get_rpc_network_threads() const { return _rpc_network_threads; }
uint32_t get_rpc_targets_per_node() const { return _rpc_targets_per_node; }
- bool get_skip_communicationmanager_thread() const { return _skip_communicationmanager_thread; }
bool get_skip_get_spi_bucket_info() const { return _skip_get_spi_bucket_info; }
bool get_use_async_message_handling_on_schedule() const { return _use_async_message_handling_on_schedule; }
bool get_use_document_api() const { return _use_document_api; }
@@ -93,7 +91,6 @@ public:
void set_rpc_events_before_wakeup(uint32_t value) { _rpc_events_before_wakeup = value; }
void set_rpc_network_threads(uint32_t threads_in) { _rpc_network_threads = threads_in; }
void set_rpc_targets_per_node(uint32_t targets_in) { _rpc_targets_per_node = targets_in; }
- void set_skip_communicationmanager_thread(bool value) { _skip_communicationmanager_thread = value; }
void set_skip_get_spi_bucket_info(bool value) { _skip_get_spi_bucket_info = value; }
void set_use_async_message_handling_on_schedule(bool value) { _use_async_message_handling_on_schedule = value; }
void set_use_document_api(bool value) { _use_document_api = value; }
diff --git a/searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp b/searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
index ff4fed44d22..2622de6320e 100644
--- a/searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
+++ b/searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
@@ -10,7 +10,6 @@
#include <vespa/messagebus/ireplyhandler.h>
#include <vespa/documentapi/messagebus/documentprotocol.h>
#include <vespa/documentapi/messagebus/messages/documentmessage.h>
-#include <vespa/storageapi/mbusprot/storageprotocol.h>
#include <vespa/storageapi/mbusprot/storagereply.h>
#include <vespa/vespalib/stllike/asciistream.h>
@@ -21,7 +20,6 @@ using documentapi::DocumentProtocol;
using mbus::RPCMessageBus;
using mbus::Reply;
using mbus::SourceSession;
-using storage::mbusprot::StorageProtocol;
using storage::mbusprot::StorageReply;
namespace search::bmcluster {
@@ -97,15 +95,7 @@ BmMessageBus::ReplyHandler::handleReply(std::unique_ptr<Reply> reply)
failed = true; // empty reply or error
} else {
auto protocol = reply->getProtocol();
- if (protocol == DocumentProtocol::NAME) {
- } else if (protocol == StorageProtocol::NAME) {
- auto sreply = dynamic_cast<storage::mbusprot::StorageReply *>(reply.get());
- if (sreply != nullptr) {
- check_error(*sreply->getReply());
- } else {
- failed = true; // unexpected message type
- }
- } else {
+ if (protocol != DocumentProtocol::NAME) {
failed = true; // unexpected protocol
}
}
@@ -139,7 +129,6 @@ BmMessageBus::BmMessageBus(const config::ConfigUri& config_uri,
mbus::RPCNetworkParams params(config_uri);
mbus::ProtocolSet protocol_set;
protocol_set.add(std::make_shared<DocumentProtocol>(document_type_repo));
- protocol_set.add(std::make_shared<StorageProtocol>(document_type_repo));
params.setIdentity(mbus::Identity("vespa-bm-client"));
_message_bus = std::make_unique<mbus::RPCMessageBus>(
protocol_set,
diff --git a/searchcore/src/vespa/searchcore/bmcluster/bm_node.cpp b/searchcore/src/vespa/searchcore/bmcluster/bm_node.cpp
index d1910087371..b18ea6dd89d 100644
--- a/searchcore/src/vespa/searchcore/bmcluster/bm_node.cpp
+++ b/searchcore/src/vespa/searchcore/bmcluster/bm_node.cpp
@@ -333,7 +333,6 @@ struct StorageConfigSet
}
stor_communicationmanager.mbusport = mbus_port;
stor_communicationmanager.rpcport = rpc_port;
- stor_communicationmanager.skipThread = params.get_skip_communicationmanager_thread();
stor_status.httpport = status_port;
make_bucketspaces_config(bucketspaces);
diff --git a/searchcore/src/vespa/searchcore/bmcluster/spi_bm_feed_handler.cpp b/searchcore/src/vespa/searchcore/bmcluster/spi_bm_feed_handler.cpp
index 69013e8d7c5..dcdba3b0715 100644
--- a/searchcore/src/vespa/searchcore/bmcluster/spi_bm_feed_handler.cpp
+++ b/searchcore/src/vespa/searchcore/bmcluster/spi_bm_feed_handler.cpp
@@ -134,8 +134,8 @@ SpiBmFeedHandler::remove(const document::Bucket& bucket, const DocumentId& docum
auto provider = get_provider(bucket);
if (provider) {
Bucket spi_bucket(bucket);
- std::vector<storage::spi::PersistenceProvider::TimeStampAndDocumentId> ids;
- ids.emplace_back(Timestamp(timestamp), document_id);
+ std::vector<storage::spi::IdAndTimestamp> ids;
+ ids.emplace_back(document_id, Timestamp(timestamp));
provider->removeAsync(spi_bucket, std::move(ids), std::make_unique<MyOperationComplete>(provider, _errors, spi_bucket, tracker));
} else {
++_errors;
diff --git a/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.cpp b/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.cpp
index 37d04f6bcb9..ecdc679e4bc 100644
--- a/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.cpp
+++ b/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.cpp
@@ -164,13 +164,15 @@ BucketDB::isActiveBucket(const BucketId &bucketId) const
return (itr != _map.end()) && itr->second.isActive();
}
-void
-BucketDB::getBuckets(BucketId::List &buckets) const
+document::BucketId::List
+BucketDB::getBuckets() const
{
+ BucketId::List buckets;
buckets.reserve(_map.size());
for (const auto & entry : _map) {
buckets.push_back(entry.first);
}
+ return buckets;
}
bool
@@ -261,8 +263,8 @@ BucketDB::populateActiveBuckets(BucketId::List buckets)
BucketState activeState;
activeState.setActive(true);
for (const BucketId & bucketId : toAdd) {
- InsertResult ins(_map.emplace(bucketId, activeState));
- assert(ins.second);
+ auto [itr, inserted] = _map.emplace(bucketId, activeState);
+ assert(inserted);
}
return fixupBuckets;
}
diff --git a/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.h b/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.h
index 6fe46d97f46..da475f2969a 100644
--- a/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.h
+++ b/searchcore/src/vespa/searchcore/proton/bucketdb/bucketdb.h
@@ -20,9 +20,7 @@ public:
typedef storage::spi::BucketChecksum BucketChecksum;
typedef bucketdb::BucketState BucketState;
typedef std::map<BucketId, BucketState> Map;
- typedef Map::iterator MapIterator;
typedef Map::const_iterator ConstMapIterator;
- typedef std::pair<MapIterator, bool> InsertResult;
private:
Map _map;
@@ -58,7 +56,7 @@ public:
storage::spi::BucketInfo cachedGetBucketInfo(const BucketId &bucketId) const;
BucketState cachedGet(const BucketId &bucketId) const;
bool hasBucket(const BucketId &bucketId) const;
- void getBuckets(BucketId::List & buckets) const;
+ BucketId::List getBuckets() const;
bool empty() const;
void setBucketState(const BucketId &bucketId, bool active);
void createBucket(const BucketId &bucketId);
@@ -69,7 +67,6 @@ public:
ConstMapIterator begin() const { return _map.begin(); }
ConstMapIterator end() const { return _map.end(); }
ConstMapIterator lowerBound(const BucketId &bucket) const { return _map.lower_bound(bucket); }
- ConstMapIterator upperBound(const BucketId &bucket) const { return _map.upper_bound(bucket); }
size_t size() const { return _map.size(); }
bool isActiveBucket(const BucketId &bucketId) const;
BucketState *getBucketStatePtr(const BucketId &bucket);
diff --git a/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp b/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp
index 3550b38383a..ee5be6abdcf 100644
--- a/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp
+++ b/searchcore/src/vespa/searchcore/proton/docsummary/documentstoreadapter.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "documentstoreadapter.h"
+#include <vespa/searchsummary/docsummary/docsum_store_document.h>
#include <vespa/searchsummary/docsummary/summaryfieldconverter.h>
#include <vespa/document/fieldvalue/stringfieldvalue.h>
#include <vespa/eval/eval/value_codec.h>
@@ -101,6 +102,10 @@ void
DocumentStoreAdapter::convertFromSearchDoc(Document &doc, uint32_t docId)
{
for (size_t i = 0; i < _resultClass->GetNumEntries(); ++i) {
+ if (i != _resultPacker.get_entry_idx()) {
+ // Entry is not present in docsum blob
+ continue;
+ }
const ResConfigEntry * entry = _resultClass->GetEntry(i);
const vespalib::string fieldName(entry->_bindname);
bool markup = _markupFields.find(fieldName) != _markupFields.end();
@@ -179,7 +184,7 @@ DocumentStoreAdapter::getMappedDocsum(uint32_t docId)
LOG(warning, "Error while getting the docsum blob for docId %u. Returning empty docsum", docId);
return DocsumStoreValue();
}
- return DocsumStoreValue(buf, buflen, std::move(document));
+ return DocsumStoreValue(buf, buflen, std::make_unique<DocsumStoreDocument>(std::move(document)));
}
} // namespace proton
diff --git a/searchcore/src/vespa/searchcore/proton/docsummary/summarymanager.cpp b/searchcore/src/vespa/searchcore/proton/docsummary/summarymanager.cpp
index a04f5bfa651..4e1fdff6d13 100644
--- a/searchcore/src/vespa/searchcore/proton/docsummary/summarymanager.cpp
+++ b/searchcore/src/vespa/searchcore/proton/docsummary/summarymanager.cpp
@@ -93,7 +93,22 @@ SummarySetup(const vespalib::string & baseDir, const DocTypeName & docTypeName,
_repo(repo),
_markupFields()
{
- auto resultConfig = std::make_unique<ResultConfig>();
+ DocsumBlobEntryFilter docsum_blob_entry_filter;
+ docsum_blob_entry_filter.add_skip(RES_INT);
+ docsum_blob_entry_filter.add_skip(RES_SHORT);
+ docsum_blob_entry_filter.add_skip(RES_BOOL);
+ docsum_blob_entry_filter.add_skip(RES_BYTE);
+ docsum_blob_entry_filter.add_skip(RES_FLOAT);
+ docsum_blob_entry_filter.add_skip(RES_DOUBLE);
+ docsum_blob_entry_filter.add_skip(RES_INT64);
+ docsum_blob_entry_filter.add_skip(RES_STRING);
+ docsum_blob_entry_filter.add_skip(RES_DATA);
+ docsum_blob_entry_filter.add_skip(RES_LONG_STRING);
+ docsum_blob_entry_filter.add_skip(RES_LONG_DATA);
+ docsum_blob_entry_filter.add_skip(RES_JSONSTRING);
+ docsum_blob_entry_filter.add_skip(RES_TENSOR);
+ docsum_blob_entry_filter.add_skip(RES_FEATUREDATA);
+ auto resultConfig = std::make_unique<ResultConfig>(docsum_blob_entry_filter);
if (!resultConfig->ReadConfig(summaryCfg, make_string("SummaryManager(%s)", baseDir.c_str()).c_str())) {
std::ostringstream oss;
::config::OstreamConfigWriter writer(oss);
@@ -108,7 +123,7 @@ SummarySetup(const vespalib::string & baseDir, const DocTypeName & docTypeName,
DynamicDocsumConfig dynCfg(this, _docsumWriter.get());
dynCfg.configure(summarymapCfg);
for (const auto & o : summarymapCfg.override) {
- if (o.command == "dynamicteaser" || o.command == "textextractor") {
+ if (o.command == "dynamicteaser") {
vespalib::string markupField = o.arguments;
if (markupField.empty())
continue;
diff --git a/searchcore/src/vespa/searchcore/proton/matching/extract_features.cpp b/searchcore/src/vespa/searchcore/proton/matching/extract_features.cpp
index ca09a3e79f1..6115d642b4a 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/extract_features.cpp
+++ b/searchcore/src/vespa/searchcore/proton/matching/extract_features.cpp
@@ -32,8 +32,9 @@ auto extract_names(const FeatureResolver &resolver, const StringStringMap &renam
result.reserve(resolver.num_features());
for (size_t i = 0; i < resolver.num_features(); ++i) {
vespalib::string name = resolver.name_of(i);
- if (renames.contains(name)) {
- name = renames[name];
+ auto iter = renames.find(name);
+ if (iter != renames.end()) {
+ name = iter->second;
}
result.emplace_back(name);
}
diff --git a/searchcore/src/vespa/searchcore/proton/matching/match_tools.cpp b/searchcore/src/vespa/searchcore/proton/matching/match_tools.cpp
index 8379f8b1a3a..e0449236af0 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/match_tools.cpp
+++ b/searchcore/src/vespa/searchcore/proton/matching/match_tools.cpp
@@ -172,10 +172,10 @@ MatchToolsFactory(QueryLimiter & queryLimiter,
bool is_search)
: _queryLimiter(queryLimiter),
_global_filter_params(extract_global_filter_params(rankSetup, rankProperties, metaStore.getNumActiveLids(), searchContext.getDocIdLimit())),
- _requestContext(doom, attributeContext, rankProperties, _global_filter_params),
_query(),
_match_limiter(),
_queryEnv(indexEnv, attributeContext, rankProperties, searchContext.getIndexes()),
+ _requestContext(doom, attributeContext, _queryEnv, _queryEnv.getObjectStore(), _global_filter_params),
_mdl(),
_rankSetup(rankSetup),
_featureOverrides(featureOverrides),
diff --git a/searchcore/src/vespa/searchcore/proton/matching/match_tools.h b/searchcore/src/vespa/searchcore/proton/matching/match_tools.h
index d01ea05f3f7..11e943957ef 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/match_tools.h
+++ b/searchcore/src/vespa/searchcore/proton/matching/match_tools.h
@@ -94,10 +94,10 @@ private:
using IAttributeFunctor = search::attribute::IAttributeFunctor;
QueryLimiter & _queryLimiter;
search::attribute::AttributeBlueprintParams _global_filter_params;
- RequestContext _requestContext;
Query _query;
MaybeMatchPhaseLimiter::UP _match_limiter;
QueryEnvironment _queryEnv;
+ RequestContext _requestContext;
search::fef::MatchDataLayout _mdl;
const search::fef::RankSetup & _rankSetup;
const search::fef::Properties & _featureOverrides;
diff --git a/searchcore/src/vespa/searchcore/proton/matching/querynodes.h b/searchcore/src/vespa/searchcore/proton/matching/querynodes.h
index d8060832d5d..bbe58338b12 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/querynodes.h
+++ b/searchcore/src/vespa/searchcore/proton/matching/querynodes.h
@@ -23,7 +23,7 @@ class ViewResolver;
class ProtonTermData : public search::fef::ITermData
{
public:
- typedef search::queryeval::FieldSpec FieldSpec;
+ using FieldSpec = search::queryeval::FieldSpec;
struct FieldEntry final : search::fef::SimpleTermFieldData {
vespalib::string field_name;
@@ -67,6 +67,7 @@ public:
void setDocumentFrequency(uint32_t estHits, uint32_t numDocs);
// ITermData interface
+ std::optional<vespalib::string> query_tensor_name() const override { return std::nullopt; }
size_t numFields() const override final { return _fields.size(); }
const FieldEntry &field(size_t i) const override final { return _fields[i]; }
const FieldEntry *lookupField(uint32_t fieldId) const override final;
@@ -106,66 +107,72 @@ struct ProtonTerm final : public ProtonTermBase<Base> {
template <typename Base>
ProtonTerm<Base>::~ProtonTerm() = default;
-typedef search::query::SimpleAnd ProtonAnd;
-typedef search::query::SimpleAndNot ProtonAndNot;
-typedef search::query::SimpleNear ProtonNear;
-typedef search::query::SimpleONear ProtonONear;
-typedef search::query::SimpleOr ProtonOr;
-typedef search::query::SimpleRank ProtonRank;
-typedef search::query::SimpleWeakAnd ProtonWeakAnd;
-typedef search::query::SimpleSameElement ProtonSameElement;
-typedef search::query::SimpleTrue ProtonTrue;
-typedef search::query::SimpleFalse ProtonFalse;
+using ProtonAnd = search::query::SimpleAnd;
+using ProtonAndNot = search::query::SimpleAndNot;
+using ProtonNear = search::query::SimpleNear;
+using ProtonONear = search::query::SimpleONear;
+using ProtonOr = search::query::SimpleOr;
+using ProtonRank = search::query::SimpleRank;
+using ProtonWeakAnd = search::query::SimpleWeakAnd;
+using ProtonSameElement = search::query::SimpleSameElement;
+using ProtonTrue = search::query::SimpleTrue;
+using ProtonFalse = search::query::SimpleFalse;
struct ProtonEquiv final : public ProtonTermBase<search::query::Equiv> {
search::fef::MatchDataLayout children_mdl;
using ProtonTermBase::ProtonTermBase;
};
-typedef ProtonTerm<search::query::LocationTerm> ProtonLocationTerm;
-typedef ProtonTerm<search::query::NumberTerm> ProtonNumberTerm;
-typedef ProtonTerm<search::query::Phrase> ProtonPhrase;
-
-typedef ProtonTerm<search::query::PrefixTerm> ProtonPrefixTerm;
-typedef ProtonTerm<search::query::RangeTerm> ProtonRangeTerm;
-typedef ProtonTerm<search::query::StringTerm> ProtonStringTerm;
-typedef ProtonTerm<search::query::SubstringTerm> ProtonSubstringTerm;
-typedef ProtonTerm<search::query::SuffixTerm> ProtonSuffixTerm;
-typedef ProtonTerm<search::query::WeightedSetTerm> ProtonWeightedSetTerm;
-typedef ProtonTerm<search::query::DotProduct> ProtonDotProduct;
-typedef ProtonTerm<search::query::WandTerm> ProtonWandTerm;
-typedef ProtonTerm<search::query::PredicateQuery> ProtonPredicateQuery;
-typedef ProtonTerm<search::query::RegExpTerm> ProtonRegExpTerm;
-typedef ProtonTerm<search::query::NearestNeighborTerm> ProtonNearestNeighborTerm;
-typedef ProtonTerm<search::query::FuzzyTerm> ProtonFuzzyTerm;
+struct ProtonNearestNeighborTerm : public ProtonTermBase<search::query::NearestNeighborTerm> {
+ using ProtonTermBase::ProtonTermBase;
+ std::optional<vespalib::string> query_tensor_name() const override {
+ return ProtonTermBase::NearestNeighborTerm::get_query_tensor_name();
+ }
+};
+
+using ProtonLocationTerm = ProtonTerm<search::query::LocationTerm>;
+using ProtonNumberTerm = ProtonTerm<search::query::NumberTerm>;
+using ProtonPhrase = ProtonTerm<search::query::Phrase>;
+
+using ProtonPrefixTerm = ProtonTerm<search::query::PrefixTerm>;
+using ProtonRangeTerm = ProtonTerm<search::query::RangeTerm>;
+using ProtonStringTerm = ProtonTerm<search::query::StringTerm>;
+using ProtonSubstringTerm = ProtonTerm<search::query::SubstringTerm>;
+using ProtonSuffixTerm = ProtonTerm<search::query::SuffixTerm>;
+using ProtonWeightedSetTerm = ProtonTerm<search::query::WeightedSetTerm>;
+using ProtonDotProduct = ProtonTerm<search::query::DotProduct>;
+using ProtonWandTerm = ProtonTerm<search::query::WandTerm>;
+using ProtonPredicateQuery = ProtonTerm<search::query::PredicateQuery>;
+using ProtonRegExpTerm = ProtonTerm<search::query::RegExpTerm>;
+using ProtonFuzzyTerm = ProtonTerm<search::query::FuzzyTerm>;
struct ProtonNodeTypes {
- typedef ProtonAnd And;
- typedef ProtonAndNot AndNot;
- typedef ProtonEquiv Equiv;
- typedef ProtonLocationTerm LocationTerm;
- typedef ProtonNear Near;
- typedef ProtonNumberTerm NumberTerm;
- typedef ProtonONear ONear;
- typedef ProtonOr Or;
- typedef ProtonPhrase Phrase;
- typedef ProtonSameElement SameElement;
- typedef ProtonPrefixTerm PrefixTerm;
- typedef ProtonRangeTerm RangeTerm;
- typedef ProtonRank Rank;
- typedef ProtonStringTerm StringTerm;
- typedef ProtonSubstringTerm SubstringTerm;
- typedef ProtonSuffixTerm SuffixTerm;
- typedef ProtonWeakAnd WeakAnd;
- typedef ProtonWeightedSetTerm WeightedSetTerm;
- typedef ProtonDotProduct DotProduct;
- typedef ProtonWandTerm WandTerm;
- typedef ProtonPredicateQuery PredicateQuery;
- typedef ProtonRegExpTerm RegExpTerm;
- typedef ProtonNearestNeighborTerm NearestNeighborTerm;
- typedef ProtonTrue TrueQueryNode;
- typedef ProtonFalse FalseQueryNode;
- typedef ProtonFuzzyTerm FuzzyTerm;
+ using And = ProtonAnd;
+ using AndNot = ProtonAndNot;
+ using Equiv = ProtonEquiv;
+ using LocationTerm = ProtonLocationTerm;
+ using Near = ProtonNear;
+ using NumberTerm = ProtonNumberTerm;
+ using ONear = ProtonONear;
+ using Or = ProtonOr;
+ using Phrase = ProtonPhrase;
+ using SameElement = ProtonSameElement;
+ using PrefixTerm = ProtonPrefixTerm;
+ using RangeTerm = ProtonRangeTerm;
+ using Rank = ProtonRank;
+ using StringTerm = ProtonStringTerm;
+ using SubstringTerm = ProtonSubstringTerm;
+ using SuffixTerm = ProtonSuffixTerm;
+ using WeakAnd = ProtonWeakAnd;
+ using WeightedSetTerm = ProtonWeightedSetTerm;
+ using DotProduct = ProtonDotProduct;
+ using WandTerm = ProtonWandTerm;
+ using PredicateQuery = ProtonPredicateQuery;
+ using RegExpTerm = ProtonRegExpTerm;
+ using NearestNeighborTerm = ProtonNearestNeighborTerm;
+ using TrueQueryNode = ProtonTrue;
+ using FalseQueryNode = ProtonFalse;
+ using FuzzyTerm = ProtonFuzzyTerm;
};
}
diff --git a/searchcore/src/vespa/searchcore/proton/matching/requestcontext.cpp b/searchcore/src/vespa/searchcore/proton/matching/requestcontext.cpp
index 055ee586856..0d5edf44d05 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/requestcontext.cpp
+++ b/searchcore/src/vespa/searchcore/proton/matching/requestcontext.cpp
@@ -4,9 +4,9 @@
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/value_codec.h>
#include <vespa/searchlib/attribute/attributevector.h>
-#include <vespa/searchlib/fef/properties.h>
+#include <vespa/searchlib/fef/iqueryenvironment.h>
+#include <vespa/searchlib/fef/query_value.h>
#include <vespa/vespalib/objects/nbostream.h>
-#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/util/issue.h>
#include <vespa/log/log.h>
@@ -20,11 +20,13 @@ namespace proton {
using search::attribute::IAttributeVector;
RequestContext::RequestContext(const Doom & doom, IAttributeContext & attributeContext,
- const search::fef::Properties& rank_properties,
+ const search::fef::IQueryEnvironment& query_env,
+ search::fef::IObjectStore& shared_store,
const search::attribute::AttributeBlueprintParams& attribute_blueprint_params)
: _doom(doom),
_attributeContext(attributeContext),
- _rank_properties(rank_properties),
+ _query_env(query_env),
+ _shared_store(shared_store),
_attribute_blueprint_params(attribute_blueprint_params)
{
}
@@ -47,22 +49,18 @@ RequestContext::asyncForAttribute(const vespalib::string &name, std::unique_ptr<
_attributeContext.asyncForAttribute(name, std::move(func));
}
-vespalib::eval::Value::UP
+const vespalib::eval::Value*
RequestContext::get_query_tensor(const vespalib::string& tensor_name) const
{
- auto property = _rank_properties.lookup(tensor_name);
- if (property.found() && !property.get().empty()) {
- const vespalib::string& value = property.get();
- vespalib::nbostream stream(value.data(), value.size());
- try {
- return decode_value(stream, FastValueBuilderFactory::get());
- } catch (vespalib::eval::DecodeValueException& ex) {
- Issue::report("Query tensor '%s' could not be deserialized: %s",
- tensor_name.c_str(), ex.getMessage().c_str());
- return {};
- }
+ try {
+ auto value = search::fef::QueryValue::from_config(tensor_name, _query_env.getIndexEnvironment());
+ value.prepare_shared_state(_query_env, _shared_store);
+ return value.lookup_value(_shared_store);
+ } catch (const search::fef::InvalidValueTypeException& ex) {
+ Issue::report("Invalid type '%s' for query tensor '%s'",
+ ex.getMessage().c_str(), tensor_name.c_str());
+ return nullptr;
}
- return {};
}
const search::attribute::AttributeBlueprintParams&
diff --git a/searchcore/src/vespa/searchcore/proton/matching/requestcontext.h b/searchcore/src/vespa/searchcore/proton/matching/requestcontext.h
index b9e566c2429..9ab9acc6d71 100644
--- a/searchcore/src/vespa/searchcore/proton/matching/requestcontext.h
+++ b/searchcore/src/vespa/searchcore/proton/matching/requestcontext.h
@@ -8,7 +8,10 @@
#include <vespa/searchlib/attribute/attribute_blueprint_params.h>
#include <vespa/vespalib/util/doom.h>
-namespace search::fef { class Properties; }
+namespace search::fef {
+class IObjectStore;
+class IQueryEnvironment;
+}
namespace proton {
@@ -19,8 +22,10 @@ public:
using IAttributeContext = search::attribute::IAttributeContext;
using IAttributeFunctor = search::attribute::IAttributeFunctor;
using Doom = vespalib::Doom;
- RequestContext(const Doom & softDoom, IAttributeContext & attributeContext,
- const search::fef::Properties& rank_properties,
+ RequestContext(const Doom& softDoom,
+ IAttributeContext& attributeContext,
+ const search::fef::IQueryEnvironment& query_env,
+ search::fef::IObjectStore& shared_store,
const search::attribute::AttributeBlueprintParams& attribute_blueprint_params);
const Doom & getDoom() const override { return _doom; }
@@ -30,14 +35,15 @@ public:
const search::attribute::IAttributeVector *getAttributeStableEnum(const vespalib::string &name) const override;
- vespalib::eval::Value::UP get_query_tensor(const vespalib::string& tensor_name) const override;
+ const vespalib::eval::Value* get_query_tensor(const vespalib::string& tensor_name) const override;
const search::attribute::AttributeBlueprintParams& get_attribute_blueprint_params() const override;
private:
const Doom _doom;
IAttributeContext & _attributeContext;
- const search::fef::Properties & _rank_properties;
+ const search::fef::IQueryEnvironment& _query_env;
+ search::fef::IObjectStore& _shared_store;
search::attribute::AttributeBlueprintParams _attribute_blueprint_params;
};
diff --git a/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp b/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp
index 5a0bcb1cd41..81a7244ba1d 100644
--- a/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp
+++ b/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp
@@ -370,21 +370,21 @@ PersistenceEngine::putAsync(const Bucket &bucket, Timestamp ts, storage::spi::Do
}
void
-PersistenceEngine::removeAsync(const Bucket& b, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP onComplete)
+PersistenceEngine::removeAsync(const Bucket& b, std::vector<storage::spi::IdAndTimestamp> ids, OperationComplete::UP onComplete)
{
if (ids.size() == 1) {
- removeAsyncSingle(b, ids[0].first, ids[0].second, std::move(onComplete));
+ removeAsyncSingle(b, ids[0].timestamp, ids[0].id, std::move(onComplete));
} else {
removeAsyncMulti(b, std::move(ids), std::move(onComplete));
}
}
void
-PersistenceEngine::removeAsyncMulti(const Bucket& b, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP onComplete) {
+PersistenceEngine::removeAsyncMulti(const Bucket& b, std::vector<storage::spi::IdAndTimestamp> ids, OperationComplete::UP onComplete) {
ReadGuard rguard(_rwMutex);
//TODO Group per document type/handler and handle in one go.
- for (const TimeStampAndDocumentId & stampedId : ids) {
- const document::DocumentId & id = stampedId.second;
+ for (const auto & stampedId : ids) {
+ const document::DocumentId & id = stampedId.id;
if (!id.hasDocType()) {
return onComplete->onComplete(
std::make_unique<RemoveResult>(Result::ErrorType::PERMANENT_ERROR,
@@ -399,11 +399,11 @@ PersistenceEngine::removeAsyncMulti(const Bucket& b, std::vector<TimeStampAndDoc
}
}
auto transportContext = std::make_shared<AsyncRemoveTransportContext>(ids.size(), std::move(onComplete));
- for (const TimeStampAndDocumentId & stampedId : ids) {
- const document::DocumentId & id = stampedId.second;
+ for (const auto & stampedId : ids) {
+ const document::DocumentId & id = stampedId.id;
DocTypeName docType(id.getDocType());
IPersistenceHandler *handler = getHandler(rguard, b.getBucketSpace(), docType);
- handler->handleRemove(feedtoken::make(transportContext), b, stampedId.first, id);
+ handler->handleRemove(feedtoken::make(transportContext), b, stampedId.timestamp, id);
}
}
diff --git a/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.h b/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.h
index a8886e19def..c16cc6e6a83 100644
--- a/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.h
+++ b/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.h
@@ -89,7 +89,7 @@ private:
ClusterState::SP savedClusterState(BucketSpace bucketSpace) const;
std::shared_ptr<BucketExecutor> get_bucket_executor() noexcept { return _bucket_executor.lock(); }
void removeAsyncSingle(const Bucket&, Timestamp, const document::DocumentId &id, OperationComplete::UP);
- void removeAsyncMulti(const Bucket&, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP);
+ void removeAsyncMulti(const Bucket&, std::vector<storage::spi::IdAndTimestamp> ids, OperationComplete::UP);
public:
typedef std::unique_ptr<PersistenceEngine> UP;
@@ -107,7 +107,7 @@ public:
void setActiveStateAsync(const Bucket&, BucketInfo::ActiveState, OperationComplete::UP) override;
BucketInfoResult getBucketInfo(const Bucket&) const override;
void putAsync(const Bucket &, Timestamp, storage::spi::DocumentSP, OperationComplete::UP) override;
- void removeAsync(const Bucket&, std::vector<TimeStampAndDocumentId> ids, OperationComplete::UP) override;
+ void removeAsync(const Bucket&, std::vector<storage::spi::IdAndTimestamp> ids, OperationComplete::UP) override;
void updateAsync(const Bucket&, Timestamp, storage::spi::DocumentUpdateSP, OperationComplete::UP) override;
GetResult get(const Bucket&, const document::FieldSet&, const document::DocumentId&, Context&) const override;
CreateIteratorResult
diff --git a/searchcore/src/vespa/searchcore/proton/server/buckethandler.cpp b/searchcore/src/vespa/searchcore/proton/server/buckethandler.cpp
index d9201ce5b9e..080d182d1fa 100644
--- a/searchcore/src/vespa/searchcore/proton/server/buckethandler.cpp
+++ b/searchcore/src/vespa/searchcore/proton/server/buckethandler.cpp
@@ -90,8 +90,7 @@ BucketHandler::handleListBuckets(IBucketIdListResultHandler &resultHandler)
// Called by SPI thread.
// BucketDBOwner ensures synchronization between SPI thread and
// master write thread in document database.
- BucketIdListResult::List buckets;
- _ready->getBucketDB().takeGuard()->getBuckets(buckets);
+ BucketIdListResult::List buckets = _ready->getBucketDB().takeGuard()->getBuckets();
resultHandler.handle(BucketIdListResult(std::move(buckets)));
}
diff --git a/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp b/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp
index bf437dd7ee3..8807def03d4 100644
--- a/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp
+++ b/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp
@@ -233,7 +233,7 @@ WarmupIndexCollection::WarmupRequestContext::WarmupRequestContext(const vespalib
{}
WarmupIndexCollection::WarmupRequestContext::~WarmupRequestContext() = default;
-std::unique_ptr<vespalib::eval::Value>
+const vespalib::eval::Value*
WarmupIndexCollection::WarmupRequestContext::get_query_tensor(const vespalib::string&) const {
return {};
}
diff --git a/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.h b/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.h
index c2d70b4fd5c..2623de5b98f 100644
--- a/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.h
+++ b/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.h
@@ -82,7 +82,7 @@ private:
const vespalib::Doom & getDoom() const override { return _doom; }
const IAttributeVector *getAttribute(const vespalib::string &) const override { return nullptr; }
const IAttributeVector *getAttributeStableEnum(const vespalib::string &) const override { return nullptr; }
- std::unique_ptr<vespalib::eval::Value> get_query_tensor(const vespalib::string&) const override;
+ const vespalib::eval::Value* get_query_tensor(const vespalib::string&) const override;
const AttributeBlueprintParams& get_attribute_blueprint_params() const override { return _params; }
private:
const vespalib::Doom _doom;
diff --git a/searchlib/CMakeLists.txt b/searchlib/CMakeLists.txt
index 43a8da19191..f9b6271b47b 100644
--- a/searchlib/CMakeLists.txt
+++ b/searchlib/CMakeLists.txt
@@ -46,6 +46,7 @@ vespa_define_module(
src/vespa/searchlib/test
src/vespa/searchlib/test/diskindex
src/vespa/searchlib/test/fakedata
+ src/vespa/searchlib/test/features
src/vespa/searchlib/test/memoryindex
src/vespa/searchlib/transactionlog
src/vespa/searchlib/uca
diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/transform/Simplifier.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/transform/Simplifier.java
index b48303ae98b..c64f0eaa211 100644
--- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/transform/Simplifier.java
+++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/transform/Simplifier.java
@@ -32,8 +32,8 @@ public class Simplifier extends ExpressionTransformer<TransformContext> {
node = transformChildren((CompositeNode) node, context); // depth first
if (node instanceof IfNode)
node = transformIf((IfNode) node);
- if (node instanceof EmbracedNode && hasSingleUndividableChild((EmbracedNode)node))
- node = ((EmbracedNode)node).children().get(0);
+ if (node instanceof EmbracedNode e && hasSingleUndividableChild(e))
+ node = e.children().get(0);
if (node instanceof ArithmeticNode)
node = transformArithmetic((ArithmeticNode) node);
if (node instanceof NegativeNode)
diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/HyperLogLogPrecisionBenchmark.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/HyperLogLogPrecisionBenchmark.java
index cd283d31931..b55396151f4 100644
--- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/HyperLogLogPrecisionBenchmark.java
+++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/HyperLogLogPrecisionBenchmark.java
@@ -8,6 +8,7 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
+import java.util.stream.Collectors;
/**
* This benchmarks performs a series of unique counting tests to analyse the HyperLogLog accuracy.
diff --git a/searchlib/src/tests/attribute/tensorattribute/tensorattribute_test.cpp b/searchlib/src/tests/attribute/tensorattribute/tensorattribute_test.cpp
index 72b2f1e320a..b93398e16a1 100644
--- a/searchlib/src/tests/attribute/tensorattribute/tensorattribute_test.cpp
+++ b/searchlib/src/tests/attribute/tensorattribute/tensorattribute_test.cpp
@@ -46,8 +46,8 @@ using search::queryeval::NearestNeighborBlueprint;
using search::tensor::DefaultNearestNeighborIndexFactory;
using search::tensor::DenseTensorAttribute;
using search::tensor::DirectTensorAttribute;
+using search::tensor::DistanceCalculator;
using search::tensor::DocVectorAccess;
-using search::tensor::SerializedFastValueAttribute;
using search::tensor::HnswIndex;
using search::tensor::HnswNode;
using search::tensor::NearestNeighborIndex;
@@ -55,13 +55,14 @@ using search::tensor::NearestNeighborIndexFactory;
using search::tensor::NearestNeighborIndexLoader;
using search::tensor::NearestNeighborIndexSaver;
using search::tensor::PrepareResult;
+using search::tensor::SerializedFastValueAttribute;
using search::tensor::TensorAttribute;
using vespalib::datastore::CompactionStrategy;
-using vespalib::eval::TensorSpec;
using vespalib::eval::CellType;
-using vespalib::eval::ValueType;
-using vespalib::eval::Value;
using vespalib::eval::SimpleValue;
+using vespalib::eval::TensorSpec;
+using vespalib::eval::Value;
+using vespalib::eval::ValueType;
using DoubleVector = std::vector<double>;
using generation_t = vespalib::GenerationHandler::generation_t;
@@ -1044,8 +1045,13 @@ TEST_F("Nearest neighbor index type is added to attribute file header", DenseTen
template <typename ParentT>
class NearestNeighborBlueprintFixtureBase : public ParentT {
+private:
+ std::unique_ptr<Value> _query_tensor;
+
public:
- NearestNeighborBlueprintFixtureBase() {
+ NearestNeighborBlueprintFixtureBase()
+ : _query_tensor()
+ {
this->set_tensor(1, vec_2d(1, 1));
this->set_tensor(2, vec_2d(2, 2));
this->set_tensor(3, vec_2d(3, 3));
@@ -1058,16 +1064,17 @@ public:
this->set_tensor(10, vec_2d(0, 0));
}
- std::unique_ptr<Value> createDenseTensor(const TensorSpec &spec) {
- return SimpleValue::from_spec(spec);
+ const Value& create_query_tensor(const TensorSpec& spec) {
+ _query_tensor = SimpleValue::from_spec(spec);
+ return *_query_tensor;
}
std::unique_ptr<NearestNeighborBlueprint> make_blueprint(bool approximate = true, double global_filter_lower_limit = 0.05) {
search::queryeval::FieldSpec field("foo", 0, 0);
auto bp = std::make_unique<NearestNeighborBlueprint>(
field,
- this->as_dense_tensor(),
- createDenseTensor(vec_2d(17, 42)),
+ std::make_unique<DistanceCalculator>(this->as_dense_tensor(),
+ create_query_tensor(vec_2d(17, 42))),
3, approximate, 5,
100100.25,
global_filter_lower_limit, 1.0);
diff --git a/searchlib/src/tests/docstore/logdatastore/logdatastore_test.cpp b/searchlib/src/tests/docstore/logdatastore/logdatastore_test.cpp
index 418182f7bbf..9538db391df 100644
--- a/searchlib/src/tests/docstore/logdatastore/logdatastore_test.cpp
+++ b/searchlib/src/tests/docstore/logdatastore/logdatastore_test.cpp
@@ -19,6 +19,7 @@
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/memory.h>
+#include <filesystem>
#include <iomanip>
using document::BucketId;
@@ -292,8 +293,7 @@ TEST("testTruncatedIdxFile"){
}
const char * magic = "mumbo jumbo";
{
- int truncate_result = truncate("bug-7257706-truncated/1422358701368384000.idx", 3830);
- EXPECT_EQUAL(0, truncate_result);
+ std::filesystem::resize_file(std::filesystem::path("bug-7257706-truncated/1422358701368384000.idx"), 3830);
LogDataStore datastore(executor, "bug-7257706-truncated", config, GrowStrategy(),
TuneFileSummary(), fileHeaderContext, tlSyncer, nullptr);
EXPECT_EQUAL(331ul, datastore.lastSyncToken());
diff --git a/searchlib/src/tests/features/nns_closeness/CMakeLists.txt b/searchlib/src/tests/features/nns_closeness/CMakeLists.txt
index 9a8c2d7c99f..d5f9ece096b 100644
--- a/searchlib/src/tests/features/nns_closeness/CMakeLists.txt
+++ b/searchlib/src/tests/features/nns_closeness/CMakeLists.txt
@@ -5,5 +5,6 @@ vespa_add_executable(searchlib_nns_closeness_test_app TEST
nns_closeness_test.cpp
DEPENDS
searchlib
+ searchlib_test
)
vespa_add_test(NAME searchlib_nns_closeness_test_app COMMAND searchlib_nns_closeness_test_app)
diff --git a/searchlib/src/tests/features/nns_closeness/nns_closeness_test.cpp b/searchlib/src/tests/features/nns_closeness/nns_closeness_test.cpp
index c7667b2cecd..e67370d48f6 100644
--- a/searchlib/src/tests/features/nns_closeness/nns_closeness_test.cpp
+++ b/searchlib/src/tests/features/nns_closeness/nns_closeness_test.cpp
@@ -1,106 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include <vespa/vespalib/testkit/test_kit.h>
-#include <vespa/searchlib/features/setup.h>
-#include <vespa/searchlib/fef/test/indexenvironment.h>
-#include <vespa/searchlib/fef/test/indexenvironmentbuilder.h>
-#include <vespa/searchlib/fef/test/queryenvironment.h>
-#include <vespa/searchlib/fef/test/labels.h>
+#include <vespa/eval/eval/tensor_spec.h>
#include <vespa/searchlib/features/closenessfeature.h>
-#include <vespa/searchlib/fef/fef.h>
+#include <vespa/searchlib/features/setup.h>
#include <vespa/searchlib/fef/test/dummy_dependency_handler.h>
+#include <vespa/searchlib/fef/test/labels.h>
+#include <vespa/searchlib/test/features/distance_closeness_fixture.h>
#include <vespa/vespalib/stllike/asciistream.h>
+#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
using search::feature_t;
-using namespace search::fef;
-using namespace search::fef::test;
+using namespace search::features::test;
using namespace search::features;
-using CollectionType = FieldInfo::CollectionType;
-using DataType = FieldInfo::DataType;
+using namespace search::fef::test;
+using namespace search::fef;
+
+using vespalib::eval::TensorSpec;
const vespalib::string labelFeatureName("closeness(label,nns)");
const vespalib::string fieldFeatureName("closeness(bar)");
-struct BlueprintFactoryFixture {
- BlueprintFactory factory;
- BlueprintFactoryFixture() : factory()
- {
- setup_search_features(factory);
- }
-};
-
-struct IndexFixture {
- IndexEnvironment indexEnv;
- IndexFixture() : indexEnv()
- {
- IndexEnvironmentBuilder builder(indexEnv);
- builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, DataType::INT64, "foo");
- builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, DataType::TENSOR, "bar");
- }
-};
-
-struct FeatureDumpFixture : public IDumpFeatureVisitor {
- virtual void visitDumpFeature(const vespalib::string &) override {
- TEST_ERROR("no features should be dumped");
- }
- FeatureDumpFixture() : IDumpFeatureVisitor() {}
- ~FeatureDumpFixture() override;
-};
-
-FeatureDumpFixture::~FeatureDumpFixture() = default;
-
-struct RankFixture : BlueprintFactoryFixture, IndexFixture {
- QueryEnvironment queryEnv;
- RankSetup rankSetup;
- MatchDataLayout mdl;
- MatchData::UP match_data;
- RankProgram::UP rankProgram;
- std::vector<TermFieldHandle> fooHandles;
- std::vector<TermFieldHandle> barHandles;
- RankFixture(size_t fooCnt, size_t barCnt, const Labels &labels, const vespalib::string &featureName)
- : queryEnv(&indexEnv), rankSetup(factory, indexEnv),
- mdl(), match_data(), rankProgram(), fooHandles(), barHandles()
- {
- for (size_t i = 0; i < fooCnt; ++i) {
- uint32_t fieldId = indexEnv.getFieldByName("foo")->id();
- fooHandles.push_back(mdl.allocTermField(fieldId));
- SimpleTermData term;
- term.setUniqueId(i + 1);
- term.addField(fieldId).setHandle(fooHandles.back());
- queryEnv.getTerms().push_back(term);
- }
- for (size_t i = 0; i < barCnt; ++i) {
- uint32_t fieldId = indexEnv.getFieldByName("bar")->id();
- barHandles.push_back(mdl.allocTermField(fieldId));
- SimpleTermData term;
- term.setUniqueId(fooCnt + i + 1);
- term.addField(fieldId).setHandle(barHandles.back());
- queryEnv.getTerms().push_back(term);
- }
- labels.inject(queryEnv.getProperties());
- rankSetup.setFirstPhaseRank(featureName);
- rankSetup.setIgnoreDefaultRankFeatures(true);
- ASSERT_TRUE(rankSetup.compile());
- match_data = mdl.createMatchData();
- rankProgram = rankSetup.create_first_phase_program();
- rankProgram->setup(*match_data, queryEnv);
- }
- feature_t getScore(uint32_t docId) {
- return Utils::getScoreFeature(*rankProgram, docId);
- }
- void setScore(TermFieldHandle handle, uint32_t docId, feature_t score) {
- match_data->resolveTermField(handle)->setRawScore(docId, score);
- }
- void setFooScore(uint32_t i, uint32_t docId, feature_t distance) {
- ASSERT_LESS(i, fooHandles.size());
- setScore(fooHandles[i], docId, 1.0/(1.0+distance));
- }
- void setBarScore(uint32_t i, uint32_t docId, feature_t distance) {
- ASSERT_LESS(i, barHandles.size());
- setScore(barHandles[i], docId, 1.0/(1.0+distance));
- }
-};
+using RankFixture = DistanceClosenessFixture;
TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) {
Blueprint::SP bp = f.factory.createBlueprint("closeness");
@@ -108,11 +29,11 @@ TEST_F("require that blueprint can be created from factory", BlueprintFactoryFix
EXPECT_TRUE(dynamic_cast<ClosenessBlueprint*>(bp.get()) != 0);
}
-TEST_FFF("require that no features are dumped", ClosenessBlueprint, IndexFixture, FeatureDumpFixture) {
+TEST_FFF("require that no features are dumped", ClosenessBlueprint, IndexEnvironmentFixture, FeatureDumpFixture) {
f1.visitDumpFeatures(f2.indexEnv, f3);
}
-TEST_FF("require that setup can be done on random label", ClosenessBlueprint, IndexFixture) {
+TEST_FF("require that setup can be done on random label", ClosenessBlueprint, IndexEnvironmentFixture) {
DummyDependencyHandler deps(f1);
f1.setName(vespalib::make_string("%s(label,random_label)", f1.getBaseName().c_str()));
EXPECT_TRUE(static_cast<Blueprint&>(f1).setup(f2.indexEnv, std::vector<vespalib::string>{"label", "random_label"}));
@@ -158,4 +79,30 @@ TEST_FF("require that stale data is ignored", SingleLabel("nns", 2), RankFixture
EXPECT_EQUAL(0, f2.getScore(10));
}
+void
+expect_raw_score_calculated_on_the_fly(RankFixture& f)
+{
+ f.setBarScore(0, 8, 13.0);
+ f.set_attribute_tensor(9, TensorSpec::from_expr("tensor(x[2]):[5,11]"));
+ f.set_attribute_tensor(10, TensorSpec::from_expr("tensor(x[2]):[7,11]"));
+
+ // For docids 9 and 10 the raw score is calculated on the fly
+ // using a distance calculator over the attribute and query tensors.
+ EXPECT_EQUAL(1/(1+13.0), f.getScore(8));
+ EXPECT_EQUAL(1/(1+(5.0-3.0)), f.getScore(9));
+ EXPECT_EQUAL(1/(1+(7.0-3.0)), f.getScore(10));
+}
+
+TEST_FF("raw score is calculated on the fly (using field setup)",
+ NoLabel(), RankFixture(0, 1, f1, fieldFeatureName, "tensor(x[2]):[3,11]"))
+{
+ expect_raw_score_calculated_on_the_fly(f2);
+}
+
+TEST_FF("raw score is calculated on the fly (using label setup)",
+ SingleLabel("nns", 1), RankFixture(0, 1, f1, labelFeatureName, "tensor(x[2]):[3,11]"))
+{
+ expect_raw_score_calculated_on_the_fly(f2);
+}
+
TEST_MAIN() { TEST_RUN_ALL(); }
diff --git a/searchlib/src/tests/features/nns_distance/CMakeLists.txt b/searchlib/src/tests/features/nns_distance/CMakeLists.txt
index 8dbee37a194..bf4e533ea45 100644
--- a/searchlib/src/tests/features/nns_distance/CMakeLists.txt
+++ b/searchlib/src/tests/features/nns_distance/CMakeLists.txt
@@ -5,5 +5,6 @@ vespa_add_executable(searchlib_nns_distance_test_app TEST
nns_distance_test.cpp
DEPENDS
searchlib
+ searchlib_test
)
vespa_add_test(NAME searchlib_nns_distance_test_app COMMAND searchlib_nns_distance_test_app)
diff --git a/searchlib/src/tests/features/nns_distance/nns_distance_test.cpp b/searchlib/src/tests/features/nns_distance/nns_distance_test.cpp
index 1e81b5576c1..fff4c9f1c0e 100644
--- a/searchlib/src/tests/features/nns_distance/nns_distance_test.cpp
+++ b/searchlib/src/tests/features/nns_distance/nns_distance_test.cpp
@@ -1,106 +1,26 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include <vespa/vespalib/testkit/test_kit.h>
-#include <vespa/searchlib/features/setup.h>
-#include <vespa/searchlib/fef/test/indexenvironment.h>
-#include <vespa/searchlib/fef/test/indexenvironmentbuilder.h>
-#include <vespa/searchlib/fef/test/queryenvironment.h>
-#include <vespa/searchlib/fef/test/labels.h>
+#include <vespa/eval/eval/tensor_spec.h>
#include <vespa/searchlib/features/distancefeature.h>
-#include <vespa/searchlib/fef/fef.h>
#include <vespa/searchlib/fef/test/dummy_dependency_handler.h>
+#include <vespa/searchlib/fef/test/labels.h>
+#include <vespa/searchlib/test/features/distance_closeness_fixture.h>
#include <vespa/vespalib/stllike/asciistream.h>
+#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
using search::feature_t;
-using namespace search::fef;
-using namespace search::fef::test;
+using namespace search::features::test;
using namespace search::features;
-using CollectionType = FieldInfo::CollectionType;
-using DataType = FieldInfo::DataType;
+using namespace search::fef::test;
+using namespace search::fef;
-const vespalib::string labelFeatureName("distance(label,label)");
+using vespalib::eval::TensorSpec;
+
+const vespalib::string labelFeatureName("distance(label,nns)");
const vespalib::string fieldFeatureName("distance(bar)");
-struct BlueprintFactoryFixture {
- BlueprintFactory factory;
- BlueprintFactoryFixture() : factory()
- {
- setup_search_features(factory);
- }
-};
-
-struct IndexFixture {
- IndexEnvironment indexEnv;
- IndexFixture() : indexEnv()
- {
- IndexEnvironmentBuilder builder(indexEnv);
- builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, DataType::INT64, "foo");
- builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, DataType::TENSOR, "bar");
- }
-};
-
-struct FeatureDumpFixture : public IDumpFeatureVisitor {
- virtual void visitDumpFeature(const vespalib::string &) override {
- TEST_ERROR("no features should be dumped");
- }
- FeatureDumpFixture() : IDumpFeatureVisitor() {}
- ~FeatureDumpFixture() override;
-};
-
-FeatureDumpFixture::~FeatureDumpFixture() = default;
-
-struct RankFixture : BlueprintFactoryFixture, IndexFixture {
- QueryEnvironment queryEnv;
- RankSetup rankSetup;
- MatchDataLayout mdl;
- MatchData::UP match_data;
- RankProgram::UP rankProgram;
- std::vector<TermFieldHandle> fooHandles;
- std::vector<TermFieldHandle> barHandles;
- RankFixture(size_t fooCnt, size_t barCnt, const Labels &labels, const vespalib::string &featureName)
- : queryEnv(&indexEnv), rankSetup(factory, indexEnv),
- mdl(), match_data(), rankProgram(), fooHandles(), barHandles()
- {
- for (size_t i = 0; i < fooCnt; ++i) {
- uint32_t fieldId = indexEnv.getFieldByName("foo")->id();
- fooHandles.push_back(mdl.allocTermField(fieldId));
- SimpleTermData term;
- term.setUniqueId(i + 1);
- term.addField(fieldId).setHandle(fooHandles.back());
- queryEnv.getTerms().push_back(term);
- }
- for (size_t i = 0; i < barCnt; ++i) {
- uint32_t fieldId = indexEnv.getFieldByName("bar")->id();
- barHandles.push_back(mdl.allocTermField(fieldId));
- SimpleTermData term;
- term.setUniqueId(fooCnt + i + 1);
- term.addField(fieldId).setHandle(barHandles.back());
- queryEnv.getTerms().push_back(term);
- }
- labels.inject(queryEnv.getProperties());
- rankSetup.setFirstPhaseRank(featureName);
- rankSetup.setIgnoreDefaultRankFeatures(true);
- ASSERT_TRUE(rankSetup.compile());
- match_data = mdl.createMatchData();
- rankProgram = rankSetup.create_first_phase_program();
- rankProgram->setup(*match_data, queryEnv);
- }
- feature_t getScore(uint32_t docId) {
- return Utils::getScoreFeature(*rankProgram, docId);
- }
- void setScore(TermFieldHandle handle, uint32_t docId, feature_t score) {
- match_data->resolveTermField(handle)->setRawScore(docId, score);
- }
- void setFooScore(uint32_t i, uint32_t docId, feature_t distance) {
- ASSERT_LESS(i, fooHandles.size());
- setScore(fooHandles[i], docId, 1.0/(1.0+distance));
- }
- void setBarScore(uint32_t i, uint32_t docId, feature_t distance) {
- ASSERT_LESS(i, barHandles.size());
- setScore(barHandles[i], docId, 1.0/(1.0+distance));
- }
-};
+using RankFixture = DistanceClosenessFixture;
TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) {
Blueprint::SP bp = f.factory.createBlueprint("distance");
@@ -108,17 +28,17 @@ TEST_F("require that blueprint can be created from factory", BlueprintFactoryFix
EXPECT_TRUE(dynamic_cast<DistanceBlueprint*>(bp.get()) != 0);
}
-TEST_FFF("require that no features are dumped", DistanceBlueprint, IndexFixture, FeatureDumpFixture) {
+TEST_FFF("require that no features are dumped", DistanceBlueprint, IndexEnvironmentFixture, FeatureDumpFixture) {
f1.visitDumpFeatures(f2.indexEnv, f3);
}
-TEST_FF("require that setup can be done on random label", DistanceBlueprint, IndexFixture) {
+TEST_FF("require that setup can be done on random label", DistanceBlueprint, IndexEnvironmentFixture) {
DummyDependencyHandler deps(f1);
f1.setName(vespalib::make_string("%s(label,random_label)", f1.getBaseName().c_str()));
EXPECT_TRUE(static_cast<Blueprint&>(f1).setup(f2.indexEnv, std::vector<vespalib::string>{"label", "random_label"}));
}
-TEST_FF("require that setup with unknown field fails", DistanceBlueprint, IndexFixture) {
+TEST_FF("require that setup with unknown field fails", DistanceBlueprint, IndexEnvironmentFixture) {
DummyDependencyHandler deps(f1);
f1.setName(vespalib::make_string("%s(field,random_fieldname)", f1.getBaseName().c_str()));
EXPECT_FALSE(static_cast<Blueprint&>(f1).setup(f2.indexEnv, std::vector<vespalib::string>{"field", "random_fieldname"}));
@@ -132,7 +52,7 @@ TEST_FF("require that unrelated label gives max-double distance", SingleLabel("u
EXPECT_EQUAL(std::numeric_limits<feature_t>::max(), f2.getScore(10));
}
-TEST_FF("require that labeled item raw score can be obtained", SingleLabel("label", 1), RankFixture(2, 2, f1, labelFeatureName)) {
+TEST_FF("require that labeled item raw score can be obtained", SingleLabel("nns", 1), RankFixture(2, 2, f1, labelFeatureName)) {
f2.setFooScore(0, 10, 5.0);
EXPECT_EQUAL(5.0, f2.getScore(10));
}
@@ -142,7 +62,7 @@ TEST_FF("require that field raw score can be obtained", NoLabel(), RankFixture(2
EXPECT_EQUAL(5.0, f2.getScore(10));
}
-TEST_FF("require that other raw scores are ignored", SingleLabel("label", 2), RankFixture(2, 2, f1, labelFeatureName)) {
+TEST_FF("require that other raw scores are ignored", SingleLabel("nns", 2), RankFixture(2, 2, f1, labelFeatureName)) {
f2.setFooScore(0, 10, 1.0);
f2.setFooScore(1, 10, 2.0);
f2.setBarScore(0, 10, 5.0);
@@ -158,10 +78,36 @@ TEST_FF("require that the correct raw score is used", NoLabel(), RankFixture(2,
EXPECT_EQUAL(7.0, f2.getScore(10));
}
-TEST_FF("require that stale data is ignored", SingleLabel("label", 2), RankFixture(2, 2, f1, labelFeatureName)) {
+TEST_FF("require that stale data is ignored", SingleLabel("nns", 2), RankFixture(2, 2, f1, labelFeatureName)) {
f2.setFooScore(0, 10, 1.0);
f2.setFooScore(1, 5, 2.0);
EXPECT_EQUAL(std::numeric_limits<feature_t>::max(), f2.getScore(10));
}
+void
+expect_raw_score_calculated_on_the_fly(RankFixture& f)
+{
+ f.setBarScore(0, 8, 13.0);
+ f.set_attribute_tensor(9, TensorSpec::from_expr("tensor(x[2]):[5,11]"));
+ f.set_attribute_tensor(10, TensorSpec::from_expr("tensor(x[2]):[7,11]"));
+
+ // For docids 9 and 10 the raw score is calculated on the fly
+ // using a distance calculator over the attribute and query tensors.
+ EXPECT_EQUAL(13.0, f.getScore(8));
+ EXPECT_EQUAL((5-3), f.getScore(9));
+ EXPECT_EQUAL((7-3), f.getScore(10));
+}
+
+TEST_FF("raw score is calculated on the fly (using field setup)",
+ NoLabel(), RankFixture(0, 1, f1, fieldFeatureName, "tensor(x[2]):[3,11]"))
+{
+ expect_raw_score_calculated_on_the_fly(f2);
+}
+
+TEST_FF("raw score is calculated on the fly (using label setup)",
+ SingleLabel("nns", 1), RankFixture(0, 1, f1, labelFeatureName, "tensor(x[2]):[3,11]"))
+{
+ expect_raw_score_calculated_on_the_fly(f2);
+}
+
TEST_MAIN() { TEST_RUN_ALL(); }
diff --git a/searchlib/src/tests/queryeval/nearest_neighbor/nearest_neighbor_test.cpp b/searchlib/src/tests/queryeval/nearest_neighbor/nearest_neighbor_test.cpp
index 5f4db88bf4c..1e341eab707 100644
--- a/searchlib/src/tests/queryeval/nearest_neighbor/nearest_neighbor_test.cpp
+++ b/searchlib/src/tests/queryeval/nearest_neighbor/nearest_neighbor_test.cpp
@@ -10,6 +10,7 @@
#include <vespa/searchlib/queryeval/nns_index_iterator.h>
#include <vespa/searchlib/queryeval/simpleresult.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
+#include <vespa/searchlib/tensor/distance_calculator.h>
#include <vespa/searchlib/tensor/distance_function_factory.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/test/insertion_operators.h>
@@ -25,6 +26,7 @@ using search::BitVector;
using search::attribute::DistanceMetric;
using search::feature_t;
using search::tensor::DenseTensorAttribute;
+using search::tensor::DistanceCalculator;
using search::tensor::DistanceFunction;
using vespalib::eval::CellType;
using vespalib::eval::SimpleValue;
@@ -111,11 +113,11 @@ struct Fixture
setTensor(docId, *t);
}
- const DistanceFunction *dist_fun() const {
+ const DistanceFunction &dist_fun() const {
if (_cfg.tensorType().cell_type() == CellType::FLOAT) {
- return euclid_f.get();
+ return *euclid_f;
} else {
- return euclid_d.get();
+ return *euclid_d;
}
}
};
@@ -125,10 +127,11 @@ SimpleResult find_matches(Fixture &env, const Value &qtv, double threshold = std
auto md = MatchData::makeTestInstance(2, 2);
auto &tfmd = *(md->resolveTermField(0));
auto &attr = *(env._tensorAttr);
+ DistanceCalculator dist_calc(attr, qtv, env.dist_fun());
NearestNeighborDistanceHeap dh(2);
- dh.set_distance_threshold(env.dist_fun()->convert_threshold(threshold));
+ dh.set_distance_threshold(env.dist_fun().convert_threshold(threshold));
const BitVector *filter = env._global_filter.get();
- auto search = NearestNeighborIterator::create(strict, tfmd, qtv, attr, dh, filter, env.dist_fun());
+ auto search = NearestNeighborIterator::create(strict, tfmd, dist_calc, dh, filter);
if (strict) {
return SimpleResult().searchStrict(*search, attr.getNumDocs());
} else {
@@ -217,8 +220,9 @@ std::vector<feature_t> get_rawscores(Fixture &env, const Value &qtv) {
auto md = MatchData::makeTestInstance(2, 2);
auto &tfmd = *(md->resolveTermField(0));
auto &attr = *(env._tensorAttr);
+ DistanceCalculator dist_calc(attr, qtv, env.dist_fun());
NearestNeighborDistanceHeap dh(2);
- auto search = NearestNeighborIterator::create(strict, tfmd, qtv, attr, dh, nullptr, env.dist_fun());
+ auto search = NearestNeighborIterator::create(strict, tfmd, dist_calc, dh, nullptr);
uint32_t limit = attr.getNumDocs();
uint32_t docid = 1;
search->initRange(docid, limit);
@@ -268,7 +272,7 @@ TEST(NnsIndexIteratorTest, require_that_iterator_works_as_expected) {
std::vector<NnsIndexIterator::Hit> hits{{2,4.0}, {3,9.0}, {5,1.0}, {8,16.0}, {9,36.0}};
auto md = MatchData::makeTestInstance(2, 2);
auto &tfmd = *(md->resolveTermField(0));
- auto search = NnsIndexIterator::create(tfmd, hits, euclid_d.get());
+ auto search = NnsIndexIterator::create(tfmd, hits, *euclid_d);
uint32_t docid = 1;
search->initFullRange();
bool match = search->seek(docid);
diff --git a/searchlib/src/vespa/searchlib/attribute/attribute_blueprint_factory.cpp b/searchlib/src/vespa/searchlib/attribute/attribute_blueprint_factory.cpp
index 4ec6c4f6565..7af2186ed1e 100644
--- a/searchlib/src/vespa/searchlib/attribute/attribute_blueprint_factory.cpp
+++ b/searchlib/src/vespa/searchlib/attribute/attribute_blueprint_factory.cpp
@@ -599,13 +599,6 @@ bool check_valid_diversity_attr(const IAttributeVector *attr) {
return (attr->hasEnum() || attr->isIntegerType() || attr->isFloatingPointType());
}
-bool
-is_compatible_for_nearest_neighbor(const vespalib::eval::ValueType& lhs,
- const vespalib::eval::ValueType& rhs)
-{
- return (lhs.dimensions() == rhs.dimensions());
-}
-
//-----------------------------------------------------------------------------
@@ -760,40 +753,24 @@ public:
setResult(std::make_unique<queryeval::EmptyBlueprint>(_field));
}
void visit(query::NearestNeighborTerm &n) override {
- const ITensorAttribute *tensor_attr = _attr.asTensorAttribute();
- if (tensor_attr == nullptr) {
- return fail_nearest_neighbor_term(n, "Attribute is not a tensor");
- }
- const auto & ta_type = tensor_attr->getTensorType();
- if ((! ta_type.is_dense()) || (ta_type.dimensions().size() != 1)) {
- return fail_nearest_neighbor_term(n, make_string("Attribute tensor type (%s) is not a dense tensor of order 1",
- ta_type.to_spec().c_str()));
- }
- auto query_tensor = getRequestContext().get_query_tensor(n.get_query_tensor_name());
- if (query_tensor.get() == nullptr) {
+ const auto* query_tensor = getRequestContext().get_query_tensor(n.get_query_tensor_name());
+ if (query_tensor == nullptr) {
return fail_nearest_neighbor_term(n, "Query tensor was not found in request context");
}
- const auto & qt_type = query_tensor->type();
- if (! qt_type.is_dense()) {
- return fail_nearest_neighbor_term(n, make_string("Query tensor is not a dense tensor (type=%s)",
- qt_type.to_spec().c_str()));
- }
- if (!is_compatible_for_nearest_neighbor(ta_type, qt_type)) {
- return fail_nearest_neighbor_term(n, make_string("Attribute tensor type (%s) and query tensor type (%s) are not compatible",
- ta_type.to_spec().c_str(), qt_type.to_spec().c_str()));
- }
- if (tensor_attr->supports_extract_cells_ref() == false) {
- return fail_nearest_neighbor_term(n, make_string("Attribute does not support access to tensor data (type=%s)",
- ta_type.to_spec().c_str()));
+ try {
+ auto calc = tensor::DistanceCalculator::make_with_validation(_attr, *query_tensor);
+ setResult(std::make_unique<queryeval::NearestNeighborBlueprint>(_field,
+ std::move(calc),
+ n.get_target_num_hits(),
+ n.get_allow_approximate(),
+ n.get_explore_additional_hits(),
+ n.get_distance_threshold(),
+ getRequestContext().get_attribute_blueprint_params().global_filter_lower_limit,
+ getRequestContext().get_attribute_blueprint_params().global_filter_upper_limit));
+ } catch (const vespalib::IllegalArgumentException& ex) {
+ return fail_nearest_neighbor_term(n, ex.getMessage());
+
}
- setResult(std::make_unique<queryeval::NearestNeighborBlueprint>(_field, *tensor_attr,
- std::move(query_tensor),
- n.get_target_num_hits(),
- n.get_allow_approximate(),
- n.get_explore_additional_hits(),
- n.get_distance_threshold(),
- getRequestContext().get_attribute_blueprint_params().global_filter_lower_limit,
- getRequestContext().get_attribute_blueprint_params().global_filter_upper_limit));
}
void visit(query::FuzzyTerm &n) override { visitTerm(n); }
diff --git a/searchlib/src/vespa/searchlib/common/bitvector.h b/searchlib/src/vespa/searchlib/common/bitvector.h
index 912c4a47c39..d3671d61ccf 100644
--- a/searchlib/src/vespa/searchlib/common/bitvector.h
+++ b/searchlib/src/vespa/searchlib/common/bitvector.h
@@ -7,6 +7,7 @@
#include <vespa/vespalib/util/alloc.h>
#include <vespa/vespalib/util/atomic.h>
#include <vespa/fastos/types.h>
+#include <algorithm>
namespace vespalib {
class nbostream;
diff --git a/searchlib/src/vespa/searchlib/diskindex/diskindex.cpp b/searchlib/src/vespa/searchlib/diskindex/diskindex.cpp
index eb8054317dc..aa3859c7fbf 100644
--- a/searchlib/src/vespa/searchlib/diskindex/diskindex.cpp
+++ b/searchlib/src/vespa/searchlib/diskindex/diskindex.cpp
@@ -27,7 +27,7 @@ void swap(DiskIndex::LookupResult & a, DiskIndex::LookupResult & b)
a.swap(b);
}
-DiskIndex::LookupResult::LookupResult()
+DiskIndex::LookupResult::LookupResult() noexcept
: indexId(0u),
wordNum(0),
counts(),
diff --git a/searchlib/src/vespa/searchlib/diskindex/diskindex.h b/searchlib/src/vespa/searchlib/diskindex/diskindex.h
index 12be8979cc3..0869bccc307 100644
--- a/searchlib/src/vespa/searchlib/diskindex/diskindex.h
+++ b/searchlib/src/vespa/searchlib/diskindex/diskindex.h
@@ -31,7 +31,7 @@ public:
index::PostingListCounts counts;
uint64_t bitOffset;
typedef std::unique_ptr<LookupResult> UP;
- LookupResult();
+ LookupResult() noexcept;
bool valid() const { return counts._numDocs > 0; }
void swap(LookupResult & rhs) {
std::swap(indexId , rhs.indexId);
diff --git a/searchlib/src/vespa/searchlib/features/CMakeLists.txt b/searchlib/src/vespa/searchlib/features/CMakeLists.txt
index 88531a46cb1..8acf28f4a2f 100644
--- a/searchlib/src/vespa/searchlib/features/CMakeLists.txt
+++ b/searchlib/src/vespa/searchlib/features/CMakeLists.txt
@@ -12,7 +12,7 @@ vespa_add_library(searchlib_features OBJECT
debug_wait.cpp
dense_tensor_attribute_executor.cpp
direct_tensor_attribute_executor.cpp
- great_circle_distance_feature.cpp
+ distance_calculator_bundle.cpp
distancefeature.cpp
distancetopathfeature.cpp
documenttestutils.cpp
@@ -29,6 +29,7 @@ vespa_add_library(searchlib_features OBJECT
foreachfeature.cpp
freshnessfeature.cpp
global_sequence_feature.cpp
+ great_circle_distance_feature.cpp
internal_max_reduce_prod_join_feature.cpp
item_raw_score_feature.cpp
jarowinklerdistancefeature.cpp
diff --git a/searchlib/src/vespa/searchlib/features/closenessfeature.cpp b/searchlib/src/vespa/searchlib/features/closenessfeature.cpp
index 04fc2a263be..e44c94dbb2d 100644
--- a/searchlib/src/vespa/searchlib/features/closenessfeature.cpp
+++ b/searchlib/src/vespa/searchlib/features/closenessfeature.cpp
@@ -1,9 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "closenessfeature.h"
+#include "distance_calculator_bundle.h"
#include "utils.h"
#include <vespa/searchcommon/common/schema.h>
#include <vespa/searchlib/fef/properties.h>
+#include <vespa/searchlib/tensor/distance_calculator.h>
#include <vespa/vespalib/util/stash.h>
#include <vespa/log/log.h>
@@ -16,8 +18,8 @@ namespace search::features {
/** Implements the executor for converting NNS rawscore to a closeness feature. */
class ConvertRawScoreToCloseness : public fef::FeatureExecutor {
private:
- std::vector<fef::TermFieldHandle> _handles;
- const fef::MatchData *_md;
+ DistanceCalculatorBundle _bundle;
+ const fef::MatchData *_md;
void handle_bind_match_data(const fef::MatchData &md) override {
_md = &md;
}
@@ -28,32 +30,15 @@ public:
};
ConvertRawScoreToCloseness::ConvertRawScoreToCloseness(const fef::IQueryEnvironment &env, uint32_t fieldId)
- : _handles(),
+ : _bundle(env, fieldId, "closeness"),
_md(nullptr)
{
- _handles.reserve(env.getNumTerms());
- for (uint32_t i = 0; i < env.getNumTerms(); ++i) {
- search::fef::TermFieldHandle handle = util::getTermFieldHandle(env, i, fieldId);
- if (handle != search::fef::IllegalHandle) {
- _handles.push_back(handle);
- }
- }
}
ConvertRawScoreToCloseness::ConvertRawScoreToCloseness(const fef::IQueryEnvironment &env, const vespalib::string &label)
- : _handles(),
+ : _bundle(env, label, "closeness"),
_md(nullptr)
{
- const ITermData *term = util::getTermByLabel(env, label);
- if (term != nullptr) {
- // expect numFields() == 1
- for (uint32_t i = 0; i < term->numFields(); ++i) {
- TermFieldHandle handle = term->field(i).getHandle();
- if (handle != IllegalHandle) {
- _handles.push_back(handle);
- }
- }
- }
}
void
@@ -61,11 +46,14 @@ ConvertRawScoreToCloseness::execute(uint32_t docId)
{
feature_t max_closeness = 0.0;
assert(_md);
- for (auto handle : _handles) {
- const TermFieldMatchData *tfmd = _md->resolveTermField(handle);
+ for (const auto& elem : _bundle.elements()) {
+ const TermFieldMatchData *tfmd = _md->resolveTermField(elem.handle);
if (tfmd->getDocId() == docId) {
feature_t converted = tfmd->getRawScore();
max_closeness = std::max(max_closeness, converted);
+ } else if (elem.calc) {
+ feature_t converted = elem.calc->calc_raw_score(docId);
+ max_closeness = std::max(max_closeness, converted);
}
}
outputs().set_number(0, max_closeness);
@@ -201,15 +189,26 @@ ClosenessBlueprint::createInstance() const
return std::make_unique<ClosenessBlueprint>();
}
-FeatureExecutor &
-ClosenessBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const
+void
+ClosenessBlueprint::prepareSharedState(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const
{
+ if (_use_nns_tensor) {
+ DistanceCalculatorBundle::prepare_shared_state(env, store, _attr_id, "closeness");
+ }
if (_use_item_label) {
- return stash.create<ConvertRawScoreToCloseness>(env, _arg_string);
+ DistanceCalculatorBundle::prepare_shared_state(env, store, _arg_string, "closeness");
}
+}
+
+FeatureExecutor &
+ClosenessBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const
+{
if (_use_nns_tensor) {
return stash.create<ConvertRawScoreToCloseness>(env, _attr_id);
}
+ if (_use_item_label) {
+ return stash.create<ConvertRawScoreToCloseness>(env, _arg_string);
+ }
assert(_use_geo_pos);
return stash.create<ClosenessExecutor>(_maxDistance, _scaleDistance);
}
diff --git a/searchlib/src/vespa/searchlib/features/closenessfeature.h b/searchlib/src/vespa/searchlib/features/closenessfeature.h
index 799495eaff5..6e265e5dcb8 100644
--- a/searchlib/src/vespa/searchlib/features/closenessfeature.h
+++ b/searchlib/src/vespa/searchlib/features/closenessfeature.h
@@ -45,6 +45,7 @@ public:
return fef::ParameterDescriptions().desc().string().desc().string().string();
}
bool setup(const fef::IIndexEnvironment & env, const fef::ParameterList & params) override;
+ void prepareSharedState(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const override;
fef::FeatureExecutor &createExecutor(const fef::IQueryEnvironment &env, vespalib::Stash &stash) const override;
};
diff --git a/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.cpp b/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.cpp
new file mode 100644
index 00000000000..90386dffd51
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.cpp
@@ -0,0 +1,172 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "distance_calculator_bundle.h"
+#include "utils.h"
+#include <vespa/searchlib/fef/iqueryenvironment.h>
+#include <vespa/searchlib/fef/query_value.h>
+#include <vespa/searchlib/tensor/distance_calculator.h>
+#include <vespa/vespalib/util/exceptions.h>
+#include <vespa/vespalib/util/issue.h>
+
+using search::fef::ITermData;
+using search::fef::IllegalHandle;
+using search::fef::InvalidValueTypeException;
+using search::fef::QueryValue;
+using search::fef::TermFieldHandle;
+using search::tensor::DistanceCalculator;
+using vespalib::Issue;
+
+namespace search::features {
+
+namespace {
+
+void
+prepare_query_tensor(const fef::IQueryEnvironment& env,
+ fef::IObjectStore& store,
+ const vespalib::string& query_tensor_name,
+ const vespalib::string& feature_name)
+{
+ try {
+ auto qvalue = QueryValue::from_config(query_tensor_name, env.getIndexEnvironment());
+ qvalue.prepare_shared_state(env, store);
+ } catch (const InvalidValueTypeException& ex) {
+ Issue::report("%s feature: Query tensor '%s' has invalid type '%s'.",
+ feature_name.c_str(), query_tensor_name.c_str(), ex.type_str().c_str());
+ }
+}
+
+std::unique_ptr<DistanceCalculator>
+make_distance_calculator(const fef::IQueryEnvironment& env,
+ const search::attribute::IAttributeVector& attr,
+ const vespalib::string& query_tensor_name,
+ const vespalib::string& feature_name)
+{
+ try {
+ auto qvalue = QueryValue::from_config(query_tensor_name, env.getIndexEnvironment());
+ const auto* query_tensor = qvalue.lookup_value(env.getObjectStore());
+ if (query_tensor == nullptr) {
+ Issue::report("%s feature: Query tensor '%s' is not found in the object store.",
+ feature_name.c_str(), query_tensor_name.c_str());
+ return {};
+ }
+ return DistanceCalculator::make_with_validation(attr, *query_tensor);
+ } catch (const InvalidValueTypeException& ex) {
+ Issue::report("%s feature: Query tensor '%s' has invalid type '%s'.",
+ feature_name.c_str(), query_tensor_name.c_str(), ex.type_str().c_str());
+ } catch (const vespalib::IllegalArgumentException& ex) {
+ Issue::report("%s feature: Could not create distance calculator for attribute '%s' and query tensor '%s': %s.",
+ feature_name.c_str(), attr.getName().c_str(), query_tensor_name.c_str(), ex.getMessage().c_str());
+ }
+ return {};
+}
+
+const search::attribute::IAttributeVector*
+resolve_attribute_for_field(const fef::IQueryEnvironment& env,
+ uint32_t field_id,
+ const vespalib::string& feature_name)
+{
+ const auto* field = env.getIndexEnvironment().getField(field_id);
+ if (field != nullptr) {
+ const auto* attr = env.getAttributeContext().getAttribute(field->name());
+ if (attr == nullptr) {
+ Issue::report("%s feature: The attribute vector '%s' for field id '%u' doesn't exist.",
+ feature_name.c_str(), field->name().c_str(), field_id);
+ }
+ return attr;
+ }
+ return nullptr;
+}
+
+}
+
+DistanceCalculatorBundle::Element::Element(fef::TermFieldHandle handle_in)
+ : handle(handle_in),
+ calc()
+{
+}
+
+DistanceCalculatorBundle::Element::Element(fef::TermFieldHandle handle_in, std::unique_ptr<search::tensor::DistanceCalculator> calc_in)
+ : handle(handle_in),
+ calc(std::move(calc_in))
+{
+}
+
+DistanceCalculatorBundle::Element::~Element() = default;
+
+DistanceCalculatorBundle::DistanceCalculatorBundle(const fef::IQueryEnvironment& env,
+ uint32_t field_id,
+ const vespalib::string& feature_name)
+
+ : _elems()
+{
+ _elems.reserve(env.getNumTerms());
+ const auto* attr = resolve_attribute_for_field(env, field_id, feature_name);
+ for (uint32_t i = 0; i < env.getNumTerms(); ++i) {
+ search::fef::TermFieldHandle handle = util::getTermFieldHandle(env, i, field_id);
+ if (handle != search::fef::IllegalHandle) {
+ const auto* term = env.getTerm(i);
+ if (term->query_tensor_name().has_value() && (attr != nullptr)) {
+ _elems.emplace_back(handle, make_distance_calculator(env, *attr, term->query_tensor_name().value(), feature_name));
+ } else {
+ _elems.emplace_back(handle);
+ }
+ }
+ }
+}
+
+DistanceCalculatorBundle::DistanceCalculatorBundle(const fef::IQueryEnvironment& env,
+ const vespalib::string& label,
+ const vespalib::string& feature_name)
+ : _elems()
+{
+ const ITermData* term = util::getTermByLabel(env, label);
+ if (term != nullptr) {
+ // expect numFields() == 1
+ for (uint32_t i = 0; i < term->numFields(); ++i) {
+ const auto& term_field = term->field(i);
+ TermFieldHandle handle = term_field.getHandle();
+ if (handle != IllegalHandle) {
+ std::unique_ptr<DistanceCalculator> calc;
+ if (term->query_tensor_name().has_value()) {
+ const auto* attr = resolve_attribute_for_field(env, term_field.getFieldId(), feature_name);
+ if (attr != nullptr) {
+ calc = make_distance_calculator(env, *attr, term->query_tensor_name().value(), feature_name);
+ }
+ }
+ _elems.emplace_back(handle, std::move(calc));
+ }
+ }
+ }
+}
+
+void
+DistanceCalculatorBundle::prepare_shared_state(const fef::IQueryEnvironment& env,
+ fef::IObjectStore& store,
+ uint32_t field_id,
+ const vespalib::string& feature_name)
+{
+ for (uint32_t i = 0; i < env.getNumTerms(); ++i) {
+ search::fef::TermFieldHandle handle = util::getTermFieldHandle(env, i, field_id);
+ if (handle != search::fef::IllegalHandle) {
+ const auto* term = env.getTerm(i);
+ if (term->query_tensor_name().has_value()) {
+ prepare_query_tensor(env, store, term->query_tensor_name().value(), feature_name);
+ }
+ }
+ }
+}
+
+void
+DistanceCalculatorBundle::prepare_shared_state(const fef::IQueryEnvironment& env,
+ fef::IObjectStore& store,
+ const vespalib::string& label,
+ const vespalib::string& feature_name)
+{
+ const auto* term = util::getTermByLabel(env, label);
+ if ((term != nullptr) && term->query_tensor_name().has_value()) {
+ prepare_query_tensor(env, store, term->query_tensor_name().value(), feature_name);
+ }
+}
+
+}
+
diff --git a/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.h b/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.h
new file mode 100644
index 00000000000..dd3fc521d96
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/features/distance_calculator_bundle.h
@@ -0,0 +1,59 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include <vespa/searchlib/fef/handle.h>
+#include <vespa/vespalib/stllike/string.h>
+#include <memory>
+#include <vector>
+
+namespace search::tensor { class DistanceCalculator; }
+namespace search::fef {
+class IObjectStore;
+class IQueryEnvironment;
+}
+
+namespace search::features {
+
+/**
+ * A bundle of term-field tuples (TermFieldHandle, DistanceCalculator) used by the closeness and distance rank features.
+ *
+ * For most document ids the raw score is available in the TermFieldMatchData retrieved using the TermFieldHandle,
+ * as it was calculated during matching. In the other cases the DistanceCalculator can be used to calculate the score on the fly.
+ */
+class DistanceCalculatorBundle {
+public:
+ struct Element {
+ fef::TermFieldHandle handle;
+ std::unique_ptr<search::tensor::DistanceCalculator> calc;
+ Element(Element&& rhs) noexcept = default; // Needed as std::vector::reserve() is used.
+ Element(fef::TermFieldHandle handle_in);
+ Element(fef::TermFieldHandle handle_in, std::unique_ptr<search::tensor::DistanceCalculator> calc_in);
+ ~Element();
+ };
+private:
+ std::vector<Element> _elems;
+
+public:
+ DistanceCalculatorBundle(const fef::IQueryEnvironment& env,
+ uint32_t field_id,
+ const vespalib::string& feature_name);
+
+ DistanceCalculatorBundle(const fef::IQueryEnvironment& env,
+ const vespalib::string& label,
+ const vespalib::string& feature_name);
+
+ const std::vector<Element>& elements() const { return _elems; }
+
+ static void prepare_shared_state(const fef::IQueryEnvironment& env,
+ fef::IObjectStore& store,
+ uint32_t field_id,
+ const vespalib::string& feature_name);
+
+ static void prepare_shared_state(const fef::IQueryEnvironment& env,
+ fef::IObjectStore& store,
+ const vespalib::string& label,
+ const vespalib::string& feature_name);
+};
+
+}
diff --git a/searchlib/src/vespa/searchlib/features/distancefeature.cpp b/searchlib/src/vespa/searchlib/features/distancefeature.cpp
index d0a2c1a3838..6add65054ac 100644
--- a/searchlib/src/vespa/searchlib/features/distancefeature.cpp
+++ b/searchlib/src/vespa/searchlib/features/distancefeature.cpp
@@ -1,16 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#include "distance_calculator_bundle.h"
#include "distancefeature.h"
+#include "utils.h"
+#include <vespa/document/datatype/positiondatatype.h>
#include <vespa/searchcommon/common/schema.h>
#include <vespa/searchlib/common/geo_location_spec.h>
#include <vespa/searchlib/fef/matchdata.h>
-#include <vespa/document/datatype/positiondatatype.h>
+#include <vespa/searchlib/tensor/distance_calculator.h>
#include <vespa/vespalib/geo/zcurve.h>
#include <vespa/vespalib/util/issue.h>
#include <vespa/vespalib/util/stash.h>
#include <cmath>
#include <limits>
-#include "utils.h"
#include <vespa/log/log.h>
LOG_SETUP(".features.distancefeature");
@@ -24,8 +26,8 @@ namespace search::features {
/** Implements the executor for converting NNS rawscore to a distance feature. */
class ConvertRawscoreToDistance : public fef::FeatureExecutor {
private:
- std::vector<fef::TermFieldHandle> _handles;
- const fef::MatchData *_md;
+ DistanceCalculatorBundle _bundle;
+ const fef::MatchData *_md;
void handle_bind_match_data(const fef::MatchData &md) override {
_md = &md;
}
@@ -36,32 +38,15 @@ public:
};
ConvertRawscoreToDistance::ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, uint32_t fieldId)
- : _handles(),
+ : _bundle(env, fieldId, "distance"),
_md(nullptr)
{
- _handles.reserve(env.getNumTerms());
- for (uint32_t i = 0; i < env.getNumTerms(); ++i) {
- search::fef::TermFieldHandle handle = util::getTermFieldHandle(env, i, fieldId);
- if (handle != search::fef::IllegalHandle) {
- _handles.push_back(handle);
- }
- }
}
ConvertRawscoreToDistance::ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, const vespalib::string &label)
- : _handles(),
+ : _bundle(env, label, "distance"),
_md(nullptr)
{
- const ITermData *term = util::getTermByLabel(env, label);
- if (term != nullptr) {
- // expect numFields() == 1
- for (uint32_t i = 0; i < term->numFields(); ++i) {
- TermFieldHandle handle = term->field(i).getHandle();
- if (handle != IllegalHandle) {
- _handles.push_back(handle);
- }
- }
- }
}
void
@@ -69,12 +54,16 @@ ConvertRawscoreToDistance::execute(uint32_t docId)
{
feature_t min_distance = std::numeric_limits<feature_t>::max();
assert(_md);
- for (auto handle : _handles) {
- const TermFieldMatchData *tfmd = _md->resolveTermField(handle);
+ for (const auto& elem : _bundle.elements()) {
+ const TermFieldMatchData *tfmd = _md->resolveTermField(elem.handle);
if (tfmd->getDocId() == docId) {
feature_t invdist = tfmd->getRawScore();
feature_t converted = (1.0 / invdist) - 1.0;
min_distance = std::min(min_distance, converted);
+ } else if (elem.calc) {
+ feature_t invdist = elem.calc->calc_raw_score(docId);
+ feature_t converted = (1.0 / invdist) - 1.0;
+ min_distance = std::min(min_distance, converted);
}
}
outputs().set_number(0, min_distance);
@@ -249,6 +238,17 @@ DistanceBlueprint::setup(const IIndexEnvironment & env,
return false;
}
+void
+DistanceBlueprint::prepareSharedState(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const
+{
+ if (_use_nns_tensor) {
+ DistanceCalculatorBundle::prepare_shared_state(env, store, _attr_id, "distance");
+ }
+ if (_use_item_label) {
+ DistanceCalculatorBundle::prepare_shared_state(env, store, _arg_string, "distance");
+ }
+}
+
FeatureExecutor &
DistanceBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const
{
diff --git a/searchlib/src/vespa/searchlib/features/distancefeature.h b/searchlib/src/vespa/searchlib/features/distancefeature.h
index 6eff0380c3a..bf578d45f42 100644
--- a/searchlib/src/vespa/searchlib/features/distancefeature.h
+++ b/searchlib/src/vespa/searchlib/features/distancefeature.h
@@ -63,6 +63,7 @@ public:
return fef::ParameterDescriptions().desc().string().desc().string().string();
}
bool setup(const fef::IIndexEnvironment & env, const fef::ParameterList & params) override;
+ void prepareSharedState(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const override;
fef::FeatureExecutor &createExecutor(const fef::IQueryEnvironment &env, vespalib::Stash &stash) const override;
};
diff --git a/searchlib/src/vespa/searchlib/features/queryfeature.cpp b/searchlib/src/vespa/searchlib/features/queryfeature.cpp
index 483ba6f82b4..acf13c55c99 100644
--- a/searchlib/src/vespa/searchlib/features/queryfeature.cpp
+++ b/searchlib/src/vespa/searchlib/features/queryfeature.cpp
@@ -1,139 +1,24 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#include "constant_tensor_executor.h"
#include "queryfeature.h"
#include "utils.h"
#include "valuefeature.h"
-#include "constant_tensor_executor.h"
-
-#include <vespa/document/datatype/tensor_data_type.h>
#include <vespa/searchlib/fef/featureexecutor.h>
-#include <vespa/searchlib/fef/indexproperties.h>
-#include <vespa/searchlib/fef/properties.h>
#include <vespa/searchlib/fef/feature_type.h>
-#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/eval/eval/value_type.h>
-#include <vespa/eval/eval/value_codec.h>
-#include <vespa/eval/eval/fast_value.h>
-#include <vespa/eval/eval/function.h>
-#include <vespa/eval/eval/interpreted_function.h>
-#include <vespa/vespalib/locale/c.h>
-#include <vespa/vespalib/util/issue.h>
-#include <cerrno>
#include <vespa/log/log.h>
LOG_SETUP(".features.queryfeature");
using namespace search::fef;
-using namespace search::fef::indexproperties;
-using document::TensorDataType;
-using vespalib::eval::ValueType;
-using vespalib::eval::Value;
-using vespalib::eval::TensorSpec;
-using vespalib::eval::Function;
-using vespalib::eval::InterpretedFunction;
-using vespalib::eval::NodeTypes;
-using vespalib::eval::SimpleObjectParams;
-using vespalib::Issue;
using search::fef::FeatureType;
-using search::fef::AnyWrapper;
-using search::fef::Anything;
-
-using ValueWrapper = AnyWrapper<Value::UP>;
namespace search::features {
-namespace {
-
-/**
- * Convert a string to a feature value using special quoting
- * mechanics; a string that can be converted directly into a feature
- * (numeric value) will be converted. If the string cannot be
- * converted directly, it will be hashed, after stripping the leading
- * "'" if it exists.
- *
- * @return feature value
- * @param str string value to be converted
- **/
-feature_t asFeature(const vespalib::string &str) {
- char *end;
- errno = 0;
- double val = vespalib::locale::c::strtod(str.c_str(), &end);
- if (errno != 0 || *end != '\0') { // not happy
- if (str.size() > 0 && str[0] == '\'') {
- val = vespalib::hash_code(str.substr(1));
- } else {
- val = vespalib::hash_code(str);
- }
- }
- return val;
-}
-
-// Create an empty tensor of the given type.
-Value::UP empty_tensor(const ValueType &type) {
- const auto &factory = vespalib::eval::FastValueBuilderFactory::get();
- return vespalib::eval::value_from_spec(TensorSpec(type.to_spec()), factory);
-}
-
-// Create a tensor value by evaluating a self-contained expression.
-Value::UP as_tensor(const vespalib::string &expr, const ValueType &wanted_type) {
- const auto &factory = vespalib::eval::FastValueBuilderFactory::get();
- auto fun = Function::parse(expr);
- if (!fun->has_error() && (fun->num_params() == 0)) {
- NodeTypes types = NodeTypes(*fun, {});
- ValueType res_type = types.get_type(fun->root());
- if (res_type == wanted_type) {
- SimpleObjectParams params({});
- InterpretedFunction ifun(factory, *fun, types);
- InterpretedFunction::Context ctx(ifun);
- return factory.copy(ifun.eval(ctx, params));
- }
- }
- return {};
-}
-
-// query(foo):
-// query.value.foo -> decoded tensor value 'foo'
-vespalib::string make_value_key(const vespalib::string &base, const vespalib::string &sub_key) {
- vespalib::string key(base);
- key.append(".value.");
- key.append(sub_key);
- return key;
-}
-
-} // namespace search::features::<unnamed>
-
-Property
-QueryBlueprint::config_lookup(const IIndexEnvironment &env) const
-{
- const auto &props = env.getProperties();
- auto res = props.lookup(getName()); // query(foo)
- if (!res.found()) {
- res = props.lookup(_old_key); // $foo
- }
- return res;
-}
-
-Property
-QueryBlueprint::request_lookup(const IQueryEnvironment &env) const
-{
- const auto &props = env.getProperties();
- auto res = props.lookup(getName()); // query(foo)
- if (!res.found()) {
- res = props.lookup(_key); // foo
- }
- if (!res.found()) {
- res = props.lookup(_old_key); // $foo
- }
- return res;
-}
-
QueryBlueprint::QueryBlueprint()
: Blueprint("query"),
- _key(),
- _old_key(),
- _stored_value_key(),
- _type(ValueType::double_type()),
- _default_number_value(),
+ _qvalue(),
_default_object_value()
{
}
@@ -154,89 +39,37 @@ QueryBlueprint::createInstance() const
bool
QueryBlueprint::setup(const IIndexEnvironment &env, const ParameterList &params)
{
- _key = params[0].getValue();
- _old_key = "$";
- _old_key.append(_key);
- _stored_value_key = make_value_key(getBaseName(), _key);
- vespalib::string type_str = type::QueryFeature::lookup(env.getProperties(), _key);
- if (!type_str.empty()) {
- _type = ValueType::from_spec(type_str);
- if (_type.is_error()) {
- return fail("invalid type: '%s'", type_str.c_str());
- }
- }
- Property p = config_lookup(env);
- if (_type.is_double()) {
- if (p.found()) {
- _default_number_value = asFeature(p.get());
- }
- } else {
- if (p.found()) {
- _default_object_value = as_tensor(p.get(), _type);
- if (_default_object_value.get() == nullptr) {
- return fail("could not create default tensor value of type '%s' from the expression '%s'",
- _type.to_spec().c_str(), p.get().c_str());
- }
- } else {
- _default_object_value = empty_tensor(_type);
- }
+ try {
+ _qvalue = QueryValue::from_config(params[0].getValue(), env);
+ _default_object_value = _qvalue.make_default_value(env);
+ } catch (const InvalidValueTypeException& ex) {
+ return fail("invalid type: '%s'", ex.type_str().c_str());
+ } catch (const InvalidTensorValueException& ex) {
+ return fail("could not create default tensor value of type '%s' from the expression '%s'",
+ _qvalue.type().to_spec().c_str(), ex.expr().c_str());
}
- FeatureType output_type = _type.is_double() ? FeatureType::number() : FeatureType::object(_type);
+ const auto& type = _qvalue.type();
+ FeatureType output_type = type.is_double() ? FeatureType::number() : FeatureType::object(type);
describeOutput("out", "The value looked up in query properties using the given key.", output_type);
- assert(_type.has_dimensions() == (_default_object_value.get() != nullptr));
return true;
}
-namespace {
-
-Value::UP decode_tensor_value(Property prop, const ValueType &valueType) {
- if (prop.found() && !prop.get().empty()) {
- const vespalib::string &value = prop.get();
- vespalib::nbostream stream(value.data(), value.size());
- try {
- auto tensor = vespalib::eval::decode_value(stream, vespalib::eval::FastValueBuilderFactory::get());
- if (TensorDataType::isAssignableType(valueType, tensor->type())) {
- return tensor;
- } else {
- Issue::report("Query feature type is '%s' but other tensor type is '%s'",
- valueType.to_spec().c_str(), tensor->type().to_spec().c_str());
- }
- } catch (const vespalib::eval::DecodeValueException &e) {
- Issue::report("Query feature has invalid binary format: %s", e.what());
- }
- }
- return {};
-}
-
-}
-
void
QueryBlueprint::prepareSharedState(const fef::IQueryEnvironment &env, fef::IObjectStore &store) const
{
- if (!_stored_value_key.empty() && _type.has_dimensions() && (store.get(_stored_value_key) == nullptr)) {
- if (auto value = decode_tensor_value(request_lookup(env), _type)) {
- store.add(_stored_value_key, std::make_unique<ValueWrapper>(std::move(value)));
- }
- }
+ _qvalue.prepare_shared_state(env, store);
}
FeatureExecutor &
QueryBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const
{
- if (_type.has_dimensions()) {
- if (const Anything *wrapped_value = env.getObjectStore().get(_stored_value_key)) {
- if (const Value *value = ValueWrapper::getValue(*wrapped_value).get()) {
- return stash.create<ConstantTensorRefExecutor>(*value);
- }
+ if (_qvalue.type().has_dimensions()) {
+ if (const vespalib::eval::Value *value = _qvalue.lookup_value(env.getObjectStore())) {
+ return stash.create<ConstantTensorRefExecutor>(*value);
}
return stash.create<ConstantTensorRefExecutor>(*_default_object_value);
} else {
- auto p = request_lookup(env);
- if (p.found()) {
- return stash.create<SingleValueExecutor>(asFeature(p.get()));
- } else {
- return stash.create<SingleValueExecutor>(_default_number_value);
- }
+ return stash.create<SingleValueExecutor>(_qvalue.lookup_number(env, _default_object_value->as_double()));
}
}
diff --git a/searchlib/src/vespa/searchlib/features/queryfeature.h b/searchlib/src/vespa/searchlib/features/queryfeature.h
index 020fd31989d..ae77a7d660f 100644
--- a/searchlib/src/vespa/searchlib/features/queryfeature.h
+++ b/searchlib/src/vespa/searchlib/features/queryfeature.h
@@ -4,6 +4,7 @@
#include <vespa/searchlib/fef/blueprint.h>
#include <vespa/searchlib/fef/properties.h>
+#include <vespa/searchlib/fef/query_value.h>
#include <vespa/eval/eval/value_type.h>
#include <vespa/eval/eval/value.h>
@@ -17,16 +18,9 @@ namespace search::features {
*/
class QueryBlueprint : public fef::Blueprint {
private:
- vespalib::string _key; // 'foo'
- vespalib::string _old_key; // '$foo'
- vespalib::string _stored_value_key; // query.value.foo
- vespalib::eval::ValueType _type;
- feature_t _default_number_value;
+ search::fef::QueryValue _qvalue;
vespalib::eval::Value::UP _default_object_value;
- fef::Property config_lookup(const fef::IIndexEnvironment &env) const;
- fef::Property request_lookup(const fef::IQueryEnvironment &env) const;
-
public:
QueryBlueprint();
~QueryBlueprint();
diff --git a/searchlib/src/vespa/searchlib/features/termeditdistancefeature.cpp b/searchlib/src/vespa/searchlib/features/termeditdistancefeature.cpp
index 41b441d2915..d85d7132feb 100644
--- a/searchlib/src/vespa/searchlib/features/termeditdistancefeature.cpp
+++ b/searchlib/src/vespa/searchlib/features/termeditdistancefeature.cpp
@@ -17,14 +17,14 @@ namespace search::features {
//---------------------------------------------------------------------------------------------------------------------
// TedCell
//---------------------------------------------------------------------------------------------------------------------
-TedCell::TedCell() :
+TedCell::TedCell() noexcept :
cost(util::FEATURE_MAX),
numDel(0),
numIns(0),
numSub(0)
{}
-TedCell::TedCell(feature_t argCost, uint32_t argNumDel, uint32_t argNumIns, uint32_t argNumSub) :
+TedCell::TedCell(feature_t argCost, uint32_t argNumDel, uint32_t argNumIns, uint32_t argNumSub) noexcept :
cost(argCost),
numDel(argNumDel),
numIns(argNumIns),
diff --git a/searchlib/src/vespa/searchlib/features/termeditdistancefeature.h b/searchlib/src/vespa/searchlib/features/termeditdistancefeature.h
index e86c2a909f1..3f49dfb802e 100644
--- a/searchlib/src/vespa/searchlib/features/termeditdistancefeature.h
+++ b/searchlib/src/vespa/searchlib/features/termeditdistancefeature.h
@@ -12,8 +12,8 @@ namespace search::features {
*/
class TedCell {
public:
- TedCell();
- TedCell(feature_t cost, uint32_t numDel, uint32_t numIns, uint32_t numSub);
+ TedCell() noexcept;
+ TedCell(feature_t cost, uint32_t numDel, uint32_t numIns, uint32_t numSub) noexcept;
feature_t cost; // The cost at this point.
uint32_t numDel; // The number of deletions to get here.
diff --git a/searchlib/src/vespa/searchlib/fef/CMakeLists.txt b/searchlib/src/vespa/searchlib/fef/CMakeLists.txt
index 8968e4e347d..ba4430ff8e6 100644
--- a/searchlib/src/vespa/searchlib/fef/CMakeLists.txt
+++ b/searchlib/src/vespa/searchlib/fef/CMakeLists.txt
@@ -26,6 +26,7 @@ vespa_add_library(searchlib_fef OBJECT
phrase_splitter_query_env.cpp
phrasesplitter.cpp
properties.cpp
+ query_value.cpp
queryproperties.cpp
rank_program.cpp
ranksetup.cpp
diff --git a/searchlib/src/vespa/searchlib/fef/itermdata.h b/searchlib/src/vespa/searchlib/fef/itermdata.h
index aca92aedfd5..306c91f7ab2 100644
--- a/searchlib/src/vespa/searchlib/fef/itermdata.h
+++ b/searchlib/src/vespa/searchlib/fef/itermdata.h
@@ -4,7 +4,9 @@
#include "itermfielddata.h"
#include <vespa/searchlib/query/weight.h>
+#include <vespa/vespalib/stllike/string.h>
#include <cstddef>
+#include <optional>
namespace search::fef {
@@ -35,6 +37,11 @@ public:
virtual uint32_t getUniqueId() const = 0;
/**
+ * Returns the name of a query tensor this term is referencing, if set.
+ */
+ virtual std::optional<vespalib::string> query_tensor_name() const = 0;
+
+ /**
* Get number of fields searched
**/
virtual size_t numFields() const = 0;
diff --git a/searchlib/src/vespa/searchlib/fef/objectstore.cpp b/searchlib/src/vespa/searchlib/fef/objectstore.cpp
index 2da08e2915d..4cf185ad55e 100644
--- a/searchlib/src/vespa/searchlib/fef/objectstore.cpp
+++ b/searchlib/src/vespa/searchlib/fef/objectstore.cpp
@@ -2,8 +2,7 @@
#include "objectstore.h"
#include <vespa/vespalib/stllike/hash_map.hpp>
-namespace search {
-namespace fef {
+namespace search::fef {
ObjectStore::ObjectStore() :
_objectMap()
@@ -37,4 +36,3 @@ ObjectStore::get(const vespalib::string & key) const
}
}
-}
diff --git a/searchlib/src/vespa/searchlib/fef/query_value.cpp b/searchlib/src/vespa/searchlib/fef/query_value.cpp
new file mode 100644
index 00000000000..a60a24425b5
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/fef/query_value.cpp
@@ -0,0 +1,231 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "iindexenvironment.h"
+#include "indexproperties.h"
+#include "iqueryenvironment.h"
+#include "query_value.h"
+#include <vespa/document/datatype/tensor_data_type.h>
+#include <vespa/eval/eval/fast_value.h>
+#include <vespa/eval/eval/interpreted_function.h>
+#include <vespa/eval/eval/value.h>
+#include <vespa/eval/eval/value_codec.h>
+#include <vespa/vespalib/locale/c.h>
+#include <vespa/vespalib/util/issue.h>
+#include <vespa/vespalib/util/string_hash.h>
+#include <cerrno>
+
+using document::TensorDataType;
+using vespalib::Issue;
+using vespalib::eval::DoubleValue;
+using vespalib::eval::Function;
+using vespalib::eval::InterpretedFunction;
+using vespalib::eval::NodeTypes;
+using vespalib::eval::SimpleObjectParams;
+using vespalib::eval::TensorSpec;
+using vespalib::eval::Value;
+using vespalib::eval::ValueType;
+
+using namespace search::fef::indexproperties;
+
+namespace search::fef {
+
+using ValueWrapper = AnyWrapper<Value::UP>;
+
+InvalidValueTypeException::InvalidValueTypeException(const vespalib::string& query_key, const vespalib::string& type_str_in)
+ : vespalib::Exception("Invalid type '" + type_str_in + "' for query value '" + query_key + "'"),
+ _type_str(type_str_in)
+{
+}
+
+InvalidTensorValueException::InvalidTensorValueException(const vespalib::eval::ValueType& type, const vespalib::string& expr_in)
+ : vespalib::Exception("Could not create tensor value of type '" + type.to_spec() + "' from the expression '" + expr_in + "'"),
+ _expr(expr_in)
+{
+}
+
+namespace {
+
+/**
+ * Convert a string to a feature value using special quoting mechanics;
+ * a string that can be converted directly into a feature
+ * (numeric value) will be converted. If the string cannot be
+ * converted directly, it will be hashed, after stripping the leading
+ * "'" if it exists.
+ */
+feature_t
+as_feature(const vespalib::string& str)
+{
+ char *end;
+ errno = 0;
+ double val = vespalib::locale::c::strtod(str.c_str(), &end);
+ if (errno != 0 || *end != '\0') { // not happy
+ if (str.size() > 0 && str[0] == '\'') {
+ val = vespalib::hash_code(str.substr(1));
+ } else {
+ val = vespalib::hash_code(str);
+ }
+ }
+ return val;
+}
+
+// Create an empty tensor of the given type.
+std::unique_ptr<Value>
+empty_tensor(const ValueType& type)
+{
+ const auto& factory = vespalib::eval::FastValueBuilderFactory::get();
+ return vespalib::eval::value_from_spec(TensorSpec(type.to_spec()), factory);
+}
+
+// Create a tensor value by evaluating a self-contained expression.
+std::unique_ptr<Value>
+as_tensor(const vespalib::string& expr, const ValueType& wanted_type)
+{
+ const auto& factory = vespalib::eval::FastValueBuilderFactory::get();
+ auto fun = Function::parse(expr);
+ if (!fun->has_error() && (fun->num_params() == 0)) {
+ NodeTypes types = NodeTypes(*fun, {});
+ ValueType res_type = types.get_type(fun->root());
+ if (res_type == wanted_type) {
+ SimpleObjectParams params({});
+ InterpretedFunction ifun(factory, *fun, types);
+ InterpretedFunction::Context ctx(ifun);
+ return factory.copy(ifun.eval(ctx, params));
+ }
+ }
+ return {};
+}
+
+std::unique_ptr<Value>
+decode_tensor_value(Property prop, const ValueType& value_type)
+{
+ if (prop.found() && !prop.get().empty()) {
+ const vespalib::string& value = prop.get();
+ vespalib::nbostream stream(value.data(), value.size());
+ try {
+ auto tensor = vespalib::eval::decode_value(stream, vespalib::eval::FastValueBuilderFactory::get());
+ if (TensorDataType::isAssignableType(value_type, tensor->type())) {
+ return tensor;
+ } else {
+ Issue::report("Query value type is '%s' but decoded tensor type is '%s'",
+ value_type.to_spec().c_str(), tensor->type().to_spec().c_str());
+ }
+ } catch (const vespalib::eval::DecodeValueException& e) {
+ Issue::report("Query value has invalid binary format: %s", e.what());
+ }
+ }
+ return {};
+}
+
+}
+
+Property
+QueryValue::config_lookup(const IIndexEnvironment& env) const
+{
+ const auto& props = env.getProperties();
+ auto res = props.lookup(_name); // query(foo)
+ if (!res.found()) {
+ res = props.lookup(_old_key); // $foo
+ }
+ return res;
+}
+
+Property
+QueryValue::request_lookup(const IQueryEnvironment& env) const
+{
+ const auto& props = env.getProperties();
+ auto res = props.lookup(_name); // query(foo)
+ if (!res.found()) {
+ res = props.lookup(_key); // foo
+ }
+ if (!res.found()) {
+ res = props.lookup(_old_key); // $foo
+ }
+ return res;
+}
+
+QueryValue::QueryValue()
+ : _key(),
+ _name(),
+ _old_key(),
+ _stored_value_key(),
+ _type(ValueType::double_type())
+{
+}
+
+QueryValue::QueryValue(const vespalib::string& key, const vespalib::eval::ValueType& type)
+ : _key(key),
+ _name("query(" + key + ")"),
+ _old_key("$" + key),
+ _stored_value_key("query.value." + key),
+ _type(type)
+{
+}
+
+QueryValue::~QueryValue() = default;
+
+QueryValue
+QueryValue::from_config(const vespalib::string& key, const IIndexEnvironment& env)
+{
+ vespalib::string type_str = type::QueryFeature::lookup(env.getProperties(), key);
+ ValueType type = type_str.empty() ? ValueType::double_type() : ValueType::from_spec(type_str);
+ if (type.is_error()) {
+ throw InvalidValueTypeException(key, type_str);
+ }
+ return {key, type};
+}
+
+std::unique_ptr<Value>
+QueryValue::make_default_value(const IIndexEnvironment& env) const
+{
+ Property p = config_lookup(env);
+ if (_type.is_double()) {
+ if (p.found()) {
+ return std::make_unique<DoubleValue>(as_feature(p.get()));
+ } else {
+ return std::make_unique<DoubleValue>(0);
+ }
+ } else {
+ if (p.found()) {
+ auto tensor = as_tensor(p.get(), _type);
+ if (tensor.get() == nullptr) {
+ throw InvalidTensorValueException(_type, p.get().c_str());
+ }
+ return tensor;
+ } else {
+ return empty_tensor(_type);
+ }
+ }
+}
+
+void
+QueryValue::prepare_shared_state(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const
+{
+ if (!_stored_value_key.empty() && _type.has_dimensions() && (store.get(_stored_value_key) == nullptr)) {
+ if (auto value = decode_tensor_value(request_lookup(env), _type)) {
+ store.add(_stored_value_key, std::make_unique<ValueWrapper>(std::move(value)));
+ }
+ }
+}
+
+const Value*
+QueryValue::lookup_value(const fef::IObjectStore& store) const
+{
+ if (const Anything* wrapped_value = store.get(_stored_value_key)) {
+ return ValueWrapper::getValue(*wrapped_value).get();
+ }
+ return nullptr;
+}
+
+double
+QueryValue::lookup_number(const fef::IQueryEnvironment& env, double default_value) const
+{
+ assert(!_type.has_dimensions());
+ auto p = request_lookup(env);
+ if (p.found()) {
+ return as_feature(p.get());
+ }
+ return default_value;
+}
+
+}
+
diff --git a/searchlib/src/vespa/searchlib/fef/query_value.h b/searchlib/src/vespa/searchlib/fef/query_value.h
new file mode 100644
index 00000000000..3cdb90ea871
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/fef/query_value.h
@@ -0,0 +1,90 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "properties.h"
+#include <vespa/eval/eval/value_type.h>
+#include <vespa/vespalib/util/exception.h>
+#include <vespa/vespalib/stllike/string.h>
+#include <memory>
+
+namespace vespalib::eval { struct Value; }
+
+namespace search::fef {
+
+class IIndexEnvironment;
+class IQueryEnvironment;
+
+/**
+ * Exception for when the value type is an error.
+ */
+class InvalidValueTypeException : public vespalib::Exception {
+private:
+ vespalib::string _type_str;
+
+public:
+ InvalidValueTypeException(const vespalib::string& query_key, const vespalib::string& type_str_in);
+ const vespalib::string& type_str() const { return _type_str; }
+};
+
+/**
+ * Exception for when a tensor value could not be created from an expression.
+ */
+class InvalidTensorValueException : public vespalib::Exception {
+private:
+ vespalib::string _expr;
+
+public:
+ InvalidTensorValueException(const vespalib::eval::ValueType& type, const vespalib::string& expr_in);
+ const vespalib::string& expr() const { return _expr; }
+};
+
+/**
+ * Class representing a vespalib::eval::Value (number or tensor) passed down with the query.
+ *
+ * The value type and optional default value are defined in IIndexEnvironment properties and extracted at config time.
+ * Per query, the value is extracted from IQueryEnvironment properties. This is stored in the shared IObjectStore.
+ */
+class QueryValue {
+private:
+ vespalib::string _key; // 'foo'
+ vespalib::string _name; // 'query(foo)'
+ vespalib::string _old_key; // '$foo'
+ vespalib::string _stored_value_key; // query.value.foo
+ vespalib::eval::ValueType _type;
+
+ Property config_lookup(const IIndexEnvironment& env) const;
+ Property request_lookup(const IQueryEnvironment& env) const;
+
+public:
+ QueryValue();
+ QueryValue(const vespalib::string& key, const vespalib::eval::ValueType& type);
+ ~QueryValue();
+
+ /**
+ * Create a QueryValue using properties from the given index environment to extract the value type.
+ *
+ * Throws InvalidValueTypeException if the value type is an error.
+ */
+ static QueryValue from_config(const vespalib::string& key, const IIndexEnvironment& env);
+
+ const vespalib::eval::ValueType& type() const { return _type; }
+
+ /**
+ * Create a default value based on properties from the given index environment.
+ *
+ * An empty value is created if not found.
+ * Throws InvalidTensorValueException if a tensor value could not be created.
+ */
+ std::unique_ptr<vespalib::eval::Value> make_default_value(const IIndexEnvironment& env) const;
+
+ void prepare_shared_state(const fef::IQueryEnvironment& env, fef::IObjectStore& store) const;
+
+ const vespalib::eval::Value* lookup_value(const fef::IObjectStore& store) const;
+
+ double lookup_number(const fef::IQueryEnvironment& env, double default_value) const;
+
+};
+
+}
+
diff --git a/searchlib/src/vespa/searchlib/fef/simpletermdata.cpp b/searchlib/src/vespa/searchlib/fef/simpletermdata.cpp
index ee079ce8239..fdea499f9b4 100644
--- a/searchlib/src/vespa/searchlib/fef/simpletermdata.cpp
+++ b/searchlib/src/vespa/searchlib/fef/simpletermdata.cpp
@@ -2,14 +2,14 @@
#include "simpletermdata.h"
-namespace search {
-namespace fef {
+namespace search::fef {
SimpleTermData::SimpleTermData()
: _weight(0),
_numTerms(0),
_termIndex(0),
_uniqueId(0),
+ _query_tensor_name(),
_fields()
{
}
@@ -18,6 +18,7 @@ SimpleTermData::SimpleTermData(const ITermData &rhs)
: _weight(rhs.getWeight()),
_numTerms(rhs.getPhraseLength()),
_uniqueId(rhs.getUniqueId()),
+ _query_tensor_name(rhs.query_tensor_name()),
_fields()
{
for (size_t i(0), m(rhs.numFields()); i < m; ++i) {
@@ -25,5 +26,6 @@ SimpleTermData::SimpleTermData(const ITermData &rhs)
}
}
-} // namespace fef
-} // namespace search
+SimpleTermData::~SimpleTermData() = default;
+
+}
diff --git a/searchlib/src/vespa/searchlib/fef/simpletermdata.h b/searchlib/src/vespa/searchlib/fef/simpletermdata.h
index 2169334e36a..c59816dc687 100644
--- a/searchlib/src/vespa/searchlib/fef/simpletermdata.h
+++ b/searchlib/src/vespa/searchlib/fef/simpletermdata.h
@@ -22,6 +22,7 @@ private:
uint32_t _numTerms;
uint32_t _termIndex;
uint32_t _uniqueId;
+ std::optional<vespalib::string> _query_tensor_name;
std::vector<SimpleTermFieldData> _fields;
@@ -36,45 +37,24 @@ public:
**/
SimpleTermData(const ITermData &rhs);
+ ~SimpleTermData();
+
//----------- ITermData implementation ------------------------------------
- /**
- * Returns the term weight.
- **/
query::Weight getWeight() const override { return _weight; }
- /**
- * Returns the number of terms represented by this term data object.
- **/
uint32_t getPhraseLength() const override { return _numTerms; }
- /**
- * Obtain the unique id of this term. 0 means not set.
- *
- * @return unique id or 0
- **/
uint32_t getUniqueId() const override { return _uniqueId; }
- /**
- * Get number of fields searched
- **/
+ std::optional<vespalib::string> query_tensor_name() const override { return _query_tensor_name; }
+
size_t numFields() const override { return _fields.size(); }
- /**
- * Direct access to data for individual fields
- * @param i local index, must have: 0 <= i < numFields()
- */
const ITermFieldData &field(size_t i) const override {
return _fields[i];
}
- /**
- * Obtain information about a specific field that may be searched
- * by this term. If the requested field is not searched by this
- * term, NULL will be returned.
- *
- * @return term field data, or NULL if not found
- **/
const ITermFieldData *lookupField(uint32_t fieldId) const override {
for (size_t fieldIdx(0), m(numFields()); fieldIdx < m; ++fieldIdx) {
const ITermFieldData &tfd = field(fieldIdx);
@@ -125,6 +105,11 @@ public:
return *this;
}
+ SimpleTermData &set_query_tensor_name(const vespalib::string &name) {
+ _query_tensor_name = name;
+ return *this;
+ }
+
/**
* Add a new field to the set that is searched by this term.
*
diff --git a/searchlib/src/vespa/searchlib/fef/test/labels.h b/searchlib/src/vespa/searchlib/fef/test/labels.h
index 5f27f786405..a69634003b4 100644
--- a/searchlib/src/vespa/searchlib/fef/test/labels.h
+++ b/searchlib/src/vespa/searchlib/fef/test/labels.h
@@ -1,5 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
#include <vespa/searchlib/fef/properties.h>
#include <vespa/vespalib/stllike/asciistream.h>
diff --git a/searchlib/src/vespa/searchlib/queryeval/fake_requestcontext.h b/searchlib/src/vespa/searchlib/queryeval/fake_requestcontext.h
index a492f055cdb..4d7e092a812 100644
--- a/searchlib/src/vespa/searchlib/queryeval/fake_requestcontext.h
+++ b/searchlib/src/vespa/searchlib/queryeval/fake_requestcontext.h
@@ -34,15 +34,15 @@ public:
? _attributeContext->getAttribute(name)
: nullptr;
}
- vespalib::eval::Value::UP get_query_tensor(const vespalib::string& tensor_name) const override {
+ vespalib::eval::Value* get_query_tensor(const vespalib::string& tensor_name) const override {
if (_query_tensor && (tensor_name == _query_tensor_name)) {
- return vespalib::eval::value_from_spec(*_query_tensor, vespalib::eval::FastValueBuilderFactory::get());
+ return _query_tensor.get();
}
- return {};
+ return nullptr;
}
void set_query_tensor(const vespalib::string& name, const vespalib::eval::TensorSpec& tensor_spec) {
_query_tensor_name = name;
- _query_tensor = std::make_unique<vespalib::eval::TensorSpec>(tensor_spec);
+ _query_tensor = vespalib::eval::value_from_spec(tensor_spec, vespalib::eval::FastValueBuilderFactory::get());
}
const search::attribute::AttributeBlueprintParams& get_attribute_blueprint_params() const override;
@@ -52,7 +52,7 @@ private:
const vespalib::Doom _doom;
attribute::IAttributeContext *_attributeContext;
vespalib::string _query_tensor_name;
- std::unique_ptr<vespalib::eval::TensorSpec> _query_tensor;
+ std::unique_ptr<vespalib::eval::Value> _query_tensor;
search::attribute::AttributeBlueprintParams _attribute_blueprint_params;
};
diff --git a/searchlib/src/vespa/searchlib/queryeval/irequestcontext.h b/searchlib/src/vespa/searchlib/queryeval/irequestcontext.h
index 376906c8e8f..5aa5db081ab 100644
--- a/searchlib/src/vespa/searchlib/queryeval/irequestcontext.h
+++ b/searchlib/src/vespa/searchlib/queryeval/irequestcontext.h
@@ -36,7 +36,7 @@ public:
* Returns the tensor of the given name that was passed with the query.
* Returns nullptr if the tensor is not found or if it is not a tensor.
*/
- virtual std::unique_ptr<vespalib::eval::Value> get_query_tensor(const vespalib::string& tensor_name) const = 0;
+ virtual const vespalib::eval::Value* get_query_tensor(const vespalib::string& tensor_name) const = 0;
virtual const search::attribute::AttributeBlueprintParams& get_attribute_blueprint_params() const = 0;
};
diff --git a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp
index 8c03800b92a..6a891341afd 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp
+++ b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp
@@ -4,7 +4,6 @@
#include "nearest_neighbor_blueprint.h"
#include "nearest_neighbor_iterator.h"
#include "nns_index_iterator.h"
-#include <vespa/eval/eval/fast_value.h>
#include <vespa/searchlib/fef/termfieldmatchdataarray.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/searchlib/tensor/distance_function_factory.h>
@@ -13,45 +12,12 @@
LOG_SETUP(".searchlib.queryeval.nearest_neighbor_blueprint");
-using vespalib::eval::CellType;
-using vespalib::eval::FastValueBuilderFactory;
-using vespalib::eval::TypedCells;
using vespalib::eval::Value;
-using vespalib::eval::ValueType;
namespace search::queryeval {
namespace {
-template<typename LCT, typename RCT>
-std::unique_ptr<Value>
-convert_cells(const ValueType &new_type, std::unique_ptr<Value> old_value)
-{
- auto old_cells = old_value->cells().typify<LCT>();
- auto builder = FastValueBuilderFactory::get().create_value_builder<RCT>(new_type);
- auto new_cells = builder->add_subspace();
- assert(old_cells.size() == new_cells.size());
- auto p = new_cells.begin();
- for (LCT value : old_cells) {
- RCT conv(value);
- *p++ = conv;
- }
- return builder->build(std::move(builder));
-}
-
-struct ConvertCellsSelector
-{
- template <typename LCT, typename RCT>
- static auto invoke(const ValueType &new_type, std::unique_ptr<Value> old_value) {
- return convert_cells<LCT, RCT>(new_type, std::move(old_value));
- }
- auto operator() (CellType from, CellType to, std::unique_ptr<Value> old_value) const {
- using MyTypify = vespalib::eval::TypifyCellType;
- ValueType new_type = old_value->type().cell_cast(to);
- return vespalib::typify_invoke<2,MyTypify,ConvertCellsSelector>(from, to, new_type, std::move(old_value));
- }
-};
-
vespalib::string
to_string(NearestNeighborBlueprint::Algorithm algorithm)
{
@@ -68,8 +34,7 @@ to_string(NearestNeighborBlueprint::Algorithm algorithm)
} // namespace <unnamed>
NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& field,
- const tensor::ITensorAttribute& attr_tensor,
- std::unique_ptr<Value> query_tensor,
+ std::unique_ptr<search::tensor::DistanceCalculator> distance_calc,
uint32_t target_hits,
bool approximate,
uint32_t explore_additional_hits,
@@ -77,8 +42,9 @@ NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& f
double global_filter_lower_limit,
double global_filter_upper_limit)
: ComplexLeafBlueprint(field),
- _attr_tensor(attr_tensor),
- _query_tensor(std::move(query_tensor)),
+ _distance_calc(std::move(distance_calc)),
+ _attr_tensor(_distance_calc->attribute_tensor()),
+ _query_tensor(_distance_calc->query_tensor()),
_target_hits(target_hits),
_adjusted_target_hits(target_hits),
_approximate(approximate),
@@ -86,7 +52,6 @@ NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& f
_distance_threshold(std::numeric_limits<double>::max()),
_global_filter_lower_limit(global_filter_lower_limit),
_global_filter_upper_limit(global_filter_upper_limit),
- _fallback_dist_fun(),
_distance_heap(target_hits),
_found_hits(),
_algorithm(Algorithm::EXACT),
@@ -95,27 +60,13 @@ NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& f
_global_filter_hits(),
_global_filter_hit_ratio()
{
- CellType attr_ct = _attr_tensor.getTensorType().cell_type();
- _fallback_dist_fun = search::tensor::make_distance_function(_attr_tensor.distance_metric(), attr_ct);
- _dist_fun = _fallback_dist_fun.get();
- assert(_dist_fun);
- auto nns_index = _attr_tensor.nearest_neighbor_index();
- if (nns_index) {
- _dist_fun = nns_index->distance_function();
- assert(_dist_fun);
- }
- auto query_ct = _query_tensor->cells().type;
- CellType required_ct = _dist_fun->expected_cell_type();
- if (query_ct != required_ct) {
- ConvertCellsSelector converter;
- _query_tensor = converter(query_ct, required_ct, std::move(_query_tensor));
- }
if (distance_threshold < std::numeric_limits<double>::max()) {
- _distance_threshold = _dist_fun->convert_threshold(distance_threshold);
+ _distance_threshold = _distance_calc->function().convert_threshold(distance_threshold);
_distance_heap.set_distance_threshold(_distance_threshold);
}
uint32_t est_hits = _attr_tensor.get_num_docs();
setEstimate(HitEstimate(est_hits, false));
+ auto nns_index = _attr_tensor.nearest_neighbor_index();
set_want_global_filter(nns_index && _approximate);
}
@@ -155,7 +106,7 @@ NearestNeighborBlueprint::set_global_filter(const GlobalFilter &global_filter, d
void
NearestNeighborBlueprint::perform_top_k(const search::tensor::NearestNeighborIndex* nns_index)
{
- auto lhs = _query_tensor->cells();
+ auto lhs = _query_tensor.cells();
uint32_t k = _adjusted_target_hits;
if (_global_filter->has_filter()) {
auto filter = _global_filter->filter();
@@ -175,13 +126,12 @@ NearestNeighborBlueprint::createLeafSearch(const search::fef::TermFieldMatchData
switch (_algorithm) {
case Algorithm::INDEX_TOP_K_WITH_FILTER:
case Algorithm::INDEX_TOP_K:
- return NnsIndexIterator::create(tfmd, _found_hits, _dist_fun);
+ return NnsIndexIterator::create(tfmd, _found_hits, _distance_calc->function());
default:
;
}
- const Value &qT = *_query_tensor;
- return NearestNeighborIterator::create(strict, tfmd, qT, _attr_tensor,
- _distance_heap, _global_filter->filter(), _dist_fun);
+ return NearestNeighborIterator::create(strict, tfmd, *_distance_calc,
+ _distance_heap, _global_filter->filter());
}
void
@@ -189,7 +139,7 @@ NearestNeighborBlueprint::visitMembers(vespalib::ObjectVisitor& visitor) const
{
ComplexLeafBlueprint::visitMembers(visitor);
visitor.visitString("attribute_tensor", _attr_tensor.getTensorType().to_spec());
- visitor.visitString("query_tensor", _query_tensor->type().to_spec());
+ visitor.visitString("query_tensor", _query_tensor.type().to_spec());
visitor.visitInt("target_hits", _target_hits);
visitor.visitInt("adjusted_target_hits", _adjusted_target_hits);
visitor.visitInt("explore_additional_hits", _explore_additional_hits);
diff --git a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.h b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.h
index 16b0e13014e..3dd03291b97 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.h
+++ b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.h
@@ -3,6 +3,7 @@
#include "blueprint.h"
#include "nearest_neighbor_distance_heap.h"
+#include <vespa/searchlib/tensor/distance_calculator.h>
#include <vespa/searchlib/tensor/distance_function.h>
#include <vespa/searchlib/tensor/nearest_neighbor_index.h>
#include <optional>
@@ -27,8 +28,9 @@ public:
INDEX_TOP_K_WITH_FILTER
};
private:
+ std::unique_ptr<search::tensor::DistanceCalculator> _distance_calc;
const tensor::ITensorAttribute& _attr_tensor;
- std::unique_ptr<vespalib::eval::Value> _query_tensor;
+ const vespalib::eval::Value& _query_tensor;
uint32_t _target_hits;
uint32_t _adjusted_target_hits;
bool _approximate;
@@ -36,8 +38,6 @@ private:
double _distance_threshold;
double _global_filter_lower_limit;
double _global_filter_upper_limit;
- search::tensor::DistanceFunction::UP _fallback_dist_fun;
- const search::tensor::DistanceFunction *_dist_fun;
mutable NearestNeighborDistanceHeap _distance_heap;
std::vector<search::tensor::NearestNeighborIndex::Neighbor> _found_hits;
Algorithm _algorithm;
@@ -49,8 +49,7 @@ private:
void perform_top_k(const search::tensor::NearestNeighborIndex* nns_index);
public:
NearestNeighborBlueprint(const queryeval::FieldSpec& field,
- const tensor::ITensorAttribute& attr_tensor,
- std::unique_ptr<vespalib::eval::Value> query_tensor,
+ std::unique_ptr<search::tensor::DistanceCalculator> distance_calc,
uint32_t target_hits, bool approximate, uint32_t explore_additional_hits,
double distance_threshold,
double global_filter_lower_limit,
@@ -59,7 +58,7 @@ public:
NearestNeighborBlueprint& operator=(const NearestNeighborBlueprint&) = delete;
~NearestNeighborBlueprint();
const tensor::ITensorAttribute& get_attribute_tensor() const { return _attr_tensor; }
- const vespalib::eval::Value& get_query_tensor() const { return *_query_tensor; }
+ const vespalib::eval::Value& get_query_tensor() const { return _query_tensor; }
uint32_t get_target_hits() const { return _target_hits; }
uint32_t get_adjusted_target_hits() const { return _adjusted_target_hits; }
void set_global_filter(const GlobalFilter &global_filter, double estimated_hit_ratio) override;
diff --git a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.cpp b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.cpp
index 6a00568bd06..e06fcc614d8 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.cpp
+++ b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.cpp
@@ -2,6 +2,8 @@
#include "nearest_neighbor_iterator.h"
#include <vespa/searchlib/common/bitvector.h>
+#include <vespa/searchlib/tensor/distance_calculator.h>
+#include <vespa/searchlib/tensor/distance_function.h>
using search::tensor::ITensorAttribute;
using vespalib::ConstArrayRef;
@@ -34,11 +36,10 @@ public:
NearestNeighborImpl(Params params_in)
: NearestNeighborIterator(params_in),
- _lhs(params().queryTensor.cells()),
_lastScore(0.0)
{
- assert(is_compatible(params().tensorAttribute.getTensorType(),
- params().queryTensor.type()));
+ assert(is_compatible(params().distance_calc.attribute_tensor().getTensorType(),
+ params().distance_calc.query_tensor().type()));
}
~NearestNeighborImpl();
@@ -64,7 +65,7 @@ public:
}
void doUnpack(uint32_t docId) override {
- double score = params().distanceFunction->to_rawscore(_lastScore);
+ double score = params().distance_calc.function().to_rawscore(_lastScore);
params().tfmd.setRawScore(docId, score);
params().distanceHeap.used(_lastScore);
}
@@ -73,11 +74,9 @@ public:
private:
double computeDistance(uint32_t docId, double limit) {
- auto rhs = params().tensorAttribute.extract_cells_ref(docId);
- return params().distanceFunction->calc_with_limit(_lhs, rhs, limit);
+ return params().distance_calc.calc_with_limit(docId, limit);
}
- TypedCells _lhs;
double _lastScore;
};
@@ -105,14 +104,12 @@ std::unique_ptr<NearestNeighborIterator>
NearestNeighborIterator::create(
bool strict,
fef::TermFieldMatchData &tfmd,
- const vespalib::eval::Value &queryTensor,
- const search::tensor::ITensorAttribute &tensorAttribute,
+ const search::tensor::DistanceCalculator &distance_calc,
NearestNeighborDistanceHeap &distanceHeap,
- const search::BitVector *filter,
- const search::tensor::DistanceFunction *dist_fun)
+ const search::BitVector *filter)
{
- Params params(tfmd, queryTensor, tensorAttribute, distanceHeap, filter, dist_fun);
+ Params params(tfmd, distance_calc, distanceHeap, filter);
if (filter) {
return resolve_strict<true>(strict, params);
} else {
diff --git a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.h b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.h
index 66622288d84..0d8f70d15c2 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.h
+++ b/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_iterator.h
@@ -7,10 +7,11 @@
#include <vespa/eval/eval/value.h>
#include <vespa/searchlib/fef/termfieldmatchdata.h>
#include <vespa/searchlib/tensor/i_tensor_attribute.h>
-#include <vespa/searchlib/tensor/distance_function.h>
#include <vespa/vespalib/util/priority_queue.h>
#include <cmath>
+namespace search::tensor { class DistanceCalculator; }
+
namespace search::queryeval {
class NearestNeighborIterator : public SearchIterator
@@ -21,24 +22,18 @@ public:
struct Params {
fef::TermFieldMatchData &tfmd;
- const Value &queryTensor;
- const ITensorAttribute &tensorAttribute;
+ const search::tensor::DistanceCalculator &distance_calc;
NearestNeighborDistanceHeap &distanceHeap;
const search::BitVector *filter;
- const search::tensor::DistanceFunction *distanceFunction;
-
+
Params(fef::TermFieldMatchData &tfmd_in,
- const Value &queryTensor_in,
- const ITensorAttribute &tensorAttribute_in,
+ const search::tensor::DistanceCalculator &distance_calc_in,
NearestNeighborDistanceHeap &distanceHeap_in,
- const search::BitVector *filter_in,
- const search::tensor::DistanceFunction *distanceFunction_in)
+ const search::BitVector *filter_in)
: tfmd(tfmd_in),
- queryTensor(queryTensor_in),
- tensorAttribute(tensorAttribute_in),
+ distance_calc(distance_calc_in),
distanceHeap(distanceHeap_in),
- filter(filter_in),
- distanceFunction(distanceFunction_in)
+ filter(filter_in)
{}
};
@@ -49,11 +44,9 @@ public:
static std::unique_ptr<NearestNeighborIterator> create(
bool strict,
fef::TermFieldMatchData &tfmd,
- const Value &queryTensor,
- const search::tensor::ITensorAttribute &tensorAttribute,
+ const search::tensor::DistanceCalculator &distance_calc,
NearestNeighborDistanceHeap &distanceHeap,
- const search::BitVector *filter,
- const search::tensor::DistanceFunction *dist_fun);
+ const search::BitVector *filter);
const Params& params() const { return _params; }
private:
diff --git a/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.cpp b/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.cpp
index cd65f01025b..95264a79431 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.cpp
+++ b/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.cpp
@@ -18,13 +18,13 @@ class NeighborVectorIterator : public NnsIndexIterator
private:
fef::TermFieldMatchData &_tfmd;
const std::vector<Neighbor> &_hits;
- const search::tensor::DistanceFunction * const _dist_fun;
+ const search::tensor::DistanceFunction &_dist_fun;
uint32_t _idx;
double _last_abstract_dist;
public:
NeighborVectorIterator(fef::TermFieldMatchData &tfmd,
const std::vector<Neighbor> &hits,
- const search::tensor::DistanceFunction *dist_fun)
+ const search::tensor::DistanceFunction &dist_fun)
: _tfmd(tfmd),
_hits(hits),
_dist_fun(dist_fun),
@@ -54,7 +54,7 @@ public:
}
void doUnpack(uint32_t docId) override {
- double score = _dist_fun->to_rawscore(_last_abstract_dist);
+ double score = _dist_fun.to_rawscore(_last_abstract_dist);
_tfmd.setRawScore(docId, score);
}
@@ -65,7 +65,7 @@ std::unique_ptr<NnsIndexIterator>
NnsIndexIterator::create(
fef::TermFieldMatchData &tfmd,
const std::vector<Neighbor> &hits,
- const search::tensor::DistanceFunction *dist_fun)
+ const search::tensor::DistanceFunction &dist_fun)
{
return std::make_unique<NeighborVectorIterator>(tfmd, hits, dist_fun);
}
diff --git a/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.h b/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.h
index 019ac8579bd..031a603de49 100644
--- a/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.h
+++ b/searchlib/src/vespa/searchlib/queryeval/nns_index_iterator.h
@@ -16,7 +16,7 @@ public:
static std::unique_ptr<NnsIndexIterator> create(
fef::TermFieldMatchData &tfmd,
const std::vector<Hit> &hits,
- const search::tensor::DistanceFunction *dist_fun);
+ const search::tensor::DistanceFunction &dist_fun);
};
} // namespace
diff --git a/searchlib/src/vespa/searchlib/tensor/CMakeLists.txt b/searchlib/src/vespa/searchlib/tensor/CMakeLists.txt
index ae34cdd66c8..9e0ccb8d37a 100644
--- a/searchlib/src/vespa/searchlib/tensor/CMakeLists.txt
+++ b/searchlib/src/vespa/searchlib/tensor/CMakeLists.txt
@@ -11,6 +11,7 @@ vespa_add_library(searchlib_tensor OBJECT
direct_tensor_attribute.cpp
direct_tensor_saver.cpp
direct_tensor_store.cpp
+ distance_calculator.cpp
distance_function_factory.cpp
euclidean_distance.cpp
geo_degrees_distance.cpp
diff --git a/searchlib/src/vespa/searchlib/tensor/distance_calculator.cpp b/searchlib/src/vespa/searchlib/tensor/distance_calculator.cpp
new file mode 100644
index 00000000000..d6d5433ff15
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/tensor/distance_calculator.cpp
@@ -0,0 +1,137 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "distance_calculator.h"
+#include "distance_function_factory.h"
+#include "nearest_neighbor_index.h"
+#include <vespa/eval/eval/fast_value.h>
+#include <vespa/searchcommon/attribute/iattributevector.h>
+#include <vespa/vespalib/util/exceptions.h>
+#include <vespa/vespalib/util/stringfmt.h>
+
+using vespalib::IllegalArgumentException;
+using vespalib::eval::CellType;
+using vespalib::eval::FastValueBuilderFactory;
+using vespalib::eval::TypedCells;
+using vespalib::eval::Value;
+using vespalib::eval::ValueType;
+using vespalib::make_string;
+
+namespace {
+
+template<typename LCT, typename RCT>
+std::unique_ptr<Value>
+convert_cells(const ValueType& new_type, const Value& old_value)
+{
+ auto old_cells = old_value.cells().typify<LCT>();
+ auto builder = FastValueBuilderFactory::get().create_value_builder<RCT>(new_type);
+ auto new_cells = builder->add_subspace();
+ assert(old_cells.size() == new_cells.size());
+ auto p = new_cells.begin();
+ for (LCT value : old_cells) {
+ RCT conv(value);
+ *p++ = conv;
+ }
+ return builder->build(std::move(builder));
+}
+
+struct ConvertCellsSelector
+{
+ template <typename LCT, typename RCT>
+ static auto invoke(const ValueType& new_type, const Value& old_value) {
+ return convert_cells<LCT, RCT>(new_type, old_value);
+ }
+ auto operator() (CellType from, CellType to, const Value& old_value) const {
+ using MyTypify = vespalib::eval::TypifyCellType;
+ ValueType new_type = old_value.type().cell_cast(to);
+ return vespalib::typify_invoke<2,MyTypify,ConvertCellsSelector>(from, to, new_type, old_value);
+ }
+};
+
+bool
+is_compatible(const vespalib::eval::ValueType& lhs,
+ const vespalib::eval::ValueType& rhs)
+{
+ return (lhs.dimensions() == rhs.dimensions());
+}
+
+}
+
+namespace search::tensor {
+
+DistanceCalculator::DistanceCalculator(const tensor::ITensorAttribute& attr_tensor,
+ const vespalib::eval::Value& query_tensor_in)
+ : _attr_tensor(attr_tensor),
+ _query_tensor_uptr(),
+ _query_tensor(&query_tensor_in),
+ _query_tensor_cells(),
+ _dist_fun_uptr(make_distance_function(_attr_tensor.distance_metric(),
+ _attr_tensor.getTensorType().cell_type())),
+ _dist_fun(_dist_fun_uptr.get())
+{
+ assert(_dist_fun);
+ auto nns_index = _attr_tensor.nearest_neighbor_index();
+ if (nns_index) {
+ _dist_fun = nns_index->distance_function();
+ assert(_dist_fun);
+ }
+ auto query_ct = _query_tensor->cells().type;
+ CellType required_ct = _dist_fun->expected_cell_type();
+ if (query_ct != required_ct) {
+ ConvertCellsSelector converter;
+ _query_tensor_uptr = converter(query_ct, required_ct, *_query_tensor);
+ _query_tensor = _query_tensor_uptr.get();
+ }
+ _query_tensor_cells = _query_tensor->cells();
+}
+
+DistanceCalculator::DistanceCalculator(const tensor::ITensorAttribute& attr_tensor,
+ const vespalib::eval::Value& query_tensor_in,
+ const DistanceFunction& function_in)
+ : _attr_tensor(attr_tensor),
+ _query_tensor_uptr(),
+ _query_tensor(&query_tensor_in),
+ _query_tensor_cells(_query_tensor->cells()),
+ _dist_fun_uptr(),
+ _dist_fun(&function_in)
+{
+}
+
+DistanceCalculator::~DistanceCalculator() = default;
+
+namespace {
+
+
+
+}
+
+std::unique_ptr<DistanceCalculator>
+DistanceCalculator::make_with_validation(const search::attribute::IAttributeVector& attr,
+ const vespalib::eval::Value& query_tensor_in)
+{
+ const ITensorAttribute* attr_tensor = attr.asTensorAttribute();
+ if (attr_tensor == nullptr) {
+ throw IllegalArgumentException("Attribute is not a tensor");
+ }
+ const auto& at_type = attr_tensor->getTensorType();
+ if ((!at_type.is_dense()) || (at_type.dimensions().size() != 1)) {
+ throw IllegalArgumentException(make_string("Attribute tensor type (%s) is not a dense tensor of order 1",
+ at_type.to_spec().c_str()));
+ }
+ const auto& qt_type = query_tensor_in.type();
+ if (!qt_type.is_dense()) {
+ throw IllegalArgumentException(make_string("Query tensor type (%s) is not a dense tensor",
+ qt_type.to_spec().c_str()));
+ }
+ if (!is_compatible(at_type, qt_type)) {
+ throw IllegalArgumentException(make_string("Attribute tensor type (%s) and query tensor type (%s) are not compatible",
+ at_type.to_spec().c_str(), qt_type.to_spec().c_str()));
+ }
+ if (!attr_tensor->supports_extract_cells_ref()) {
+ throw IllegalArgumentException(make_string("Attribute tensor does not support access to tensor data (type=%s)",
+ at_type.to_spec().c_str()));
+ }
+ return std::make_unique<DistanceCalculator>(*attr_tensor, query_tensor_in);
+}
+
+}
+
diff --git a/searchlib/src/vespa/searchlib/tensor/distance_calculator.h b/searchlib/src/vespa/searchlib/tensor/distance_calculator.h
new file mode 100644
index 00000000000..3ef41906b92
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/tensor/distance_calculator.h
@@ -0,0 +1,64 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
+#include "distance_function.h"
+#include "i_tensor_attribute.h"
+
+namespace vespalib::eval { struct Value; }
+
+namespace search::attribute { class IAttributeVector; }
+
+namespace search::tensor {
+
+/**
+ * Class used to calculate the distance between two n-dimensional vectors,
+ * where one is stored in a TensorAttribute and the other comes from the query.
+ *
+ * The distance function to use is defined in the TensorAttribute.
+ */
+class DistanceCalculator {
+private:
+ const tensor::ITensorAttribute& _attr_tensor;
+ std::unique_ptr<vespalib::eval::Value> _query_tensor_uptr;
+ const vespalib::eval::Value* _query_tensor;
+ vespalib::eval::TypedCells _query_tensor_cells;
+ std::unique_ptr<DistanceFunction> _dist_fun_uptr;
+ const DistanceFunction* _dist_fun;
+
+public:
+ DistanceCalculator(const tensor::ITensorAttribute& attr_tensor,
+ const vespalib::eval::Value& query_tensor_in);
+
+ /**
+ * Only used by unit tests where ownership of query tensor and distance function is handled outside.
+ */
+ DistanceCalculator(const tensor::ITensorAttribute& attr_tensor,
+ const vespalib::eval::Value& query_tensor_in,
+ const DistanceFunction& function_in);
+
+ ~DistanceCalculator();
+
+ const tensor::ITensorAttribute& attribute_tensor() const { return _attr_tensor; }
+ const vespalib::eval::Value& query_tensor() const { return *_query_tensor; }
+ const DistanceFunction& function() const { return *_dist_fun; }
+
+ double calc_raw_score(uint32_t docid) const {
+ double distance = _dist_fun->calc(_query_tensor_cells, _attr_tensor.extract_cells_ref(docid));
+ return _dist_fun->to_rawscore(distance);
+ }
+
+ double calc_with_limit(uint32_t docid, double limit) const {
+ return _dist_fun->calc_with_limit(_query_tensor_cells, _attr_tensor.extract_cells_ref(docid), limit);
+ }
+
+ /**
+ * Create a calculator for the given attribute tensor and query tensor, if possible.
+ *
+ * Throws vespalib::IllegalArgumentException if the inputs are not supported or incompatible.
+ */
+ static std::unique_ptr<DistanceCalculator> make_with_validation(const search::attribute::IAttributeVector& attr,
+ const vespalib::eval::Value& query_tensor_in);
+
+};
+
+}
diff --git a/searchlib/src/vespa/searchlib/tensor/distance_function.h b/searchlib/src/vespa/searchlib/tensor/distance_function.h
index 77873cb7ced..d5ebf656189 100644
--- a/searchlib/src/vespa/searchlib/tensor/distance_function.h
+++ b/searchlib/src/vespa/searchlib/tensor/distance_function.h
@@ -23,7 +23,7 @@ public:
DistanceFunction(vespalib::eval::CellType expected) : _expect_cell_type(expected) {}
- virtual ~DistanceFunction() {}
+ virtual ~DistanceFunction() = default;
// input (query) vectors must be converted to this cell type:
vespalib::eval::CellType expected_cell_type() const {
diff --git a/searchlib/src/vespa/searchlib/test/CMakeLists.txt b/searchlib/src/vespa/searchlib/test/CMakeLists.txt
index 0d56fb8b4be..ed884a46217 100644
--- a/searchlib/src/vespa/searchlib/test/CMakeLists.txt
+++ b/searchlib/src/vespa/searchlib/test/CMakeLists.txt
@@ -13,6 +13,7 @@ vespa_add_library(searchlib_test
$<TARGET_OBJECTS:searchlib_test_gtest_migration>
DEPENDS
searchlib
+ searchlib_searchlib_test_features
searchlib_searchlib_test_memoryindex
GTest::GTest
)
diff --git a/searchlib/src/vespa/searchlib/test/features/CMakeLists.txt b/searchlib/src/vespa/searchlib/test/features/CMakeLists.txt
new file mode 100644
index 00000000000..ba70fe57e88
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/test/features/CMakeLists.txt
@@ -0,0 +1,7 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+vespa_add_library(searchlib_searchlib_test_features
+ SOURCES
+ distance_closeness_fixture.cpp
+ DEPENDS
+ searchlib
+)
diff --git a/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.cpp b/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.cpp
new file mode 100644
index 00000000000..e161a4e9839
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.cpp
@@ -0,0 +1,112 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "distance_closeness_fixture.h"
+#include <vespa/eval/eval/simple_value.h>
+#include <vespa/eval/eval/value.h>
+#include <vespa/eval/eval/value_codec.h>
+#include <vespa/eval/eval/value_type.h>
+#include <vespa/searchcommon/attribute/config.h>
+#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
+
+using search::attribute::BasicType;
+using search::attribute::CollectionType;
+using search::attribute::Config;
+using search::attribute::DistanceMetric;
+using search::fef::test::IndexEnvironment;
+using search::fef::test::QueryEnvironment;
+using search::tensor::DenseTensorAttribute;
+using vespalib::eval::SimpleValue;
+using vespalib::eval::TensorSpec;
+using vespalib::eval::Value;
+using vespalib::eval::ValueType;
+
+namespace search::features::test {
+
+namespace {
+
+std::shared_ptr<DenseTensorAttribute>
+create_tensor_attribute(const vespalib::string& attr_name,
+ const vespalib::string& tensor_type,
+ uint32_t docid_limit)
+{
+ Config cfg(BasicType::TENSOR, CollectionType::SINGLE);
+ cfg.setTensorType(ValueType::from_spec(tensor_type));
+ cfg.set_distance_metric(DistanceMetric::Euclidean);
+ auto result = std::make_shared<DenseTensorAttribute>(attr_name, cfg);
+ result->addReservedDoc();
+ result->addDocs(docid_limit-1);
+ result->commit();
+ return result;
+}
+
+}
+
+FeatureDumpFixture::~FeatureDumpFixture() = default;
+
+DistanceClosenessFixture::DistanceClosenessFixture(size_t fooCnt, size_t barCnt,
+ const Labels& labels,
+ const vespalib::string& featureName,
+ const vespalib::string& query_tensor)
+ : queryEnv(&indexEnv), rankSetup(factory, indexEnv),
+ mdl(), match_data(), rankProgram(), fooHandles(), barHandles(),
+ tensor_attr(),
+ docid_limit(11)
+{
+ for (size_t i = 0; i < fooCnt; ++i) {
+ uint32_t fieldId = indexEnv.getFieldByName("foo")->id();
+ fooHandles.push_back(mdl.allocTermField(fieldId));
+ SimpleTermData term;
+ term.setUniqueId(i + 1);
+ term.addField(fieldId).setHandle(fooHandles.back());
+ queryEnv.getTerms().push_back(term);
+ }
+ for (size_t i = 0; i < barCnt; ++i) {
+ uint32_t fieldId = indexEnv.getFieldByName("bar")->id();
+ barHandles.push_back(mdl.allocTermField(fieldId));
+ SimpleTermData term;
+ term.setUniqueId(fooCnt + i + 1);
+ term.addField(fieldId).setHandle(barHandles.back());
+ if (!query_tensor.empty()) {
+ term.set_query_tensor_name("qbar");
+ }
+ queryEnv.getTerms().push_back(term);
+ }
+ if (!query_tensor.empty()) {
+ tensor_attr = create_tensor_attribute("bar", "tensor(x[2])", docid_limit);
+ indexEnv.getAttributeMap().add(tensor_attr);
+ set_query_tensor("qbar", "tensor(x[2])", TensorSpec::from_expr(query_tensor));
+ }
+ labels.inject(queryEnv.getProperties());
+ rankSetup.setFirstPhaseRank(featureName);
+ rankSetup.setIgnoreDefaultRankFeatures(true);
+ ASSERT_TRUE(rankSetup.compile());
+ rankSetup.prepareSharedState(queryEnv, queryEnv.getObjectStore());
+ match_data = mdl.createMatchData();
+ rankProgram = rankSetup.create_first_phase_program();
+ rankProgram->setup(*match_data, queryEnv);
+}
+
+DistanceClosenessFixture::~DistanceClosenessFixture() = default;
+
+void
+DistanceClosenessFixture::set_attribute_tensor(uint32_t docid, const vespalib::eval::TensorSpec& spec)
+{
+ auto tensor = SimpleValue::from_spec(spec);
+ tensor_attr->setTensor(docid, *tensor);
+ tensor_attr->commit();
+}
+
+void
+DistanceClosenessFixture::set_query_tensor(const vespalib::string& query_tensor_name,
+ const vespalib::string& tensor_type,
+ const TensorSpec& spec)
+{
+ search::fef::indexproperties::type::QueryFeature::set(indexEnv.getProperties(), query_tensor_name, tensor_type);
+ auto tensor = SimpleValue::from_spec(spec);
+ vespalib::nbostream stream;
+ vespalib::eval::encode_value(*tensor, stream);
+ queryEnv.getProperties().add(query_tensor_name, vespalib::stringref(stream.peek(), stream.size()));
+}
+
+}
+
diff --git a/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.h b/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.h
new file mode 100644
index 00000000000..cc1c0a6fb15
--- /dev/null
+++ b/searchlib/src/vespa/searchlib/test/features/distance_closeness_fixture.h
@@ -0,0 +1,84 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include <vespa/searchlib/features/setup.h>
+#include <vespa/searchlib/fef/fef.h>
+#include <vespa/searchlib/fef/test/indexenvironment.h>
+#include <vespa/searchlib/fef/test/indexenvironmentbuilder.h>
+#include <vespa/searchlib/fef/test/labels.h>
+#include <vespa/searchlib/fef/test/queryenvironment.h>
+#include <vespa/vespalib/testkit/test_kit.h>
+
+using namespace search::fef;
+using namespace search::fef::test;
+
+namespace search::tensor { class DenseTensorAttribute; }
+namespace vespalib::eval { class TensorSpec; }
+
+namespace search::features::test {
+
+struct BlueprintFactoryFixture {
+ BlueprintFactory factory;
+ BlueprintFactoryFixture() : factory()
+ {
+ setup_search_features(factory);
+ }
+};
+
+struct IndexEnvironmentFixture {
+ IndexEnvironment indexEnv;
+ IndexEnvironmentFixture() : indexEnv()
+ {
+ IndexEnvironmentBuilder builder(indexEnv);
+ builder.addField(FieldType::ATTRIBUTE, FieldInfo::CollectionType::SINGLE, FieldInfo::DataType::INT64, "foo");
+ builder.addField(FieldType::ATTRIBUTE, FieldInfo::CollectionType::SINGLE, FieldInfo::DataType::TENSOR, "bar");
+ }
+};
+
+struct FeatureDumpFixture : public IDumpFeatureVisitor {
+ virtual void visitDumpFeature(const vespalib::string &) override {
+ TEST_ERROR("no features should be dumped");
+ }
+ FeatureDumpFixture() : IDumpFeatureVisitor() {}
+ ~FeatureDumpFixture() override;
+};
+
+/**
+ * Fixture used by unit tests for distance and closeness rank features.
+ */
+struct DistanceClosenessFixture : BlueprintFactoryFixture, IndexEnvironmentFixture {
+ QueryEnvironment queryEnv;
+ RankSetup rankSetup;
+ MatchDataLayout mdl;
+ MatchData::UP match_data;
+ RankProgram::UP rankProgram;
+ std::vector<TermFieldHandle> fooHandles;
+ std::vector<TermFieldHandle> barHandles;
+ std::shared_ptr<search::tensor::DenseTensorAttribute> tensor_attr;
+ uint32_t docid_limit;
+ DistanceClosenessFixture(size_t fooCnt, size_t barCnt,
+ const Labels &labels, const vespalib::string &featureName,
+ const vespalib::string& query_tensor = "");
+ ~DistanceClosenessFixture();
+ void set_attribute_tensor(uint32_t docid, const vespalib::eval::TensorSpec& spec);
+ void set_query_tensor(const vespalib::string& query_tensor_name,
+ const vespalib::string& tensor_type,
+ const vespalib::eval::TensorSpec& spec);
+ feature_t getScore(uint32_t docId) {
+ return Utils::getScoreFeature(*rankProgram, docId);
+ }
+ void setScore(TermFieldHandle handle, uint32_t docId, feature_t score) {
+ match_data->resolveTermField(handle)->setRawScore(docId, score);
+ }
+ void setFooScore(uint32_t i, uint32_t docId, feature_t distance) {
+ ASSERT_LESS(i, fooHandles.size());
+ setScore(fooHandles[i], docId, 1.0/(1.0+distance));
+ }
+ void setBarScore(uint32_t i, uint32_t docId, feature_t distance) {
+ ASSERT_LESS(i, barHandles.size());
+ setScore(barHandles[i], docId, 1.0/(1.0+distance));
+ }
+};
+
+}
diff --git a/searchsummary/CMakeLists.txt b/searchsummary/CMakeLists.txt
index d51e29dbd00..8c34f1b2016 100644
--- a/searchsummary/CMakeLists.txt
+++ b/searchsummary/CMakeLists.txt
@@ -19,8 +19,10 @@ vespa_define_module(
src/tests/docsummary
src/tests/docsummary/attribute_combiner
src/tests/docsummary/attributedfw
+ src/tests/docsummary/document_id_dfw
src/tests/docsummary/matched_elements_filter
src/tests/docsummary/slime_summary
+ src/tests/docsummary/summary_field_converter
src/tests/extractkeywords
src/tests/juniper
)
diff --git a/searchsummary/src/tests/docsumformat/docsum-pack.cpp b/searchsummary/src/tests/docsumformat/docsum-pack.cpp
index ed1ba23017c..07aceea83e0 100644
--- a/searchsummary/src/tests/docsumformat/docsum-pack.cpp
+++ b/searchsummary/src/tests/docsumformat/docsum-pack.cpp
@@ -113,7 +113,7 @@ MyApp::Equal(GeneralResult *a, GeneralResult *b)
void
MyApp::TestIntValue(uint32_t line, GeneralResult *gres, const char *field, uint32_t value)
{
- ResEntry *entry = (gres != nullptr) ? gres->GetEntry(field) : nullptr;
+ ResEntry *entry = (gres != nullptr) ? gres->GetPresentEntry(field) : nullptr;
bool rc = (entry != nullptr &&
entry->_type == RES_INT &&
@@ -125,7 +125,7 @@ MyApp::TestIntValue(uint32_t line, GeneralResult *gres, const char *field, uint3
void
MyApp::TestDoubleValue(uint32_t line, GeneralResult *gres, const char *field, double value)
{
- ResEntry *entry = (gres != nullptr) ? gres->GetEntry(field) : nullptr;
+ ResEntry *entry = (gres != nullptr) ? gres->GetPresentEntry(field) : nullptr;
bool rc = (entry != nullptr &&
entry->_type == RES_DOUBLE &&
@@ -137,7 +137,7 @@ MyApp::TestDoubleValue(uint32_t line, GeneralResult *gres, const char *field, do
void
MyApp::TestInt64Value(uint32_t line, GeneralResult *gres, const char *field, uint64_t value)
{
- ResEntry *entry = (gres != nullptr) ? gres->GetEntry(field) : nullptr;
+ ResEntry *entry = (gres != nullptr) ? gres->GetPresentEntry(field) : nullptr;
bool rc = (entry != nullptr &&
entry->_type == RES_INT64 &&
@@ -150,7 +150,7 @@ MyApp::TestInt64Value(uint32_t line, GeneralResult *gres, const char *field, uin
void
MyApp::TestStringValue(uint32_t line, GeneralResult *gres, const char *field, const char *value)
{
- ResEntry *entry = (gres != nullptr) ? gres->GetEntry(field) : nullptr;
+ ResEntry *entry = (gres != nullptr) ? gres->GetPresentEntry(field) : nullptr;
bool rc = (entry != nullptr &&
entry->_type == RES_STRING &&
@@ -168,7 +168,7 @@ MyApp::TestStringValue(uint32_t line, GeneralResult *gres, const char *field, co
void
MyApp::TestDataValue(uint32_t line, GeneralResult *gres, const char *field, const char *value)
{
- ResEntry *entry = (gres != nullptr) ? gres->GetEntry(field) : nullptr;
+ ResEntry *entry = (gres != nullptr) ? gres->GetPresentEntry(field) : nullptr;
bool rc = (entry != nullptr &&
entry->_type == RES_DATA &&
diff --git a/searchsummary/src/tests/docsummary/attribute_combiner/attribute_combiner_test.cpp b/searchsummary/src/tests/docsummary/attribute_combiner/attribute_combiner_test.cpp
index d5a908fc8bd..7265dd89be4 100644
--- a/searchsummary/src/tests/docsummary/attribute_combiner/attribute_combiner_test.cpp
+++ b/searchsummary/src/tests/docsummary/attribute_combiner/attribute_combiner_test.cpp
@@ -5,7 +5,7 @@
#include <vespa/searchlib/common/matching_elements.h>
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/searchlib/util/slime_output_raw_buf_adapter.h>
-#include <vespa/searchsummary/docsummary/docsumfieldwriter.h>
+#include <vespa/searchsummary/docsummary/docsum_field_writer.h>
#include <vespa/searchsummary/docsummary/docsumstate.h>
#include <vespa/searchsummary/docsummary/docsum_field_writer_state.h>
#include <vespa/searchsummary/docsummary/attribute_combiner_dfw.h>
@@ -24,7 +24,7 @@ using search::docsummary::AttributeCombinerDFW;
using search::docsummary::GetDocsumsState;
using search::docsummary::GetDocsumsStateCallback;
using search::docsummary::IDocsumEnvironment;
-using search::docsummary::IDocsumFieldWriter;
+using search::docsummary::DocsumFieldWriter;
using search::docsummary::test::MockAttributeManager;
using search::docsummary::test::MockStateCallback;
using search::docsummary::test::SlimeValue;
@@ -34,7 +34,7 @@ namespace {
struct AttributeCombinerTest : public ::testing::Test
{
MockAttributeManager attrs;
- std::unique_ptr<IDocsumFieldWriter> writer;
+ std::unique_ptr<DocsumFieldWriter> writer;
MockStateCallback callback;
GetDocsumsState state;
std::shared_ptr<search::MatchingElementsFields> _matching_elems_fields;
diff --git a/searchsummary/src/tests/docsummary/attributedfw/attributedfw_test.cpp b/searchsummary/src/tests/docsummary/attributedfw/attributedfw_test.cpp
index 67d505582d8..42443cf1058 100644
--- a/searchsummary/src/tests/docsummary/attributedfw/attributedfw_test.cpp
+++ b/searchsummary/src/tests/docsummary/attributedfw/attributedfw_test.cpp
@@ -16,7 +16,7 @@ using search::attribute::BasicType;
using search::attribute::CollectionType;
using search::docsummary::AttributeDFWFactory;
using search::docsummary::GetDocsumsState;
-using search::docsummary::IDocsumFieldWriter;
+using search::docsummary::DocsumFieldWriter;
using search::docsummary::test::MockAttributeManager;
using search::docsummary::test::MockStateCallback;
using search::docsummary::test::SlimeValue;
@@ -26,7 +26,7 @@ using ElementVector = std::vector<uint32_t>;
class AttributeDFWTest : public ::testing::Test {
protected:
MockAttributeManager _attrs;
- std::unique_ptr<IDocsumFieldWriter> _writer;
+ std::unique_ptr<DocsumFieldWriter> _writer;
MockStateCallback _callback;
GetDocsumsState _state;
std::shared_ptr<search::MatchingElementsFields> _matching_elems_fields;
diff --git a/searchsummary/src/tests/docsummary/document_id_dfw/CMakeLists.txt b/searchsummary/src/tests/docsummary/document_id_dfw/CMakeLists.txt
new file mode 100644
index 00000000000..3591a36c8de
--- /dev/null
+++ b/searchsummary/src/tests/docsummary/document_id_dfw/CMakeLists.txt
@@ -0,0 +1,10 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+vespa_add_executable(searchsummary_document_id_dfw_test_app TEST
+ SOURCES
+ document_id_dfw_test.cpp
+ DEPENDS
+ searchsummary
+ searchsummary_test
+ GTest::GTest
+)
+vespa_add_test(NAME searchsummary_document_id_dfw_test_app COMMAND searchsummary_document_id_dfw_test_app)
diff --git a/searchsummary/src/tests/docsummary/document_id_dfw/document_id_dfw_test.cpp b/searchsummary/src/tests/docsummary/document_id_dfw/document_id_dfw_test.cpp
new file mode 100644
index 00000000000..0ea78b722c0
--- /dev/null
+++ b/searchsummary/src/tests/docsummary/document_id_dfw/document_id_dfw_test.cpp
@@ -0,0 +1,153 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include <vespa/document/base/documentid.h>
+#include <vespa/document/datatype/documenttype.h>
+#include <vespa/document/fieldvalue/document.h>
+#include <vespa/document/repo/configbuilder.h>
+#include <vespa/document/repo/documenttyperepo.h>
+#include <vespa/searchsummary/docsummary/docsum_blob_entry_filter.h>
+#include <vespa/searchsummary/docsummary/docsum_store_document.h>
+#include <vespa/searchsummary/docsummary/document_id_dfw.h>
+#include <vespa/searchsummary/docsummary/general_result.h>
+#include <vespa/searchsummary/docsummary/resultconfig.h>
+#include <vespa/searchsummary/docsummary/resultpacker.h>
+#include <vespa/vespalib/data/slime/slime.h>
+#include <vespa/vespalib/gtest/gtest.h>
+#include <iostream>
+#include <memory>
+
+using document::Document;
+using document::DocumentId;
+using document::DocumentType;
+using document::DocumentTypeRepo;
+using document::config_builder::DocumenttypesConfigBuilderHelper;
+using document::config_builder::Struct;
+using search::docsummary::DocsumBlobEntryFilter;
+using search::docsummary::DocsumStoreDocument;
+using search::docsummary::DocsumStoreValue;
+using search::docsummary::DocumentIdDFW;
+using search::docsummary::IDocsumStoreDocument;
+using search::docsummary::ResultClass;
+using search::docsummary::ResultConfig;
+using search::docsummary::ResultPacker;
+using search::docsummary::GeneralResult;
+using vespalib::Slime;
+using vespalib::slime::Cursor;
+using vespalib::slime::ObjectInserter;
+using vespalib::slime::SlimeInserter;
+
+namespace {
+
+const int32_t doc_type_id = 787121340;
+const vespalib::string doc_type_name = "test";
+const vespalib::string header_name = doc_type_name + ".header";
+const vespalib::string body_name = doc_type_name + ".body";
+
+
+std::unique_ptr<const DocumentTypeRepo>
+make_doc_type_repo()
+{
+ DocumenttypesConfigBuilderHelper builder;
+ builder.document(doc_type_id, doc_type_name,
+ Struct(header_name), Struct(body_name));
+ return std::unique_ptr<const DocumentTypeRepo>(new DocumentTypeRepo(builder.config()));
+}
+
+class DocumentIdDFWTest : public ::testing::Test
+{
+ vespalib::string _field_name;
+ vespalib::Memory _field_name_view;
+ DocsumBlobEntryFilter _docsum_blob_entry_filter;
+ std::unique_ptr<ResultConfig> _result_config;
+ std::unique_ptr<ResultPacker> _packer; // owns docsum blob
+ std::unique_ptr<const DocumentTypeRepo> _repo;
+ const DocumentType* _document_type;
+
+protected:
+ DocumentIdDFWTest();
+ ~DocumentIdDFWTest() override;
+
+ std::unique_ptr<DocsumStoreDocument> make_docsum_store_document(const vespalib::string &id);
+ std::unique_ptr<DocsumStoreValue> make_docsum_store_value(std::unique_ptr<DocsumStoreDocument> doc);
+ vespalib::Slime write(const DocsumStoreValue& value);
+ vespalib::Memory get_field_name_view() const noexcept { return _field_name_view; }
+};
+
+DocumentIdDFWTest::DocumentIdDFWTest()
+ : testing::Test(),
+ _field_name("documentid"),
+ _field_name_view(_field_name.data(), _field_name.size()),
+ _docsum_blob_entry_filter(DocsumBlobEntryFilter().add_skip(search::docsummary::RES_LONG_STRING)),
+ _result_config(std::make_unique<ResultConfig>(_docsum_blob_entry_filter)),
+ _packer(std::make_unique<ResultPacker>(_result_config.get())),
+ _repo(make_doc_type_repo()),
+ _document_type(_repo->getDocumentType(doc_type_name))
+{
+ auto* cfg = _result_config->AddResultClass("default", 0);
+ cfg->AddConfigEntry(_field_name.c_str(), search::docsummary::RES_LONG_STRING);
+ _result_config->CreateEnumMaps();
+}
+
+
+DocumentIdDFWTest::~DocumentIdDFWTest() = default;
+
+
+std::unique_ptr<DocsumStoreDocument>
+DocumentIdDFWTest::make_docsum_store_document(const vespalib::string& id)
+{
+ auto doc = std::make_unique<Document>(*_document_type, DocumentId(id));
+ doc->setRepo(*_repo);
+ return std::make_unique<DocsumStoreDocument>(std::move(doc));
+}
+
+std::unique_ptr<DocsumStoreValue>
+DocumentIdDFWTest::make_docsum_store_value(std::unique_ptr<DocsumStoreDocument> doc)
+{
+ EXPECT_TRUE(_packer->Init(0));
+ const char *ptr = nullptr;
+ uint32_t len = 0;
+ EXPECT_TRUE(_packer->GetDocsumBlob(&ptr, &len));
+ return std::make_unique<DocsumStoreValue>(ptr, len, std::move(doc));
+}
+
+vespalib::Slime
+DocumentIdDFWTest::write(const DocsumStoreValue& value)
+{
+ auto result = std::make_unique<GeneralResult>(_result_config->LookupResultClass(0));
+ EXPECT_TRUE(result->inplaceUnpack(value));
+ Slime slime;
+ SlimeInserter top_inserter(slime);
+ Cursor & docsum = top_inserter.insertObject();
+ ObjectInserter field_inserter(docsum, _field_name_view);
+ DocumentIdDFW writer;
+ writer.insertField(0, result.get(), nullptr, search::docsummary::RES_LONG_STRING, field_inserter);
+ return slime;
+}
+
+TEST_F(DocumentIdDFWTest, insert_document_id)
+{
+ vespalib::string id("id::test::0");
+ auto doc = make_docsum_store_document(id);
+ auto dsvalue = make_docsum_store_value(std::move(doc));
+ auto slime = write(*dsvalue);
+ EXPECT_TRUE(slime.get()[get_field_name_view()].valid());
+ EXPECT_EQ(id, slime.get()[get_field_name_view()].asString().make_string());
+}
+
+TEST_F(DocumentIdDFWTest, insert_document_id_no_document_doc)
+{
+ auto dsvalue = make_docsum_store_value(std::make_unique<DocsumStoreDocument>(std::unique_ptr<Document>()));
+ auto slime = write(*dsvalue);
+ EXPECT_FALSE(slime.get()[get_field_name_view()].valid());
+}
+
+TEST_F(DocumentIdDFWTest, insert_document_id_no_docsum_store_doc)
+{
+ auto dsvalue = make_docsum_store_value({});
+ auto slime = write(*dsvalue);
+ EXPECT_FALSE(slime.get()[get_field_name_view()].valid());
+}
+
+}
+
+GTEST_MAIN_RUN_ALL_TESTS()
diff --git a/searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp b/searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp
index de6b704189d..82aa9ceba92 100644
--- a/searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp
+++ b/searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp
@@ -15,8 +15,11 @@
#include <vespa/searchlib/common/matching_elements.h>
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/searchlib/util/slime_output_raw_buf_adapter.h>
+#include <vespa/searchsummary/docsummary/docsum_store_document.h>
+#include <vespa/searchsummary/docsummary/docsumstorevalue.h>
#include <vespa/searchsummary/docsummary/docsumstate.h>
#include <vespa/searchsummary/docsummary/idocsumenvironment.h>
+#include <vespa/searchsummary/docsummary/general_result.h>
#include <vespa/searchsummary/docsummary/matched_elements_filter_dfw.h>
#include <vespa/searchsummary/docsummary/resultconfig.h>
#include <vespa/searchsummary/docsummary/resultpacker.h>
@@ -132,7 +135,7 @@ public:
const char* buf;
uint32_t buf_len;
assert(_packer.GetDocsumBlob(&buf, &buf_len));
- return DocsumStoreValue(buf, buf_len, std::move(doc));
+ return DocsumStoreValue(buf, buf_len, std::make_unique<DocsumStoreDocument>(std::move(doc)));
}
};
@@ -214,7 +217,7 @@ public:
{
}
~MatchedElementsFilterTest();
- std::unique_ptr<IDocsumFieldWriter> make_field_writer(const std::string& input_field_name) {
+ std::unique_ptr<DocsumFieldWriter> make_field_writer(const std::string& input_field_name) {
int input_field_enum = _doc_store.get_config().GetFieldNameEnum().Lookup(input_field_name.c_str());
return MatchedElementsFilterDFW::create(input_field_name, input_field_enum,
_attr_ctx, _fields);
diff --git a/searchsummary/src/tests/docsummary/positionsdfw_test.cpp b/searchsummary/src/tests/docsummary/positionsdfw_test.cpp
index 11f0d0eb6d6..60584b26e31 100644
--- a/searchsummary/src/tests/docsummary/positionsdfw_test.cpp
+++ b/searchsummary/src/tests/docsummary/positionsdfw_test.cpp
@@ -4,7 +4,7 @@
#include <vespa/searchlib/attribute/extendableattributes.h>
#include <vespa/searchlib/attribute/iattributemanager.h>
#include <vespa/searchlib/common/matching_elements.h>
-#include <vespa/searchsummary/docsummary/docsumfieldwriter.h>
+#include <vespa/searchsummary/docsummary/docsum_field_writer.h>
#include <vespa/searchsummary/docsummary/positionsdfw.h>
#include <vespa/searchsummary/docsummary/idocsumenvironment.h>
#include <vespa/searchsummary/docsummary/docsumstate.h>
diff --git a/searchsummary/src/tests/docsummary/summary_field_converter/CMakeLists.txt b/searchsummary/src/tests/docsummary/summary_field_converter/CMakeLists.txt
new file mode 100644
index 00000000000..cfda566ee6c
--- /dev/null
+++ b/searchsummary/src/tests/docsummary/summary_field_converter/CMakeLists.txt
@@ -0,0 +1,8 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+vespa_add_executable(searchsummary_summary_field_converter_test_app
+ SOURCES
+ summary_field_converter_test.cpp
+ DEPENDS
+ searchsummary
+)
+vespa_add_test(NAME searchsummary_summary_field_converter_test_app COMMAND searchsummary_summary_field_converter_test_app)
diff --git a/searchcore/src/tests/proton/docsummary/summaryfieldconverter_test.cpp b/searchsummary/src/tests/docsummary/summary_field_converter/summary_field_converter_test.cpp
index 06766ba370a..06766ba370a 100644
--- a/searchcore/src/tests/proton/docsummary/summaryfieldconverter_test.cpp
+++ b/searchsummary/src/tests/docsummary/summary_field_converter/summary_field_converter_test.cpp
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/CMakeLists.txt b/searchsummary/src/vespa/searchsummary/docsummary/CMakeLists.txt
index 1f6004111cc..f27bac80d5b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/CMakeLists.txt
+++ b/searchsummary/src/vespa/searchsummary/docsummary/CMakeLists.txt
@@ -5,29 +5,35 @@ vespa_add_library(searchsummary_docsummary OBJECT
attribute_combiner_dfw.cpp
attribute_field_writer.cpp
attributedfw.cpp
+ check_undefined_value_visitor.cpp
+ copy_dfw.cpp
docsumconfig.cpp
- docsumfieldwriter.cpp
+ docsum_field_writer.cpp
+ docsum_store_document.cpp
docsumstate.cpp
docsumstorevalue.cpp
docsumwriter.cpp
+ document_id_dfw.cpp
dynamicteaserdfw.cpp
+ empty_dfw.cpp
general_result.cpp
geoposdfw.cpp
getdocsumargs.cpp
+ juniper_input.cpp
juniperproperties.cpp
keywordextractor.cpp
linguisticsannotation.cpp
matched_elements_filter_dfw.cpp
positionsdfw.cpp
rankfeaturesdfw.cpp
+ res_type_utils.cpp
resultclass.cpp
resultconfig.cpp
resultpacker.cpp
searchdatatype.cpp
+ simple_dfw.cpp
struct_fields_resolver.cpp
struct_map_attribute_combiner_dfw.cpp
summaryfeaturesdfw.cpp
summaryfieldconverter.cpp
- textextractordfw.cpp
- tokenizer.cpp
)
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.cpp
index ff5c2c5e05b..f308795a1bc 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.cpp
@@ -9,6 +9,7 @@
#include <vespa/searchlib/common/matching_elements.h>
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/vespalib/data/slime/cursor.h>
+#include <vespa/vespalib/data/slime/inserter.h>
#include <vespa/vespalib/util/stash.h>
#include <algorithm>
#include <cassert>
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.h
index 18b4fd34e66..e5bed876b63 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/array_attribute_combiner_dfw.h
@@ -3,6 +3,7 @@
#pragma once
#include "attribute_combiner_dfw.h"
+#include <vector>
namespace search::attribute { class IAttributeContext; }
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp
index 79c11b20479..bf5578f38d6 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp
@@ -18,7 +18,7 @@ namespace search::docsummary {
AttributeCombinerDFW::AttributeCombinerDFW(const vespalib::string &fieldName, bool filter_elements,
std::shared_ptr<MatchingElementsFields> matching_elems_fields)
- : ISimpleDFW(),
+ : SimpleDFW(),
_stateIndex(0),
_filter_elements(filter_elements),
_fieldName(fieldName),
@@ -41,13 +41,13 @@ AttributeCombinerDFW::setFieldWriterStateIndex(uint32_t fieldWriterStateIndex)
return true;
}
-std::unique_ptr<IDocsumFieldWriter>
+std::unique_ptr<DocsumFieldWriter>
AttributeCombinerDFW::create(const vespalib::string &fieldName, IAttributeContext &attrCtx, bool filter_elements,
std::shared_ptr<MatchingElementsFields> matching_elems_fields)
{
StructFieldsResolver structFields(fieldName, attrCtx, true);
if (structFields.has_error()) {
- return std::unique_ptr<IDocsumFieldWriter>();
+ return std::unique_ptr<DocsumFieldWriter>();
} else if (structFields.is_map_of_struct()) {
return std::make_unique<StructMapAttributeCombinerDFW>(fieldName, structFields, filter_elements, std::move(matching_elems_fields));
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.h
index c1742595745..39f2d498c5b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.h
@@ -2,7 +2,8 @@
#pragma once
-#include "docsumfieldwriter.h"
+#include "simple_dfw.h"
+#include <memory>
namespace search {
class MatchingElements;
@@ -21,7 +22,7 @@ class DynamicDocsumWriter;
* This class reads values from multiple struct field attributes and
* inserts them as an array of struct or a map of struct.
*/
-class AttributeCombinerDFW : public ISimpleDFW
+class AttributeCombinerDFW : public SimpleDFW
{
protected:
uint32_t _stateIndex;
@@ -36,8 +37,8 @@ public:
~AttributeCombinerDFW() override;
bool IsGenerated() const override;
bool setFieldWriterStateIndex(uint32_t fieldWriterStateIndex) override;
- static std::unique_ptr<IDocsumFieldWriter> create(const vespalib::string &fieldName, search::attribute::IAttributeContext &attrCtx,
- bool filter_elements, std::shared_ptr<MatchingElementsFields> matching_elems_fields);
+ static std::unique_ptr<DocsumFieldWriter> create(const vespalib::string &fieldName, search::attribute::IAttributeContext &attrCtx,
+ bool filter_elements, std::shared_ptr<MatchingElementsFields> matching_elems_fields);
void insertField(uint32_t docid, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) override;
};
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.cpp
index d5fdee096b1..e7b6acec646 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.cpp
@@ -2,6 +2,7 @@
#include "attributedfw.h"
#include "docsumwriter.h"
+#include "docsumstate.h"
#include "docsum_field_writer_state.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/value_codec.h>
@@ -38,6 +39,24 @@ AttrDFW::AttrDFW(const vespalib::string & attrName) :
{
}
+const attribute::IAttributeVector&
+AttrDFW::get_attribute(const GetDocsumsState& s) const
+{
+ return *s.getAttribute(getIndex());
+}
+
+const vespalib::string &
+AttrDFW::getAttributeName() const
+{
+ return _attrName;
+}
+
+bool
+AttrDFW::IsGenerated() const
+{
+ return true;
+}
+
namespace {
class SingleAttrDFW : public AttrDFW
@@ -333,7 +352,7 @@ MultiAttrDFW::insertField(uint32_t docid, GetDocsumsState *state, ResType, vespa
field_writer_state->insertField(docid, target);
}
-std::unique_ptr<IDocsumFieldWriter>
+std::unique_ptr<DocsumFieldWriter>
create_multi_writer(const IAttributeVector& attr, bool filter_elements, std::shared_ptr<MatchingElementsFields> matching_elems_fields)
{
auto type = attr.getBasicType();
@@ -355,7 +374,7 @@ create_multi_writer(const IAttributeVector& attr, bool filter_elements, std::sha
}
-std::unique_ptr<IDocsumFieldWriter>
+std::unique_ptr<DocsumFieldWriter>
AttributeDFWFactory::create(IAttributeManager& attr_mgr,
const vespalib::string& attr_name,
bool filter_elements,
@@ -365,7 +384,7 @@ AttributeDFWFactory::create(IAttributeManager& attr_mgr,
const auto* attr = ctx->getAttribute(attr_name);
if (attr == nullptr) {
Issue::report("No valid attribute vector found: '%s'", attr_name.c_str());
- return std::unique_ptr<IDocsumFieldWriter>();
+ return std::unique_ptr<DocsumFieldWriter>();
}
if (attr->hasMultiValue()) {
return create_multi_writer(*attr, filter_elements, std::move(matching_elems_fields));
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.h b/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.h
index 35f67fd5446..26351bdf501 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/attributedfw.h
@@ -2,38 +2,38 @@
#pragma once
-#include "docsumfieldwriter.h"
-#include "docsumstate.h"
+#include "simple_dfw.h"
+#include <memory>
-namespace search { class MatchingElementsFields; }
+namespace search {
+class IAttributeManager;
+class MatchingElementsFields;
+}
namespace search::attribute { class IAttributeVector; }
namespace search::docsummary {
/**
- * Factory to create an IDocsumFieldWriter to write an attribute vector to slime.
+ * Factory to create an DocsumFieldWriter to write an attribute vector to slime.
*/
class AttributeDFWFactory {
public:
- static std::unique_ptr<IDocsumFieldWriter> create(IAttributeManager& attr_mgr,
- const vespalib::string& attr_name,
- bool filter_elements = false,
- std::shared_ptr<MatchingElementsFields> matching_elems_fields
- = std::shared_ptr<MatchingElementsFields>());
+ static std::unique_ptr<DocsumFieldWriter> create(IAttributeManager& attr_mgr,
+ const vespalib::string& attr_name,
+ bool filter_elements = false,
+ std::shared_ptr<MatchingElementsFields> matching_elems_fields = std::shared_ptr<MatchingElementsFields>());
};
-class AttrDFW : public ISimpleDFW
+class AttrDFW : public SimpleDFW
{
private:
vespalib::string _attrName;
protected:
- const attribute::IAttributeVector& get_attribute(const GetDocsumsState& s) const {
- return *s.getAttribute(getIndex());
- }
- const vespalib::string & getAttributeName() const override { return _attrName; }
+ const attribute::IAttributeVector& get_attribute(const GetDocsumsState& s) const;
+ const vespalib::string & getAttributeName() const override;
public:
AttrDFW(const vespalib::string & attrName);
- bool IsGenerated() const override { return true; }
+ bool IsGenerated() const override;
};
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.cpp b/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.cpp
new file mode 100644
index 00000000000..624efd5d834
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.cpp
@@ -0,0 +1,131 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "check_undefined_value_visitor.h"
+#include <vespa/searchcommon/common/undefinedvalues.h>
+#include <vespa/document/fieldvalue/fieldvalues.h>
+
+using search::attribute::isUndefined;
+
+
+namespace search::docsummary {
+
+void
+CheckUndefinedValueVisitor::visit(const document::AnnotationReferenceFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::ArrayFieldValue& value)
+{
+ if (value.isEmpty()) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::BoolFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::ByteFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::Document&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::DoubleFieldValue& value)
+{
+ if (isUndefined(value.getValue())) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::FloatFieldValue& value)
+{
+ if (isUndefined(value.getValue())) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::IntFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::LongFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::MapFieldValue& value)
+{
+ if (value.isEmpty()) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::PredicateFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::RawFieldValue& value)
+{
+ if (value.getValueRef().empty()) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::ShortFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::StringFieldValue& value)
+{
+ if (isUndefined(value.getValue())) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::StructFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::WeightedSetFieldValue& value)
+{
+ if (value.isEmpty()) {
+ _is_undefined = true;
+ }
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::TensorFieldValue&)
+{
+}
+
+void
+CheckUndefinedValueVisitor::visit(const document::ReferenceFieldValue&)
+{
+}
+
+CheckUndefinedValueVisitor::CheckUndefinedValueVisitor()
+ : _is_undefined(false)
+{
+}
+
+
+CheckUndefinedValueVisitor::~CheckUndefinedValueVisitor() = default;
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.h b/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.h
new file mode 100644
index 00000000000..e652d5d122b
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/check_undefined_value_visitor.h
@@ -0,0 +1,41 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include <vespa/document/fieldvalue/fieldvaluevisitor.h>
+
+namespace search::docsummary {
+
+/*
+ * This class checks if field value is considered the same value as
+ * undefined values string/double/float attribute vectors or empty
+ * array/map/weighted set.
+ */
+class CheckUndefinedValueVisitor : public document::ConstFieldValueVisitor
+{
+ bool _is_undefined;
+ void visit(const document::AnnotationReferenceFieldValue&) override;
+ void visit(const document::ArrayFieldValue& value) override;
+ void visit(const document::BoolFieldValue&) override;
+ void visit(const document::ByteFieldValue&) override;
+ void visit(const document::Document&) override;
+ void visit(const document::DoubleFieldValue& value) override;
+ void visit(const document::FloatFieldValue& value) override;
+ void visit(const document::IntFieldValue&) override;
+ void visit(const document::LongFieldValue&) override;
+ void visit(const document::MapFieldValue& value) override;
+ void visit(const document::PredicateFieldValue&) override;
+ void visit(const document::RawFieldValue& value) override;
+ void visit(const document::ShortFieldValue&) override;
+ void visit(const document::StringFieldValue& value) override;
+ void visit(const document::StructFieldValue&) override;
+ void visit(const document::WeightedSetFieldValue& value) override;
+ void visit(const document::TensorFieldValue&) override;
+ void visit(const document::ReferenceFieldValue&) override;
+public:
+ CheckUndefinedValueVisitor();
+ ~CheckUndefinedValueVisitor() override;
+ bool is_undefined() const noexcept { return _is_undefined; }
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.cpp b/searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.cpp
index 47d94a716f7..836273ce3d8 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.cpp
@@ -1,50 +1,19 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include "docsumfieldwriter.h"
-#include "idocsumenvironment.h"
-#include "docsumstate.h"
-#include <vespa/searchlib/common/documentlocations.h>
-#include <vespa/searchlib/common/location.h>
-#include <vespa/searchlib/parsequery/stackdumpiterator.h>
+#include "copy_dfw.h"
+#include "general_result.h"
+#include "i_docsum_store_document.h"
+#include "resultconfig.h"
+#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/log/log.h>
-LOG_SETUP(".searchlib.docsummary.docsumfieldwriter");
+LOG_SETUP(".searchlib.docsummary.copy_dfw");
namespace search::docsummary {
-using search::attribute::IAttributeContext;
-using search::attribute::IAttributeVector;
-using search::attribute::BasicType;
-using search::common::Location;
-
-//--------------------------------------------------------------------------
-
-const vespalib::string IDocsumFieldWriter::_empty("");
-
-bool
-IDocsumFieldWriter::setFieldWriterStateIndex(uint32_t)
-{
- return false; // Don't need any field writer state by default
-}
-
-//--------------------------------------------------------------------------
-
-EmptyDFW::EmptyDFW() = default;
-
-EmptyDFW::~EmptyDFW() = default;
-
-void
-EmptyDFW::insertField(uint32_t, GetDocsumsState *, ResType, vespalib::slime::Inserter &target)
-{
- // insert explicitly-empty field?
- // target.insertNix();
- (void)target;
-}
-
-//--------------------------------------------------------------------------
-
CopyDFW::CopyDFW()
- : _inputFieldEnumValue(static_cast<uint32_t>(-1))
+ : _inputFieldEnumValue(static_cast<uint32_t>(-1)),
+ _input_field_name()
{
}
@@ -54,15 +23,16 @@ bool
CopyDFW::Init(const ResultConfig & config, const char *inputField)
{
_inputFieldEnumValue = config.GetFieldNameEnum().Lookup(inputField);
+ _input_field_name = inputField;
if (_inputFieldEnumValue >= config.GetFieldNameEnum().GetNumEntries()) {
LOG(warning, "no docsum format contains field '%s'; copied fields will be empty", inputField);
}
- for (const auto & field : config) {
- const ResConfigEntry *entry = field.GetEntry(field.GetIndexFromEnumValue(_inputFieldEnumValue));
+ for (const auto & result_class : config) {
+ const ResConfigEntry *entry = result_class.GetEntry(result_class.GetIndexFromEnumValue(_inputFieldEnumValue));
- if (entry != nullptr &&
+ if (entry != nullptr && !entry->_not_present &&
!IsRuntimeCompatible(entry->_type, RES_INT) &&
!IsRuntimeCompatible(entry->_type, RES_DOUBLE) &&
!IsRuntimeCompatible(entry->_type, RES_INT64) &&
@@ -70,7 +40,7 @@ CopyDFW::Init(const ResultConfig & config, const char *inputField)
!IsRuntimeCompatible(entry->_type, RES_DATA)) {
LOG(warning, "cannot use docsum field '%s' as input to copy; type conflict with result class %d (%s)",
- inputField, field.GetClassID(), field.GetClassName());
+ inputField, result_class.GetClassID(), result_class.GetClassName());
return false;
}
}
@@ -82,11 +52,14 @@ CopyDFW::insertField(uint32_t /*docid*/, GeneralResult *gres, GetDocsumsState *,
vespalib::slime::Inserter &target)
{
int idx = gres->GetClass()->GetIndexFromEnumValue(_inputFieldEnumValue);
- ResEntry *entry = gres->GetEntry(idx);
+ ResEntry *entry = gres->GetPresentEntry(idx);
- if (entry != nullptr &&
- IsRuntimeCompatible(entry->_type, type))
- {
+ if (entry == nullptr) {
+ const auto* document = gres->get_document();
+ if (document != nullptr) {
+ document->insert_summary_field(_input_field_name, target);
+ }
+ } else if (IsRuntimeCompatible(entry->_type, type)) {
switch (type) {
case RES_INT: {
uint32_t val32 = entry->_intval;
@@ -121,7 +94,23 @@ CopyDFW::insertField(uint32_t /*docid*/, GeneralResult *gres, GetDocsumsState *,
target.insertLong(valint64);
break; }
- case RES_JSONSTRING:
+ case RES_JSONSTRING: {
+ uint32_t len;
+ const char *spt;
+ // resolve field
+ entry->_resolve_field(&spt, &len);
+ if (len != 0) {
+ // note: 'JSONSTRING' really means 'structured data'
+ vespalib::Slime input_field_as_slime;
+ size_t d = vespalib::slime::BinaryFormat::decode(vespalib::Memory(spt, len), input_field_as_slime);
+ if (d != len) {
+ LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d);
+ }
+ if (d != 0) {
+ inject(input_field_as_slime.get(), target);
+ }
+ }
+ break; }
case RES_FEATUREDATA:
case RES_LONG_STRING:
case RES_STRING: {
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.h
new file mode 100644
index 00000000000..dab7417f60a
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/copy_dfw.h
@@ -0,0 +1,31 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "docsum_field_writer.h"
+
+namespace search::docsummary {
+
+class ResultConfig;
+
+/*
+ * Class for writing document summaries with content from another field.
+ */
+class CopyDFW : public DocsumFieldWriter
+{
+private:
+ uint32_t _inputFieldEnumValue;
+ vespalib::string _input_field_name;
+
+public:
+ CopyDFW();
+ ~CopyDFW() override;
+
+ bool Init(const ResultConfig & config, const char *inputField);
+
+ bool IsGenerated() const override { return false; }
+ void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType type,
+ vespalib::slime::Inserter &target) override;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsum_blob_entry_filter.h b/searchsummary/src/vespa/searchsummary/docsummary/docsum_blob_entry_filter.h
new file mode 100644
index 00000000000..1d006386d35
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsum_blob_entry_filter.h
@@ -0,0 +1,29 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "res_type.h"
+#include <bitset>
+
+namespace search::docsummary {
+
+/*
+ * Class containing the set of result types not stored in docsum blobs.
+ * This is used for gradual migration towards elimination of docsum blobs.
+ */
+class DocsumBlobEntryFilter {
+ std::bitset<14> _skip_types;
+
+public:
+ DocsumBlobEntryFilter()
+ : _skip_types()
+ {
+ }
+ bool skip(ResType type) const noexcept { return _skip_types.test(type); }
+ DocsumBlobEntryFilter &add_skip(ResType type) {
+ _skip_types.set(type);
+ return *this;
+ }
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.cpp b/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.cpp
new file mode 100644
index 00000000000..c698f0603c6
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.cpp
@@ -0,0 +1,27 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "docsum_field_writer.h"
+
+namespace search::docsummary {
+
+const vespalib::string DocsumFieldWriter::_empty("");
+
+const vespalib::string&
+DocsumFieldWriter::getAttributeName() const
+{
+ return _empty;
+}
+
+bool
+DocsumFieldWriter::isDefaultValue(uint32_t, const GetDocsumsState*) const
+{
+ return false;
+}
+
+bool
+DocsumFieldWriter::setFieldWriterStateIndex(uint32_t)
+{
+ return false; // Don't need any field writer state by default
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.h b/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.h
new file mode 100644
index 00000000000..764f3507380
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsum_field_writer.h
@@ -0,0 +1,41 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "res_type_utils.h"
+#include <vespa/vespalib/stllike/string.h>
+
+namespace vespalib::slime { struct Inserter; }
+
+namespace search::docsummary {
+
+class GeneralResult;
+class GetDocsumsState;
+
+/*
+ * Abstract class for writing document summaries.
+ */
+class DocsumFieldWriter
+{
+public:
+ DocsumFieldWriter()
+ : _index(0)
+ {
+ }
+ virtual ~DocsumFieldWriter() = default;
+ static bool IsRuntimeCompatible(ResType a, ResType b) {
+ return ResTypeUtils::IsRuntimeCompatible(a, b);
+ }
+ virtual bool IsGenerated() const = 0;
+ virtual void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) = 0;
+ virtual const vespalib::string & getAttributeName() const;
+ virtual bool isDefaultValue(uint32_t docid, const GetDocsumsState * state) const;
+ void setIndex(size_t v) { _index = v; }
+ size_t getIndex() const { return _index; }
+ virtual bool setFieldWriterStateIndex(uint32_t fieldWriterStateIndex);
+private:
+ size_t _index;
+ static const vespalib::string _empty;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.cpp b/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.cpp
new file mode 100644
index 00000000000..e6c8d0b6ab8
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.cpp
@@ -0,0 +1,53 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "docsum_store_document.h"
+#include "check_undefined_value_visitor.h"
+#include "summaryfieldconverter.h"
+#include <vespa/document/datatype/datatype.h>
+#include <vespa/document/fieldvalue/document.h>
+#include <vespa/vespalib/data/slime/inserter.h>
+
+namespace search::docsummary {
+
+DocsumStoreDocument::DocsumStoreDocument(std::unique_ptr<document::Document> document)
+ : _document(std::move(document))
+{
+}
+
+DocsumStoreDocument::~DocsumStoreDocument() = default;
+
+std::unique_ptr<document::FieldValue>
+DocsumStoreDocument::get_field_value(const vespalib::string& field_name) const
+{
+ if (_document) {
+ const document::Field& field = _document->getField(field_name);
+ auto value(field.getDataType().createFieldValue());
+ if (value) {
+ if (_document->getValue(field, *value)) {
+ return value;
+ }
+ }
+ }
+ return {};
+}
+
+void
+DocsumStoreDocument::insert_summary_field(const vespalib::string& field_name, vespalib::slime::Inserter& inserter) const
+{
+ auto field_value = get_field_value(field_name);
+ if (field_value) {
+ SummaryFieldConverter::insert_summary_field(*field_value, inserter);
+ }
+}
+
+void
+DocsumStoreDocument::insert_document_id(vespalib::slime::Inserter& inserter) const
+{
+ if (_document) {
+ auto id = _document->getId().toString();
+ vespalib::Memory id_view(id.data(), id.size());
+ inserter.insertString(id_view);
+ }
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.h b/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.h
new file mode 100644
index 00000000000..3b0bea6e721
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsum_store_document.h
@@ -0,0 +1,25 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "i_docsum_store_document.h"
+
+namespace document { class Document; }
+
+namespace search::docsummary {
+
+/**
+ * Class providing access to a document retrieved from an IDocsumStore.
+ **/
+class DocsumStoreDocument : public IDocsumStoreDocument
+{
+ std::unique_ptr<document::Document> _document;
+public:
+ DocsumStoreDocument(std::unique_ptr<document::Document> document);
+ ~DocsumStoreDocument() override;
+ std::unique_ptr<document::FieldValue> get_field_value(const vespalib::string& field_name) const override;
+ void insert_summary_field(const vespalib::string& field_name, vespalib::slime::Inserter& inserter) const override;
+ void insert_document_id(vespalib::slime::Inserter& inserter) const override;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.cpp b/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.cpp
index 24642c418fd..c61ef4a0330 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.cpp
@@ -1,15 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include "attribute_combiner_dfw.h"
#include "docsumconfig.h"
+#include "attribute_combiner_dfw.h"
+#include "copy_dfw.h"
#include "docsumwriter.h"
+#include "document_id_dfw.h"
+#include "empty_dfw.h"
#include "geoposdfw.h"
#include "idocsumenvironment.h"
#include "juniperdfw.h"
#include "matched_elements_filter_dfw.h"
#include "positionsdfw.h"
#include "rankfeaturesdfw.h"
-#include "textextractordfw.h"
+#include "summaryfeaturesdfw.h"
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>
@@ -24,12 +27,12 @@ DynamicDocsumConfig::getResultConfig() const {
return *_writer->GetResultConfig();
}
-IDocsumFieldWriter::UP
+std::unique_ptr<DocsumFieldWriter>
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc, std::shared_ptr<MatchingElementsFields> matching_elems_fields)
{
const ResultConfig & resultConfig = getResultConfig();
rc = false;
- IDocsumFieldWriter::UP fieldWriter;
+ std::unique_ptr<DocsumFieldWriter> fieldWriter;
if (overrideName == "dynamicteaser") {
if ( ! argument.empty() ) {
const char *langFieldName = "something unused";
@@ -39,14 +42,6 @@ DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string &
} else {
throw IllegalArgumentException("Missing argument");
}
- } else if (overrideName == "textextractor") {
- if ( ! argument.empty() ) {
- TextExtractorDFW * fw = new TextExtractorDFW();
- fieldWriter.reset(fw);
- rc = fw->init(fieldName, argument, resultConfig);
- } else {
- throw IllegalArgumentException("Missing argument");
- }
} else if (overrideName == "summaryfeatures") {
fieldWriter = std::make_unique<SummaryFeaturesDFW>(getEnvironment());
rc = true;
@@ -110,6 +105,9 @@ DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string &
*attr_ctx, matching_elems_fields);
rc = static_cast<bool>(fieldWriter);
}
+ } else if (overrideName == "documentid") {
+ fieldWriter = std::make_unique<DocumentIdDFW>();
+ rc = true;
} else {
throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
}
@@ -127,7 +125,7 @@ DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cf
for (size_t i = 0; i < cfg.override.size(); ++i) {
const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
bool rc(false);
- IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc, matching_elems_fields);
+ std::unique_ptr<DocsumFieldWriter> fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc, matching_elems_fields);
if (rc && fieldWriter) {
rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.h b/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.h
index 70c8d524527..b86313dfbd4 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumconfig.h
@@ -8,9 +8,9 @@ namespace search { class MatchingElementsFields; }
namespace search::docsummary {
class IDocsumEnvironment;
+class DocsumFieldWriter;
class DynamicDocsumWriter;
class ResultConfig;
-class IDocsumFieldWriter;
class DynamicDocsumConfig
{
@@ -27,7 +27,7 @@ protected:
const IDocsumEnvironment * getEnvironment() const { return _env; }
const ResultConfig & getResultConfig() const;
- virtual std::unique_ptr<IDocsumFieldWriter>
+ virtual std::unique_ptr<DocsumFieldWriter>
createFieldWriter(const string & fieldName, const string & overrideName,
const string & argument, bool & rc, std::shared_ptr<MatchingElementsFields> matching_elems_fields);
private:
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.h b/searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.h
deleted file mode 100644
index 19e22eba4de..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumfieldwriter.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#pragma once
-
-#include "general_result.h"
-#include "resultconfig.h"
-#include <vespa/searchlib/util/rawbuf.h>
-#include <vespa/vespalib/data/slime/inserter.h>
-
-namespace search { class IAttributeManager; }
-
-namespace search::docsummary {
-
-class GetDocsumsState;
-
-class IDocsumFieldWriter
-{
-public:
- using UP = std::unique_ptr<IDocsumFieldWriter>;
- IDocsumFieldWriter() : _index(0) { }
- virtual ~IDocsumFieldWriter() = default;
-
- static bool IsRuntimeCompatible(ResType a, ResType b) {
- return ResultConfig::IsRuntimeCompatible(a, b);
- }
-
- virtual bool IsGenerated() const = 0;
- virtual void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType type,
- vespalib::slime::Inserter &target) = 0;
- virtual const vespalib::string & getAttributeName() const { return _empty; }
- virtual bool isDefaultValue(uint32_t docid, const GetDocsumsState * state) const {
- (void) docid;
- (void) state;
- return false;
- }
- void setIndex(size_t v) { _index = v; }
- size_t getIndex() const { return _index; }
- virtual bool setFieldWriterStateIndex(uint32_t fieldWriterStateIndex);
-private:
- size_t _index;
- static const vespalib::string _empty;
-};
-
-class ISimpleDFW : public IDocsumFieldWriter
-{
-public:
- virtual void insertField(uint32_t docid, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) = 0;
- void insertField(uint32_t docid, GeneralResult *, GetDocsumsState *state, ResType type,
- vespalib::slime::Inserter &target) override
- {
- insertField(docid, state, type, target);
- }
-};
-
-//--------------------------------------------------------------------------
-
-class EmptyDFW : public ISimpleDFW
-{
-public:
- EmptyDFW();
- ~EmptyDFW() override;
-
- bool IsGenerated() const override { return true; }
- void insertField(uint32_t docid, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) override;
-};
-
-//--------------------------------------------------------------------------
-
-class CopyDFW : public IDocsumFieldWriter
-{
-private:
- uint32_t _inputFieldEnumValue;
-
-public:
- CopyDFW();
- ~CopyDFW() override;
-
- bool Init(const ResultConfig & config, const char *inputField);
-
- bool IsGenerated() const override { return false; }
- void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType type,
- vespalib::slime::Inserter &target) override;
-};
-
-}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.cpp b/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.cpp
index d63be095291..a60ae93b58f 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.cpp
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "docsumstorevalue.h"
-#include <vespa/document/fieldvalue/document.h>
+#include "i_docsum_store_document.h"
namespace search::docsummary {
@@ -17,9 +17,9 @@ DocsumStoreValue::DocsumStoreValue(const char *pt_, uint32_t len_)
{
}
-DocsumStoreValue::DocsumStoreValue(const char *pt_, uint32_t len_, std::unique_ptr<document::Document> document_)
+DocsumStoreValue::DocsumStoreValue(const char *pt_, uint32_t len_, std::unique_ptr<IDocsumStoreDocument> document)
: _value(pt_, len_),
- _document(std::move(document_))
+ _document(std::move(document))
{
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.h b/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.h
index c0bbaa15975..bdc4e7b9e19 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumstorevalue.h
@@ -5,10 +5,10 @@
#include <memory>
#include <utility>
-namespace document { class Document; }
-
namespace search::docsummary {
+class IDocsumStoreDocument;
+
/**
* Simple wrapper class containing the location and size of a docsum
* blob located in memory. The memory containing the docsum blob is
@@ -19,10 +19,11 @@ class DocsumStoreValue
{
private:
std::pair<const char *, uint32_t> _value;
- // The document instance that was used to generate the docsum blob.
+ // An interface for accessing the document instance that was used
+ // to generate the docsum blob.
// Note: This is temporary until the docsummary framework is simplified,
// and the docsum blob concept is removed.
- std::unique_ptr<document::Document> _document;
+ std::unique_ptr<IDocsumStoreDocument> _document;
public:
DocsumStoreValue(const DocsumStoreValue&) = delete;
@@ -46,9 +47,9 @@ public:
*
* @param pt_ docsum location
* @param len_ docsum size
- * @param document_ document instance used to generate the docsum blob
+ * @param document docsum store document instance
**/
- DocsumStoreValue(const char *pt_, uint32_t len_, std::unique_ptr<document::Document> document_);
+ DocsumStoreValue(const char *pt_, uint32_t len_, std::unique_ptr<IDocsumStoreDocument> document);
~DocsumStoreValue();
@@ -77,7 +78,7 @@ public:
**/
bool valid() const { return (_value.first != 0) && (_value.second >= sizeof(uint32_t)); }
- const document::Document* get_document() const { return _document.get(); }
+ const IDocsumStoreDocument* get_document() const { return _document.get(); }
};
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.cpp b/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.cpp
index e7a9840c47f..1492ce2b435 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.cpp
@@ -3,6 +3,9 @@
#include "docsumwriter.h"
#include "docsumstate.h"
#include "docsum_field_writer_state.h"
+#include "i_docsum_store_document.h"
+#include "summaryfieldconverter.h"
+#include <vespa/document/fieldvalue/fieldvalue.h>
#include <vespa/searchcommon/common/undefinedvalues.h>
#include <vespa/searchlib/util/slime_output_raw_buf_adapter.h>
#include <vespa/searchlib/attribute/iattributemanager.h>
@@ -86,6 +89,7 @@ constexpr uint64_t default_64bits_int = search::attribute::getUndefined<int64_t>
static void convertEntry(const ResConfigEntry *resCfg,
const ResEntry *entry,
+ const GeneralResult& gres,
Inserter &inserter,
Slime &slime)
{
@@ -93,7 +97,16 @@ static void convertEntry(const ResConfigEntry *resCfg,
const char *ptr;
uint32_t len;
- LOG_ASSERT(resCfg != nullptr && entry != nullptr);
+ LOG_ASSERT(resCfg != nullptr);
+ if (entry == nullptr || entry->_not_present) {
+ // Entry is not present in docsum blob
+ const auto* document = gres.get_document();
+ if (document != nullptr) {
+ document->insert_summary_field(resCfg->_bindname, inserter);
+ }
+ return;
+ }
+
switch (resCfg->_type) {
case RES_INT:
case RES_SHORT:
@@ -155,7 +168,7 @@ DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid,
vespalib::slime::Cursor & docsum = topInserter.insertObject();
for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i);
- IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue];
+ DocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue];
if (! writer->isDefaultValue(docid, state)) {
const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size());
ObjectInserter inserter(docsum, field_name);
@@ -175,7 +188,7 @@ DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid,
vespalib::slime::Cursor & docsum = topInserter.insertObject();
for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i);
- IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue];
+ DocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue];
const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size());
ObjectInserter inserter(docsum, field_name);
if (writer != nullptr) {
@@ -184,15 +197,20 @@ DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid,
}
} else {
if (rci.inputClass == rci.outputClass) {
- convertEntry(outCfg, gres.GetEntry(i), inserter, slime);
+ convertEntry(outCfg, gres.GetEntry(i), gres, inserter, slime);
} else {
int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue);
const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx);
- if (inCfg != nullptr && inCfg->_type == outCfg->_type) {
+ if (inCfg != nullptr && inCfg->_type == outCfg->_type && !inCfg->_not_present) {
// copy field
const ResEntry *entry = gres.GetEntry(inIdx);
LOG_ASSERT(entry != nullptr);
- convertEntry(outCfg, entry, inserter, slime);
+ convertEntry(outCfg, entry, gres, inserter, slime);
+ } else {
+ const auto* document = gres.get_document();
+ if (document != nullptr) {
+ document->insert_summary_field(outCfg->_bindname, inserter);
+ }
}
}
}
@@ -212,7 +230,7 @@ DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor
{
LOG_ASSERT(config != nullptr);
_classInfoTable = new ResultClass::DynamicInfo[_numClasses];
- _overrideTable = new IDocsumFieldWriter*[_numEnumValues];
+ _overrideTable = new DocsumFieldWriter*[_numEnumValues];
uint32_t i = 0;
for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) {
@@ -261,7 +279,7 @@ DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID)
bool
-DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer)
+DynamicDocsumWriter::Override(const char *fieldName, DocsumFieldWriter *writer)
{
uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName);
@@ -284,10 +302,10 @@ DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer)
++_numFieldWriterStates;
}
- for (auto & entry : *_resultConfig) {
+ for (auto & result_class : *_resultConfig) {
- if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) {
- ResultClass::DynamicInfo *info = entry.getDynamicInfo();
+ if (result_class.GetIndexFromEnumValue(fieldEnumValue) >= 0) {
+ ResultClass::DynamicInfo *info = result_class.getDynamicInfo();
info->_overrideCnt++;
if (writer->IsGenerated())
info->_generateCnt++;
@@ -306,7 +324,7 @@ DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *sta
state->_attributes.resize(_numEnumValues);
state->_fieldWriterStates.resize(_numFieldWriterStates);
for (size_t i(0); i < state->_attributes.size(); i++) {
- const IDocsumFieldWriter *fw = _overrideTable[i];
+ const DocsumFieldWriter *fw = _overrideTable[i];
if (fw) {
const vespalib::string & attributeName = fw->getAttributeName();
if (!attributeName.empty()) {
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.h b/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.h
index e70e3db8655..b3182221b68 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/docsumwriter.h
@@ -7,12 +7,14 @@
#include "resultconfig.h"
#include "docsumstore.h"
#include "keywordextractor.h"
-#include "docsumfieldwriter.h"
+#include "docsum_field_writer.h"
#include <vespa/searchlib/util/rawbuf.h>
#include <vespa/fastlib/text/unicodeutil.h>
#include <vespa/fastlib/text/wordfolder.h>
-using search::IAttributeManager;
+namespace search { class IAttributeManager; }
+
+namespace vespalib { class Slime; }
namespace search::docsummary {
@@ -36,7 +38,7 @@ public:
};
virtual ~IDocsumWriter() {}
- virtual void InitState(IAttributeManager & attrMan, GetDocsumsState *state) = 0;
+ virtual void InitState(search::IAttributeManager & attrMan, GetDocsumsState *state) = 0;
virtual uint32_t WriteDocsum(uint32_t docid, GetDocsumsState *state,
IDocsumStore *docinfos, search::RawBuf *target) = 0;
virtual void insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state,
@@ -58,7 +60,7 @@ private:
uint32_t _numEnumValues;
uint32_t _numFieldWriterStates;
ResultClass::DynamicInfo *_classInfoTable;
- IDocsumFieldWriter **_overrideTable;
+ DocsumFieldWriter** _overrideTable;
void resolveInputClass(ResolveClassInfo &rci, uint32_t id) const;
@@ -73,8 +75,8 @@ public:
ResultConfig *GetResultConfig() { return _resultConfig; }
bool SetDefaultOutputClass(uint32_t classID);
- bool Override(const char *fieldName, IDocsumFieldWriter *writer);
- void InitState(IAttributeManager & attrMan, GetDocsumsState *state) override;
+ bool Override(const char *fieldName, DocsumFieldWriter *writer);
+ void InitState(search::IAttributeManager & attrMan, GetDocsumsState *state) override;
uint32_t WriteDocsum(uint32_t docid, GetDocsumsState *state,
IDocsumStore *docinfos, search::RawBuf *target) override;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.cpp
new file mode 100644
index 00000000000..8fcf7c95cdc
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.cpp
@@ -0,0 +1,31 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "document_id_dfw.h"
+#include "general_result.h"
+#include "i_docsum_store_document.h"
+
+namespace search::docsummary {
+
+DocumentIdDFW::DocumentIdDFW()
+{
+}
+
+DocumentIdDFW::~DocumentIdDFW() = default;
+
+bool
+DocumentIdDFW::IsGenerated() const
+{
+ return false;
+}
+
+void
+DocumentIdDFW::insertField(uint32_t, GeneralResult *gres, GetDocsumsState *, ResType,
+ vespalib::slime::Inserter &target)
+{
+ const auto* document = gres->get_document();
+ if (document != nullptr) {
+ document->insert_document_id(target);
+ }
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.h
new file mode 100644
index 00000000000..f6353912384
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/document_id_dfw.h
@@ -0,0 +1,22 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "docsum_field_writer.h"
+
+namespace search::docsummary {
+
+/*
+ * Class for writing document id field.
+ */
+class DocumentIdDFW : public DocsumFieldWriter
+{
+private:
+public:
+ DocumentIdDFW();
+ ~DocumentIdDFW() override;
+ bool IsGenerated() const override;
+ void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) override;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp
index ef1ffded941..024046b679b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/dynamicteaserdfw.cpp
@@ -3,6 +3,8 @@
#include "juniperdfw.h"
#include "docsumwriter.h"
#include "docsumstate.h"
+#include "i_docsum_store_document.h"
+#include <vespa/document/fieldvalue/fieldvalue.h>
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/searchlib/queryeval/split_float.h>
#include <vespa/vespalib/objects/hexdump.h>
@@ -282,10 +284,11 @@ JuniperQueryAdapter::Traverse(juniper::IQueryVisitor *v) const
}
JuniperDFW::JuniperDFW(juniper::Juniper * juniper)
- : _inputFieldEnumValue(static_cast<uint32_t>(-1))
- , _juniperConfig()
- , _langFieldEnumValue(static_cast<uint32_t>(-1))
- , _juniper(juniper)
+ : _inputFieldEnumValue(static_cast<uint32_t>(-1)),
+ _input_field_name(),
+ _juniperConfig(),
+ _langFieldEnumValue(static_cast<uint32_t>(-1)),
+ _juniper(juniper)
{
}
@@ -310,6 +313,7 @@ JuniperDFW::Init(
}
_inputFieldEnumValue = enums.Lookup(inputField);
+ _input_field_name = inputField;
if (_inputFieldEnumValue >= enums.GetNumEntries()) {
LOG(warning, "no docsum format contains field '%s'; dynamic teasers will be empty",
@@ -332,7 +336,7 @@ JuniperTeaserDFW::Init(
const ResConfigEntry *entry =
it->GetEntry(it->GetIndexFromEnumValue(_inputFieldEnumValue));
- if (entry != nullptr &&
+ if (entry != nullptr && !entry->_not_present &&
!IsRuntimeCompatible(entry->_type, RES_STRING) &&
!IsRuntimeCompatible(entry->_type, RES_DATA))
{
@@ -344,17 +348,21 @@ JuniperTeaserDFW::Init(
return rc;
}
-vespalib::stringref
+JuniperInput
DynamicTeaserDFW::getJuniperInput(GeneralResult *gres) {
int idx = gres->GetClass()->GetIndexFromEnumValue(_inputFieldEnumValue);
- ResEntry *entry = gres->GetEntry(idx);
+ ResEntry *entry = gres->GetPresentEntry(idx);
if (entry != nullptr) {
const char *buf;
uint32_t buflen;
entry->_resolve_field(&buf, &buflen);
- return vespalib::stringref(buf, buflen);
+ return JuniperInput(vespalib::stringref(buf, buflen));
}
- return vespalib::stringref();
+ const auto* document = gres->get_document();
+ if (document != nullptr) {
+ return JuniperInput(document->get_field_value(_input_field_name).get());
+ }
+ return JuniperInput(vespalib::stringref());
}
vespalib::string
@@ -428,9 +436,9 @@ void
DynamicTeaserDFW::insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state, ResType,
vespalib::slime::Inserter &target)
{
- vespalib::stringref input = getJuniperInput(gres);
- if (input.length() > 0) {
- vespalib::string teaser = makeDynamicTeaser(docid, input, state);
+ auto input = getJuniperInput(gres);
+ if (!input.empty()) {
+ vespalib::string teaser = makeDynamicTeaser(docid, input.get_value(), state);
vespalib::Memory value(teaser.c_str(), teaser.size());
target.insertString(value);
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.cpp
new file mode 100644
index 00000000000..3d3b1e11626
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.cpp
@@ -0,0 +1,19 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "empty_dfw.h"
+
+namespace search::docsummary {
+
+EmptyDFW::EmptyDFW() = default;
+
+EmptyDFW::~EmptyDFW() = default;
+
+void
+EmptyDFW::insertField(uint32_t, GetDocsumsState *, ResType, vespalib::slime::Inserter &target)
+{
+ // insert explicitly-empty field?
+ // target.insertNix();
+ (void)target;
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.h
new file mode 100644
index 00000000000..d43eed8e9c6
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/empty_dfw.h
@@ -0,0 +1,22 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "simple_dfw.h"
+
+namespace search::docsummary {
+
+/*
+ * Class for writing empty document summaries.
+ */
+class EmptyDFW : public SimpleDFW
+{
+public:
+ EmptyDFW();
+ ~EmptyDFW() override;
+
+ bool IsGenerated() const override { return true; }
+ void insertField(uint32_t docid, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) override;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/general_result.cpp b/searchsummary/src/vespa/searchsummary/docsummary/general_result.cpp
index be6664e41a3..825c3b39c1b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/general_result.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/general_result.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "general_result.h"
+#include "i_docsum_store_document.h"
#include "resultconfig.h"
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/datatype/datatype.h>
@@ -12,55 +13,32 @@ LOG_SETUP(".searchlib.docsummary.urlresult");
namespace search::docsummary {
void
-GeneralResult::AllocEntries(uint32_t buflen, bool inplace)
+GeneralResult::AllocEntries()
{
uint32_t cnt = _resClass->GetNumEntries();
- uint32_t needMem = (inplace)
- ? cnt * sizeof(ResEntry)
- : cnt * sizeof(ResEntry) + buflen + 1;
+ uint32_t needMem = cnt * sizeof(ResEntry);
if (cnt > 0) {
_entrycnt = cnt;
_entries = (ResEntry *) malloc(needMem);
assert(_entries != nullptr);
- if (inplace) {
- _buf = nullptr;
- _bufEnd = nullptr;
- } else {
- _buf = ((char *)_entries) + cnt * sizeof(ResEntry);
- _bufEnd = _buf + buflen + 1;
- }
memset(_entries, 0, cnt * sizeof(ResEntry));
} else {
_entrycnt = 0;
_entries = nullptr;
- _buf = nullptr;
- _bufEnd = nullptr;
}
}
void
GeneralResult::FreeEntries()
{
- uint32_t cnt = _entrycnt;
-
- // (_buf == nullptr) <=> (_inplace_unpack() || (cnt == 0))
- if (_buf != nullptr) {
- for (uint32_t i = 0; i < cnt; i++) {
- if (ResultConfig::IsVariableSize(_entries[i]._type) &&
- !InBuf(_entries[i]._stringval))
- delete [] (_entries[i]._stringval);
- }
- }
- free(_entries); // free '_entries'/'_buf' chunk
+ free(_entries); // free '_entries' chunk
}
GeneralResult::GeneralResult(const ResultClass *resClass)
: _resClass(resClass),
_entrycnt(0),
_entries(nullptr),
- _buf(nullptr),
- _bufEnd(nullptr),
_document()
{
}
@@ -71,40 +49,26 @@ GeneralResult::~GeneralResult()
}
ResEntry *
-GeneralResult::GetEntry(uint32_t idx)
-{
- return (idx < _entrycnt) ? &_entries[idx] : nullptr;
-}
-
-ResEntry *
-GeneralResult::GetEntry(const char *name)
+GeneralResult::GetPresentEntry(const char *name)
{
int idx = _resClass->GetIndexFromName(name);
-
- return (idx >= 0 && (uint32_t)idx < _entrycnt) ? &_entries[idx] : nullptr;
+ return GetPresentEntry(idx);
}
-
ResEntry *
-GeneralResult::GetEntryFromEnumValue(uint32_t value)
+GeneralResult::GetPresentEntryFromEnumValue(uint32_t value)
{
int idx = _resClass->GetIndexFromEnumValue(value);
- return (idx >= 0 && (uint32_t)idx < _entrycnt) ? &_entries[idx] : nullptr;
+ return GetPresentEntry(idx);
}
std::unique_ptr<document::FieldValue>
GeneralResult::get_field_value(const vespalib::string& field_name) const
{
if (_document != nullptr) {
- const document::Field & field = _document->getField(field_name);
- auto value(field.getDataType().createFieldValue());
- if (value) {
- if (_document->getValue(field, *value)) {
- return value;
- }
- }
+ return _document->get_field_value(field_name);
}
- return std::unique_ptr<document::FieldValue>();
+ return {};
}
bool
@@ -117,11 +81,17 @@ GeneralResult::unpack(const char *buf, const size_t buflen)
if (_entries != nullptr)
FreeEntries();
- AllocEntries(buflen, true);
+ AllocEntries();
for (uint32_t i = 0; rc && i < _entrycnt; i++) {
const ResConfigEntry *entry = _resClass->GetEntry(i);
+ _entries[i]._not_present = entry->_not_present;
+ if (entry->_not_present) {
+ // Entry is not present in docsum blob
+ _entries[i]._type = entry->_type;
+ continue;
+ }
switch (entry->_type) {
case RES_INT: {
@@ -331,8 +301,6 @@ GeneralResult::unpack(const char *buf, const size_t buflen)
FreeEntries();
_entrycnt = 0;
_entries = nullptr;
- _buf = nullptr;
- _bufEnd = nullptr;
return false; // FAIL
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/general_result.h b/searchsummary/src/vespa/searchsummary/docsummary/general_result.h
index b5d07d714ee..cff27a496e3 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/general_result.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/general_result.h
@@ -6,12 +6,13 @@
#include "docsumstorevalue.h"
namespace document {
-class Document;
class FieldValue;
}
namespace search::docsummary {
+class DocsumStoreDocument;
+
class GeneralResult
{
private:
@@ -21,16 +22,9 @@ private:
const ResultClass *_resClass;
uint32_t _entrycnt;
ResEntry *_entries;
- char *_buf; // allocated in same chunk as _entries
- char *_bufEnd; // first byte after _buf
- const document::Document* _document;
-
- bool InBuf(const void *pt) const {
- return ((const char *)pt >= _buf &&
- (const char *)pt < _bufEnd);
- }
+ const IDocsumStoreDocument* _document;
- void AllocEntries(uint32_t buflen, bool inplace = false);
+ void AllocEntries();
void FreeEntries();
public:
@@ -38,9 +32,16 @@ public:
~GeneralResult();
const ResultClass *GetClass() const { return _resClass; }
- ResEntry *GetEntry(uint32_t idx);
- ResEntry *GetEntry(const char *name);
- ResEntry *GetEntryFromEnumValue(uint32_t val);
+ ResEntry *GetEntry(uint32_t idx) { return (idx < _entrycnt) ? &_entries[idx] : nullptr; }
+ ResEntry *GetPresentEntry(uint32_t idx) {
+ if (idx >= _entrycnt) {
+ return nullptr;
+ }
+ ResEntry* entry = &_entries[idx];
+ return entry->_not_present ? nullptr : entry;
+ }
+ ResEntry *GetPresentEntry(const char *name);
+ ResEntry *GetPresentEntryFromEnumValue(uint32_t val);
std::unique_ptr<document::FieldValue> get_field_value(const vespalib::string& field_name) const;
bool unpack(const char *buf, const size_t buflen);
@@ -52,6 +53,8 @@ public:
return false;
}
}
+
+ const IDocsumStoreDocument *get_document() const noexcept { return _document; }
};
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/geoposdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/geoposdfw.cpp
index 8f627ac1b9a..c3806d6e7ea 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/geoposdfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/geoposdfw.cpp
@@ -6,6 +6,7 @@
#include <vespa/searchlib/common/location.h>
#include <vespa/vespalib/util/jsonwriter.h>
#include <vespa/vespalib/data/slime/cursor.h>
+#include <vespa/vespalib/data/slime/inserter.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/issue.h>
#include <climits>
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/i_docsum_store_document.h b/searchsummary/src/vespa/searchsummary/docsummary/i_docsum_store_document.h
new file mode 100644
index 00000000000..c177568c467
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/i_docsum_store_document.h
@@ -0,0 +1,28 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include <vespa/vespalib/stllike/string.h>
+#include <memory>
+
+namespace document { class FieldValue; }
+
+namespace vespalib::slime { struct Inserter; }
+
+namespace search::docsummary {
+
+/**
+ * Interface class providing access to a document retrieved from an
+ * IDocsumStore. Some implementations (e.g. DocsumStoreVsmDocument) might
+ * apply transforms when accessing some fields.
+ **/
+class IDocsumStoreDocument
+{
+public:
+ virtual ~IDocsumStoreDocument() = default;
+ virtual std::unique_ptr<document::FieldValue> get_field_value(const vespalib::string& field_name) const = 0;
+ virtual void insert_summary_field(const vespalib::string& field_name, vespalib::slime::Inserter& inserter) const = 0;
+ virtual void insert_document_id(vespalib::slime::Inserter& inserter) const = 0;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h b/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h
deleted file mode 100644
index 83da9e4da15..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/itokenizer.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#pragma once
-
-#include <vespa/vespalib/stllike/string.h>
-
-namespace search::docsummary {
-
-/**
- * Interface for a tokenizer.
- */
-class ITokenizer
-{
-public:
- /**
- * Representation of a token with type and text and optional stemmed variant.
- */
- class Token
- {
- public:
- enum Type {
- WORD, // Fast_UnicodeUtil::IsWordChar() returns true
- NON_WORD, // Fast_UnicodeUtil::IsWordChar() returns false
- PUNCTUATION, // Fast_UnicodeUtil::IsTerminalPunctuationChar() returns true
- ANNOTATION, // Interlinear annotation
- NOT_DEF
- };
- private:
- vespalib::stringref _text;
- vespalib::stringref _stem;
- Type _type;
-
- public:
- Token(const char * textBegin, const char * textEnd, Type type) :
- _text(textBegin, textEnd - textBegin), _stem(), _type(type) {}
- Token(const char * textBegin, const char * textEnd, const char * stemBegin, const char * stemEnd, Type type) :
- _text(textBegin, textEnd - textBegin), _stem(stemBegin, stemEnd - stemBegin), _type(type) {}
- vespalib::stringref getText() const { return _text; }
- vespalib::stringref getStem() const { return _stem; }
- bool hasStem() const { return _stem.data() != NULL; }
- Type getType() const { return _type; }
- };
-
- virtual ~ITokenizer() {}
-
- /**
- * Reset the tokenizer using the given buffer.
- */
- virtual void reset(const char * buf, size_t len) = 0;
-
- /**
- * Returns the size of the underlying buffer.
- */
- virtual size_t getBufferSize() const = 0;
-
- /**
- * Returns true if the text buffer has more tokens.
- */
- virtual bool hasMoreTokens() = 0;
-
- /**
- * Returns the next token from the text buffer.
- */
- virtual Token getNextToken() = 0;
-};
-
-}
-
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.cpp b/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.cpp
new file mode 100644
index 00000000000..a9f265b0842
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.cpp
@@ -0,0 +1,30 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "juniper_input.h"
+#include "summaryfieldconverter.h"
+#include <vespa/document/fieldvalue/stringfieldvalue.h>
+
+namespace search::docsummary {
+
+JuniperInput::JuniperInput(vespalib::stringref value)
+ : _field_value_with_markup(),
+ _value(value)
+{
+}
+
+JuniperInput::JuniperInput(const document::FieldValue* value)
+ : _field_value_with_markup(),
+ _value()
+{
+ if (value != nullptr) {
+ _field_value_with_markup = SummaryFieldConverter::convertSummaryField(true, *value);
+ }
+ if (_field_value_with_markup && _field_value_with_markup->isA(document::FieldValue::Type::STRING)) {
+ const auto& string_field_value_with_markup = static_cast<document::StringFieldValue&>(*_field_value_with_markup);
+ _value = string_field_value_with_markup.getValueRef();
+ }
+}
+
+JuniperInput::~JuniperInput() = default;
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.h b/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.h
new file mode 100644
index 00000000000..b9c3ee169e6
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/juniper_input.h
@@ -0,0 +1,26 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include <vespa/vespalib/stllike/string.h>
+#include <memory>
+
+namespace document { class FieldValue; }
+
+namespace search::docsummary {
+
+/*
+ * Class containing input for juniper processing.
+ */
+class JuniperInput {
+ std::unique_ptr<document::FieldValue> _field_value_with_markup;
+ vespalib::stringref _value;
+public:
+ JuniperInput(vespalib::stringref value);
+ JuniperInput(const document::FieldValue* value);
+ ~JuniperInput();
+ bool empty() const noexcept { return _value.empty(); }
+ vespalib::stringref get_value() const noexcept { return _value; };
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/juniperdfw.h b/searchsummary/src/vespa/searchsummary/docsummary/juniperdfw.h
index d9a657038c4..382cc999956 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/juniperdfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/juniperdfw.h
@@ -4,14 +4,15 @@
#include "general_result.h"
#include "resultconfig.h"
-#include "docsumfieldwriter.h"
+#include "docsum_field_writer.h"
+#include "juniper_input.h"
#include <vespa/searchlib/util/rawbuf.h>
#include <vespa/vespalib/data/slime/inserter.h>
#include <vespa/juniper/rpinterface.h>
namespace search::docsummary {
-class JuniperDFW : public IDocsumFieldWriter
+class JuniperDFW : public DocsumFieldWriter
{
public:
virtual bool Init(
@@ -21,9 +22,10 @@ public:
const char *inputField);
protected:
JuniperDFW(juniper::Juniper * juniper);
- virtual ~JuniperDFW();
+ ~JuniperDFW() override;
uint32_t _inputFieldEnumValue;
+ vespalib::string _input_field_name;
std::unique_ptr<juniper::Config> _juniperConfig;
uint32_t _langFieldEnumValue;
juniper::Juniper *_juniper;
@@ -46,13 +48,12 @@ protected:
class DynamicTeaserDFW : public JuniperTeaserDFW
{
-public:
- DynamicTeaserDFW(juniper::Juniper * juniper) : JuniperTeaserDFW(juniper) { }
-
- vespalib::stringref getJuniperInput(GeneralResult *gres);
+ JuniperInput getJuniperInput(GeneralResult *gres) __attribute__((noinline));
vespalib::string makeDynamicTeaser(uint32_t docid,
vespalib::stringref input,
GetDocsumsState *state);
+public:
+ DynamicTeaserDFW(juniper::Juniper * juniper) : JuniperTeaserDFW(juniper) { }
void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state,
ResType type, vespalib::slime::Inserter &target) override;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.cpp
index fb53ddcc470..c05fec7a0ce 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.cpp
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include "docsumstate.h"
#include "matched_elements_filter_dfw.h"
+#include "docsumstate.h"
+#include "general_result.h"
#include "struct_fields_resolver.h"
#include "summaryfieldconverter.h"
#include <vespa/document/fieldvalue/document.h>
@@ -40,21 +41,21 @@ MatchedElementsFilterDFW::MatchedElementsFilterDFW(const std::string& input_fiel
{
}
-std::unique_ptr<IDocsumFieldWriter>
+std::unique_ptr<DocsumFieldWriter>
MatchedElementsFilterDFW::create(const std::string& input_field_name, uint32_t input_field_enum,
std::shared_ptr<MatchingElementsFields> matching_elems_fields)
{
return std::make_unique<MatchedElementsFilterDFW>(input_field_name, input_field_enum, std::move(matching_elems_fields));
}
-std::unique_ptr<IDocsumFieldWriter>
+std::unique_ptr<DocsumFieldWriter>
MatchedElementsFilterDFW::create(const std::string& input_field_name, uint32_t input_field_enum,
search::attribute::IAttributeContext& attr_ctx,
std::shared_ptr<MatchingElementsFields> matching_elems_fields)
{
StructFieldsResolver resolver(input_field_name, attr_ctx, false);
if (resolver.has_error()) {
- return std::unique_ptr<IDocsumFieldWriter>();
+ return std::unique_ptr<DocsumFieldWriter>();
}
resolver.apply_to(*matching_elems_fields);
return std::make_unique<MatchedElementsFilterDFW>(input_field_name, input_field_enum, std::move(matching_elems_fields));
@@ -93,7 +94,7 @@ filter_matching_elements_in_input_field_while_converting_to_slime(const FieldVal
bool
resolve_input_field_as_slime(GeneralResult& result, int entry_idx, Slime& input_field_as_slime)
{
- ResEntry* entry = result.GetEntry(entry_idx);
+ ResEntry* entry = result.GetPresentEntry(entry_idx);
if (entry != nullptr) {
decode_input_field_to_slime(*entry, input_field_as_slime);
return true;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.h
index 505a2557408..b117da541d6 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/matched_elements_filter_dfw.h
@@ -2,7 +2,11 @@
#pragma once
-#include "docsumfieldwriter.h"
+#include "docsum_field_writer.h"
+#include <memory>
+#include <vector>
+
+namespace search { class MatchingElementsFields; }
namespace search::attribute { class IAttributeContext; }
@@ -13,7 +17,7 @@ namespace search::docsummary {
* (array of primitive, weighted set of primitive, map of primitives, map of struct, array of struct)
* that is retrieved from the document store.
*/
-class MatchedElementsFilterDFW : public IDocsumFieldWriter {
+class MatchedElementsFilterDFW : public DocsumFieldWriter {
private:
std::string _input_field_name;
uint32_t _input_field_enum;
@@ -24,11 +28,11 @@ private:
public:
MatchedElementsFilterDFW(const std::string& input_field_name, uint32_t input_field_enum,
std::shared_ptr<MatchingElementsFields> matching_elems_fields);
- static std::unique_ptr<IDocsumFieldWriter> create(const std::string& input_field_name, uint32_t input_field_enum,
- std::shared_ptr<MatchingElementsFields> matching_elems_fields);
- static std::unique_ptr<IDocsumFieldWriter> create(const std::string& input_field_name, uint32_t input_field_enum,
- search::attribute::IAttributeContext& attr_ctx,
- std::shared_ptr<MatchingElementsFields> matching_elems_fields);
+ static std::unique_ptr<DocsumFieldWriter> create(const std::string& input_field_name, uint32_t input_field_enum,
+ std::shared_ptr<MatchingElementsFields> matching_elems_fields);
+ static std::unique_ptr<DocsumFieldWriter> create(const std::string& input_field_name, uint32_t input_field_enum,
+ search::attribute::IAttributeContext& attr_ctx,
+ std::shared_ptr<MatchingElementsFields> matching_elems_fields);
~MatchedElementsFilterDFW();
bool IsGenerated() const override { return false; }
void insertField(uint32_t docid, GeneralResult* result, GetDocsumsState *state,
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.cpp
index 1fcb0a49be1..7f3a929a62f 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.cpp
@@ -270,8 +270,9 @@ PositionsDFW::UP PositionsDFW::create(const char *attribute_name, IAttributeMana
return std::make_unique<PositionsDFW>(attribute_name, useV8geoPositions);
}
-AbsDistanceDFW::UP AbsDistanceDFW::create(const char *attribute_name, IAttributeManager *attribute_manager) {
- AbsDistanceDFW::UP ret;
+std::unique_ptr<DocsumFieldWriter>
+AbsDistanceDFW::create(const char *attribute_name, IAttributeManager *attribute_manager) {
+ std::unique_ptr<DocsumFieldWriter> ret;
if (attribute_manager != nullptr) {
if (!attribute_name) {
LOG(debug, "createAbsDistanceDFW: missing attribute name '%p'", attribute_name);
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.h b/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.h
index b3e041c1379..d9445abd2ff 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/positionsdfw.h
@@ -45,7 +45,7 @@ public:
void insertField(uint32_t docid, GetDocsumsState *state,
ResType type, vespalib::slime::Inserter &target) override;
- static UP create(const char *attribute_name, IAttributeManager *index_man);
+ static std::unique_ptr<DocsumFieldWriter> create(const char *attribute_name, IAttributeManager *index_man);
};
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp
index 38b58ef94fc..5d3b104189b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.cpp
@@ -3,6 +3,7 @@
#include "rankfeaturesdfw.h"
#include "docsumstate.h"
#include <vespa/vespalib/data/slime/cursor.h>
+#include <vespa/vespalib/data/slime/inserter.h>
namespace search::docsummary {
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.h b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.h
index eab9fab60b2..91f9e80d303 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/rankfeaturesdfw.h
@@ -2,11 +2,13 @@
#pragma once
-#include "summaryfeaturesdfw.h"
+#include "simple_dfw.h"
namespace search::docsummary {
-class RankFeaturesDFW : public ISimpleDFW
+class IDocsumEnvironment;
+
+class RankFeaturesDFW : public SimpleDFW
{
private:
IDocsumEnvironment * _env;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/res_type.h b/searchsummary/src/vespa/searchsummary/docsummary/res_type.h
new file mode 100644
index 00000000000..02c9f1522a4
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/res_type.h
@@ -0,0 +1,30 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+namespace search::docsummary {
+
+/**
+ * This enumeration contains values denoting the different types of
+ * docsum fields. NOTE: The internal implementation depends on RES_INT
+ * having the value 0. All types < RES_STRING must be fixed size and
+ * all types > RES_STRING must be variable size.
+ **/
+enum ResType {
+ RES_INT = 0,
+ RES_SHORT,
+ RES_BOOL,
+ RES_BYTE,
+ RES_FLOAT,
+ RES_DOUBLE,
+ RES_INT64,
+ RES_STRING,
+ RES_DATA,
+ RES_LONG_STRING,
+ RES_LONG_DATA,
+ RES_JSONSTRING,
+ RES_TENSOR,
+ RES_FEATUREDATA
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.cpp b/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.cpp
new file mode 100644
index 00000000000..98cc8372ac1
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.cpp
@@ -0,0 +1,29 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "res_type_utils.h"
+
+namespace search::docsummary {
+
+const char *
+ResTypeUtils::GetResTypeName(ResType type)
+{
+ switch (type) {
+ case RES_INT: return "integer";
+ case RES_SHORT: return "short";
+ case RES_BYTE: return "byte";
+ case RES_BOOL: return "bool";
+ case RES_FLOAT: return "float";
+ case RES_DOUBLE: return "double";
+ case RES_INT64: return "int64";
+ case RES_STRING: return "string";
+ case RES_DATA: return "data";
+ case RES_LONG_STRING: return "longstring";
+ case RES_LONG_DATA: return "longdata";
+ case RES_JSONSTRING: return "jsonstring";
+ case RES_TENSOR: return "tensor";
+ case RES_FEATUREDATA: return "featuredata";
+ }
+ return "unknown-type";
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.h b/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.h
new file mode 100644
index 00000000000..194a008c179
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/res_type_utils.h
@@ -0,0 +1,102 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "res_type.h"
+
+namespace search::docsummary {
+
+
+/*
+ * Utilitiy functions for checking if result type is ok.
+ */
+struct ResTypeUtils
+{
+ /**
+ * Determine if a result field type is of variable size.
+ *
+ * @return true for variable size field types, false for fixed
+ * size field types
+ **/
+ static bool IsVariableSize(ResType t) { return (t >= RES_STRING); }
+
+
+ /**
+ * Determine if a pair of result field types are binary
+ * compatible. A pair of types are binary compatible if the packed
+ * representation is identical.
+ *
+ * @return true if the given types are binary compatible.
+ * @param a enum value of a result field type.
+ * @param b enum value of a result field type.
+ **/
+ static bool IsBinaryCompatible(ResType a, ResType b)
+ {
+ if (a == b) {
+ return true;
+ }
+ switch (a) {
+ case RES_BYTE:
+ case RES_BOOL:
+ return (b == RES_BYTE || b == RES_BOOL);
+ case RES_STRING:
+ case RES_DATA:
+ return (b == RES_STRING || b == RES_DATA);
+ case RES_LONG_STRING:
+ case RES_LONG_DATA:
+ case RES_FEATUREDATA:
+ case RES_JSONSTRING:
+ return (b == RES_LONG_STRING || b == RES_LONG_DATA ||
+ b == RES_FEATUREDATA || b == RES_JSONSTRING);
+ default:
+ return false;
+ }
+ return false;
+ }
+
+
+ /**
+ * Determine if a pair of result field types are runtime
+ * compatible. A pair of types are runtime compatible if the
+ * unpacked (@ref ResEntry) representation is identical.
+ *
+ * @return true if the given types are runtime compatible.
+ * @param a enum value of a result field type.
+ * @param b enum value of a result field type.
+ **/
+ static bool IsRuntimeCompatible(ResType a, ResType b)
+ {
+ switch (a) {
+ case RES_INT:
+ case RES_SHORT:
+ case RES_BYTE:
+ case RES_BOOL:
+ return (b == RES_INT || b == RES_SHORT || b == RES_BYTE || b == RES_BOOL);
+ case RES_FLOAT:
+ case RES_DOUBLE:
+ return (b == RES_FLOAT || b == RES_DOUBLE);
+ case RES_INT64:
+ return b == RES_INT64;
+ case RES_STRING:
+ case RES_LONG_STRING:
+ case RES_JSONSTRING:
+ return (b == RES_STRING || b == RES_LONG_STRING || b == RES_JSONSTRING);
+ case RES_DATA:
+ case RES_LONG_DATA:
+ return (b == RES_DATA || b == RES_LONG_DATA);
+ case RES_TENSOR:
+ return (b == RES_TENSOR);
+ case RES_FEATUREDATA:
+ return (b == RES_FEATUREDATA);
+ }
+ return false;
+ }
+
+ /**
+ * @return the name of the given result field type.
+ * @param resType enum value of a result field type.
+ **/
+ static const char *GetResTypeName(ResType type);
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultclass.cpp b/searchsummary/src/vespa/searchsummary/docsummary/resultclass.cpp
index 37be8e0a1b2..65db72efc40 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultclass.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultclass.cpp
@@ -7,7 +7,7 @@
namespace search::docsummary {
-ResultClass::ResultClass(const char *name, uint32_t id, util::StringEnum & fieldEnum)
+ResultClass::ResultClass(const char *name, uint32_t id, util::StringEnum & fieldEnum, const DocsumBlobEntryFilter& docsum_blob_entry_filter)
: _name(name),
_classID(id),
_entries(),
@@ -15,7 +15,8 @@ ResultClass::ResultClass(const char *name, uint32_t id, util::StringEnum & field
_fieldEnum(fieldEnum),
_enumMap(),
_dynInfo(NULL),
- _omit_summary_features(false)
+ _omit_summary_features(false),
+ _docsum_blob_entry_filter(docsum_blob_entry_filter)
{ }
@@ -37,6 +38,7 @@ ResultClass::AddConfigEntry(const char *name, ResType type)
_nameMap[name] = _entries.size();
ResConfigEntry e;
e._type = type;
+ e._not_present = _docsum_blob_entry_filter.skip(type);
e._bindname = name;
e._enumValue = _fieldEnum.Add(name);
assert(e._enumValue >= 0);
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultclass.h b/searchsummary/src/vespa/searchsummary/docsummary/resultclass.h
index be3bb7570d2..47feed70e97 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultclass.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultclass.h
@@ -2,6 +2,7 @@
#pragma once
+#include "docsum_blob_entry_filter.h"
#include <vespa/searchlib/util/rawbuf.h>
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/stllike/hash_map.h>
@@ -10,30 +11,6 @@
namespace search::docsummary {
/**
- * This enumeration contains values denoting the different types of
- * docsum fields. NOTE: The internal implementation depends on RES_INT
- * having the value 0. All types < RES_STRING must be fixed size and
- * all types > RES_STRING must be variable size.
- **/
-enum ResType {
- RES_INT = 0,
- RES_SHORT,
- RES_BOOL,
- RES_BYTE,
- RES_FLOAT,
- RES_DOUBLE,
- RES_INT64,
- RES_STRING,
- RES_DATA,
- RES_LONG_STRING,
- RES_LONG_DATA,
- RES_JSONSTRING,
- RES_TENSOR,
- RES_FEATUREDATA
-};
-
-
-/**
* This struct describes a single docsum field (name and type). A
* docsum blob is unpacked into an array of ResEntry instances
* by interpreting it as described by an array of ResConfigEntry
@@ -41,6 +18,7 @@ enum ResType {
**/
struct ResConfigEntry {
ResType _type;
+ bool _not_present; // Entry not present in docsum blob when _not_present is set
vespalib::string _bindname;
int _enumValue;
};
@@ -57,6 +35,7 @@ struct ResConfigEntry {
struct ResEntry
{
ResType _type;
+ bool _not_present; // Entry not present in docsum blob when _not_present is set
union {
uint32_t _intval;
uint32_t _stringlen;
@@ -71,15 +50,6 @@ struct ResEntry
void *_pt;
};
- uint32_t _get_length() const { return _len; }
- uint32_t _get_real_length() const
- {
- // precond: IsVariableSize(_type) && _len >= sizeof(uint32_t)
-
- uint32_t rlen;
- memcpy(&rlen, _pt, sizeof(rlen));
- return rlen;
- }
void _resolve_field(const char **buf, uint32_t *buflen) const
{
// precond: IsVariableSize(_type)
@@ -122,6 +92,7 @@ private:
// Whether or not summary features should be omitted when filling this summary class.
// As default, summary features are always included.
bool _omit_summary_features;
+ DocsumBlobEntryFilter _docsum_blob_entry_filter;
public:
typedef std::unique_ptr<ResultClass> UP;
@@ -134,7 +105,7 @@ public:
* @param id the numeric id of this result class.
* @param fieldEnum shared object used to enumerate field names.
**/
- ResultClass(const char *name, uint32_t id, util::StringEnum & fieldEnum);
+ ResultClass(const char *name, uint32_t id, util::StringEnum & fieldEnum, const DocsumBlobEntryFilter& docsum_blob_entry_filter);
/**
* Destructor. Delete internal structures.
@@ -225,7 +196,7 @@ public:
* GeneralResult::GetEntry(string) method; no need to call it
* directly.
*
- * @return field index or -1 if not found.
+ * @return field index or -1 if not found
**/
int GetIndexFromName(const char* name) const;
@@ -242,7 +213,7 @@ public:
* call it directly. NOTE3: You need to call the CreateEnumMap
* method before calling this one.
*
- * @return field index or -1 if not found.
+ * @return field index or -1 if not found
**/
int GetIndexFromEnumValue(uint32_t value) const
{
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.cpp b/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.cpp
index 02bb5d25ca4..168b4c81374 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "resultconfig.h"
+#include "resultclass.h"
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <atomic>
@@ -25,9 +26,15 @@ ResultConfig::Init()
ResultConfig::ResultConfig()
+ : ResultConfig(DocsumBlobEntryFilter())
+{
+}
+
+ResultConfig::ResultConfig(const DocsumBlobEntryFilter& docsum_blob_entry_filter)
: _defaultSummaryId(-1),
_classLookup(),
- _nameLookup()
+ _nameLookup(),
+ _docsum_blob_entry_filter(docsum_blob_entry_filter)
{
Init();
}
@@ -39,28 +46,6 @@ ResultConfig::~ResultConfig()
}
-const char *
-ResultConfig::GetResTypeName(ResType type)
-{
- switch (type) {
- case RES_INT: return "integer";
- case RES_SHORT: return "short";
- case RES_BYTE: return "byte";
- case RES_BOOL: return "bool";
- case RES_FLOAT: return "float";
- case RES_DOUBLE: return "double";
- case RES_INT64: return "int64";
- case RES_STRING: return "string";
- case RES_DATA: return "data";
- case RES_LONG_STRING: return "longstring";
- case RES_LONG_DATA: return "longdata";
- case RES_JSONSTRING: return "jsonstring";
- case RES_TENSOR: return "tensor";
- case RES_FEATUREDATA: return "featuredata";
- }
- return "unknown-type";
-}
-
void
ResultConfig::Reset()
{
@@ -77,7 +62,7 @@ ResultConfig::AddResultClass(const char *name, uint32_t id)
ResultClass *ret = nullptr;
if (id != NoClassID() && (_classLookup.find(id) == _classLookup.end())) {
- ResultClass::UP rc(new ResultClass(name, id, _fieldEnum));
+ ResultClass::UP rc(new ResultClass(name, id, _fieldEnum, _docsum_blob_entry_filter));
ret = rc.get();
_classLookup[id] = std::move(rc);
if (_nameLookup.find(name) != _nameLookup.end()) {
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.h b/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.h
index 8c5895a779d..945eef8514f 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultconfig.h
@@ -2,14 +2,15 @@
#pragma once
-#include "resultclass.h"
-#include "general_result.h"
+#include "docsum_blob_entry_filter.h"
+#include "res_type_utils.h"
#include <vespa/config-summary.h>
-#include <vespa/searchlib/util/rawbuf.h>
#include <vespa/searchlib/util/stringenum.h>
namespace search::docsummary {
+class ResultClass;
+
/**
* This class represents the overall result configuration. A result
* configuration may contain multiple result classes, where each
@@ -31,12 +32,13 @@ private:
ResultConfig& operator=(const ResultConfig &);
typedef vespalib::hash_map<vespalib::string, uint32_t> NameMap;
- typedef vespalib::hash_map<uint32_t, ResultClass::UP> IdMap;
+ typedef vespalib::hash_map<uint32_t, std::unique_ptr<ResultClass>> IdMap;
uint32_t _defaultSummaryId;
bool _useV8geoPositions;
search::util::StringEnum _fieldEnum;
IdMap _classLookup;
NameMap _nameLookup; // name -> class id
+ DocsumBlobEntryFilter _docsum_blob_entry_filter;
void Clean();
void Init();
@@ -79,6 +81,7 @@ public:
* NOTE: This method simply calls the Init method.
**/
ResultConfig();
+ ResultConfig(const DocsumBlobEntryFilter& docsum_blob_entry_filter);
/**
* Destructor. Delete all internal structures. NOTE: This method
@@ -93,85 +96,9 @@ public:
static uint32_t NoClassID() { return static_cast<uint32_t>(-1); }
- /**
- * Determine if a result field type is of variable size.
- *
- * @return true for variable size field types, false for fixed
- * size field types
- **/
- static bool IsVariableSize(ResType t) { return (t >= RES_STRING); }
-
-
- /**
- * Determine if a pair of result field types are binary
- * compatible. A pair of types are binary compatible if the packed
- * representation is identical.
- *
- * @return true if the given types are binary compatible.
- * @param a enum value of a result field type.
- * @param b enum value of a result field type.
- **/
- static bool IsBinaryCompatible(ResType a, ResType b)
- {
- if (a == b) {
- return true;
- }
- switch (a) {
- case RES_BYTE:
- case RES_BOOL:
- return (b == RES_BYTE || b == RES_BOOL);
- case RES_STRING:
- case RES_DATA:
- return (b == RES_STRING || b == RES_DATA);
- case RES_LONG_STRING:
- case RES_LONG_DATA:
- case RES_FEATUREDATA:
- case RES_JSONSTRING:
- return (b == RES_LONG_STRING || b == RES_LONG_DATA ||
- b == RES_FEATUREDATA || b == RES_JSONSTRING);
- default:
- return false;
- }
- return false;
- }
-
-
- /**
- * Determine if a pair of result field types are runtime
- * compatible. A pair of types are runtime compatible if the
- * unpacked (@ref ResEntry) representation is identical.
- *
- * @return true if the given types are runtime compatible.
- * @param a enum value of a result field type.
- * @param b enum value of a result field type.
- **/
- static bool IsRuntimeCompatible(ResType a, ResType b)
- {
- switch (a) {
- case RES_INT:
- case RES_SHORT:
- case RES_BYTE:
- case RES_BOOL:
- return (b == RES_INT || b == RES_SHORT || b == RES_BYTE || b == RES_BOOL);
- case RES_FLOAT:
- case RES_DOUBLE:
- return (b == RES_FLOAT || b == RES_DOUBLE);
- case RES_INT64:
- return b == RES_INT64;
- case RES_STRING:
- case RES_LONG_STRING:
- case RES_JSONSTRING:
- return (b == RES_STRING || b == RES_LONG_STRING || b == RES_JSONSTRING);
- case RES_DATA:
- case RES_LONG_DATA:
- return (b == RES_DATA || b == RES_LONG_DATA);
- case RES_TENSOR:
- return (b == RES_TENSOR);
- case RES_FEATUREDATA:
- return (b == RES_FEATUREDATA);
- }
- return false;
- }
+ static bool IsVariableSize(ResType t) { return ResTypeUtils::IsVariableSize(t); }
+ static bool IsBinaryCompatible(ResType a, ResType b) { return ResTypeUtils::IsBinaryCompatible(a, b); }
+ static bool IsRuntimeCompatible(ResType a, ResType b) { return ResTypeUtils::IsRuntimeCompatible(a, b); }
// whether last config seen wanted useV8geoPositions = true
static bool wantedV8geoPositions();
@@ -180,7 +107,7 @@ public:
* @return the name of the given result field type.
* @param resType enum value of a result field type.
**/
- static const char *GetResTypeName(ResType type);
+ static const char *GetResTypeName(ResType type) { return ResTypeUtils::GetResTypeName(type); }
/**
* Discard the current configuration and start over. After this
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.cpp b/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.cpp
index 4ab06cbd41a..66b15c1c8a9 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "resultpacker.h"
+#include "resultconfig.h"
#include <vespa/searchcommon/common/undefinedvalues.h>
#include <vespa/vespalib/util/size_literals.h>
@@ -19,6 +20,14 @@ ResultPacker::WarnType(ResType type) const
GetResTypeName(_cfgEntry->_type));
}
+void
+ResultPacker::skip_entries_not_present()
+{
+ while (_cfgEntry != nullptr && _cfgEntry->_not_present) {
+ _cfgEntry = _resClass->GetEntry(++_entryIdx);
+ }
+}
+
bool ResultPacker::CheckEntry(ResType type)
{
if (_error)
@@ -32,6 +41,7 @@ bool ResultPacker::CheckEntry(ResType type)
WarnType(type);
}
_cfgEntry = _resClass->GetEntry(++_entryIdx);
+ skip_entries_not_present();
} else {
SetFormatError(type);
}
@@ -88,6 +98,7 @@ ResultPacker::Init(uint32_t classID)
uint32_t id = _resClass->GetClassID();
_buf.append(&id, sizeof(id));
_cfgEntry = _resClass->GetEntry(_entryIdx);
+ skip_entries_not_present();
_error = false;
} else {
_cfgEntry = nullptr;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.h b/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.h
index 4aa31b2df23..816433652b8 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/resultpacker.h
@@ -2,9 +2,14 @@
#pragma once
-#include "resultconfig.h"
+#include "res_type_utils.h"
+#include "resultclass.h"
+#include <vespa/searchlib/util/rawbuf.h>
namespace search::docsummary {
+
+class ResultConfig;
+
/**
* An Object of this class may be used to create docsum blobs. A
* single blob is created by first indicating what result class the
@@ -27,15 +32,13 @@ private:
const ResConfigEntry *_cfgEntry; // current field of current blob
bool _error; // error flag for current blob
- static const char *GetResTypeName(ResType type)
- { return ResultConfig::GetResTypeName(type); }
-
- static bool IsBinaryCompatible(ResType a, ResType b)
- { return ResultConfig::IsBinaryCompatible(a, b); }
+ static const char *GetResTypeName(ResType type) { return ResTypeUtils::GetResTypeName(type); }
+ static bool IsBinaryCompatible(ResType a, ResType b) { return ResTypeUtils::IsBinaryCompatible(a, b); }
void WarnType(ResType type) const;
void SetFormatError(ResType type);
+ void skip_entries_not_present();
bool CheckEntry(ResType type);
public:
@@ -249,6 +252,11 @@ public:
**/
bool GetDocsumBlob(const char **buf, uint32_t *buflen);
+ /*
+ * Get index of next entry to add. Used by proton::DocumentStoreAdapter
+ * and vsm::DocsumFilter to track entries to skip.
+ */
+ uint32_t get_entry_idx() const noexcept { return _entryIdx; }
};
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.cpp
new file mode 100644
index 00000000000..8cc872378bd
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.cpp
@@ -0,0 +1,13 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "simple_dfw.h"
+
+namespace search::docsummary {
+
+void
+SimpleDFW::insertField(uint32_t docid, GeneralResult *, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target)
+{
+ insertField(docid, state, type, target);
+}
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.h b/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.h
new file mode 100644
index 00000000000..abebb7de2b8
--- /dev/null
+++ b/searchsummary/src/vespa/searchsummary/docsummary/simple_dfw.h
@@ -0,0 +1,20 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+#include "docsum_field_writer.h"
+
+namespace search::docsummary {
+
+/*
+ * Abstract class for writing document summaries that don't need
+ * access to a document retrieved from IDocsumStore.
+ */
+class SimpleDFW : public DocsumFieldWriter
+{
+public:
+ virtual void insertField(uint32_t docid, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) = 0;
+ void insertField(uint32_t docid, GeneralResult *, GetDocsumsState *state, ResType type, vespalib::slime::Inserter &target) override;
+};
+
+}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/struct_map_attribute_combiner_dfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/struct_map_attribute_combiner_dfw.cpp
index aec55977546..38a9cc8c50b 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/struct_map_attribute_combiner_dfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/struct_map_attribute_combiner_dfw.cpp
@@ -9,6 +9,7 @@
#include <vespa/searchlib/common/matching_elements.h>
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/vespalib/data/slime/cursor.h>
+#include <vespa/vespalib/data/slime/inserter.h>
#include <vespa/vespalib/util/stash.h>
#include <algorithm>
#include <cassert>
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp
index f920b7be0cd..c28e986612c 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.cpp
@@ -3,6 +3,7 @@
#include "summaryfeaturesdfw.h"
#include "docsumstate.h"
#include <vespa/vespalib/data/slime/cursor.h>
+#include <vespa/vespalib/data/slime/inserter.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.docsummary.summaryfeaturesdfw");
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.h b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.h
index 6c4084b0221..d12feb69182 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/summaryfeaturesdfw.h
@@ -2,13 +2,13 @@
#pragma once
-#include "docsumfieldwriter.h"
+#include "simple_dfw.h"
namespace search::docsummary {
class IDocsumEnvironment;
-class SummaryFeaturesDFW : public ISimpleDFW
+class SummaryFeaturesDFW : public SimpleDFW
{
private:
IDocsumEnvironment * _env;
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.cpp b/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.cpp
index c107e5c8739..18ed7ebd6cc 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.cpp
+++ b/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "summaryfieldconverter.h"
+#include "check_undefined_value_visitor.h"
#include "linguisticsannotation.h"
#include "resultconfig.h"
#include "searchdatatype.h"
@@ -462,7 +463,7 @@ private:
}
void visit(const PredicateFieldValue &value) override {
- vespalib::slime::inject(value.getSlime().get(), _inserter);
+ _inserter.insertString(value.toString());
}
void visit(const RawFieldValue &value) override {
@@ -593,5 +594,15 @@ SummaryFieldConverter::convert_field_with_filter(bool markup,
return SummaryFieldValueConverter(markup, sub_conv).convert(value);
}
+void
+SummaryFieldConverter::insert_summary_field(const FieldValue& value, vespalib::slime::Inserter& inserter)
+{
+ CheckUndefinedValueVisitor check_undefined;
+ value.accept(check_undefined);
+ if (!check_undefined.is_undefined()) {
+ SlimeFiller visitor(inserter, false);
+ value.accept(visitor);
+ }
+}
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.h b/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.h
index 526b8c64130..23d20b23c1f 100644
--- a/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.h
+++ b/searchsummary/src/vespa/searchsummary/docsummary/summaryfieldconverter.h
@@ -4,6 +4,8 @@
#include <vespa/document/fieldvalue/fieldvalue.h>
+namespace vespalib::slime { struct Inserter; }
+
namespace search::docsummary {
/**
@@ -22,6 +24,8 @@ public:
static document::FieldValue::UP convert_field_with_filter(bool markup,
const document::FieldValue& value,
const std::vector<uint32_t>& matching_elems);
+
+ static void insert_summary_field(const document::FieldValue& value, vespalib::slime::Inserter& inserter);
};
}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp b/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp
deleted file mode 100644
index c85a4fb5788..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "textextractordfw.h"
-#include "tokenizer.h"
-#include "docsumstate.h"
-
-#include <vespa/log/log.h>
-LOG_SETUP(".searchlib.docsummary.textextractordfw");
-
-namespace search::docsummary {
-
-TextExtractorDFW::TextExtractorDFW() :
- _inputFieldEnum(-1)
-{
-}
-
-bool
-TextExtractorDFW::init(const vespalib::string & fieldName, const vespalib::string & inputField, const ResultConfig & config)
-{
- _inputFieldEnum = config.GetFieldNameEnum().Lookup(inputField.c_str());
- if (_inputFieldEnum == -1) {
- LOG(warning, "Did not find input field '%s' as part of the docsum fields when initializing writer for field '%s'",
- inputField.c_str(), fieldName.c_str());
- return false;
- }
- return true;
-}
-
-void
-TextExtractorDFW::insertField(uint32_t, GeneralResult *gres, GetDocsumsState *, ResType,
- vespalib::slime::Inserter &target)
-{
- vespalib::string extracted;
- ResEntry * entry = gres->GetEntryFromEnumValue(_inputFieldEnum);
- if (entry != nullptr) {
- const char * buf = nullptr;
- uint32_t buflen = 0;
- entry->_resolve_field(&buf, &buflen);
- // extract the text
- Tokenizer tokenizer(buf, buflen);
- while (tokenizer.hasMoreTokens()) {
- Tokenizer::Token token = tokenizer.getNextToken();
- extracted.append(token.getText());
- }
- } else {
- LOG(warning, "Did not find input entry using field enum %d. Write an empty field", _inputFieldEnum);
- }
- target.insertString(vespalib::Memory(extracted.c_str(), extracted.size()));
-}
-
-}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.h b/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.h
deleted file mode 100644
index 10764e5c21d..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#pragma once
-
-#include "docsumfieldwriter.h"
-
-namespace search::docsummary {
-
-/**
- * This is the docsum field writer used to extract the original text from a disk summary on the juniper format.
- **/
-class TextExtractorDFW : public IDocsumFieldWriter
-{
-private:
- TextExtractorDFW(const TextExtractorDFW &);
- TextExtractorDFW & operator=(const TextExtractorDFW &);
-
- int _inputFieldEnum;
-
-public:
- TextExtractorDFW();
- ~TextExtractorDFW() {}
- bool init(const vespalib::string & fieldName, const vespalib::string & inputField, const ResultConfig & config);
- bool IsGenerated() const override { return false; }
- void insertField(uint32_t docid, GeneralResult *gres, GetDocsumsState *state,
- ResType type, vespalib::slime::Inserter &target) override;
-};
-
-}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.cpp b/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.cpp
deleted file mode 100644
index 44dbedb4fe9..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "tokenizer.h"
-#include <cassert>
-
-namespace search::docsummary {
-
-Tokenizer::Token::Type
-Tokenizer::getTokenType(ucs4_t ch) const
-{
- if (Fast_UnicodeUtil::IsWordChar(ch)) {
- return Token::WORD;
- } else {
- if (Fast_UnicodeUtil::IsTerminalPunctuationChar(ch)) {
- return Token::PUNCTUATION;
- } else {
- return Token::NON_WORD;
- }
- }
-}
-
-Tokenizer::Tokenizer(const char * buf, size_t len) :
- _pos(buf),
- _begin(buf),
- _end(buf + len),
- _tokenBegin(buf),
- _type(Token::NOT_DEF),
- _hasMoreTokens(_pos < _end)
-{
-}
-
-void
-Tokenizer::reset(const char * buf, size_t len)
-{
- _pos = buf;
- _begin = buf;
- _end = buf + len;
- _tokenBegin = buf;
- _type = Token::NOT_DEF;
- _hasMoreTokens = (_pos < _end);
-}
-
-bool
-Tokenizer::hasMoreTokens()
-{
- return _hasMoreTokens;
-}
-
-Tokenizer::Token
-Tokenizer::getNextToken()
-{
- const char * textBegin = _tokenBegin;
- const char * textEnd = _pos;
- const char * stemBegin = NULL;
- const char * stemEnd = NULL;
- const char * next = _pos;
- bool insideAnnotation = false;
- for (; _pos < _end; ) {
- ucs4_t ch;
- if (static_cast<unsigned char>(*next) < 0x80) {
- ch = *next++;
- if (ch == 0x1F) { // unit separator
- Token t(textBegin, textEnd, stemBegin, stemEnd, _type);
- _pos = next; // advance to next char
- _tokenBegin = next; // the next token begins at the next char
- _type = Token::NOT_DEF; // reset the token type
- if (_pos == _end) { // this is the last token
- _hasMoreTokens = false;
- }
- return t;
- }
- } else {
- ch = Fast_UnicodeUtil::GetUTF8CharNonAscii(next); // updates next to the next utf8 character
- if (ch == 0xFFF9) { // anchor
- insideAnnotation = true;
- textBegin = next;
- _type = Token::ANNOTATION;
- }
- }
- if (!insideAnnotation) {
- Token::Type tmpType = getTokenType(ch);
- if (_type != Token::NOT_DEF && _type != tmpType) { // we found a new token type
- Token t(textBegin, textEnd, stemBegin, stemEnd, _type);
- _tokenBegin = _pos; // the next token begins at this char
- _pos = next; // advance to next char
- _type = tmpType; // remember the new token type
- return t;
- }
- _type = tmpType;
- textEnd = next; // advance to next char
- } else { // inside annotation
- if (ch == 0xFFFA) { // separator
- textEnd = _pos;
- stemBegin = next;
- } else if (ch == 0xFFFB && stemBegin != NULL) { // terminator
- stemEnd = _pos;
- insideAnnotation = false;
- }
- }
-
- _pos = next;
- }
- assert(_pos == _end);
- _hasMoreTokens = false;
- return Token(textBegin, _pos, _type); // return the last token
-}
-
-}
diff --git a/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.h b/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.h
deleted file mode 100644
index 77acc97aec9..00000000000
--- a/searchsummary/src/vespa/searchsummary/docsummary/tokenizer.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#pragma once
-
-#include "itokenizer.h"
-#include <vespa/fastlib/text/unicodeutil.h>
-
-namespace search::docsummary {
-
-/**
- * This class is used to tokenize an utf-8 text buffer into tokens of type
- * WORD, NON_WORD, PUNCTUATION, and ANNOTATION.
- *
- * Functions in Fast_UnicodeUtil are used to determine word characters and terminal punctuation characters.
- * The unit separator 0x1F is always treated as a token separator. The unit separator itself is not returned as a token.
- * Interlinear annotation (0xFFF9 original 0xFFFA stemmed 0xFFFB) is used to specify the stemmed variant of a word.
- * The annotation characters are not returned as part of a token.
- */
-class Tokenizer : public ITokenizer
-{
-private:
- const char * _pos; // the current position in the input buffer
- const char * _begin; // the begin of input buffer
- const char * _end; // the end of the input buffer
- const char * _tokenBegin; // the start of the next token
- Token::Type _type; // the type of the current position
- bool _hasMoreTokens; // do we have more tokens
-
- Token::Type getTokenType(ucs4_t ch) const;
-
-public:
- /**
- * Creates a new tokenizer for the given utf-8 text buffer.
- */
- Tokenizer(const char * buf, size_t len);
-
- void reset(const char * buf, size_t len) override;
- size_t getBufferSize() const override { return _end - _begin; }
- bool hasMoreTokens() override;
- Token getNextToken() override;
-};
-
-}
diff --git a/security-tools/pom.xml b/security-tools/pom.xml
index 7f248c185a2..2af6e09a84d 100644
--- a/security-tools/pom.xml
+++ b/security-tools/pom.xml
@@ -27,13 +27,18 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java b/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
index 4b8f4bf0156..b1d263a1a82 100644
--- a/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
+++ b/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.security.tool.securityenv;
import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.TransportSecurityOptions;
import com.yahoo.security.tls.TransportSecurityUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
+import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@@ -30,18 +30,18 @@ public class MainTest {
private final PrintStream stdOut = new PrintStream(stdOutBytes);
private final PrintStream stdError = new PrintStream(stdErrBytes);
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void prints_help_page_on_help_option() throws IOException {
+ void prints_help_page_on_help_option() throws IOException {
int exitCode = runMain(List.of("--help"), Map.of());
assertThat(exitCode).isEqualTo(0);
assertThat(stdOut()).isEqualTo(readTestResource("expected-help-output.txt"));
}
@Test
- public void unsets_all_variables_when_no_security_config() throws IOException {
+ void unsets_all_variables_when_no_security_config() throws IOException {
int exitCode = runMain(List.of(), Map.of());
assertThat(exitCode).isEqualTo(0);
assertThat(stdErr()).isEmpty();
@@ -49,7 +49,7 @@ public class MainTest {
}
@Test
- public void prints_security_variables_with_specified_shell() throws IOException {
+ void prints_security_variables_with_specified_shell() throws IOException {
Path configFile = generateConfigFile();
Map<String, String> env = Map.of(TransportSecurityUtils.CONFIG_FILE_ENVIRONMENT_VARIABLE, configFile.toString());
int exitCode = runMain(List.of(), env);
@@ -58,7 +58,7 @@ public class MainTest {
}
@Test
- public void prints_security_variables_with_auto_detected_shell() throws IOException {
+ void prints_security_variables_with_auto_detected_shell() throws IOException {
Path configFile = generateConfigFile();
Map<String, String> env = Map.of(
TransportSecurityUtils.CONFIG_FILE_ENVIRONMENT_VARIABLE, configFile.toString(),
@@ -71,14 +71,14 @@ public class MainTest {
@Test
- public void prints_error_message_on_unknown_shell_name() {
+ void prints_error_message_on_unknown_shell_name() {
int exitCode = runMain(List.of("--shell", "invalid-shell-name"), Map.of());
assertThat(exitCode).isEqualTo(1);
assertThat(stdErr()).isEqualTo("Invalid command line arguments: Unknown shell: invalid-shell-name\n");
}
@Test
- public void prints_error_message_on_unknown_command_line_parameter() {
+ void prints_error_message_on_unknown_command_line_parameter() {
int exitCode = runMain(List.of("--unknown-parameter"), Map.of());
assertThat(exitCode).isEqualTo(1);
assertThat(stdErr()).isEqualTo("Failed to parse command line arguments: Unrecognized option: --unknown-parameter\n");
@@ -108,7 +108,7 @@ public class MainTest {
.withCaCertificates(Paths.get("/path/to/cacerts"))
.withHostnameValidationDisabled(true)
.build();
- Path configFile = tmpFolder.newFile().toPath();
+ Path configFile = File.createTempFile("junit", null, tmpFolder).toPath();
options.toJsonFile(configFile);
return configFile;
}
diff --git a/security-utils/pom.xml b/security-utils/pom.xml
index d4b4bc8d0f6..71920327fbb 100644
--- a/security-utils/pom.xml
+++ b/security-utils/pom.xml
@@ -35,17 +35,6 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>testutil</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
@@ -60,21 +49,12 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <release>${vespaClients.jdk.releaseVersion}</release>
- <showDeprecation>true</showDeprecation>
- </configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
@@ -89,7 +69,10 @@
</executions>
</plugin>
<plugin>
- <!-- Build with maven-bundle-plugin to avoid depending on jdisc_core to get the correct Import-Packages -->
+ <!--
+ Build with maven-bundle-plugin to avoid depending on jdisc_core to get the correct Import-Packages
+ Jackson and BC compile scope dependencies are not embedded. Packages are instead imported through manifest.
+ -->
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/AutoReloadingX509KeyManager.java b/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java
index 259d4b50d3f..243343240cb 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/AutoReloadingX509KeyManager.java
+++ b/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java
@@ -1,11 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
-
-import com.yahoo.security.KeyStoreBuilder;
-import com.yahoo.security.KeyStoreType;
-import com.yahoo.security.KeyUtils;
-import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.X509CertificateWithKey;
+package com.yahoo.security;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/KeyManagerUtils.java b/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java
index c9216d7273c..5611ef5162b 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/KeyManagerUtils.java
+++ b/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java
@@ -1,8 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
-
-import com.yahoo.security.KeyStoreBuilder;
-import com.yahoo.security.KeyStoreType;
+package com.yahoo.security;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/MutableX509KeyManager.java b/security-utils/src/main/java/com/yahoo/security/MutableX509KeyManager.java
index 6d784efc3e8..3ba6c8f2723 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/MutableX509KeyManager.java
+++ b/security-utils/src/main/java/com/yahoo/security/MutableX509KeyManager.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/MutableX509TrustManager.java b/security-utils/src/main/java/com/yahoo/security/MutableX509TrustManager.java
index 6db43ef94a9..afbd0a6fa86 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/MutableX509TrustManager.java
+++ b/security-utils/src/main/java/com/yahoo/security/MutableX509TrustManager.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
diff --git a/security-utils/src/main/java/com/yahoo/security/Pkcs10CsrBuilder.java b/security-utils/src/main/java/com/yahoo/security/Pkcs10CsrBuilder.java
index 9b999e056e0..d7353711a2a 100644
--- a/security-utils/src/main/java/com/yahoo/security/Pkcs10CsrBuilder.java
+++ b/security-utils/src/main/java/com/yahoo/security/Pkcs10CsrBuilder.java
@@ -21,7 +21,7 @@ import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
/**
* @author bjorncs
@@ -49,7 +49,7 @@ public class Pkcs10CsrBuilder {
}
public Pkcs10CsrBuilder addSubjectAlternativeName(String dns) {
- this.subjectAlternativeNames.add(new SubjectAlternativeName(DNS_NAME, dns));
+ this.subjectAlternativeNames.add(new SubjectAlternativeName(DNS, dns));
return this;
}
diff --git a/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java b/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java
index 5c16e4ed70d..d91c47e5eed 100644
--- a/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java
+++ b/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java
@@ -1,10 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import com.yahoo.security.tls.KeyManagerUtils;
-import com.yahoo.security.tls.TlsContext;
-import com.yahoo.security.tls.TrustManagerUtils;
-
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
@@ -133,7 +129,7 @@ public class SslContextBuilder {
public SSLContext build() {
try {
- SSLContext sslContext = SSLContext.getInstance(TlsContext.SSL_CONTEXT_VERSION);
+ SSLContext sslContext = SSLContext.getInstance("TLS");
X509ExtendedTrustManager trustManager = this.trustManager != null
? this.trustManager
: trustManagerFactory.createTrustManager(trustStoreSupplier.get());
diff --git a/security-utils/src/main/java/com/yahoo/security/SubjectAlternativeName.java b/security-utils/src/main/java/com/yahoo/security/SubjectAlternativeName.java
index 92dd41f7f88..c01de58987c 100644
--- a/security-utils/src/main/java/com/yahoo/security/SubjectAlternativeName.java
+++ b/security-utils/src/main/java/com/yahoo/security/SubjectAlternativeName.java
@@ -99,15 +99,15 @@ public class SubjectAlternativeName {
}
public enum Type {
- OTHER_NAME(0),
- RFC822_NAME(1),
- DNS_NAME(2),
- X400_ADDRESS(3),
- DIRECTORY_NAME(4),
- EDI_PARITY_NAME(5),
- UNIFORM_RESOURCE_IDENTIFIER(6),
- IP_ADDRESS(7),
- REGISTERED_ID(8);
+ OTHER(0),
+ EMAIL(1),
+ DNS(2),
+ X400(3),
+ DIRECTORY(4),
+ EDI_PARITY(5),
+ URI(6),
+ IP(7),
+ REGISTERED(8);
final int tag;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/TrustAllX509TrustManager.java b/security-utils/src/main/java/com/yahoo/security/TrustAllX509TrustManager.java
index b0303620cf7..89a737b1ef7 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/TrustAllX509TrustManager.java
+++ b/security-utils/src/main/java/com/yahoo/security/TrustAllX509TrustManager.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/TrustManagerUtils.java b/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java
index 4172e337789..bb852ee89a3 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/TrustManagerUtils.java
+++ b/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
diff --git a/security-utils/src/main/java/com/yahoo/security/X509CertificateBuilder.java b/security-utils/src/main/java/com/yahoo/security/X509CertificateBuilder.java
index 6ec10a2f803..f59d34ebb10 100644
--- a/security-utils/src/main/java/com/yahoo/security/X509CertificateBuilder.java
+++ b/security-utils/src/main/java/com/yahoo/security/X509CertificateBuilder.java
@@ -28,7 +28,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
/**
@@ -116,7 +116,7 @@ public class X509CertificateBuilder {
}
public X509CertificateBuilder addSubjectAlternativeName(String dnsName) {
- this.subjectAlternativeNames.add(new SubjectAlternativeName(DNS_NAME, dnsName));
+ this.subjectAlternativeNames.add(new SubjectAlternativeName(DNS, dnsName));
return this;
}
diff --git a/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java b/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java
index f9f23ee1eb2..feb3b4df3e0 100644
--- a/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java
+++ b/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java
@@ -32,10 +32,10 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
-import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Optional;
import java.util.Random;
import static com.yahoo.security.Extension.SUBJECT_ALTERNATIVE_NAMES;
@@ -115,6 +115,12 @@ public class X509CertificateUtils {
return getCommonNames(certificate.getSubjectX500Principal());
}
+ public static Optional<String> getSubjectCommonName(X509Certificate c) {
+ List<String> names = getSubjectCommonNames(c);
+ if (names.isEmpty()) return Optional.empty();
+ return Optional.of(names.get(names.size() - 1));
+ }
+
public static List<String> getIssuerCommonNames(X509Certificate certificate) {
return getCommonNames(certificate.getIssuerX500Principal());
}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/AuthorizedPeers.java b/security-utils/src/main/java/com/yahoo/security/tls/AuthorizedPeers.java
new file mode 100644
index 00000000000..9631ab32334
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/AuthorizedPeers.java
@@ -0,0 +1,32 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.util.Set;
+
+/**
+ * @author bjorncs
+ */
+public record AuthorizedPeers(Set<PeerPolicy> peerPolicies) {
+
+ private static final AuthorizedPeers EMPTY = new AuthorizedPeers(Set.of());
+
+ public AuthorizedPeers {
+ peerPolicies = verifyPeerPolicies(peerPolicies);
+ }
+
+ public static AuthorizedPeers empty() { return EMPTY; }
+
+ private static Set<PeerPolicy> verifyPeerPolicies(Set<PeerPolicy> peerPolicies) {
+ long distinctNames = peerPolicies.stream()
+ .map(PeerPolicy::policyName)
+ .distinct()
+ .count();
+ if (distinctNames != peerPolicies.size()) {
+ throw new IllegalArgumentException("'authorized-peers' contains entries with duplicate names");
+ }
+ return Set.copyOf(peerPolicies);
+ }
+
+ public boolean isEmpty() { return peerPolicies.isEmpty(); }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/Capability.java b/security-utils/src/main/java/com/yahoo/security/tls/Capability.java
new file mode 100644
index 00000000000..0ae253985a6
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/Capability.java
@@ -0,0 +1,32 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.util.Arrays;
+
+/**
+ * @author bjorncs
+ */
+public enum Capability {
+ CONTENT__CLUSTER_CONTROLLER__INTERNAL_STATE_API("vespa.content.cluster_controller.internal_state_api"),
+ CONTENT__DOCUMENT_API("vespa.content.document_api"),
+ CONTENT__METRICS_API("vespa.content.metrics_api"),
+ CONTENT__SEARCH_API("vespa.content.search_api"),
+ CONTENT__STATUS_PAGES("vespa.content.status_pages"),
+ CONTENT__STORAGE_API("vespa.content.storage_api"),
+ SLOBROK__API("vespa.slobrok.api"),
+ ;
+
+ private final String name;
+
+ Capability(String name) { this.name = name; }
+
+ public String asString() { return name; }
+
+ public static Capability fromName(String name) {
+ return Arrays.stream(values())
+ .filter(c -> c.name.equals(name))
+ .findAny().orElseThrow(() ->
+ new IllegalArgumentException("Cannot find predefined capability set with name '" + name + "'"));
+ }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/CapabilityMode.java b/security-utils/src/main/java/com/yahoo/security/tls/CapabilityMode.java
new file mode 100644
index 00000000000..c2fa11ce7f7
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/CapabilityMode.java
@@ -0,0 +1,26 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.util.Arrays;
+
+/**
+ * @author bjorncs
+ */
+public enum CapabilityMode {
+ DISABLE("disable"), LOG_ONLY("log_only"), ENFORCE("enforce");
+
+ private final String configValue;
+
+ CapabilityMode(String configValue) { this.configValue = configValue; }
+
+ public String configValue() { return configValue; }
+
+ /** @return Default value when mode is not explicitly specified */
+ public static CapabilityMode defaultValue() { return DISABLE; }
+
+ public static CapabilityMode fromConfigValue(String configValue) {
+ return Arrays.stream(values())
+ .filter(c -> c.configValue.equals(configValue))
+ .findFirst().orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
+ }
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/CapabilitySet.java b/security-utils/src/main/java/com/yahoo/security/tls/CapabilitySet.java
new file mode 100644
index 00000000000..7e6c7f394cd
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/CapabilitySet.java
@@ -0,0 +1,106 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+/**
+ * @author bjorncs
+ */
+public class CapabilitySet {
+ public enum Predefined {
+ CONTENT_NODE("vespa.content_node",
+ Capability.CONTENT__STORAGE_API, Capability.CONTENT__DOCUMENT_API, Capability.SLOBROK__API),
+ CONTAINER_NODE("vespa.container_node",
+ Capability.CONTENT__DOCUMENT_API, Capability.CONTENT__SEARCH_API, Capability.SLOBROK__API),
+ TELEMETRY("vespa.telemetry",
+ Capability.CONTENT__STATUS_PAGES, Capability.CONTENT__METRICS_API),
+ CLUSTER_CONTROLLER_NODE("vespa.cluster_controller_node",
+ Capability.CONTENT__CLUSTER_CONTROLLER__INTERNAL_STATE_API, Capability.SLOBROK__API),
+ CONFIG_SERVER("vespa.config_server"),
+ ;
+
+ private final String name;
+ private final CapabilitySet set;
+
+ Predefined(String name, Capability... caps) {
+ this.name = name;
+ this.set = caps.length == 0 ? CapabilitySet.none() : CapabilitySet.from(caps); }
+
+ public static Optional<Predefined> fromName(String name) {
+ return Arrays.stream(values()).filter(p -> p.name.equals(name)).findAny();
+ }
+
+ public CapabilitySet capabilities() { return set; }
+ }
+
+ private static final CapabilitySet ALL_CAPABILITIES = new CapabilitySet(EnumSet.allOf(Capability.class));
+ private static final CapabilitySet NO_CAPABILITIES = new CapabilitySet(EnumSet.noneOf(Capability.class));
+
+ private final EnumSet<Capability> caps;
+
+ private CapabilitySet(EnumSet<Capability> caps) { this.caps = caps; }
+
+ public static CapabilitySet fromNames(Collection<String> names) {
+ EnumSet<Capability> caps = EnumSet.noneOf(Capability.class);
+ for (String name : names) {
+ Predefined predefined = Predefined.fromName(name).orElse(null);
+ if (predefined != null) caps.addAll(predefined.set.caps);
+ else caps.add(Capability.fromName(name));
+ }
+ return new CapabilitySet(caps);
+ }
+
+ public static CapabilitySet unionOf(Collection<CapabilitySet> capSets) {
+ EnumSet<Capability> union = EnumSet.noneOf(Capability.class);
+ capSets.forEach(cs -> union.addAll(cs.caps));
+ return new CapabilitySet(union);
+ }
+
+ public static CapabilitySet from(EnumSet<Capability> caps) { return new CapabilitySet(EnumSet.copyOf(caps)); }
+ public static CapabilitySet from(Collection<Capability> caps) { return new CapabilitySet(EnumSet.copyOf(caps)); }
+ public static CapabilitySet from(Capability... caps) { return new CapabilitySet(EnumSet.copyOf(List.of(caps))); }
+ public static CapabilitySet all() { return ALL_CAPABILITIES; }
+ public static CapabilitySet none() { return NO_CAPABILITIES; }
+
+ public boolean hasAll() { return this.caps.equals(ALL_CAPABILITIES.caps); }
+ public boolean hasNone() { return this.caps.equals(NO_CAPABILITIES.caps); }
+ public boolean has(CapabilitySet caps) { return this.caps.containsAll(caps.caps); }
+ public boolean has(Collection<Capability> caps) { return this.caps.containsAll(caps); }
+ public boolean has(Capability... caps) { return this.caps.containsAll(List.of(caps)); }
+
+ public SortedSet<String> toNames() {
+ return caps.stream().map(Capability::asString).collect(Collectors.toCollection(TreeSet::new));
+ }
+
+ public Set<Capability> asSet() { return Collections.unmodifiableSet(caps); }
+
+ @Override
+ public String toString() {
+ return "CapabilitySet{" +
+ "caps=" + caps +
+ '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CapabilitySet that = (CapabilitySet) o;
+ return Objects.equals(caps, that.caps);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(caps);
+ }
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/ConfigFileBasedTlsContext.java b/security-utils/src/main/java/com/yahoo/security/tls/ConfigFileBasedTlsContext.java
index 6d4684666ea..69635b92e74 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/ConfigFileBasedTlsContext.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/ConfigFileBasedTlsContext.java
@@ -4,10 +4,10 @@ package com.yahoo.security.tls;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
+import com.yahoo.security.MutableX509KeyManager;
+import com.yahoo.security.MutableX509TrustManager;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.tls.authz.PeerAuthorizerTrustManager;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
@@ -19,7 +19,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.time.Duration;
-import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -112,9 +111,8 @@ public class ConfigFileBasedTlsContext implements TlsContext {
PeerAuthentication peerAuthentication) {
HostnameVerification hostnameVerification = options.isHostnameValidationDisabled() ? HostnameVerification.DISABLED : HostnameVerification.ENABLED;
- PeerAuthorizerTrustManager authorizerTrustManager = options.getAuthorizedPeers()
- .map(authorizedPeers -> new PeerAuthorizerTrustManager(authorizedPeers, mode, hostnameVerification, mutableTrustManager))
- .orElseGet(() -> new PeerAuthorizerTrustManager(new AuthorizedPeers(Collections.emptySet()), AuthorizationMode.DISABLE, hostnameVerification, mutableTrustManager));
+ PeerAuthorizerTrustManager authorizerTrustManager =
+ new PeerAuthorizerTrustManager(options.getAuthorizedPeers(), mode, hostnameVerification, mutableTrustManager);
SSLContext sslContext = new SslContextBuilder()
.withKeyManager(mutableKeyManager)
.withTrustManager(authorizerTrustManager)
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/ConnectionAuthContext.java b/security-utils/src/main/java/com/yahoo/security/tls/ConnectionAuthContext.java
new file mode 100644
index 00000000000..f231e8429ce
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/ConnectionAuthContext.java
@@ -0,0 +1,122 @@
+package com.yahoo.security.tls;
+
+import com.yahoo.security.SubjectAlternativeName;
+import com.yahoo.security.X509CertificateUtils;
+
+import java.security.cert.X509Certificate;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
+import static com.yahoo.security.SubjectAlternativeName.Type.URI;
+import static com.yahoo.security.tls.CapabilityMode.DISABLE;
+import static com.yahoo.security.tls.CapabilityMode.LOG_ONLY;
+
+/**
+ * @author bjorncs
+ */
+public record ConnectionAuthContext(List<X509Certificate> peerCertificateChain,
+ CapabilitySet capabilities,
+ Set<String> matchedPolicies,
+ CapabilityMode capabilityMode) {
+
+ private static final Logger log = Logger.getLogger(ConnectionAuthContext.class.getName());
+
+ public ConnectionAuthContext {
+ peerCertificateChain = List.copyOf(peerCertificateChain);
+ matchedPolicies = Set.copyOf(matchedPolicies);
+ }
+
+ private ConnectionAuthContext(List<X509Certificate> certs, CapabilityMode capabilityMode) {
+ this(certs, CapabilitySet.all(), Set.of(), capabilityMode);
+ }
+
+ public boolean authorized() { return !capabilities.hasNone(); }
+
+ /** Throws checked exception to force caller to handle verification failed. */
+ public void verifyCapabilities(CapabilitySet requiredCapabilities) throws MissingCapabilitiesException {
+ verifyCapabilities(requiredCapabilities, null, null, null);
+ }
+
+ /**
+ * Throws checked exception to force caller to handle verification failed.
+ * Provided strings are used for improved logging only
+ * */
+ public void verifyCapabilities(CapabilitySet requiredCapabilities, String action, String resource, String peer)
+ throws MissingCapabilitiesException {
+ if (capabilityMode == DISABLE) return;
+ boolean hasCapabilities = capabilities.has(requiredCapabilities);
+ if (!hasCapabilities) {
+ String msg = createPermissionDeniedErrorMessage(requiredCapabilities, action, resource, peer);
+ if (capabilityMode == LOG_ONLY) {
+ log.info(msg);
+ } else {
+ // Ideally log as warning, but we have no mechanism for de-duplicating repeated log spamming.
+ log.fine(msg);
+ throw new MissingCapabilitiesException(msg);
+ }
+ }
+ }
+
+ String createPermissionDeniedErrorMessage(
+ CapabilitySet required, String action, String resource, String peer) {
+ StringBuilder b = new StringBuilder();
+ if (capabilityMode == LOG_ONLY) b.append("Dry-run: ");
+ b.append("Permission denied");
+ if (resource != null) {
+ b.append(" for '");
+ if (action != null) {
+ b.append(action).append("' on '");
+ }
+ b.append(resource).append("'");
+ }
+ b.append(". Peer ");
+ if (peer != null) b.append("'").append(peer).append("' ");
+ return b.append("with ").append(peerCertificateString().orElse("<missing-certificate>")).append(". Requires capabilities ")
+ .append(required.toNames()).append(" but peer has ").append(capabilities.toNames())
+ .append(".").toString();
+ }
+
+ public Optional<X509Certificate> peerCertificate() {
+ return peerCertificateChain.isEmpty() ? Optional.empty() : Optional.of(peerCertificateChain.get(0));
+ }
+
+ public Optional<String> peerCertificateString() {
+ X509Certificate cert = peerCertificate().orElse(null);
+ if (cert == null) return Optional.empty();
+ StringBuilder b = new StringBuilder("[");
+ String cn = X509CertificateUtils.getSubjectCommonName(cert).orElse(null);
+ if (cn != null) {
+ b.append("CN='").append(cn).append("'");
+ }
+ var sans = X509CertificateUtils.getSubjectAlternativeNames(cert);
+ List<String> dnsNames = sans.stream()
+ .filter(s -> s.getType() == DNS)
+ .map(SubjectAlternativeName::getValue)
+ .toList();
+ if (!dnsNames.isEmpty()) {
+ if (cn != null) b.append(", ");
+ b.append("SAN_DNS=").append(dnsNames);
+ }
+ List<String> uris = sans.stream()
+ .filter(s -> s.getType() == URI)
+ .map(SubjectAlternativeName::getValue)
+ .toList();
+ if (!uris.isEmpty()) {
+ if (cn != null || !dnsNames.isEmpty()) b.append(", ");
+ b.append("SAN_URI=").append(uris);
+ }
+ return Optional.of(b.append("]").toString());
+ }
+
+ /** Construct instance with all capabilities */
+ public static ConnectionAuthContext defaultAllCapabilities() { return new ConnectionAuthContext(List.of(), DISABLE); }
+
+ /** Construct instance with all capabilities */
+ public static ConnectionAuthContext defaultAllCapabilities(List<X509Certificate> certs) {
+ return new ConnectionAuthContext(certs, DISABLE);
+ }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java b/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java
index a01283318b6..88e4f409260 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java
@@ -2,8 +2,6 @@
package com.yahoo.security.tls;
import com.yahoo.security.SslContextBuilder;
-import com.yahoo.security.tls.authz.PeerAuthorizerTrustManager;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
@@ -11,7 +9,6 @@ import javax.net.ssl.SSLParameters;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
@@ -136,13 +133,9 @@ public class DefaultTlsContext implements TlsContext {
if (!caCertificates.isEmpty()) {
builder.withTrustStore(caCertificates);
}
- if (authorizedPeers != null) {
- builder.withTrustManagerFactory(truststore -> new PeerAuthorizerTrustManager(authorizedPeers, mode, hostnameVerification, truststore));
- } else {
- builder.withTrustManagerFactory(truststore -> new PeerAuthorizerTrustManager(
- new AuthorizedPeers(Collections.emptySet()), AuthorizationMode.DISABLE, hostnameVerification, truststore));
- }
- return builder.build();
+ return builder.withTrustManagerFactory(truststore ->
+ new PeerAuthorizerTrustManager(authorizedPeers, mode, hostnameVerification, truststore))
+ .build();
}
}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/GlobPattern.java b/security-utils/src/main/java/com/yahoo/security/tls/GlobPattern.java
index 46a38a77844..c945e48a361 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/GlobPattern.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/GlobPattern.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import java.util.Arrays;
import java.util.Objects;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/HostGlobPattern.java b/security-utils/src/main/java/com/yahoo/security/tls/HostGlobPattern.java
index cb9ba13cae4..7e2c40182f0 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/HostGlobPattern.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/HostGlobPattern.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import java.util.Objects;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/MissingCapabilitiesException.java b/security-utils/src/main/java/com/yahoo/security/tls/MissingCapabilitiesException.java
new file mode 100644
index 00000000000..1c3ad9444e4
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/MissingCapabilitiesException.java
@@ -0,0 +1,13 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+/**
+ * Intentionally checked to force caller to handle missing permissions at call site.
+ *
+ * @author bjorncs
+ */
+public class MissingCapabilitiesException extends Exception {
+
+ public MissingCapabilitiesException(String message) { super(message); }
+
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizationFailedException.java b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizationFailedException.java
new file mode 100644
index 00000000000..02dbf3bb8e7
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizationFailedException.java
@@ -0,0 +1,23 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+/**
+ * @author bjorncs
+ */
+public class PeerAuthorizationFailedException extends CertificateException {
+ private final List<X509Certificate> certChain;
+
+ public PeerAuthorizationFailedException(String msg, List<X509Certificate> certChain) {
+ super(msg);
+ this.certChain = certChain;
+ }
+
+ public PeerAuthorizationFailedException(String msg) { this(msg, List.of()); }
+
+ public List<X509Certificate> peerCertificateChain() { return certChain; }
+}
+
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizer.java b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizer.java
index 40f3817c5f9..951b5c57c9e 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizer.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizer.java
@@ -1,23 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.authz;
+package com.yahoo.security.tls;
import com.yahoo.security.SubjectAlternativeName;
import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.Role;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.List;
-import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
-import static com.yahoo.security.SubjectAlternativeName.Type.IP_ADDRESS;
-import static com.yahoo.security.SubjectAlternativeName.Type.UNIFORM_RESOURCE_IDENTIFIER;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
+import static com.yahoo.security.SubjectAlternativeName.Type.IP;
+import static com.yahoo.security.SubjectAlternativeName.Type.URI;
import static java.util.stream.Collectors.toList;
/**
@@ -35,19 +30,27 @@ public class PeerAuthorizer {
this.authorizedPeers = authorizedPeers;
}
- public AuthorizationResult authorizePeer(X509Certificate peerCertificate) {
- Set<Role> assumedRoles = new HashSet<>();
+
+ public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); }
+
+ public ConnectionAuthContext authorizePeer(List<X509Certificate> certChain) {
+ if (authorizedPeers.isEmpty()) return ConnectionAuthContext.defaultAllCapabilities(certChain);
+ X509Certificate cert = certChain.get(0);
Set<String> matchedPolicies = new HashSet<>();
- String cn = getCommonName(peerCertificate).orElse(null);
- List<String> sans = getSubjectAlternativeNames(peerCertificate);
+ Set<CapabilitySet> grantedCapabilities = new HashSet<>();
+ String cn = X509CertificateUtils.getSubjectCommonName(cert).orElse(null);
+ List<String> sans = getSubjectAlternativeNames(cert);
log.fine(() -> String.format("Subject info from x509 certificate: CN=[%s], 'SAN=%s", cn, sans));
for (PeerPolicy peerPolicy : authorizedPeers.peerPolicies()) {
if (matchesPolicy(peerPolicy, cn, sans)) {
- assumedRoles.addAll(peerPolicy.assumedRoles());
matchedPolicies.add(peerPolicy.policyName());
+ grantedCapabilities.add(peerPolicy.capabilities());
}
}
- return new AuthorizationResult(assumedRoles, matchedPolicies);
+ // TODO Pass this through constructor
+ CapabilityMode capabilityMode = TransportSecurityUtils.getCapabilityMode();
+ return new ConnectionAuthContext(
+ certChain, CapabilitySet.unionOf(grantedCapabilities), matchedPolicies, capabilityMode);
}
private static boolean matchesPolicy(PeerPolicy peerPolicy, String cn, List<String> sans) {
@@ -68,14 +71,9 @@ public class PeerAuthorizer {
}
}
- private static Optional<String> getCommonName(X509Certificate peerCertificate) {
- return X509CertificateUtils.getSubjectCommonNames(peerCertificate).stream()
- .findFirst();
- }
-
private static List<String> getSubjectAlternativeNames(X509Certificate peerCertificate) {
return X509CertificateUtils.getSubjectAlternativeNames(peerCertificate).stream()
- .filter(san -> san.getType() == DNS_NAME || san.getType() == IP_ADDRESS || san.getType() == UNIFORM_RESOURCE_IDENTIFIER)
+ .filter(san -> san.getType() == DNS || san.getType() == IP || san.getType() == URI)
.map(SubjectAlternativeName::getValue)
.collect(toList());
}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizerTrustManager.java b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizerTrustManager.java
index e8d558205c4..c3dcdf1dc9e 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/authz/PeerAuthorizerTrustManager.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/PeerAuthorizerTrustManager.java
@@ -1,32 +1,33 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.authz;
+package com.yahoo.security.tls;
+import com.yahoo.security.TrustManagerUtils;
import com.yahoo.security.X509CertificateUtils;
-import com.yahoo.security.tls.AuthorizationMode;
-import com.yahoo.security.tls.HostnameVerification;
-import com.yahoo.security.tls.TrustManagerUtils;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
-import java.util.Optional;
+import java.util.List;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@link X509ExtendedTrustManager} that performs additional certificate verification through {@link PeerAuthorizer}.
*
+ * Implementation assumes that provided {@link X509ExtendedTrustManager} will throw {@link IllegalArgumentException}
+ * when chain is empty or null.
+ *
* @author bjorncs
*/
-// Note: Implementation assumes that provided X509ExtendedTrustManager will throw IllegalArgumentException when chain is empty or null
-public class PeerAuthorizerTrustManager extends X509ExtendedTrustManager {
+class PeerAuthorizerTrustManager extends X509ExtendedTrustManager {
- public static final String HANDSHAKE_SESSION_AUTHZ_RESULT_PROPERTY = "vespa.tls.authorization.result";
+ static final String AUTH_CONTEXT_PROPERTY = "vespa.tls.auth.ctx";
private static final Logger log = Logger.getLogger(PeerAuthorizerTrustManager.class.getName());
@@ -35,59 +36,55 @@ public class PeerAuthorizerTrustManager extends X509ExtendedTrustManager {
private final AuthorizationMode mode;
private final HostnameVerification hostnameVerification;
- public PeerAuthorizerTrustManager(AuthorizedPeers authorizedPeers,
- AuthorizationMode mode,
- HostnameVerification hostnameVerification,
- X509ExtendedTrustManager defaultTrustManager) {
+ PeerAuthorizerTrustManager(AuthorizedPeers authorizedPeers, AuthorizationMode mode,
+ HostnameVerification hostnameVerification, X509ExtendedTrustManager defaultTrustManager) {
this.authorizer = new PeerAuthorizer(authorizedPeers);
this.mode = mode;
this.hostnameVerification = hostnameVerification;
this.defaultTrustManager = defaultTrustManager;
}
- public PeerAuthorizerTrustManager(AuthorizedPeers authorizedPeers,
- AuthorizationMode mode,
- HostnameVerification hostnameVerification,
- KeyStore truststore) {
+ PeerAuthorizerTrustManager(AuthorizedPeers authorizedPeers, AuthorizationMode mode,
+ HostnameVerification hostnameVerification, KeyStore truststore) {
this(authorizedPeers, mode, hostnameVerification, TrustManagerUtils.createDefaultX509TrustManager(truststore));
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkClientTrusted(chain, authType);
- authorizePeer(chain[0], authType, true, null);
+ authorizePeer(chain, authType, true, null);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkServerTrusted(chain, authType);
- authorizePeer(chain[0], authType, false, null);
+ authorizePeer(chain, authType, false, null);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
defaultTrustManager.checkClientTrusted(chain, authType, socket);
- authorizePeer(chain[0], authType, true, null);
+ authorizePeer(chain, authType, true, ((SSLSocket)socket).getHandshakeSession());
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
overrideHostnameVerificationForClient(socket);
defaultTrustManager.checkServerTrusted(chain, authType, socket);
- authorizePeer(chain[0], authType, false, null);
+ authorizePeer(chain, authType, false, ((SSLSocket)socket).getHandshakeSession());
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine) throws CertificateException {
defaultTrustManager.checkClientTrusted(chain, authType, sslEngine);
- authorizePeer(chain[0], authType, true, sslEngine);
+ authorizePeer(chain, authType, true, sslEngine.getHandshakeSession());
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine) throws CertificateException {
overrideHostnameVerificationForClient(sslEngine);
defaultTrustManager.checkServerTrusted(chain, authType, sslEngine);
- authorizePeer(chain[0], authType, false, sslEngine);
+ authorizePeer(chain, authType, false, sslEngine.getHandshakeSession());
}
@Override
@@ -95,36 +92,33 @@ public class PeerAuthorizerTrustManager extends X509ExtendedTrustManager {
return defaultTrustManager.getAcceptedIssuers();
}
- /**
- * Note: The authorization result is only available during handshake. The underlying handshake session is removed once handshake is complete.
- */
- public static Optional<AuthorizationResult> getAuthorizationResult(SSLEngine sslEngine) {
- return Optional.ofNullable(sslEngine.getHandshakeSession())
- .flatMap(session -> Optional.ofNullable((AuthorizationResult) session.getValue(HANDSHAKE_SESSION_AUTHZ_RESULT_PROPERTY)));
- }
-
- private void authorizePeer(X509Certificate certificate, String authType, boolean isVerifyingClient, SSLEngine sslEngine) throws CertificateException {
- if (mode == AuthorizationMode.DISABLE) return;
-
- log.fine(() -> "Verifying certificate: " + createInfoString(certificate, authType, isVerifyingClient));
- AuthorizationResult result = authorizer.authorizePeer(certificate);
- if (sslEngine != null) { // getHandshakeSession() will never return null in this context
- sslEngine.getHandshakeSession().putValue(HANDSHAKE_SESSION_AUTHZ_RESULT_PROPERTY, result);
+ private void authorizePeer(X509Certificate[] certChain, String authType, boolean isVerifyingClient,
+ SSLSession handshakeSessionOrNull) throws PeerAuthorizationFailedException {
+ log.fine(() -> "Verifying certificate: " + createInfoString(certChain[0], authType, isVerifyingClient));
+ ConnectionAuthContext result = mode != AuthorizationMode.DISABLE
+ ? authorizer.authorizePeer(List.of(certChain))
+ : ConnectionAuthContext.defaultAllCapabilities(List.of(certChain));
+ if (handshakeSessionOrNull != null) {
+ handshakeSessionOrNull.putValue(AUTH_CONTEXT_PROPERTY, result);
+ } else {
+ log.log(Level.FINE,
+ () -> "Warning: unable to provide ConnectionAuthContext as no SSLSession is available");
}
- if (result.succeeded()) {
+ if (result.authorized()) {
log.fine(() -> String.format("Verification result: %s", result));
} else {
- String errorMessage = "Authorization failed: " + createInfoString(certificate, authType, isVerifyingClient);
+ String errorMessage = "Authorization failed: " + createInfoString(certChain[0], authType, isVerifyingClient);
log.warning(errorMessage);
if (mode == AuthorizationMode.ENFORCE) {
- throw new CertificateException(errorMessage);
+ throw new PeerAuthorizationFailedException(errorMessage, List.of(certChain));
}
}
}
- private static String createInfoString(X509Certificate certificate, String authType, boolean isVerifyingClient) {
- return String.format("DN='%s', SANs=%s, authType='%s', isVerifyingClient='%b'",
- certificate.getSubjectX500Principal(), X509CertificateUtils.getSubjectAlternativeNames(certificate), authType, isVerifyingClient);
+ private String createInfoString(X509Certificate certificate, String authType, boolean isVerifyingClient) {
+ return String.format("DN='%s', SANs=%s, authType='%s', isVerifyingClient='%b', mode=%s",
+ certificate.getSubjectX500Principal(), X509CertificateUtils.getSubjectAlternativeNames(certificate),
+ authType, isVerifyingClient, mode);
}
private void overrideHostnameVerificationForClient(SSLEngine engine) {
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/PeerPolicy.java b/security-utils/src/main/java/com/yahoo/security/tls/PeerPolicy.java
new file mode 100644
index 00000000000..ea3d4cfe002
--- /dev/null
+++ b/security-utils/src/main/java/com/yahoo/security/tls/PeerPolicy.java
@@ -0,0 +1,24 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @author bjorncs
+ */
+public record PeerPolicy(String policyName, Optional<String> description, CapabilitySet capabilities,
+ List<RequiredPeerCredential> requiredCredentials) {
+
+ public PeerPolicy {
+ requiredCredentials = List.copyOf(requiredCredentials);
+ }
+
+ public PeerPolicy(String policyName, List<RequiredPeerCredential> requiredCredentials) {
+ this(policyName, Optional.empty(), CapabilitySet.all(), requiredCredentials);
+ }
+
+ public PeerPolicy(String policyName, String description, List<RequiredPeerCredential> requiredCredentials) {
+ this(policyName, Optional.ofNullable(description), CapabilitySet.all(), requiredCredentials);
+ }
+}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/RequiredPeerCredential.java b/security-utils/src/main/java/com/yahoo/security/tls/RequiredPeerCredential.java
index 4c96a2935f8..9a18da9dffd 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/RequiredPeerCredential.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/RequiredPeerCredential.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import java.util.Objects;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptions.java b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptions.java
index 65c87bee0b9..4397f27ebb7 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptions.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptions.java
@@ -1,9 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
-import com.yahoo.security.tls.json.TransportSecurityOptionsJsonSerializer;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -55,9 +52,7 @@ public class TransportSecurityOptions {
return Optional.ofNullable(caCertificatesFile);
}
- public Optional<AuthorizedPeers> getAuthorizedPeers() {
- return Optional.ofNullable(authorizedPeers);
- }
+ public AuthorizedPeers getAuthorizedPeers() { return authorizedPeers; }
public List<String> getAcceptedCiphers() { return acceptedCiphers; }
@@ -96,7 +91,7 @@ public class TransportSecurityOptions {
private Path privateKeyFile;
private Path certificatesFile;
private Path caCertificatesFile;
- private AuthorizedPeers authorizedPeers;
+ private AuthorizedPeers authorizedPeers = AuthorizedPeers.empty();
private List<String> acceptedCiphers = new ArrayList<>();
private boolean isHostnameValidationDisabled;
private List<String> acceptedProtocols = new ArrayList<>();
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsEntity.java b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsEntity.java
index 12ac75aae80..f1799a64a57 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsEntity.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsEntity.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.json;
+package com.yahoo.security.tls;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -36,7 +36,7 @@ class TransportSecurityOptionsEntity {
@JsonProperty("required-credentials") List<RequiredCredential> requiredCredentials;
@JsonProperty("name") String name;
@JsonProperty("description") @JsonInclude(NON_NULL) String description;
- @JsonProperty("roles") @JsonInclude(NON_EMPTY) List<String> roles;
+ @JsonProperty("capabilities") @JsonInclude(NON_EMPTY) List<String> capabilities;
}
@JsonIgnoreProperties(ignoreUnknown = true)
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializer.java b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializer.java
index 516a0c83d37..0349d4085db 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializer.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializer.java
@@ -1,16 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.json;
+package com.yahoo.security.tls;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.yahoo.security.tls.TransportSecurityOptions;
-import com.yahoo.security.tls.json.TransportSecurityOptionsEntity.AuthorizedPeer;
-import com.yahoo.security.tls.json.TransportSecurityOptionsEntity.CredentialField;
-import com.yahoo.security.tls.json.TransportSecurityOptionsEntity.Files;
-import com.yahoo.security.tls.json.TransportSecurityOptionsEntity.RequiredCredential;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.Role;
+import com.yahoo.security.tls.TransportSecurityOptionsEntity.AuthorizedPeer;
+import com.yahoo.security.tls.TransportSecurityOptionsEntity.CredentialField;
+import com.yahoo.security.tls.TransportSecurityOptionsEntity.Files;
+import com.yahoo.security.tls.TransportSecurityOptionsEntity.RequiredCredential;
import java.io.IOException;
import java.io.InputStream;
@@ -18,9 +13,9 @@ import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Paths;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import static java.util.stream.Collectors.toList;
@@ -29,11 +24,11 @@ import static java.util.stream.Collectors.toSet;
/**
* @author bjorncs
*/
-public class TransportSecurityOptionsJsonSerializer {
+class TransportSecurityOptionsJsonSerializer {
private static final ObjectMapper mapper = new ObjectMapper();
- public TransportSecurityOptions deserialize(InputStream in) {
+ TransportSecurityOptions deserialize(InputStream in) {
try {
TransportSecurityOptionsEntity entity = mapper.readValue(in, TransportSecurityOptionsEntity.class);
return toTransportSecurityOptions(entity);
@@ -42,7 +37,7 @@ public class TransportSecurityOptionsJsonSerializer {
}
}
- public void serialize(OutputStream out, TransportSecurityOptions options) {
+ void serialize(OutputStream out, TransportSecurityOptions options) {
try {
mapper.writerWithDefaultPrettyPrinter().writeValue(out, toTransportSecurityOptionsEntity(options));
} catch (IOException e) {
@@ -101,14 +96,16 @@ public class TransportSecurityOptionsJsonSerializer {
if (authorizedPeer.requiredCredentials == null) {
throw missingFieldException("required-credentials");
}
- return new PeerPolicy(authorizedPeer.name, authorizedPeer.description, toRoles(authorizedPeer.roles), toRequestPeerCredentials(authorizedPeer.requiredCredentials));
+ return new PeerPolicy(authorizedPeer.name, Optional.ofNullable(authorizedPeer.description),
+ toCapabilities(authorizedPeer.capabilities), toRequestPeerCredentials(authorizedPeer.requiredCredentials));
}
- private static Set<Role> toRoles(List<String> roles) {
- if (roles == null) return Collections.emptySet();
- return roles.stream()
- .map(Role::new)
- .collect(toSet());
+ private static CapabilitySet toCapabilities(List<String> capabilities) {
+ if (capabilities == null) return CapabilitySet.all();
+ if (capabilities.isEmpty())
+ throw new IllegalArgumentException("\"capabilities\" array must either be not present " +
+ "(implies all capabilities) or contain at least one capability name");
+ return CapabilitySet.fromNames(capabilities);
}
private static List<RequiredPeerCredential> toRequestPeerCredentials(List<RequiredCredential> requiredCredentials) {
@@ -142,29 +139,27 @@ public class TransportSecurityOptionsJsonSerializer {
options.getCaCertificatesFile().ifPresent(value -> entity.files.caCertificatesFile = value.toString());
options.getCertificatesFile().ifPresent(value -> entity.files.certificatesFile = value.toString());
options.getPrivateKeyFile().ifPresent(value -> entity.files.privateKeyFile = value.toString());
- options.getAuthorizedPeers().ifPresent( authorizedPeers -> entity.authorizedPeers =
- authorizedPeers.peerPolicies().stream()
- // Makes tests stable
- .sorted(Comparator.comparing(PeerPolicy::policyName))
- .map(peerPolicy -> {
- AuthorizedPeer authorizedPeer = new AuthorizedPeer();
- authorizedPeer.name = peerPolicy.policyName();
- authorizedPeer.requiredCredentials = new ArrayList<>();
- authorizedPeer.description = peerPolicy.description().orElse(null);
- for (RequiredPeerCredential requiredPeerCredential : peerPolicy.requiredCredentials()) {
- RequiredCredential requiredCredential = new RequiredCredential();
- requiredCredential.field = toField(requiredPeerCredential.field());
- requiredCredential.matchExpression = requiredPeerCredential.pattern().asString();
- authorizedPeer.requiredCredentials.add(requiredCredential);
- }
- if (!peerPolicy.assumedRoles().isEmpty()) {
- authorizedPeer.roles = new ArrayList<>();
- peerPolicy.assumedRoles().forEach(role -> authorizedPeer.roles.add(role.name()));
- }
-
- return authorizedPeer;
- })
- .collect(toList()));
+ entity.authorizedPeers = options.getAuthorizedPeers().peerPolicies().stream()
+ // Makes tests stable
+ .sorted(Comparator.comparing(PeerPolicy::policyName))
+ .map(peerPolicy -> {
+ AuthorizedPeer authorizedPeer = new AuthorizedPeer();
+ authorizedPeer.name = peerPolicy.policyName();
+ authorizedPeer.requiredCredentials = new ArrayList<>();
+ authorizedPeer.description = peerPolicy.description().orElse(null);
+ CapabilitySet caps = peerPolicy.capabilities();
+ if (!caps.hasAll()) {
+ authorizedPeer.capabilities = List.copyOf(caps.toNames());
+ }
+ for (RequiredPeerCredential requiredPeerCredential : peerPolicy.requiredCredentials()) {
+ RequiredCredential requiredCredential = new RequiredCredential();
+ requiredCredential.field = toField(requiredPeerCredential.field());
+ requiredCredential.matchExpression = requiredPeerCredential.pattern().asString();
+ authorizedPeer.requiredCredentials.add(requiredCredential);
+ }
+ return authorizedPeer;
+ })
+ .toList();
if (!options.getAcceptedCiphers().isEmpty()) {
entity.acceptedCiphers = options.getAcceptedCiphers();
}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityUtils.java b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityUtils.java
index cbd3857d2d5..ae6cef65156 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityUtils.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/TransportSecurityUtils.java
@@ -1,6 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
@@ -18,6 +21,7 @@ public class TransportSecurityUtils {
public static final String CONFIG_FILE_ENVIRONMENT_VARIABLE = "VESPA_TLS_CONFIG_FILE";
public static final String INSECURE_MIXED_MODE_ENVIRONMENT_VARIABLE = "VESPA_TLS_INSECURE_MIXED_MODE";
public static final String INSECURE_AUTHORIZATION_MODE_ENVIRONMENT_VARIABLE = "VESPA_TLS_INSECURE_AUTHORIZATION_MODE";
+ public static final String CAPABILITIES_ENV_VAR = "VESPA_TLS_CAPABILITIES_ENFORCEMENT_MODE";
private TransportSecurityUtils() {}
@@ -49,6 +53,12 @@ public class TransportSecurityUtils {
.orElse(AuthorizationMode.defaultValue());
}
+ public static CapabilityMode getCapabilityMode() {
+ return getEnvironmentVariable(System.getenv(), CAPABILITIES_ENV_VAR)
+ .map(CapabilityMode::fromConfigValue)
+ .orElse(CapabilityMode.defaultValue());
+ }
+
public static Optional<Path> getConfigFile() {
return getConfigFile(System.getenv());
}
@@ -80,6 +90,24 @@ public class TransportSecurityUtils {
}
}
+ /**
+ * @return {@link ConnectionAuthContext} instance if {@link SSLEngine} was constructed by a {@link TlsContext}.
+ * Only available after TLS handshake is completed.
+ */
+ public static Optional<ConnectionAuthContext> getConnectionAuthContext(SSLSession s) {
+ return Optional.ofNullable((ConnectionAuthContext) s.getValue(PeerAuthorizerTrustManager.AUTH_CONTEXT_PROPERTY));
+ }
+
+ /** @see #getConnectionAuthContext(SSLSession) */
+ public static Optional<ConnectionAuthContext> getConnectionAuthContext(SSLEngine e) {
+ return getConnectionAuthContext(e.getSession());
+ }
+
+ /** @see #getConnectionAuthContext(SSLSession) */
+ public static Optional<ConnectionAuthContext> getConnectionAuthContext(SSLSocket s) {
+ return getConnectionAuthContext(s.getSession());
+ }
+
private static Optional<String> getEnvironmentVariable(Map<String, String> environmentVariables, String variableName) {
return Optional.ofNullable(environmentVariables.get(variableName))
.filter(var -> !var.isEmpty());
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/UriGlobPattern.java b/security-utils/src/main/java/com/yahoo/security/tls/UriGlobPattern.java
index b2cc0688bb9..18d18a5ab3c 100644
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/UriGlobPattern.java
+++ b/security-utils/src/main/java/com/yahoo/security/tls/UriGlobPattern.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import java.util.Objects;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/authz/AuthorizationResult.java b/security-utils/src/main/java/com/yahoo/security/tls/authz/AuthorizationResult.java
deleted file mode 100644
index 963bb469d6e..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/authz/AuthorizationResult.java
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.authz;
-
-import com.yahoo.security.tls.policy.Role;
-
-import java.util.Collections;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * @author bjorncs
- */
-public class AuthorizationResult {
- private final Set<Role> assumedRoles;
- private final Set<String> matchedPolicies;
-
- public AuthorizationResult(Set<Role> assumedRoles, Set<String> matchedPolicies) {
- this.assumedRoles = Collections.unmodifiableSet(assumedRoles);
- this.matchedPolicies = Collections.unmodifiableSet(matchedPolicies);
- }
-
- public Set<Role> assumedRoles() {
- return assumedRoles;
- }
-
- public Set<String> matchedPolicies() {
- return matchedPolicies;
- }
-
- public boolean succeeded() {
- return matchedPolicies.size() > 0;
- }
-
- @Override
- public String toString() {
- return "AuthorizationResult{" +
- "assumedRoles=" + assumedRoles +
- ", matchedPolicies=" + matchedPolicies +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- AuthorizationResult that = (AuthorizationResult) o;
- return Objects.equals(assumedRoles, that.assumedRoles) &&
- Objects.equals(matchedPolicies, that.matchedPolicies);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(assumedRoles, matchedPolicies);
- }
-}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/authz/package-info.java b/security-utils/src/main/java/com/yahoo/security/tls/authz/package-info.java
deleted file mode 100644
index 5066026757d..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/authz/package-info.java
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-/**
- * @author bjorncs
- */
-@ExportPackage
-package com.yahoo.security.tls.authz;
-
-import com.yahoo.osgi.annotation.ExportPackage;
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/json/package-info.java b/security-utils/src/main/java/com/yahoo/security/tls/json/package-info.java
deleted file mode 100644
index be7ec33bf04..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/json/package-info.java
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-/**
- * @author bjorncs
- */
-@ExportPackage
-package com.yahoo.security.tls.json;
-
-import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/AuthorizedPeers.java b/security-utils/src/main/java/com/yahoo/security/tls/policy/AuthorizedPeers.java
deleted file mode 100644
index 66621224906..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/AuthorizedPeers.java
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
-
-import java.util.Collections;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * @author bjorncs
- */
-public class AuthorizedPeers {
-
- private final Set<PeerPolicy> peerPolicies;
-
- public AuthorizedPeers(Set<PeerPolicy> peerPolicies) {
- this.peerPolicies = verifyPeerPolicies(peerPolicies);
- }
-
- private Set<PeerPolicy> verifyPeerPolicies(Set<PeerPolicy> peerPolicies) {
- long distinctNames = peerPolicies.stream()
- .map(PeerPolicy::policyName)
- .distinct()
- .count();
- if (distinctNames != peerPolicies.size()) {
- throw new IllegalArgumentException("'authorized-peers' contains entries with duplicate names");
- }
- return Collections.unmodifiableSet(peerPolicies);
- }
-
- public Set<PeerPolicy> peerPolicies() {
- return peerPolicies;
- }
-
- @Override
- public String toString() {
- return "AuthorizedPeers{" +
- "peerPolicies=" + peerPolicies +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- AuthorizedPeers that = (AuthorizedPeers) o;
- return Objects.equals(peerPolicies, that.peerPolicies);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(peerPolicies);
- }
-}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/PeerPolicy.java b/security-utils/src/main/java/com/yahoo/security/tls/policy/PeerPolicy.java
deleted file mode 100644
index 4783889ec62..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/PeerPolicy.java
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-
-/**
- * @author bjorncs
- */
-public class PeerPolicy {
-
- private final String policyName;
- private final String description;
- private final Set<Role> assumedRoles;
- private final List<RequiredPeerCredential> requiredCredentials;
-
- public PeerPolicy(String policyName, Set<Role> assumedRoles, List<RequiredPeerCredential> requiredCredentials) {
- this(policyName, null, assumedRoles, requiredCredentials);
- }
-
- public PeerPolicy(
- String policyName, String description, Set<Role> assumedRoles, List<RequiredPeerCredential> requiredCredentials) {
- this.policyName = policyName;
- this.description = description;
- this.assumedRoles = assumedRoles;
- this.requiredCredentials = Collections.unmodifiableList(requiredCredentials);
- }
-
- public String policyName() {
- return policyName;
- }
-
- public Optional<String> description() { return Optional.ofNullable(description); }
-
- public Set<Role> assumedRoles() {
- return assumedRoles;
- }
-
- public List<RequiredPeerCredential> requiredCredentials() {
- return requiredCredentials;
- }
-
- @Override
- public String toString() {
- return "PeerPolicy{" +
- "policyName='" + policyName + '\'' +
- ", description='" + description + '\'' +
- ", assumedRoles=" + assumedRoles +
- ", requiredCredentials=" + requiredCredentials +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- PeerPolicy that = (PeerPolicy) o;
- return Objects.equals(policyName, that.policyName) &&
- Objects.equals(description, that.description) &&
- Objects.equals(assumedRoles, that.assumedRoles) &&
- Objects.equals(requiredCredentials, that.requiredCredentials);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(policyName, description, assumedRoles, requiredCredentials);
- }
-}
diff --git a/security-utils/src/main/java/com/yahoo/security/tls/policy/Role.java b/security-utils/src/main/java/com/yahoo/security/tls/policy/Role.java
deleted file mode 100644
index b35bf328847..00000000000
--- a/security-utils/src/main/java/com/yahoo/security/tls/policy/Role.java
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
-
-import java.util.Objects;
-
-/**
- * @author bjorncs
- */
-public class Role {
-
- private final String name;
-
- public Role(String name) {
- this.name = name;
- }
-
- public String name() {
- return name;
- }
-
- @Override
- public String toString() {
- return "Role{" +
- "name='" + name + '\'' +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Role role = (Role) o;
- return Objects.equals(name, role.name);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(name);
- }
-}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/AutoReloadingX509KeyManagerTest.java b/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java
index f5bc2a9c84e..c335acc12be 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/AutoReloadingX509KeyManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java
@@ -1,18 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
+import com.yahoo.security.AutoReloadingX509KeyManager;
import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
@@ -35,16 +37,16 @@ import static org.mockito.Mockito.verify;
public class AutoReloadingX509KeyManagerTest {
private static final X500Principal SUBJECT = new X500Principal("CN=dummy");
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void crypto_material_is_reloaded_when_scheduler_task_is_executed() throws IOException {
+ void crypto_material_is_reloaded_when_scheduler_task_is_executed() throws IOException {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
- Path privateKeyFile = tempDirectory.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate()).getBytes());
- Path certificateFile = tempDirectory.newFile().toPath();
+ Path certificateFile = File.createTempFile("junit", null, tempDirectory).toPath();
BigInteger serialNumberInitialCertificate = BigInteger.ONE;
X509Certificate initialCertificate = generateCertificate(keyPair, serialNumberInitialCertificate);
Files.write(certificateFile, X509CertificateUtils.toPem(initialCertificate).getBytes());
diff --git a/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java
index 0d3924063f3..d9ca9731065 100644
--- a/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -20,11 +20,11 @@ public class KeyStoreBuilderTest {
private static final char[] PASSWORD = new char[0];
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_create_jks_keystore_from_privatekey_and_certificate() throws Exception {
+ void can_create_jks_keystore_from_privatekey_and_certificate() throws Exception {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X509Certificate certificate = createCertificate(keyPair);
KeyStoreBuilder.withType(KeyStoreType.JKS)
@@ -33,8 +33,8 @@ public class KeyStoreBuilderTest {
}
@Test
- public void can_build_jks_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_jks_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.JKS, PASSWORD);
KeyStoreBuilder.withType(KeyStoreType.JKS)
@@ -43,8 +43,8 @@ public class KeyStoreBuilderTest {
}
@Test
- public void can_build_pcks12_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_pcks12_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.PKCS12, PASSWORD);
KeyStoreBuilder.withType(KeyStoreType.PKCS12)
diff --git a/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java
index f6f48d8b1b8..afaa25ce606 100644
--- a/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java
@@ -1,15 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -17,41 +17,41 @@ import static org.junit.Assert.assertTrue;
public class KeyUtilsTest {
@Test
- public void can_extract_public_key_from_rsa_private() {
+ void can_extract_public_key_from_rsa_private() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
PublicKey publicKey = KeyUtils.extractPublicKey(keyPair.getPrivate());
assertNotNull(publicKey);
}
@Test
- public void can_extract_public_key_from_ecdsa_private() {
+ void can_extract_public_key_from_ecdsa_private() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
PublicKey publicKey = KeyUtils.extractPublicKey(keyPair.getPrivate());
assertNotNull(publicKey);
}
@Test
- public void can_serialize_and_deserialize_rsa_privatekey_using_pkcs1_pem_format() {
+ void can_serialize_and_deserialize_rsa_privatekey_using_pkcs1_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.RSA, KeyFormat.PKCS1, "RSA PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_rsa_privatekey_using_pkcs8_pem_format() {
+ void can_serialize_and_deserialize_rsa_privatekey_using_pkcs8_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.RSA, KeyFormat.PKCS8, "PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_ec_privatekey_using_pkcs1_pem_format() {
+ void can_serialize_and_deserialize_ec_privatekey_using_pkcs1_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.EC, KeyFormat.PKCS1, "EC PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_ec_privatekey_using_pkcs8_pem_format() {
+ void can_serialize_and_deserialize_ec_privatekey_using_pkcs8_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.EC, KeyFormat.PKCS8, "PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_rsa_publickey_using_pem_format() {
+ void can_serialize_and_deserialize_rsa_publickey_using_pem_format() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
String pem = KeyUtils.toPem(keyPair.getPublic());
assertTrue(pem.contains("BEGIN PUBLIC KEY"));
@@ -62,7 +62,7 @@ public class KeyUtilsTest {
}
@Test
- public void can_serialize_and_deserialize_ec_publickey_using_pem_format() {
+ void can_serialize_and_deserialize_ec_publickey_using_pem_format() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
String pem = KeyUtils.toPem(keyPair.getPublic());
assertTrue(pem.contains("BEGIN PUBLIC KEY"));
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/MutableX509KeyManagerTest.java b/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java
index 3f45d22d8ed..ddceb762d2a 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/MutableX509KeyManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
+import com.yahoo.security.MutableX509KeyManager;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -28,7 +29,7 @@ public class MutableX509KeyManagerTest {
private static final X500Principal SUBJECT = new X500Principal("CN=dummy");
@Test
- public void key_manager_can_be_updated_with_new_certificate() {
+ void key_manager_can_be_updated_with_new_certificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
BigInteger serialNumberInitialCertificate = BigInteger.ONE;
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/MutableX509TrustManagerTest.java b/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java
index 1d04ed86322..ea9f9a4a68a 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/MutableX509TrustManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java
@@ -1,13 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls;
+package com.yahoo.security;
-import com.yahoo.security.KeyAlgorithm;
-import com.yahoo.security.KeyStoreBuilder;
-import com.yahoo.security.KeyStoreType;
-import com.yahoo.security.KeyUtils;
-import com.yahoo.security.SignatureAlgorithm;
-import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -25,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class MutableX509TrustManagerTest {
@Test
- public void key_manager_can_be_updated_with_new_certificate() {
+ void key_manager_can_be_updated_with_new_certificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
X509Certificate initialCertificate = generateCertificate(new X500Principal("CN=issuer1"), keyPair);
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
index 5ad49bbc599..ca8fb280ec7 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class Pkcs10CsrBuilderTest {
@Test
- public void can_build_csr_with_sans() {
+ void can_build_csr_with_sans() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java
index 6dd5eb52373..3fe36dc6a7c 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
import java.util.Arrays;
import java.util.List;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -18,11 +18,11 @@ import static org.junit.Assert.assertTrue;
public class Pkcs10CsrTest {
@Test
- public void can_read_subject_alternative_names() {
+ void can_read_subject_alternative_names() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
- SubjectAlternativeName san1 = new SubjectAlternativeName(DNS_NAME, "san1.com");
- SubjectAlternativeName san2 = new SubjectAlternativeName(DNS_NAME, "san2.com");
+ SubjectAlternativeName san1 = new SubjectAlternativeName(DNS, "san1.com");
+ SubjectAlternativeName san2 = new SubjectAlternativeName(DNS, "san2.com");
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
.addSubjectAlternativeName(san1)
.addSubjectAlternativeName(san2)
@@ -31,7 +31,7 @@ public class Pkcs10CsrTest {
}
@Test
- public void can_read_basic_constraints() {
+ void can_read_basic_constraints() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
@@ -42,7 +42,7 @@ public class Pkcs10CsrTest {
}
@Test
- public void can_read_extensions() {
+ void can_read_extensions() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
index 32b8dfc5bcd..48ff3e9a6fd 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class Pkcs10CsrUtilsTest {
@Test
- public void can_deserialize_serialized_pem_csr() {
+ void can_deserialize_serialized_pem_csr() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA).build();
diff --git a/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java
index 3c40cb89e6c..b08494bb8da 100644
--- a/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -20,25 +20,25 @@ public class SslContextBuilderTest {
private static final char[] PASSWORD = new char[0];
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_build_sslcontext_with_truststore_only() throws Exception {
+ void can_build_sslcontext_with_truststore_only() throws Exception {
new SslContextBuilder()
.withTrustStore(createKeystore(KeyStoreType.JKS, PASSWORD))
.build();
}
@Test
- public void can_build_sslcontext_with_keystore_only() throws Exception {
+ void can_build_sslcontext_with_keystore_only() throws Exception {
new SslContextBuilder()
.withKeyStore(createKeystore(KeyStoreType.JKS, PASSWORD), PASSWORD)
.build();
}
@Test
- public void can_build_sslcontext_with_truststore_and_keystore() throws Exception {
+ void can_build_sslcontext_with_truststore_and_keystore() throws Exception {
new SslContextBuilder()
.withKeyStore(createKeystore(KeyStoreType.JKS, PASSWORD), PASSWORD)
.withTrustStore(createKeystore(KeyStoreType.JKS, PASSWORD))
@@ -46,7 +46,7 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_keystore_from_private_key_and_certificate() throws Exception {
+ void can_build_sslcontext_with_keystore_from_private_key_and_certificate() throws Exception {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X509Certificate certificate = createCertificate(keyPair);
new SslContextBuilder()
@@ -55,8 +55,8 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_jks_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_sslcontext_with_jks_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.JKS, PASSWORD);
new SslContextBuilder()
@@ -65,8 +65,8 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_pcks12_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_sslcontext_with_pcks12_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.PKCS12, PASSWORD);
new SslContextBuilder()
diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
index eb6fe4286d8..1a9c4999146 100644
--- a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
@@ -1,9 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -14,35 +13,35 @@ import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
-@RunWith(Parameterized.class)
public class X509CertificateBuilderTest {
- @Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
+ return Arrays.asList(new Object[][]{
{KeyAlgorithm.RSA, 2048, SignatureAlgorithm.SHA512_WITH_RSA},
{KeyAlgorithm.EC, 256, SignatureAlgorithm.SHA512_WITH_ECDSA}});
}
- private final KeyAlgorithm keyAlgorithm;
- private final int keySize;
- private final SignatureAlgorithm signatureAlgorithm;
+ private KeyAlgorithm keyAlgorithm;
+ private int keySize;
+ private SignatureAlgorithm signatureAlgorithm;
- public X509CertificateBuilderTest(KeyAlgorithm keyAlgorithm,
- int keySize,
- SignatureAlgorithm signatureAlgorithm) {
+ public void initX509CertificateBuilderTest(KeyAlgorithm keyAlgorithm,
+ int keySize,
+ SignatureAlgorithm signatureAlgorithm) {
this.keyAlgorithm = keyAlgorithm;
this.keySize = keySize;
this.signatureAlgorithm = signatureAlgorithm;
}
- @Test
- public void can_build_self_signed_certificate() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "{0}")
+ void can_build_self_signed_certificate(KeyAlgorithm keyAlgorithm, int keySize, SignatureAlgorithm signatureAlgorithm) {
+ initX509CertificateBuilderTest(keyAlgorithm, keySize, signatureAlgorithm);
KeyPair keyPair = KeyUtils.generateKeypair(keyAlgorithm, keySize);
X500Principal subject = new X500Principal("CN=myservice");
X509Certificate cert =
@@ -53,13 +52,15 @@ public class X509CertificateBuilderTest {
Instant.now().plus(1, ChronoUnit.DAYS),
signatureAlgorithm,
BigInteger.valueOf(1))
- .setBasicConstraints(true, true)
- .build();
+ .setBasicConstraints(true, true)
+ .build();
assertEquals(subject, cert.getSubjectX500Principal());
}
- @Test
- public void can_build_certificate_from_csr() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "{0}")
+ void can_build_certificate_from_csr(KeyAlgorithm keyAlgorithm, int keySize, SignatureAlgorithm signatureAlgorithm) {
+ initX509CertificateBuilderTest(keyAlgorithm, keySize, signatureAlgorithm);
X500Principal subject = new X500Principal("CN=subject");
X500Principal issuer = new X500Principal("CN=issuer");
KeyPair csrKeypair = KeyUtils.generateKeypair(keyAlgorithm, keySize);
diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java
index b2e800542b8..c0560627661 100644
--- a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -12,18 +12,18 @@ import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
*/
public class X509CertificateUtilsTest {
@Test
- public void can_deserialize_serialized_pem_certificate() {
+ void can_deserialize_serialized_pem_certificate() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=myservice");
X509Certificate cert = TestUtils.createCertificate(keypair, subject);
@@ -36,7 +36,7 @@ public class X509CertificateUtilsTest {
}
@Test
- public void can_deserialize_serialized_pem_certificate_list() {
+ void can_deserialize_serialized_pem_certificate_list() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject1 = new X500Principal("CN=myservice1");
X509Certificate cert1 = TestUtils.createCertificate(keypair, subject1);
@@ -51,10 +51,10 @@ public class X509CertificateUtilsTest {
}
@Test
- public void can_list_subject_alternative_names() {
+ void can_list_subject_alternative_names() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=myservice");
- SubjectAlternativeName san = new SubjectAlternativeName(DNS_NAME, "dns-san");
+ SubjectAlternativeName san = new SubjectAlternativeName(DNS, "dns-san");
X509Certificate cert = X509CertificateBuilder
.fromKeypair(
keypair,
@@ -72,7 +72,7 @@ public class X509CertificateUtilsTest {
}
@Test
- public void verifies_matching_cert_and_key() {
+ void verifies_matching_cert_and_key() {
KeyPair ecKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair ecKeypairB = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair rsaKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 1024);
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java
new file mode 100644
index 00000000000..2a7149ba2e3
--- /dev/null
+++ b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java
@@ -0,0 +1,27 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.HashSet;
+
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * @author bjorncs
+ */
+public class AuthorizedPeersTest {
+
+ @Test
+ void throws_exception_on_peer_policies_with_duplicate_names() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "mycfgserver")));
+ PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "myclient")));
+ new AuthorizedPeers(new HashSet<>(asList(peerPolicy1, peerPolicy2)));
+ });
+ }
+
+}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/CapabilitySetTest.java b/security-utils/src/test/java/com/yahoo/security/tls/CapabilitySetTest.java
new file mode 100644
index 00000000000..87b16dbff1f
--- /dev/null
+++ b/security-utils/src/test/java/com/yahoo/security/tls/CapabilitySetTest.java
@@ -0,0 +1,27 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * @author bjorncs
+ */
+class CapabilitySetTest {
+
+ @Test
+ void contains_all_capabilities() {
+ SortedSet<String> expectedNames = Arrays.stream(Capability.values())
+ .map(Capability::asString)
+ .collect(Collectors.toCollection(TreeSet::new));
+ SortedSet<String> actualNames = CapabilitySet.all().toNames();
+ assertEquals(expectedNames, actualNames);
+ }
+
+}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
index 0af6d231701..7b70c842a4c 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
@@ -4,12 +4,13 @@ package com.yahoo.security.tls;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLEngine;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
@@ -28,23 +29,23 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ConfigFileBasedTlsContextTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_create_sslcontext_from_credentials() throws IOException, InterruptedException {
+ void can_create_sslcontext_from_credentials() throws IOException, InterruptedException {
KeyPair keyPair = KeyUtils.generateKeypair(EC);
- Path privateKeyFile = tempDirectory.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate()).getBytes());
X509Certificate certificate = X509CertificateBuilder
.fromKeypair(keyPair, new X500Principal("CN=dummy"), EPOCH, EPOCH.plus(1, DAYS), SHA256_WITH_ECDSA, BigInteger.ONE)
.build();
- Path certificateChainFile = tempDirectory.newFile().toPath();
+ Path certificateChainFile = File.createTempFile("junit", null, tempDirectory).toPath();
String certificatePem = X509CertificateUtils.toPem(certificate);
Files.write(certificateChainFile, certificatePem.getBytes());
- Path caCertificatesFile = tempDirectory.newFile().toPath();
+ Path caCertificatesFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(caCertificatesFile, certificatePem.getBytes());
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
@@ -52,7 +53,7 @@ public class ConfigFileBasedTlsContextTest {
.withCaCertificates(caCertificatesFile)
.build();
- Path optionsFile = tempDirectory.newFile().toPath();
+ Path optionsFile = File.createTempFile("junit", null, tempDirectory).toPath();
options.toJsonFile(optionsFile);
try (TlsContext tlsContext = new ConfigFileBasedTlsContext(optionsFile, AuthorizationMode.ENFORCE)) {
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/ConnectionAuthContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/ConnectionAuthContextTest.java
new file mode 100644
index 00000000000..c30a812a30d
--- /dev/null
+++ b/security-utils/src/test/java/com/yahoo/security/tls/ConnectionAuthContextTest.java
@@ -0,0 +1,62 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.security.tls;
+
+import com.yahoo.security.KeyAlgorithm;
+import com.yahoo.security.KeyUtils;
+import com.yahoo.security.X509CertificateBuilder;
+import org.junit.jupiter.api.Test;
+
+import javax.security.auth.x500.X500Principal;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.cert.X509Certificate;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
+import java.util.Set;
+
+import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * @author bjorncs
+ */
+class ConnectionAuthContextTest {
+
+ @Test
+ void fails_on_missing_capabilities() {
+ ConnectionAuthContext ctx = createConnectionAuthContext();
+ assertThrows(MissingCapabilitiesException.class,
+ () -> ctx.verifyCapabilities(CapabilitySet.from(Capability.CONTENT__STATUS_PAGES)));
+ }
+
+ @Test
+ void creates_correct_error_message() {
+ ConnectionAuthContext ctx = createConnectionAuthContext();
+ CapabilitySet requiredCaps = CapabilitySet.from(Capability.CONTENT__STATUS_PAGES);
+ String expectedMessage = """
+ Permission denied for 'myaction' on 'myresource'. Peer 'mypeer' with [CN='myidentity'].
+ Requires capabilities [vespa.content.status_pages] but peer has
+ [vespa.content.document_api, vespa.content.search_api, vespa.slobrok.api].
+ """;
+ String actualMessage = ctx.createPermissionDeniedErrorMessage(requiredCaps, "myaction", "myresource", "mypeer");
+ assertThat(actualMessage).isEqualToIgnoringWhitespace(expectedMessage);
+ }
+
+ private static ConnectionAuthContext createConnectionAuthContext() {
+ return new ConnectionAuthContext(
+ List.of(createCertificate()), CapabilitySet.Predefined.CONTAINER_NODE.capabilities(), Set.of(),
+ CapabilityMode.ENFORCE);
+ }
+
+ private static X509Certificate createCertificate() {
+ KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
+ return X509CertificateBuilder.fromKeypair(
+ keyPair, new X500Principal("CN=myidentity"), Instant.EPOCH,
+ Instant.EPOCH.plus(100000, ChronoUnit.DAYS), SHA256_WITH_ECDSA, BigInteger.ONE)
+ .build();
+ }
+
+
+}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
index 8236ce081ba..bf4a618d9ce 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
@@ -3,11 +3,7 @@ package com.yahoo.security.tls;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.Role;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLEngine;
import javax.security.auth.x500.X500Principal;
@@ -30,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DefaultTlsContextTest {
@Test
- public void can_create_sslcontext_from_credentials() {
+ void can_create_sslcontext_from_credentials() {
KeyPair keyPair = KeyUtils.generateKeypair(EC);
X509Certificate certificate = X509CertificateBuilder
@@ -41,7 +37,6 @@ public class DefaultTlsContextTest {
singleton(
new PeerPolicy(
"dummy-policy",
- singleton(new Role("dummy-role")),
singletonList(RequiredPeerCredential.of(RequiredPeerCredential.Field.CN, "dummy")))));
DefaultTlsContext tlsContext =
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/policy/GlobPatternTest.java b/security-utils/src/test/java/com/yahoo/security/tls/GlobPatternTest.java
index 4350aa2b0a9..a93bffe6961 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/policy/GlobPatternTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/GlobPatternTest.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import org.junit.jupiter.api.Test;
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/policy/HostGlobPatternTest.java b/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java
index a42eaaf74b0..b63b1dfeaa0 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/policy/HostGlobPatternTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -13,28 +13,28 @@ import static org.junit.Assert.assertTrue;
public class HostGlobPatternTest {
@Test
- public void glob_without_wildcards_matches_entire_string() {
+ void glob_without_wildcards_matches_entire_string() {
assertTrue(globMatches("foo", "foo"));
assertFalse(globMatches("foo", "fooo"));
assertFalse(globMatches("foo", "ffoo"));
}
@Test
- public void wildcard_glob_can_match_prefix() {
+ void wildcard_glob_can_match_prefix() {
assertTrue(globMatches("foo*", "foo"));
assertTrue(globMatches("foo*", "foobar"));
assertFalse(globMatches("foo*", "ffoo"));
}
@Test
- public void wildcard_glob_can_match_suffix() {
+ void wildcard_glob_can_match_suffix() {
assertTrue(globMatches("*foo", "foo"));
assertTrue(globMatches("*foo", "ffoo"));
assertFalse(globMatches("*foo", "fooo"));
}
@Test
- public void wildcard_glob_can_match_substring() {
+ void wildcard_glob_can_match_substring() {
assertTrue(globMatches("f*o", "fo"));
assertTrue(globMatches("f*o", "foo"));
assertTrue(globMatches("f*o", "ffoo"));
@@ -42,7 +42,7 @@ public class HostGlobPatternTest {
}
@Test
- public void wildcard_glob_does_not_cross_multiple_dot_delimiter_boundaries() {
+ void wildcard_glob_does_not_cross_multiple_dot_delimiter_boundaries() {
assertTrue(globMatches("*.bar.baz", "foo.bar.baz"));
assertTrue(globMatches("*.bar.baz", ".bar.baz"));
assertFalse(globMatches("*.bar.baz", "zoid.foo.bar.baz"));
@@ -51,7 +51,7 @@ public class HostGlobPatternTest {
}
@Test
- public void single_char_glob_matches_non_dot_characters() {
+ void single_char_glob_matches_non_dot_characters() {
assertTrue(globMatches("f?o", "foo"));
assertFalse(globMatches("f?o", "fooo"));
assertFalse(globMatches("f?o", "ffoo"));
@@ -59,7 +59,7 @@ public class HostGlobPatternTest {
}
@Test
- public void other_regex_meta_characters_are_matched_as_literal_characters() {
+ void other_regex_meta_characters_are_matched_as_literal_characters() {
assertTrue(globMatches("<([{\\^-=$!|]})+.>", "<([{\\^-=$!|]})+.>"));
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/authz/PeerAuthorizerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java
index fdfed781286..bea5c6108f2 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/authz/PeerAuthorizerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java
@@ -1,16 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.authz;
+package com.yahoo.security.tls;
import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SubjectAlternativeName.Type;
import com.yahoo.security.X509CertificateBuilder;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.RequiredPeerCredential.Field;
-import com.yahoo.security.tls.policy.Role;
-import org.junit.Test;
+import com.yahoo.security.tls.RequiredPeerCredential.Field;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -20,20 +16,20 @@ import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.CN;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.SAN_DNS;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.SAN_URI;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_DNS;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_URI;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
-import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -41,60 +37,57 @@ import static org.junit.Assert.assertTrue;
public class PeerAuthorizerTest {
private static final KeyPair KEY_PAIR = KeyUtils.generateKeypair(KeyAlgorithm.EC);
- private static final String ROLE_1 = "role-1", ROLE_2 = "role-2", ROLE_3 = "role-3", POLICY_1 = "policy-1", POLICY_2 = "policy-2";
+ private static final String POLICY_1 = "policy-1", POLICY_2 = "policy-2";
@Test
- public void certificate_must_match_both_san_and_cn_pattern() {
+ void certificate_must_match_both_san_and_cn_pattern() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
- PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, createRoles(ROLE_1), cnRequirement, sanRequirement));
+ PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanRequirement));
- AuthorizationResult result = authorizer.authorizePeer(createCertificate("foo.matching.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList()));
+ ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList()));
assertAuthorized(result);
- assertThat(result.assumedRoles()).extracting(Role::name).containsOnly(ROLE_1);
assertThat(result.matchedPolicies()).containsOnly(POLICY_1);
assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList())));
- assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", asList("foo.matching.san", "foo.invalid.san"),emptyList())));
+ assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList())));
assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.invalid.san"), emptyList())));
}
@Test
- public void can_match_multiple_policies() {
+ void can_match_multiple_policies() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
- createPolicy(POLICY_1, createRoles(ROLE_1, ROLE_2), cnRequirement, sanRequirement),
- createPolicy(POLICY_2, createRoles(ROLE_2, ROLE_3), cnRequirement, sanRequirement));
+ createPolicy(POLICY_1, cnRequirement, sanRequirement),
+ createPolicy(POLICY_2, cnRequirement, sanRequirement));
- AuthorizationResult result = peerAuthorizer
+ ConnectionAuthContext result = peerAuthorizer
.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.matching.san"), emptyList()));
assertAuthorized(result);
- assertThat(result.assumedRoles()).extracting(Role::name).containsOnly(ROLE_1, ROLE_2, ROLE_3);
assertThat(result.matchedPolicies()).containsOnly(POLICY_1, POLICY_2);
}
@Test
- public void can_match_subset_of_policies() {
+ void can_match_subset_of_policies() {
PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
- createPolicy(POLICY_1, createRoles(ROLE_1), createRequiredCredential(CN, "*.matching.cn")),
- createPolicy(POLICY_2, createRoles(ROLE_1, ROLE_2), createRequiredCredential(SAN_DNS, "*.matching.san")));
+ createPolicy(POLICY_1, createRequiredCredential(CN, "*.matching.cn")),
+ createPolicy(POLICY_2, createRequiredCredential(SAN_DNS, "*.matching.san")));
- AuthorizationResult result = peerAuthorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList()));
+ ConnectionAuthContext result = peerAuthorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList()));
assertAuthorized(result);
- assertThat(result.assumedRoles()).extracting(Role::name).containsOnly(ROLE_1, ROLE_2);
assertThat(result.matchedPolicies()).containsOnly(POLICY_2);
}
@Test
- public void must_match_all_cn_and_san_patterns() {
+ void must_match_all_cn_and_san_patterns() {
RequiredPeerCredential cnSuffixRequirement = createRequiredCredential(CN, "*.*.matching.suffix.cn");
RequiredPeerCredential cnPrefixRequirement = createRequiredCredential(CN, "matching.prefix.*.*.*");
RequiredPeerCredential sanPrefixRequirement = createRequiredCredential(SAN_DNS, "*.*.matching.suffix.san");
RequiredPeerCredential sanSuffixRequirement = createRequiredCredential(SAN_DNS, "matching.prefix.*.*.*");
PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
- createPolicy(POLICY_1, emptySet(), cnSuffixRequirement, cnPrefixRequirement, sanPrefixRequirement, sanSuffixRequirement));
+ createPolicy(POLICY_1, cnSuffixRequirement, cnPrefixRequirement, sanPrefixRequirement, sanSuffixRequirement));
assertAuthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", singletonList("matching.prefix.matching.suffix.san"), emptyList())));
assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", singletonList("matching.prefix.invalid.suffix.san"), emptyList())));
@@ -102,19 +95,33 @@ public class PeerAuthorizerTest {
}
@Test
- public void can_match_policy_with_san_uri_pattern() {
+ void can_match_policy_with_san_uri_pattern() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanUriRequirement = createRequiredCredential(SAN_URI, "myscheme://my/*/uri");
- PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, createRoles(ROLE_1), cnRequirement, sanUriRequirement));
+ PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanUriRequirement));
- AuthorizationResult result = authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.irrelevant.san"), singletonList("myscheme://my/matching/uri")));
+ ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.irrelevant.san"), singletonList("myscheme://my/matching/uri")));
assertAuthorized(result);
- assertThat(result.assumedRoles()).extracting(Role::name).containsOnly(ROLE_1);
assertThat(result.matchedPolicies()).containsOnly(POLICY_1);
assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", emptyList(), singletonList("myscheme://my/nonmatching/url"))));
}
+ @Test
+ void auth_context_contains_union_of_granted_capabilities_from_policies() {
+ RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
+ RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
+
+ PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
+ createPolicy(POLICY_1, List.of(Capability.SLOBROK__API, Capability.CONTENT__DOCUMENT_API), List.of(cnRequirement)),
+ createPolicy(POLICY_2, List.of(Capability.SLOBROK__API, Capability.CONTENT__SEARCH_API), List.of(sanRequirement)));
+
+ var result = peerAuthorizer
+ .authorizePeer(createCertificate("foo.matching.cn", List.of("foo.matching.san"), List.of()));
+ assertAuthorized(result);
+ assertCapabiltiesGranted(result, Set.of(Capability.SLOBROK__API, Capability.CONTENT__DOCUMENT_API, Capability.CONTENT__SEARCH_API));
+ }
+
private static X509Certificate createCertificate(String subjectCn, List<String> sanDns, List<String> sanUri) {
X509CertificateBuilder builder =
X509CertificateBuilder.fromKeypair(
@@ -124,8 +131,8 @@ public class PeerAuthorizerTest {
Instant.EPOCH.plus(100000, ChronoUnit.DAYS),
SHA256_WITH_ECDSA,
BigInteger.ONE);
- sanDns.forEach(san -> builder.addSubjectAlternativeName(Type.DNS_NAME, san));
- sanUri.forEach(san -> builder.addSubjectAlternativeName(Type.UNIFORM_RESOURCE_IDENTIFIER, san));
+ sanDns.forEach(san -> builder.addSubjectAlternativeName(Type.DNS, san));
+ sanUri.forEach(san -> builder.addSubjectAlternativeName(Type.URI, san));
return builder.build();
}
@@ -133,24 +140,28 @@ public class PeerAuthorizerTest {
return RequiredPeerCredential.of(field, pattern);
}
- private static Set<Role> createRoles(String... roleNames) {
- return Arrays.stream(roleNames).map(Role::new).collect(toSet());
- }
-
private static PeerAuthorizer createPeerAuthorizer(PeerPolicy... policies) {
return new PeerAuthorizer(new AuthorizedPeers(Arrays.stream(policies).collect(toSet())));
}
- private static PeerPolicy createPolicy(String name, Set<Role> roles, RequiredPeerCredential... requiredCredentials) {
- return new PeerPolicy(name, roles, asList(requiredCredentials));
+ private static PeerPolicy createPolicy(String name, RequiredPeerCredential... requiredCredentials) {
+ return new PeerPolicy(name, asList(requiredCredentials));
+ }
+
+ private static PeerPolicy createPolicy(String name, List<Capability> caps, List<RequiredPeerCredential> creds) {
+ return new PeerPolicy(name, Optional.empty(), CapabilitySet.from(caps), creds);
+ }
+
+ private static void assertAuthorized(ConnectionAuthContext result) {
+ assertTrue(result.authorized());
}
- private static void assertAuthorized(AuthorizationResult result) {
- assertTrue(result.succeeded());
+ private static void assertUnauthorized(ConnectionAuthContext result) {
+ assertFalse(result.authorized());
}
- private static void assertUnauthorized(AuthorizationResult result) {
- assertFalse(result.succeeded());
+ private static void assertCapabiltiesGranted(ConnectionAuthContext ctx, Set<Capability> expected) {
+ assertThat(ctx.capabilities().asSet()).containsOnly(expected.toArray(new Capability[0]));
}
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java
index 6bca49aee83..895428037ed 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/json/TransportSecurityOptionsJsonSerializerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java
@@ -1,14 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.json;
+package com.yahoo.security.tls;
-import com.yahoo.security.tls.TransportSecurityOptions;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
-import com.yahoo.security.tls.policy.PeerPolicy;
-import com.yahoo.security.tls.policy.RequiredPeerCredential;
-import com.yahoo.security.tls.policy.Role;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -21,25 +17,26 @@ import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
+import java.util.Optional;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.CN;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.SAN_DNS;
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.SAN_URI;
-import static com.yahoo.test.json.JsonTestHelper.assertJsonEquals;
-import static java.util.Collections.singleton;
-import static org.junit.Assert.assertEquals;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_DNS;
+import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_URI;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
public class TransportSecurityOptionsJsonSerializerTest {
- @Rule public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
private static final Path TEST_CONFIG_FILE = Paths.get("src/test/resources/transport-security-options.json");
+ private static final ObjectMapper mapper = new ObjectMapper();
@Test
- public void can_serialize_and_deserialize_transport_security_options() throws IOException {
+ void can_serialize_and_deserialize_transport_security_options() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCaCertificates(Paths.get("/path/to/ca-certs.pem"))
.withCertificates(Paths.get("/path/to/cert.pem"), Paths.get("/path/to/key.pem"))
@@ -47,11 +44,13 @@ public class TransportSecurityOptionsJsonSerializerTest {
.withAuthorizedPeers(
new AuthorizedPeers(
new LinkedHashSet<>(Arrays.asList(
- new PeerPolicy("cfgserver", "cfgserver policy description", singleton(new Role("myrole")), Arrays.asList(
+ new PeerPolicy("cfgserver", "cfgserver policy description", Arrays.asList(
RequiredPeerCredential.of(CN, "mycfgserver"),
RequiredPeerCredential.of(SAN_DNS, "*.suffix.com"),
RequiredPeerCredential.of(SAN_URI, "myscheme://resource/path/"))),
- new PeerPolicy("node", singleton(new Role("anotherrole")), Collections.singletonList(RequiredPeerCredential.of(CN, "hostname")))))))
+ new PeerPolicy("node", Optional.empty(),
+ CapabilitySet.from(Capability.SLOBROK__API),
+ Collections.singletonList(RequiredPeerCredential.of(CN, "hostname")))))))
.build();
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -64,15 +63,15 @@ public class TransportSecurityOptionsJsonSerializerTest {
}
@Test
- public void can_serialize_options_without_authorized_peers() throws IOException {
+ void can_serialize_options_without_authorized_peers() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
- .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" , "TLS_AES_256_GCM_SHA384"))
+ .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384"))
.withAcceptedProtocols(Collections.singletonList("TLSv1.2"))
.withHostnameValidationDisabled(true)
.build();
- File outputFile = tempDirectory.newFile();
+ File outputFile = File.createTempFile("junit", null, tempDirectory);
try (OutputStream out = Files.newOutputStream(outputFile.toPath())) {
new TransportSecurityOptionsJsonSerializer().serialize(out, options);
}
@@ -82,13 +81,13 @@ public class TransportSecurityOptionsJsonSerializerTest {
}
@Test
- public void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
+ void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
.withHostnameValidationDisabled(false)
.build();
- File outputFile = tempDirectory.newFile();
+ File outputFile = File.createTempFile("junit", null, tempDirectory);
try (OutputStream out = Files.newOutputStream(outputFile.toPath())) {
new TransportSecurityOptionsJsonSerializer().serialize(out, options);
}
@@ -99,4 +98,8 @@ public class TransportSecurityOptionsJsonSerializerTest {
assertJsonEquals(expectedOutput, actualOutput);
}
+ private static void assertJsonEquals(String inputJson, String expectedJson) throws JsonProcessingException {
+ assertEquals(mapper.readTree(expectedJson), mapper.readTree(inputJson));
+ }
+
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java
index 7d67c492170..089a4ca6de5 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -11,7 +11,7 @@ import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -28,13 +28,13 @@ public class TransportSecurityOptionsTest {
.build();
@Test
- public void can_read_options_from_json_file() {
+ void can_read_options_from_json_file() {
TransportSecurityOptions actualOptions = TransportSecurityOptions.fromJsonFile(TEST_CONFIG_FILE);
assertEquals(OPTIONS, actualOptions);
}
@Test
- public void can_read_options_from_json() throws IOException {
+ void can_read_options_from_json() throws IOException {
String tlsJson = new String(Files.readAllBytes(TEST_CONFIG_FILE), StandardCharsets.UTF_8);
TransportSecurityOptions actualOptions = TransportSecurityOptions.fromJson(tlsJson);
assertEquals(OPTIONS, actualOptions);
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/policy/UriGlobPatternTest.java b/security-utils/src/test/java/com/yahoo/security/tls/UriGlobPatternTest.java
index c60c782da14..4d89d71cf85 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/policy/UriGlobPatternTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/UriGlobPatternTest.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
+package com.yahoo.security.tls;
import org.junit.jupiter.api.Test;
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/policy/AuthorizedPeersTest.java b/security-utils/src/test/java/com/yahoo/security/tls/policy/AuthorizedPeersTest.java
deleted file mode 100644
index c44a23ecf2b..00000000000
--- a/security-utils/src/test/java/com/yahoo/security/tls/policy/AuthorizedPeersTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-package com.yahoo.security.tls.policy;
-
-import org.junit.Test;
-
-import java.util.HashSet;
-import java.util.List;
-
-import static com.yahoo.security.tls.policy.RequiredPeerCredential.Field.CN;
-import static java.util.Arrays.asList;
-import static java.util.Collections.singleton;
-import static java.util.Collections.singletonList;
-
-/**
- * @author bjorncs
- */
-public class AuthorizedPeersTest {
-
- @Test(expected = IllegalArgumentException.class)
- public void throws_exception_on_peer_policies_with_duplicate_names() {
- List<RequiredPeerCredential> requiredPeerCredential = singletonList(RequiredPeerCredential.of(CN, "mycfgserver"));
- PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", singleton(new Role("role")), requiredPeerCredential);
- PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", singleton(new Role("anotherrole")), requiredPeerCredential);
- new AuthorizedPeers(new HashSet<>(asList(peerPolicy1, peerPolicy2)));
- }
-
-}
diff --git a/security-utils/src/test/resources/transport-security-options-with-authz-rules.json b/security-utils/src/test/resources/transport-security-options-with-authz-rules.json
index ea0bee38c8a..85c3a78311e 100644
--- a/security-utils/src/test/resources/transport-security-options-with-authz-rules.json
+++ b/security-utils/src/test/resources/transport-security-options-with-authz-rules.json
@@ -16,14 +16,13 @@
"must-match" : "myscheme://resource/path/"
} ],
"name" : "cfgserver",
- "description" : "cfgserver policy description",
- "roles" : [ "myrole" ]
+ "description" : "cfgserver policy description"
}, {
"required-credentials" : [ {
"field" : "CN",
"must-match" : "hostname"
} ],
"name" : "node",
- "roles" : [ "anotherrole" ]
+ "capabilities" : [ "vespa.slobrok.api" ]
} ]
} \ No newline at end of file
diff --git a/standalone-container/pom.xml b/standalone-container/pom.xml
index 86cad2ad012..590872282ca 100644
--- a/standalone-container/pom.xml
+++ b/standalone-container/pom.xml
@@ -93,14 +93,26 @@
<discApplicationClass>com.yahoo.container.standalone.StandaloneContainerApplication</discApplicationClass>
<buildLegacyVespaPlatformBundle>true</buildLegacyVespaPlatformBundle>
<discPreInstallBundle>
+ <!-- Standalone container has an embedded config model, so model related bundles cannot be retrieved via config -->
configdefinitions-jar-with-dependencies.jar,
config-provisioning-jar-with-dependencies.jar,
config-bundle-jar-with-dependencies.jar,
config-model-api-jar-with-dependencies.jar,
config-model-jar-with-dependencies.jar,
+
container-disc-jar-with-dependencies.jar,
+
+ <!-- START bundles that can be moved to config-model when all standalone containers are set up via the model -->
+ container-spifly.jar, <!-- Aries SPIFly repackaged -->
+ javax.servlet-api-3.1.0.jar, <!-- Needed by vespa-athenz. TODO Vespa 9: remove the need for servlet-api -->
+ <!-- END bundles that can be moved to config-model -->
+
+ <!-- START config-model dependencies -->
+ container-search-and-docproc-jar-with-dependencies.jar,
+ linguistics-components-jar-with-dependencies.jar,
model-evaluation-jar-with-dependencies.jar,
model-integration-jar-with-dependencies.jar,
+ <!-- END config-model dependencies -->
</discPreInstallBundle>
</configuration>
</plugin>
diff --git a/storage/src/tests/persistence/common/persistenceproviderwrapper.cpp b/storage/src/tests/persistence/common/persistenceproviderwrapper.cpp
index 7e0b96b1d82..fcb56c4a553 100644
--- a/storage/src/tests/persistence/common/persistenceproviderwrapper.cpp
+++ b/storage/src/tests/persistence/common/persistenceproviderwrapper.cpp
@@ -106,11 +106,11 @@ PersistenceProviderWrapper::putAsync(const spi::Bucket& bucket, spi::Timestamp t
}
void
-PersistenceProviderWrapper::removeAsync(const spi::Bucket& bucket, std::vector<TimeStampAndDocumentId> ids,
+PersistenceProviderWrapper::removeAsync(const spi::Bucket& bucket, std::vector<spi::IdAndTimestamp> ids,
spi::OperationComplete::UP onComplete)
{
- for (const TimeStampAndDocumentId & stampedId : ids) {
- LOG_SPI("remove(" << bucket << ", " << stampedId.first << ", " << stampedId.second << ")");
+ for (const auto & stampedId : ids) {
+ LOG_SPI("remove(" << bucket << ", " << stampedId.timestamp << ", " << stampedId.id << ")");
}
CHECK_ERROR_ASYNC(spi::RemoveResult, FAIL_REMOVE, onComplete);
_spi.removeAsync(bucket, std::move(ids), std::move(onComplete));
diff --git a/storage/src/tests/persistence/common/persistenceproviderwrapper.h b/storage/src/tests/persistence/common/persistenceproviderwrapper.h
index 3c93bc91d85..ec7ca70d7c7 100644
--- a/storage/src/tests/persistence/common/persistenceproviderwrapper.h
+++ b/storage/src/tests/persistence/common/persistenceproviderwrapper.h
@@ -106,7 +106,7 @@ public:
spi::BucketIdListResult listBuckets(BucketSpace bucketSpace) const override;
spi::BucketInfoResult getBucketInfo(const spi::Bucket&) const override;
void putAsync(const spi::Bucket&, spi::Timestamp, spi::DocumentSP, spi::OperationComplete::UP) override;
- void removeAsync(const spi::Bucket&, std::vector<TimeStampAndDocumentId> ids, spi::OperationComplete::UP) override;
+ void removeAsync(const spi::Bucket&, std::vector<spi::IdAndTimestamp> ids, spi::OperationComplete::UP) override;
void removeIfFoundAsync(const spi::Bucket&, spi::Timestamp, const spi::DocumentId&, spi::OperationComplete::UP) override;
void updateAsync(const spi::Bucket&, spi::Timestamp, spi::DocumentUpdateSP, spi::OperationComplete::UP) override;
spi::GetResult get(const spi::Bucket&, const document::FieldSet&, const spi::DocumentId&, spi::Context&) const override;
diff --git a/storage/src/tests/storageapi/mbusprot/storageprotocoltest.cpp b/storage/src/tests/storageapi/mbusprot/storageprotocoltest.cpp
index c130e433285..d4d22d6a36c 100644
--- a/storage/src/tests/storageapi/mbusprot/storageprotocoltest.cpp
+++ b/storage/src/tests/storageapi/mbusprot/storageprotocoltest.cpp
@@ -112,8 +112,7 @@ std::string version_as_gtest_string(TestParamInfo<vespalib::Version> info) {
}
VESPA_GTEST_INSTANTIATE_TEST_SUITE_P(MultiVersionTest, StorageProtocolTest,
- Values(vespalib::Version(6, 240, 0),
- vespalib::Version(7, 41, 19)),
+ Values(vespalib::Version(7, 41, 19)),
version_as_gtest_string);
namespace {
@@ -301,10 +300,6 @@ TEST_P(StorageProtocolTest, get_internal_read_consistency_is_strong_by_default)
}
TEST_P(StorageProtocolTest, can_set_internal_read_consistency_on_get_commands) {
- // Only supported on protocol version 7+. Will default to Strong on older versions, which is what we want.
- if (GetParam().getMajor() < 7) {
- return;
- }
auto cmd = std::make_shared<GetCommand>(_bucket, _testDocId, "foo,bar,vekterli", 123);
cmd->set_internal_read_consistency(InternalReadConsistency::Weak);
auto cmd2 = copyCommand(cmd);
@@ -316,10 +311,6 @@ TEST_P(StorageProtocolTest, can_set_internal_read_consistency_on_get_commands) {
}
TEST_P(StorageProtocolTest, tombstones_propagated_for_gets) {
- // Only supported on protocol version 7+.
- if (GetParam().getMajor() < 7) {
- return;
- }
auto cmd = std::make_shared<GetCommand>(_bucket, _testDocId, "foo,bar", 123);
auto reply = std::make_shared<GetReply>(*cmd, std::shared_ptr<Document>(), 100, false, true);
set_dummy_bucket_info_reply_fields(*reply);
@@ -332,23 +323,6 @@ TEST_P(StorageProtocolTest, tombstones_propagated_for_gets) {
EXPECT_TRUE(reply2->is_tombstone());
}
-// TODO remove this once pre-protobuf serialization is removed
-TEST_P(StorageProtocolTest, old_serialization_format_treats_tombstone_get_replies_as_not_found) {
- if (GetParam().getMajor() >= 7) {
- return;
- }
- auto cmd = std::make_shared<GetCommand>(_bucket, _testDocId, "foo,bar", 123);
- auto reply = std::make_shared<GetReply>(*cmd, std::shared_ptr<Document>(), 100, false, true);
- set_dummy_bucket_info_reply_fields(*reply);
- auto reply2 = copyReply(reply);
-
- EXPECT_TRUE(reply2->getDocument().get() == nullptr);
- EXPECT_EQ(_testDoc->getId(), reply2->getDocumentId());
- EXPECT_EQ(Timestamp(123), reply2->getBeforeTimestamp());
- EXPECT_EQ(Timestamp(0), reply2->getLastModifiedTimestamp());
- EXPECT_FALSE(reply2->is_tombstone()); // Protocol version doesn't understand explicit tombstones.
-}
-
TEST_P(StorageProtocolTest, remove) {
auto cmd = std::make_shared<RemoveCommand>(_bucket, _testDocId, 159);
auto cmd2 = copyCommand(cmd);
@@ -486,11 +460,7 @@ TEST_P(StorageProtocolTest, merge_bucket) {
EXPECT_EQ(Timestamp(1234), cmd2->getMaxTimestamp());
EXPECT_EQ(uint32_t(567), cmd2->getClusterStateVersion());
EXPECT_EQ(chain, cmd2->getChain());
- if (GetParam().getMajor() >= 7) {
- EXPECT_EQ(cmd2->use_unordered_forwarding(), cmd->use_unordered_forwarding());
- } else {
- EXPECT_FALSE(cmd2->use_unordered_forwarding());
- }
+ EXPECT_EQ(cmd2->use_unordered_forwarding(), cmd->use_unordered_forwarding());
auto reply = std::make_shared<MergeBucketReply>(*cmd);
auto reply2 = copyReply(reply);
@@ -569,18 +539,10 @@ TEST_P(StorageProtocolTest, remove_location) {
uint32_t n_docs_removed = 12345;
auto reply = std::make_shared<RemoveLocationReply>(*cmd2, n_docs_removed);
auto reply2 = copyReply(reply);
- if (GetParam().getMajor() == 7) {
- // Statistics are only available for protobuf-enabled version.
- EXPECT_EQ(n_docs_removed, reply2->documents_removed());
- } else {
- EXPECT_EQ(0, reply2->documents_removed());
- }
+ EXPECT_EQ(n_docs_removed, reply2->documents_removed());
}
TEST_P(StorageProtocolTest, stat_bucket) {
- if (GetParam().getMajor() < 7) {
- return; // Only available for protobuf-backed protocol version.
- }
auto cmd = std::make_shared<StatBucketCommand>(_bucket, "id.group == 'mygroup'");
auto cmd2 = copyCommand(cmd);
EXPECT_EQ("id.group == 'mygroup'", cmd2->getDocumentSelection());
@@ -823,11 +785,7 @@ TEST_P(StorageProtocolTest, serialized_size_is_used_to_set_approx_size_of_storag
auto cmd2 = copyCommand(cmd);
auto version = GetParam();
- if (version.getMajor() == 7) { // Protobuf-based encoding
- EXPECT_EQ(158u, cmd2->getApproxByteSize());
- } else { // Legacy encoding
- EXPECT_EQ(181u, cmd2->getApproxByteSize());
- }
+ EXPECT_EQ(158u, cmd2->getApproxByteSize());
}
TEST_P(StorageProtocolTest, track_memory_footprint_for_some_messages) {
diff --git a/storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp b/storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp
index cd80244af87..8b8801f9cf5 100644
--- a/storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp
+++ b/storage/src/tests/storageserver/rpc/storage_api_rpc_service_test.cpp
@@ -196,10 +196,6 @@ public:
return _messages.pop_first_message();
}
- bool target_supports_direct_rpc(const api::StorageMessageAddress& addr) const noexcept {
- return _service->target_supports_direct_rpc(addr);
- }
-
void send_raw_request_and_expect_error(StorageApiNode& node,
FRT_RPCRequest* req,
const vespalib::string& expected_msg) {
@@ -220,16 +216,6 @@ StorageApiNode::~StorageApiNode() {
_shared_rpc_resources->shutdown();
}
-struct NodeWithoutStorageApiService : RpcNode {
- NodeWithoutStorageApiService(uint16_t node_index, bool is_distributor, const mbus::Slobrok& slobrok)
- : RpcNode(node_index, is_distributor, slobrok)
- {
- _shared_rpc_resources->start_server_and_register_slobrok(_slobrok_id);
- // Explicitly wait until we are visible in Slobrok. Just waiting for mirror readiness is not enough.
- wait_until_visible_in_slobrok(_slobrok_id);
- }
-};
-
} // anonymous namespace
// TODO consider completely mocking Slobrok to avoid any race conditions during node registration
@@ -357,28 +343,6 @@ TEST_F(StorageApiRpcServiceTest, response_trace_only_propagated_if_trace_level_s
EXPECT_THAT(trace_str, Not(HasSubstr("Doing cool things")));
}
-TEST_F(StorageApiRpcServiceTest, rpc_method_not_found_toggles_rpc_as_not_supported) {
- NodeWithoutStorageApiService dummy_node(10, false, _slobrok);
- _node_0->wait_until_visible_in_slobrok(to_slobrok_id(dummy_node.node_address()));
-
- // Initially we assume targets are on a new enough version to understand storage API RPCs.
- EXPECT_TRUE(_node_0->target_supports_direct_rpc(dummy_node.node_address()));
- EXPECT_TRUE(_node_0->target_supports_direct_rpc(_node_1->node_address()));
-
- // Send to an endpoint exposing RPC but not the Storage API server method.
- // It will bounce back immediately with an FRT "no such method" error.
- auto cmd = _node_0->create_dummy_put_command();
- cmd->setAddress(dummy_node.node_address());
- _node_0->send_request(cmd);
- auto bounced_msg = _node_0->wait_and_receive_single_message();
- ASSERT_TRUE(bounced_msg);
-
- // For now (and for the sake of simplicity), fall back to assuming no targets
- // support direct storage API RPC.
- EXPECT_FALSE(_node_0->target_supports_direct_rpc(dummy_node.node_address()));
- EXPECT_FALSE(_node_0->target_supports_direct_rpc(_node_1->node_address()));
-}
-
TEST_F(StorageApiRpcServiceTest, malformed_request_header_returns_rpc_error) {
auto& supervisor = _node_0->shared_rpc_resources().supervisor();
auto* req = supervisor.AllocRPCRequest();
diff --git a/storage/src/vespa/storage/config/stor-communicationmanager.def b/storage/src/vespa/storage/config/stor-communicationmanager.def
index c22cf7b8b01..3083fb37081 100644
--- a/storage/src/vespa/storage/config/stor-communicationmanager.def
+++ b/storage/src/vespa/storage/config/stor-communicationmanager.def
@@ -38,33 +38,19 @@ mbus.tcp_no_delay bool default=true restart
## Number of threads for network.
mbus.num_network_threads int default=1 restart
-## Number of workers threads for messagebus
-## Any value below 1 will be 1.
-mbus.num_threads int default=4 restart
-
-mbus.optimize_for enum {LATENCY, THROUGHPUT, ADAPTIVE} default = LATENCY
+## The number of events in the queue of a network (FNET) thread before it is woken up.
+mbus.events_before_wakeup int default=1 restart
## Enable to use above thread pool for encoding replies
## False will use network(fnet) thread
+## Deprecated and void
mbus.dispatch_on_encode bool default=true restart
## Enable to use above thread pool for decoding replies
## False will use network(fnet) thread
-## Todo: Change default once verified in large scale deployment.
+## Deprecated and void
mbus.dispatch_on_decode bool default=true restart
-## Skip messenger thread on reply
-## Experimental
-mbus.skip_reply_thread bool default=false restart
-
-## Skip messenger thread on reply
-## Experimental
-mbus.skip_request_thread bool default=false restart
-
-## Skip communication manager thread on mbus requests
-## Experimental
-skip_thread bool default=false
-
## The number of network (FNET) threads used by the shared rpc resource.
rpc.num_network_threads int default=2 restart
diff --git a/storage/src/vespa/storage/distributor/externaloperationhandler.cpp b/storage/src/vespa/storage/distributor/externaloperationhandler.cpp
index 3f3924df229..9ce8d871fc3 100644
--- a/storage/src/vespa/storage/distributor/externaloperationhandler.cpp
+++ b/storage/src/vespa/storage/distributor/externaloperationhandler.cpp
@@ -97,9 +97,9 @@ ExternalOperationHandler::~ExternalOperationHandler() = default;
bool
ExternalOperationHandler::handleMessage(const std::shared_ptr<api::StorageMessage>& msg, Operation::SP& op)
{
- _op = Operation::SP();
+ _op.reset();
bool retVal = msg->callHandler(*this, msg);
- op = _op;
+ op = std::move(_op); // Don't maintain any strong refs in _op after we've passed it on.
return retVal;
}
diff --git a/storage/src/vespa/storage/persistence/asynchandler.cpp b/storage/src/vespa/storage/persistence/asynchandler.cpp
index f5d29fb32a7..d5bf733a30c 100644
--- a/storage/src/vespa/storage/persistence/asynchandler.cpp
+++ b/storage/src/vespa/storage/persistence/asynchandler.cpp
@@ -114,13 +114,13 @@ bucketStatesAreSemanticallyEqual(const api::BucketInfo& a, const api::BucketInfo
class UnrevertableRemoveEntryProcessor : public BucketProcessor::EntryProcessor {
public:
- using DocumentIdsAndTimeStamps = std::vector<std::pair<spi::Timestamp, spi::DocumentId>>;
+ using DocumentIdsAndTimeStamps = std::vector<spi::IdAndTimestamp>;
UnrevertableRemoveEntryProcessor(DocumentIdsAndTimeStamps & to_remove)
: _to_remove(to_remove)
{}
void process(spi::DocEntry& entry) override {
- _to_remove.emplace_back(entry.getTimestamp(), *entry.getDocumentId());
+ _to_remove.emplace_back(*entry.getDocumentId(), entry.getTimestamp());
}
private:
DocumentIdsAndTimeStamps & _to_remove;
diff --git a/storage/src/vespa/storage/persistence/mergehandler.cpp b/storage/src/vespa/storage/persistence/mergehandler.cpp
index 012d5c2619d..ae68a694c90 100644
--- a/storage/src/vespa/storage/persistence/mergehandler.cpp
+++ b/storage/src/vespa/storage/persistence/mergehandler.cpp
@@ -522,9 +522,9 @@ MergeHandler::applyDiffEntry(std::shared_ptr<ApplyBucketDiffState> async_results
_clock, _env._metrics.merge_handler_metrics.put_latency);
_spi.putAsync(bucket, timestamp, std::move(doc), std::move(complete));
} else {
- std::vector<spi::PersistenceProvider::TimeStampAndDocumentId> ids;
- ids.emplace_back(timestamp, e._docName);
- auto complete = std::make_unique<ApplyBucketDiffEntryComplete>(std::move(async_results), ids[0].second,
+ std::vector<spi::IdAndTimestamp> ids;
+ ids.emplace_back(document::DocumentId(e._docName), timestamp);
+ auto complete = std::make_unique<ApplyBucketDiffEntryComplete>(std::move(async_results), ids[0].id,
std::move(throttle_token), "remove",
_clock, _env._metrics.merge_handler_metrics.remove_latency);
_spi.removeAsync(bucket, std::move(ids), std::move(complete));
diff --git a/storage/src/vespa/storage/persistence/provider_error_wrapper.cpp b/storage/src/vespa/storage/persistence/provider_error_wrapper.cpp
index 1be9679c641..9e55c0f9088 100644
--- a/storage/src/vespa/storage/persistence/provider_error_wrapper.cpp
+++ b/storage/src/vespa/storage/persistence/provider_error_wrapper.cpp
@@ -152,7 +152,7 @@ ProviderErrorWrapper::putAsync(const spi::Bucket &bucket, spi::Timestamp ts, spi
}
void
-ProviderErrorWrapper::removeAsync(const spi::Bucket &bucket, std::vector<TimeStampAndDocumentId> ids,
+ProviderErrorWrapper::removeAsync(const spi::Bucket &bucket, std::vector<spi::IdAndTimestamp> ids,
spi::OperationComplete::UP onComplete)
{
onComplete->addResultHandler(this);
diff --git a/storage/src/vespa/storage/persistence/provider_error_wrapper.h b/storage/src/vespa/storage/persistence/provider_error_wrapper.h
index 7bd406a8758..82447fe4549 100644
--- a/storage/src/vespa/storage/persistence/provider_error_wrapper.h
+++ b/storage/src/vespa/storage/persistence/provider_error_wrapper.h
@@ -58,7 +58,7 @@ public:
void register_error_listener(std::shared_ptr<ProviderErrorListener> listener);
void putAsync(const spi::Bucket &, spi::Timestamp, spi::DocumentSP, spi::OperationComplete::UP) override;
- void removeAsync(const spi::Bucket&, std::vector<TimeStampAndDocumentId>, spi::OperationComplete::UP) override;
+ void removeAsync(const spi::Bucket&, std::vector<spi::IdAndTimestamp>, spi::OperationComplete::UP) override;
void removeIfFoundAsync(const spi::Bucket&, spi::Timestamp, const document::DocumentId&, spi::OperationComplete::UP) override;
void updateAsync(const spi::Bucket &, spi::Timestamp, spi::DocumentUpdateSP, spi::OperationComplete::UP) override;
void setActiveStateAsync(const spi::Bucket& b, spi::BucketInfo::ActiveState newState, spi::OperationComplete::UP onComplete) override;
diff --git a/storage/src/vespa/storage/storageserver/communicationmanager.cpp b/storage/src/vespa/storage/storageserver/communicationmanager.cpp
index 975e9361072..7fb6685a8b5 100644
--- a/storage/src/vespa/storage/storageserver/communicationmanager.cpp
+++ b/storage/src/vespa/storage/storageserver/communicationmanager.cpp
@@ -35,10 +35,6 @@ StorageTransportContext::StorageTransportContext(std::unique_ptr<documentapi::Do
: _docAPIMsg(std::move(msg))
{ }
-StorageTransportContext::StorageTransportContext(std::unique_ptr<mbusprot::StorageCommand> msg)
- : _storageProtocolMsg(std::move(msg))
-{ }
-
StorageTransportContext::StorageTransportContext(std::unique_ptr<RPCRequestWrapper> request)
: _request(std::move(request))
{ }
@@ -49,7 +45,7 @@ void
CommunicationManager::receiveStorageReply(const std::shared_ptr<api::StorageReply>& reply)
{
assert(reply);
- enqueue_or_process(reply);
+ process(reply);
}
namespace {
@@ -104,19 +100,7 @@ CommunicationManager::handleMessage(std::unique_ptr<mbus::Message> msg)
cmd->setTrace(docMsgPtr->steal_trace());
cmd->setTransportContext(std::make_unique<StorageTransportContext>(std::move(docMsgPtr)));
- enqueue_or_process(std::move(cmd));
- } else if (protocolName == mbusprot::StorageProtocol::NAME) {
- std::unique_ptr<mbusprot::StorageCommand> storMsgPtr(static_cast<mbusprot::StorageCommand*>(msg.release()));
-
- assert(storMsgPtr);
-
- //TODO: Can it be moved ?
- std::shared_ptr<api::StorageCommand> cmd = storMsgPtr->getCommand();
- cmd->setTimeout(storMsgPtr->getTimeRemaining());
- cmd->setTrace(storMsgPtr->steal_trace());
- cmd->setTransportContext(std::make_unique<StorageTransportContext>(std::move(storMsgPtr)));
-
- enqueue_or_process(std::move(cmd));
+ process(std::move(cmd));
} else {
LOGBM(warning, "Received unsupported message type %d for protocol '%s'",
msg->getType(), msg->getProtocol().c_str());
@@ -145,26 +129,6 @@ CommunicationManager::handleReply(std::unique_ptr<mbus::Reply> reply)
const vespalib::string& protocolName = message->getProtocol();
if (protocolName == documentapi::DocumentProtocol::NAME) {
convertedReply = static_cast<documentapi::DocumentMessage &>(*message).createReply();
- } else if (protocolName == mbusprot::StorageProtocol::NAME) {
- std::shared_ptr<api::StorageReply> repl(static_cast<mbusprot::StorageCommand &>(*message).getCommand()->makeReply());
- auto sreply = std::make_unique<mbusprot::StorageReply>(repl);
-
- if (reply->hasErrors()) {
- // Convert only the first error since storageapi only
- // supports one return code.
- uint32_t mbuscode = reply->getError(0).getCode();
- api::ReturnCode::Result code((api::ReturnCode::Result) mbuscode);
- // Encode mbuscode into message not to lose it
- sreply->getReply()->setResult(storage::api::ReturnCode(
- code,
- mbus::ErrorCode::getName(mbuscode)
- + vespalib::string(": ")
- + reply->getError(0).getMessage()
- + vespalib::string(" (from ")
- + reply->getError(0).getService()
- + vespalib::string(")")));
- }
- convertedReply = std::move(sreply);
} else {
LOG(warning, "Received reply of unhandled protocol '%s'", protocolName.c_str());
return;
@@ -205,10 +169,6 @@ CommunicationManager::handleReply(std::unique_ptr<mbus::Reply> reply)
sar->setTrace(reply->steal_trace());
receiveStorageReply(sar);
}
- } else if (protocolName == mbusprot::StorageProtocol::NAME) {
- mbusprot::StorageReply* sr(static_cast<mbusprot::StorageReply*>(reply.get()));
- sr->getReply()->setTrace(reply->steal_trace());
- receiveStorageReply(sr->getReply());
} else {
LOGBM(warning, "Received unsupported reply type %d for protocol '%s'.",
reply->getType(), reply->getProtocol().c_str());
@@ -268,8 +228,7 @@ CommunicationManager::CommunicationManager(StorageComponentRegister& compReg, co
_configUri(configUri),
_closed(false),
_docApiConverter(configUri, std::make_shared<PlaceHolderBucketResolver>()),
- _thread(),
- _skip_thread(false)
+ _thread()
{
_component.registerMetricUpdateHook(*this, framework::SecondTime(5));
_component.registerMetric(_metrics);
@@ -372,7 +331,6 @@ CommunicationManager::configureMessageBusLimits(const CommunicationManagerConfig
void CommunicationManager::configure(std::unique_ptr<CommunicationManagerConfig> config)
{
// Only allow dynamic (live) reconfiguration of message bus limits.
- _skip_thread = config->skipThread;
if (_mbus) {
configureMessageBusLimits(*config);
if (_mbus->getRPCNetwork().getPort() != config->mbusport) {
@@ -394,11 +352,9 @@ void CommunicationManager::configure(std::unique_ptr<CommunicationManagerConfig>
LOG(debug, "setting up slobrok config from id: '%s", _configUri.getConfigId().c_str());
mbus::RPCNetworkParams params(_configUri);
params.setConnectionExpireSecs(config->mbus.rpctargetcache.ttl);
- params.setNumThreads(std::max(1, config->mbus.numThreads));
params.setNumNetworkThreads(std::max(1, config->mbus.numNetworkThreads));
params.setNumRpcTargets(std::max(1, config->mbus.numRpcTargets));
- params.setDispatchOnDecode(config->mbus.dispatchOnDecode);
- params.setDispatchOnEncode(config->mbus.dispatchOnEncode);
+ params.events_before_wakeup(std::max(1, config->mbus.eventsBeforeWakeup));
params.setTcpNoDelay(config->mbus.tcpNoDelay);
params.setIdentity(mbus::Identity(_component.getIdentity()));
@@ -411,16 +367,12 @@ void CommunicationManager::configure(std::unique_ptr<CommunicationManagerConfig>
CommunicationManagerConfig::Mbus::Compress::getTypeName(config->mbus.compress.type).c_str());
params.setCompressionConfig(CompressionConfig(compressionType, config->mbus.compress.level,
90, config->mbus.compress.limit));
- params.setSkipRequestThread(config->mbus.skipRequestThread);
- params.setSkipReplyThread(config->mbus.skipReplyThread);
// Configure messagebus here as we for legacy reasons have
// config here.
auto documentTypeRepo = _component.getTypeRepo()->documentTypeRepo;
_mbus = std::make_unique<mbus::RPCMessageBus>(
- mbus::ProtocolSet()
- .add(std::make_shared<documentapi::DocumentProtocol>(documentTypeRepo))
- .add(std::make_shared<mbusprot::StorageProtocol>(documentTypeRepo)),
+ mbus::ProtocolSet().add(std::make_shared<documentapi::DocumentProtocol>(documentTypeRepo)),
params,
_configUri);
@@ -472,18 +424,6 @@ CommunicationManager::process(const std::shared_ptr<api::StorageMessage>& msg)
}
}
-void
-CommunicationManager::enqueue_or_process(std::shared_ptr<api::StorageMessage> msg)
-{
- assert(msg);
- if (_skip_thread.load(std::memory_order_relaxed)) {
- LOG(spam, "Process storage message %s, priority %d", msg->toString().c_str(), msg->getPriority());
- process(msg);
- } else {
- dispatch_async(std::move(msg));
- }
-}
-
void CommunicationManager::dispatch_sync(std::shared_ptr<api::StorageMessage> msg) {
LOG(spam, "Direct dispatch of storage message %s, priority %d", msg->toString().c_str(), msg->getPriority());
process(std::move(msg));
@@ -570,23 +510,13 @@ CommunicationManager::sendCommand(
framework::MilliSecTimer startTime(_component.getClock());
switch (address.getProtocol()) {
- case api::StorageMessageAddress::Protocol::STORAGE:
+ case api::StorageMessageAddress::Protocol::STORAGE:
{
LOG(debug, "Send to %s: %s", address.toString().c_str(), msg->toString().c_str());
- if (_storage_api_rpc_service->target_supports_direct_rpc(address)) {
- _storage_api_rpc_service->send_rpc_v1_request(msg);
- } else {
- auto cmd = std::make_unique<mbusprot::StorageCommand>(msg);
-
- cmd->setContext(mbus::Context(msg->getMsgId()));
- cmd->setRetryEnabled(false);
- cmd->setTimeRemaining(msg->getTimeout());
- cmd->setTrace(msg->steal_trace());
- sendMessageBusMessage(msg, std::move(cmd), address.to_mbus_route());
- }
+ _storage_api_rpc_service->send_rpc_v1_request(msg);
break;
}
- case api::StorageMessageAddress::Protocol::DOCUMENT:
+ case api::StorageMessageAddress::Protocol::DOCUMENT:
{
MBUS_TRACE(msg->getTrace(), 7, "Communication manager: Converting storageapi message to documentapi");
@@ -682,47 +612,32 @@ CommunicationManager::sendMessageBusReply(
mbus::Reply::UP replyUP;
LOG(spam, "Sending message bus reply %s", reply->toString().c_str());
+ assert(context._docAPIMsg); // StorageProtocol no longer uses MessageBus carrier.
- // If this was originally documentapi, create a reply now and transfer the
- // state.
- if (context._docAPIMsg) {
- if (reply->getResult().getResult() == api::ReturnCode::WRONG_DISTRIBUTION) {
- replyUP = std::make_unique<documentapi::WrongDistributionReply>(reply->getResult().getMessage());
- replyUP->swapState(*context._docAPIMsg);
- replyUP->setTrace(reply->steal_trace());
- replyUP->addError(mbus::Error(documentapi::DocumentProtocol::ERROR_WRONG_DISTRIBUTION,
- reply->getResult().getMessage()));
- } else {
- replyUP = context._docAPIMsg->createReply();
- replyUP->swapState(*context._docAPIMsg);
- replyUP->setTrace(reply->steal_trace());
- replyUP->setMessage(std::move(context._docAPIMsg));
- _docApiConverter.transferReplyState(*reply, *replyUP);
- }
- } else if (context._storageProtocolMsg) {
- replyUP = std::make_unique<mbusprot::StorageReply>(reply);
- if (reply->getResult().getResult() != api::ReturnCode::OK) {
- replyUP->addError(mbus::Error(reply->getResult().getResult(), reply->getResult().getMessage()));
- }
-
- replyUP->swapState(*context._storageProtocolMsg);
+ // Create an MBus reply and transfer state to it.
+ if (reply->getResult().getResult() == api::ReturnCode::WRONG_DISTRIBUTION) {
+ replyUP = std::make_unique<documentapi::WrongDistributionReply>(reply->getResult().getMessage());
+ replyUP->swapState(*context._docAPIMsg);
+ replyUP->setTrace(reply->steal_trace());
+ replyUP->addError(mbus::Error(documentapi::DocumentProtocol::ERROR_WRONG_DISTRIBUTION,
+ reply->getResult().getMessage()));
+ } else {
+ replyUP = context._docAPIMsg->createReply();
+ replyUP->swapState(*context._docAPIMsg);
replyUP->setTrace(reply->steal_trace());
- replyUP->setMessage(std::move(context._storageProtocolMsg));
+ replyUP->setMessage(std::move(context._docAPIMsg));
+ _docApiConverter.transferReplyState(*reply, *replyUP);
}
- if (replyUP) {
- // Forward message only if it was successfully stored in storage.
- if (!replyUP->hasErrors()) {
- mbus::Message::UP messageUP = replyUP->getMessage();
+ if (!replyUP->hasErrors()) {
+ mbus::Message::UP messageUP = replyUP->getMessage();
- if (messageUP && messageUP->getRoute().hasHops()) {
- messageUP->setContext(mbus::Context(FORWARDED_MESSAGE));
- _sourceSession->send(std::move(messageUP));
- }
+ if (messageUP && messageUP->getRoute().hasHops()) {
+ messageUP->setContext(mbus::Context(FORWARDED_MESSAGE));
+ _sourceSession->send(std::move(messageUP));
}
-
- _messageBusSession->reply(std::move(replyUP));
}
+ _messageBusSession->reply(std::move(replyUP));
}
bool
@@ -795,8 +710,6 @@ void CommunicationManager::updateMessagebusProtocol(const std::shared_ptr<const
auto newDocumentProtocol = std::make_shared<documentapi::DocumentProtocol>(repo);
std::lock_guard<std::mutex> guard(_earlierGenerationsLock);
_earlierGenerations.push_back(std::make_pair(now, _mbus->getMessageBus().putProtocol(newDocumentProtocol)));
- auto newStorageProtocol = std::make_shared<mbusprot::StorageProtocol>(repo);
- _earlierGenerations.push_back(std::make_pair(now, _mbus->getMessageBus().putProtocol(newStorageProtocol)));
}
if (_message_codec_provider) {
_message_codec_provider->update_atomically(repo);
diff --git a/storage/src/vespa/storage/storageserver/communicationmanager.h b/storage/src/vespa/storage/storageserver/communicationmanager.h
index 31c6fa00f0e..6f953411cac 100644
--- a/storage/src/vespa/storage/storageserver/communicationmanager.h
+++ b/storage/src/vespa/storage/storageserver/communicationmanager.h
@@ -55,12 +55,10 @@ class RPCRequestWrapper;
class StorageTransportContext : public api::TransportContext {
public:
explicit StorageTransportContext(std::unique_ptr<documentapi::DocumentMessage> msg);
- explicit StorageTransportContext(std::unique_ptr<mbusprot::StorageCommand> msg);
explicit StorageTransportContext(std::unique_ptr<RPCRequestWrapper> request);
~StorageTransportContext() override;
std::unique_ptr<documentapi::DocumentMessage> _docAPIMsg;
- std::unique_ptr<mbusprot::StorageCommand> _storageProtocolMsg;
std::unique_ptr<RPCRequestWrapper> _request;
};
@@ -121,10 +119,8 @@ private:
std::atomic<bool> _closed;
DocumentApiConverter _docApiConverter;
framework::Thread::UP _thread;
- std::atomic<bool> _skip_thread;
void updateMetrics(const MetricLockGuard &) override;
- void enqueue_or_process(std::shared_ptr<api::StorageMessage> msg);
// Test needs access to configure() for live reconfig testing.
friend struct CommunicationManagerTest;
diff --git a/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.cpp b/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.cpp
index 78a9956c334..41dcafc055a 100644
--- a/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.cpp
+++ b/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.cpp
@@ -5,6 +5,7 @@
#include "rpc_envelope_proto.h"
#include "shared_rpc_resources.h"
#include "storage_api_rpc_service.h"
+#include <vespa/fnet/frt/require_capabilities.h>
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/target.h>
#include <vespa/slobrok/sbmirror.h>
@@ -37,8 +38,7 @@ StorageApiRpcService::StorageApiRpcService(MessageDispatcher& message_dispatcher
_message_codec_provider(message_codec_provider),
_params(params),
_target_resolver(std::make_unique<CachingRpcTargetResolver>(_rpc_resources.slobrok_mirror(), _rpc_resources.target_factory(),
- params.num_rpc_targets_per_node)),
- _direct_rpc_supported(true)
+ params.num_rpc_targets_per_node))
{
register_server_methods(rpc_resources);
}
@@ -55,6 +55,9 @@ StorageApiRpcService::Params::~Params() = default;
void StorageApiRpcService::register_server_methods(SharedRpcResources& rpc_resources) {
FRT_ReflectionBuilder rb(&rpc_resources.supervisor());
rb.DefineMethod(rpc_v1_method_name(), "bixbix", "bixbix", FRT_METHOD(StorageApiRpcService::RPC_rpc_v1_send), this);
+ rb.RequestAccessFilter(std::make_unique<FRT_RequireCapabilities>(vespalib::net::tls::CapabilitySet::of({
+ vespalib::net::tls::Capability::content_storage_api()
+ })));
rb.MethodDesc("V1 of StorageAPI direct RPC protocol");
rb.ParamDesc("header_encoding", "0=raw, 6=lz4");
rb.ParamDesc("header_decoded_size", "Uncompressed header blob size");
@@ -312,8 +315,8 @@ void StorageApiRpcService::handle_request_done_rpc_error(FRT_RPCRequest& req,
auto& cmd = *req_ctx._originator_cmd;
api::ReturnCode error;
if (req.GetErrorCode() == FRTE_RPC_NO_SUCH_METHOD) {
- mark_peer_without_direct_rpc_support(*cmd.getAddress());
- error = api::ReturnCode(api::ReturnCode::NOT_CONNECTED, "Direct Storage RPC protocol not supported");
+ error = api::ReturnCode(api::ReturnCode::NOT_CONNECTED, "Legacy MessageBus StorageAPI transport is no longer supported. "
+ "Old nodes must be upgraded to a newer Vespa version.");
} else {
error = map_frt_error_to_storage_api_error(req, req_ctx);
}
@@ -378,22 +381,6 @@ StorageApiRpcService::make_no_address_for_service_error(const api::StorageMessag
return api::ReturnCode(error_code, std::move(error_msg));
}
-void StorageApiRpcService::mark_peer_without_direct_rpc_support(const api::StorageMessageAddress& addr) {
- bool expected = true;
- if (_direct_rpc_supported.compare_exchange_strong(expected, false, std::memory_order_relaxed)) {
- LOG(info, "Node %s does not support direct Storage API RPC; falling back "
- "to legacy MessageBus protocol. Not logging this for any further nodes",
- addr.toString().c_str());
- }
-}
-
-bool StorageApiRpcService::target_supports_direct_rpc(
- [[maybe_unused]] const api::StorageMessageAddress& addr) const noexcept {
- // Stale reads isn't an issue here, since the worst case is just receiving
- // a few more "no such method" errors.
- return _direct_rpc_supported.load(std::memory_order_relaxed);
-}
-
bool
StorageApiRpcService::address_visible_in_slobrok_uncached(
const api::StorageMessageAddress& addr) const noexcept
diff --git a/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.h b/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.h
index 2526cf5434c..3166abba956 100644
--- a/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.h
+++ b/storage/src/vespa/storage/storageserver/rpc/storage_api_rpc_service.h
@@ -47,7 +47,6 @@ private:
MessageCodecProvider& _message_codec_provider;
const Params _params;
std::unique_ptr<CachingRpcTargetResolver> _target_resolver;
- std::atomic<bool> _direct_rpc_supported;
public:
StorageApiRpcService(MessageDispatcher& message_dispatcher,
SharedRpcResources& rpc_resources,
@@ -55,7 +54,6 @@ public:
const Params& params);
~StorageApiRpcService() override;
- [[nodiscard]] bool target_supports_direct_rpc(const api::StorageMessageAddress& addr) const noexcept;
// Bypasses resolver cache and returns whether local Slobrok mirror has at least 1 spec for the given address.
[[nodiscard]] bool address_visible_in_slobrok_uncached(const api::StorageMessageAddress& addr) const noexcept;
@@ -91,8 +89,6 @@ private:
api::ReturnCode map_frt_error_to_storage_api_error(FRT_RPCRequest& req, const RpcRequestContext& req_ctx);
api::ReturnCode make_no_address_for_service_error(const api::StorageMessageAddress& addr) const;
-
- void mark_peer_without_direct_rpc_support(const api::StorageMessageAddress& addr);
};
} // rpc
diff --git a/storage/src/vespa/storageapi/mbusprot/CMakeLists.txt b/storage/src/vespa/storageapi/mbusprot/CMakeLists.txt
index 43c1da32502..4999201fbeb 100644
--- a/storage/src/vespa/storageapi/mbusprot/CMakeLists.txt
+++ b/storage/src/vespa/storageapi/mbusprot/CMakeLists.txt
@@ -23,11 +23,6 @@ vespa_add_library(storageapi_mbusprot OBJECT
storagereply.cpp
protocolserialization.cpp
storageprotocol.cpp
- protocolserialization4_2.cpp
- protocolserialization5_0.cpp
- protocolserialization5_1.cpp
- protocolserialization5_2.cpp
- protocolserialization6_0.cpp
protocolserialization7.cpp
${storageapi_PROTOBUF_SRCS}
DEPENDS
diff --git a/storage/src/vespa/storageapi/mbusprot/legacyprotocolserialization.h b/storage/src/vespa/storageapi/mbusprot/legacyprotocolserialization.h
deleted file mode 100644
index f3c6a6f6856..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/legacyprotocolserialization.h
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#pragma once
-
-#include "protocolserialization.h"
-
-namespace storage::mbusprot {
-
-/*
- * Utility base class for pre-v7 (protobuf) serialization implementations.
- *
- * TODO remove on Vespa 8 alongside legacy serialization formats.
- */
-class LegacyProtocolSerialization : public ProtocolSerialization {
- const std::shared_ptr<const document::DocumentTypeRepo> _repo;
-public:
- explicit LegacyProtocolSerialization(const std::shared_ptr<const document::DocumentTypeRepo>& repo)
- : _repo(repo)
- {}
-
- const document::DocumentTypeRepo& getTypeRepo() const { return *_repo; }
- const std::shared_ptr<const document::DocumentTypeRepo> getTypeRepoSp() const { return _repo; }
-
- virtual document::Bucket getBucket(document::ByteBuffer& buf) const = 0;
- virtual void putBucket(const document::Bucket& bucket, vespalib::GrowableByteBuffer& buf) const = 0;
- virtual document::BucketSpace getBucketSpace(document::ByteBuffer& buf) const = 0;
- virtual void putBucketSpace(document::BucketSpace bucketSpace, vespalib::GrowableByteBuffer& buf) const = 0;
- virtual api::BucketInfo getBucketInfo(document::ByteBuffer& buf) const = 0;
- virtual void putBucketInfo(const api::BucketInfo& info, vespalib::GrowableByteBuffer& buf) const = 0;
-};
-
-} // storage::mbusprot
diff --git a/storage/src/vespa/storageapi/mbusprot/oldreturncodemapper.h b/storage/src/vespa/storageapi/mbusprot/oldreturncodemapper.h
deleted file mode 100644
index 40e09f23697..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/oldreturncodemapper.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-/**
- * \brief Maps return code values used between 4.2 and 5.0
- */
-#pragma once
-
-namespace storage {
-namespace mbusprot {
-
-int getOldErrorCode(api::ReturnCode::Result newErrorCode) {
- switch (newErrorCode) {
- case api::ReturnCode::OK: return 1;
- case api::ReturnCode::EXISTS: return 1001;
- case api::ReturnCode::NOT_READY: return 2000;
- case api::ReturnCode::WRONG_DISTRIBUTION: return 2001;
- case api::ReturnCode::REJECTED: return 2002;
- case api::ReturnCode::ABORTED: return 2003;
- case api::ReturnCode::BUCKET_NOT_FOUND: return 2004;
- case api::ReturnCode::BUCKET_DELETED: return 2004;
- case api::ReturnCode::TIMESTAMP_EXIST: return 2005;
- case api::ReturnCode::UNKNOWN_COMMAND: return 3000;
- case api::ReturnCode::NOT_IMPLEMENTED: return 3001;
- case api::ReturnCode::ILLEGAL_PARAMETERS: return 3002;
- case api::ReturnCode::IGNORED: return 3003;
- case api::ReturnCode::UNPARSEABLE: return 3004;
- case api::ReturnCode::NOT_CONNECTED: return 4000;
- case api::ReturnCode::TIMEOUT: return 4003;
- case api::ReturnCode::BUSY: return 4004;
- case api::ReturnCode::NO_SPACE: return 5000;
- case api::ReturnCode::DISK_FAILURE: return 5001;
- case api::ReturnCode::IO_FAILURE: return 5003;
- case api::ReturnCode::INTERNAL_FAILURE: return 6000;
- default: return 6001;
- }
-}
-
-api::ReturnCode::Result getNewErrorCode(int oldErrorCode) {
- switch (oldErrorCode) {
- case 1: return api::ReturnCode::OK;
- case 1000: return api::ReturnCode::OK; // NOT_FOUND
- case 1001: return api::ReturnCode::EXISTS;
- case 2000: return api::ReturnCode::NOT_READY;
- case 2001: return api::ReturnCode::WRONG_DISTRIBUTION;
- case 2002: return api::ReturnCode::REJECTED;
- case 2003: return api::ReturnCode::ABORTED;
- case 2004: return api::ReturnCode::BUCKET_NOT_FOUND;
- case 2005: return api::ReturnCode::TIMESTAMP_EXIST;
- case 3000: return api::ReturnCode::UNKNOWN_COMMAND;
- case 3001: return api::ReturnCode::NOT_IMPLEMENTED;
- case 3002: return api::ReturnCode::ILLEGAL_PARAMETERS;
- case 3003: return api::ReturnCode::IGNORED;
- case 3004: return api::ReturnCode::UNPARSEABLE;
- case 4000: return api::ReturnCode::NOT_CONNECTED;
- case 4001: return api::ReturnCode::BUSY; // OVERLOAD;
- case 4002: return api::ReturnCode::NOT_READY; // REMOTE_DISABLED;
- case 4003: return api::ReturnCode::TIMEOUT;
- case 4004: return api::ReturnCode::BUSY;
- case 5000: return api::ReturnCode::NO_SPACE;
- case 5001: return api::ReturnCode::DISK_FAILURE;
- case 5003: return api::ReturnCode::IO_FAILURE;
- case 6000: return api::ReturnCode::INTERNAL_FAILURE;
- default: return api::ReturnCode::INTERNAL_FAILURE;
- }
-}
-
-} // mbusprot
-} // storage
-
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization.cpp
index 4614659c458..59ea60e6e0d 100644
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization.cpp
+++ b/storage/src/vespa/storageapi/mbusprot/protocolserialization.cpp
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include "protocolserialization4_2.h"
+#include "protocolserialization7.h"
#include "serializationhelper.h"
#include "storagecommand.h"
#include "storagereply.h"
#include <vespa/storageapi/message/bucketsplitting.h>
-#include <vespa/storageapi/message/visitor.h>
+#include <vespa/storageapi/message/persistence.h>
#include <vespa/storageapi/message/removelocation.h>
#include <vespa/storageapi/message/stat.h>
+#include <vespa/storageapi/message/visitor.h>
#include <vespa/vespalib/util/exceptions.h>
-
#include <sstream>
#include <vespa/log/log.h>
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.cpp
deleted file mode 100644
index 1bea0ea74c9..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.cpp
+++ /dev/null
@@ -1,553 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "protocolserialization4_2.h"
-#include "oldreturncodemapper.h"
-#include "serializationhelper.h"
-#include "storagecommand.h"
-#include "storagereply.h"
-
-#include <vespa/storageapi/message/bucketsplitting.h>
-#include <vespa/storageapi/message/visitor.h>
-#include <vespa/storageapi/message/removelocation.h>
-#include <vespa/vespalib/util/exceptions.h>
-#include <vespa/document/fieldset/fieldsets.h>
-
-#include <vespa/log/log.h>
-LOG_SETUP(".storage.api.mbusprot.serialization.4_2");
-
-using document::BucketSpace;
-using document::AllFields;
-
-namespace storage::mbusprot {
-
-ProtocolSerialization4_2::ProtocolSerialization4_2(
- const std::shared_ptr<const document::DocumentTypeRepo>& repo)
- : LegacyProtocolSerialization(repo)
-{
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::GetCommand& msg) const
-{
- buf.putString(msg.getDocumentId().toString());
- putBucket(msg.getBucket(), buf);
- buf.putLong(msg.getBeforeTimestamp());
- buf.putBoolean(false);
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeGetCommand(BBuf& buf) const
-{
- document::DocumentId did(SH::getString(buf));
- document::Bucket bucket = getBucket(buf);
- api::Timestamp beforeTimestamp(SH::getLong(buf));
- bool headerOnly(SH::getBoolean(buf)); // Ignored header only flag
- (void) headerOnly;
- auto msg = std::make_unique<api::GetCommand>(bucket, did, AllFields::NAME, beforeTimestamp);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::RemoveCommand& msg) const
-{
- buf.putString(msg.getDocumentId().toString());
- putBucket(msg.getBucket(), buf);
- buf.putLong(msg.getTimestamp());
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeRemoveCommand(BBuf& buf) const
-{
- document::DocumentId did(SH::getString(buf));
- document::Bucket bucket = getBucket(buf);
- api::Timestamp timestamp(SH::getLong(buf));
- auto msg = std::make_unique<api::RemoveCommand>(bucket, did, timestamp);
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::RevertCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- buf.putInt(msg.getRevertTokens().size());
- for (uint32_t i=0, n=msg.getRevertTokens().size(); i<n; ++i) {
- buf.putLong(msg.getRevertTokens()[i]);
- }
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeRevertCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- std::vector<api::Timestamp> tokens(SH::getInt(buf));
- for (uint32_t i=0, n=tokens.size(); i<n; ++i) {
- tokens[i] = SH::getLong(buf);
- }
- auto msg = std::make_unique<api::RevertCommand>(bucket, tokens);
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::CreateBucketCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeCreateBucketCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- auto msg = std::make_unique<api::CreateBucketCommand>(bucket);
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::MergeBucketCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- const std::vector<api::MergeBucketCommand::Node>& nodes(msg.getNodes());
- buf.putShort(nodes.size());
- for (uint32_t i=0; i<nodes.size(); ++i) {
- buf.putShort(nodes[i].index);
- buf.putBoolean(nodes[i].sourceOnly);
- }
- buf.putLong(msg.getMaxTimestamp());
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeMergeBucketCommand(BBuf& buf) const
-{
- typedef api::MergeBucketCommand::Node Node;
- document::Bucket bucket = getBucket(buf);
- uint16_t nodeCount = SH::getShort(buf);
- std::vector<Node> nodes;
- nodes.reserve(nodeCount);
- for (uint32_t i=0; i<nodeCount; ++i) {
- uint16_t index(SH::getShort(buf));
- bool sourceOnly = SH::getBoolean(buf);
- nodes.push_back(Node(index, sourceOnly));
- }
- api::Timestamp timestamp(SH::getLong(buf));
- auto msg = std::make_unique<api::MergeBucketCommand>(bucket, nodes, timestamp);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::GetBucketDiffCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- const std::vector<api::MergeBucketCommand::Node>& nodes(msg.getNodes());
- buf.putShort(nodes.size());
- for (uint32_t i=0; i<nodes.size(); ++i) {
- buf.putShort(nodes[i].index);
- buf.putBoolean(nodes[i].sourceOnly);
- }
- buf.putLong(msg.getMaxTimestamp());
- const std::vector<api::GetBucketDiffCommand::Entry>& entries(msg.getDiff());
- buf.putInt(entries.size());
- for (uint32_t i=0; i<entries.size(); ++i) {
- onEncodeDiffEntry(buf, entries[i]);
- }
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeGetBucketDiffCommand(BBuf& buf) const
-{
- typedef api::MergeBucketCommand::Node Node;
- document::Bucket bucket = getBucket(buf);
- uint16_t nodeCount = SH::getShort(buf);
- std::vector<Node> nodes;
- nodes.reserve(nodeCount);
- for (uint32_t i=0; i<nodeCount; ++i) {
- uint16_t index(SH::getShort(buf));
- bool sourceOnly = SH::getBoolean(buf);
- nodes.push_back(Node(index, sourceOnly));
- }
- api::Timestamp timestamp = SH::getLong(buf);
- auto msg = std::make_unique<api::GetBucketDiffCommand>(bucket, nodes, timestamp);
- std::vector<api::GetBucketDiffCommand::Entry>& entries(msg->getDiff());
- uint32_t entryCount = SH::getInt(buf);
- if (entryCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(entryCount);
- }
- entries.resize(entryCount);
- for (uint32_t i=0; i<entries.size(); ++i) {
- onDecodeDiffEntry(buf, entries[i]);
- }
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::ApplyBucketDiffCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- const std::vector<api::MergeBucketCommand::Node>& nodes(msg.getNodes());
- buf.putShort(nodes.size());
- for (uint32_t i=0; i<nodes.size(); ++i) {
- buf.putShort(nodes[i].index);
- buf.putBoolean(nodes[i].sourceOnly);
- }
- buf.putInt(0x400000);
- const std::vector<api::ApplyBucketDiffCommand::Entry>& entries(msg.getDiff());
- buf.putInt(entries.size());
- for (uint32_t i=0; i<entries.size(); ++i) {
- onEncodeDiffEntry(buf, entries[i]._entry);
- buf.putString(entries[i]._docName);
- buf.putInt(entries[i]._headerBlob.size());
- buf.putBytes(&entries[i]._headerBlob[0], entries[i]._headerBlob.size());
- buf.putInt(entries[i]._bodyBlob.size());
- buf.putBytes(&entries[i]._bodyBlob[0], entries[i]._bodyBlob.size());
- }
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeApplyBucketDiffCommand(BBuf& buf) const
-{
- typedef api::MergeBucketCommand::Node Node;
- document::Bucket bucket = getBucket(buf);
- uint16_t nodeCount = SH::getShort(buf);
- std::vector<Node> nodes;
- nodes.reserve(nodeCount);
- for (uint32_t i=0; i<nodeCount; ++i) {
- uint16_t index(SH::getShort(buf));
- bool sourceOnly = SH::getBoolean(buf);
- nodes.push_back(Node(index, sourceOnly));
- }
- (void) SH::getInt(buf); // Unused field
- auto msg = std::make_unique<api::ApplyBucketDiffCommand>(bucket, nodes);
- std::vector<api::ApplyBucketDiffCommand::Entry>& entries(msg->getDiff());
- uint32_t entryCount = SH::getInt(buf);
- if (entryCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(entryCount);
- }
- entries.resize(entryCount);
- for (uint32_t i=0; i<entries.size(); ++i) {
- onDecodeDiffEntry(buf, entries[i]._entry);
- entries[i]._docName = SH::getString(buf);
- uint32_t headerSize = SH::getInt(buf);
- if (headerSize > buf.getRemaining()) {
- buf.incPos(headerSize);
- }
- entries[i]._headerBlob.resize(headerSize);
- buf.getBytes(&entries[i]._headerBlob[0], entries[i]._headerBlob.size());
- uint32_t bodySize = SH::getInt(buf);
- if (bodySize > buf.getRemaining()) {
- buf.incPos(bodySize);
- }
- entries[i]._bodyBlob.resize(bodySize);
- buf.getBytes(&entries[i]._bodyBlob[0], entries[i]._bodyBlob.size());
- }
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::RequestBucketInfoReply& msg) const
-{
- buf.putInt(msg.getBucketInfo().size());
- for (const auto & entry : msg.getBucketInfo()) {
- buf.putLong(entry._bucketId.getRawId());
- putBucketInfo(entry._info, buf);
- }
- onEncodeReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeRequestBucketInfoReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::RequestBucketInfoReply>(static_cast<const api::RequestBucketInfoCommand&>(cmd));
- api::RequestBucketInfoReply::EntryVector & entries(msg->getBucketInfo());
- uint32_t entryCount = SH::getInt(buf);
- if (entryCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(entryCount);
- }
- entries.resize(entryCount);
- for (auto & entry : entries) {
- entry._bucketId = document::BucketId(SH::getLong(buf));
- entry._info = getBucketInfo(buf);
- }
- onDecodeReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::NotifyBucketChangeCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- putBucketInfo(msg.getBucketInfo(), buf);
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeNotifyBucketChangeCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- api::BucketInfo info(getBucketInfo(buf));
- auto msg = std::make_unique<api::NotifyBucketChangeCommand>(bucket, info);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::NotifyBucketChangeReply& msg) const
-{
- onEncodeReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeNotifyBucketChangeReply(const SCmd& cmd,BBuf& buf) const
-{
- auto msg = std::make_unique<api::NotifyBucketChangeReply>(static_cast<const api::NotifyBucketChangeCommand&>(cmd));
- onDecodeReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::SplitBucketCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- buf.putByte(msg.getMinSplitBits());
- buf.putByte(msg.getMaxSplitBits());
- buf.putInt(msg.getMinByteSize());
- buf.putInt(msg.getMinDocCount());
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeSplitBucketCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- auto msg = std::make_unique<api::SplitBucketCommand>(bucket);
- msg->setMinSplitBits(SH::getByte(buf));
- msg->setMaxSplitBits(SH::getByte(buf));
- msg->setMinByteSize(SH::getInt(buf));
- msg->setMinDocCount(SH::getInt(buf));
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf&, const api::SetBucketStateCommand&) const
-{
- throw vespalib::IllegalStateException("Unsupported serialization", VESPA_STRLOC);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeSetBucketStateCommand(BBuf&) const
-{
- throw vespalib::IllegalStateException("Unsupported deserialization", VESPA_STRLOC);
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf&, const api::SetBucketStateReply&) const
-{
- throw vespalib::IllegalStateException("Unsupported serialization", VESPA_STRLOC);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeSetBucketStateReply(const SCmd&, BBuf&) const
-{
- throw vespalib::IllegalStateException("Unsupported deserialization", VESPA_STRLOC);
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::CreateVisitorCommand& msg) const
-{
- putBucketSpace(msg.getBucketSpace(), buf);
- buf.putString(msg.getLibraryName());
- buf.putString(msg.getInstanceId());
- buf.putString(msg.getDocumentSelection());
- buf.putInt(msg.getVisitorCmdId());
- buf.putString(msg.getControlDestination());
- buf.putString(msg.getDataDestination());
- buf.putInt(msg.getMaximumPendingReplyCount());
- buf.putLong(msg.getFromTime());
- buf.putLong(msg.getToTime());
-
- buf.putInt(msg.getBuckets().size());
- for (uint32_t i = 0; i < msg.getBuckets().size(); i++) {
- buf.putLong(msg.getBuckets()[i].getRawId());
- }
-
- buf.putBoolean(msg.visitRemoves());
- buf.putBoolean(false);
- buf.putBoolean(msg.visitInconsistentBuckets());
- buf.putInt(vespalib::count_ms(msg.getQueueTimeout()));
- msg.getParameters().serialize(buf);
-
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeCreateVisitorCommand(BBuf& buf) const
-{
- BucketSpace bucketSpace = getBucketSpace(buf);
- vespalib::stringref libraryName = SH::getString(buf);
- vespalib::stringref instanceId = SH::getString(buf);
- vespalib::stringref selection = SH::getString(buf);
- auto msg = std::make_unique<api::CreateVisitorCommand>(bucketSpace, libraryName, instanceId, selection);
- msg->setVisitorCmdId(SH::getInt(buf));
- msg->setControlDestination(SH::getString(buf));
- msg->setDataDestination(SH::getString(buf));
- msg->setMaximumPendingReplyCount(SH::getInt(buf));
-
- msg->setFromTime(SH::getLong(buf));
- msg->setToTime(SH::getLong(buf));
- uint32_t count = SH::getInt(buf);
-
- if (count > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(count);
- }
-
- for (uint32_t i = 0; i < count; i++) {
- msg->getBuckets().push_back(document::BucketId(SH::getLong(buf)));
- }
-
- if (SH::getBoolean(buf)) {
- msg->setVisitRemoves();
- }
- if (SH::getBoolean(buf)) {
- msg->setFieldSet(AllFields::NAME);
- }
- if (SH::getBoolean(buf)) {
- msg->setVisitInconsistentBuckets();
- }
- msg->setQueueTimeout(std::chrono::milliseconds(SH::getInt(buf)));
- msg->getParameters().deserialize(buf);
-
- onDecodeCommand(buf, *msg);
- msg->setVisitorDispatcherVersion(42);
- return msg;
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::DestroyVisitorCommand& msg) const
-{
- buf.putString(msg.getInstanceId());
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeDestroyVisitorCommand(BBuf& buf) const
-{
- vespalib::stringref instanceId = SH::getString(buf);
- auto msg = std::make_unique<api::DestroyVisitorCommand>(instanceId);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::DestroyVisitorReply& msg) const
-{
- onEncodeReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeDestroyVisitorReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::DestroyVisitorReply>(static_cast<const api::DestroyVisitorCommand&>(cmd));
- onDecodeReply(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::RemoveLocationCommand& msg) const
-{
- buf.putString(msg.getDocumentSelection());
- putBucket(msg.getBucket(), buf);
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeRemoveLocationCommand(BBuf& buf) const
-{
- vespalib::stringref documentSelection = SH::getString(buf);
- document::Bucket bucket = getBucket(buf);
-
- auto msg = std::make_unique<api::RemoveLocationCommand>(documentSelection, bucket);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::RemoveLocationReply& msg) const
-{
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeRemoveLocationReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::RemoveLocationReply>(static_cast<const api::RemoveLocationCommand&>(cmd));
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf&, const api::StatBucketCommand&) const {
- throw vespalib::IllegalStateException("StatBucketCommand not expected for legacy protocol version", VESPA_STRLOC);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization4_2::onDecodeStatBucketCommand(BBuf&) const {
- throw vespalib::IllegalStateException("StatBucketCommand not expected for legacy protocol version", VESPA_STRLOC);
-}
-
-void ProtocolSerialization4_2::onEncode(GBBuf&, const api::StatBucketReply&) const {
- throw vespalib::IllegalStateException("StatBucketReply not expected for legacy protocol version", VESPA_STRLOC);
-}
-
-api::StorageReply::UP
-ProtocolSerialization4_2::onDecodeStatBucketReply(const SCmd&, BBuf&) const {
- throw vespalib::IllegalStateException("StatBucketReply not expected for legacy protocol version", VESPA_STRLOC);
-}
-
-// Utility functions for serialization
-
-void
-ProtocolSerialization4_2::onEncodeBucketInfoCommand(GBBuf& buf, const api::BucketInfoCommand& msg) const
-{
- onEncodeCommand(buf, msg);
-}
-
-void
-ProtocolSerialization4_2::onDecodeBucketInfoCommand(BBuf& buf, api::BucketInfoCommand& msg) const
-{
- onDecodeCommand(buf, msg);
-}
-
-void
-ProtocolSerialization4_2::onEncode(GBBuf& buf, const api::ReturnCode& rc) const
-{
- // Convert error code to codes used in 4.2
- buf.putInt(getOldErrorCode(rc.getResult()));
- buf.putString(rc.getMessage());
-}
-
-void
-ProtocolSerialization4_2::onEncodeDiffEntry(GBBuf& buf, const api::GetBucketDiffCommand::Entry& entry) const
-{
- buf.putLong(entry._timestamp);
- SH::putGlobalId(entry._gid, buf);
- buf.putInt(entry._headerSize);
- buf.putInt(entry._bodySize);
- buf.putShort(entry._flags);
- buf.putShort(entry._hasMask);
-}
-
-void
-ProtocolSerialization4_2::onDecodeDiffEntry(BBuf& buf, api::GetBucketDiffCommand::Entry& entry) const
-{
- entry._timestamp = SH::getLong(buf);
- entry._gid = SH::getGlobalId(buf);
- entry._headerSize = SH::getInt(buf);
- entry._bodySize = SH::getInt(buf);
- entry._flags = SH::getShort(buf);
- entry._hasMask = SH::getShort(buf);
-}
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.h b/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.h
deleted file mode 100644
index b8a20e9e401..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization4_2.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#pragma once
-
-#include "legacyprotocolserialization.h"
-
-namespace storage::mbusprot {
-
-class ProtocolSerialization4_2 : public LegacyProtocolSerialization {
-public:
- explicit ProtocolSerialization4_2(const std::shared_ptr<const document::DocumentTypeRepo>&);
-
-protected:
- void onEncode(GBBuf&, const api::GetCommand&) const override;
- void onEncode(GBBuf&, const api::RemoveCommand&) const override;
- void onEncode(GBBuf&, const api::RevertCommand&) const override;
- void onEncode(GBBuf&, const api::CreateBucketCommand&) const override;
- void onEncode(GBBuf&, const api::MergeBucketCommand&) const override;
- void onEncode(GBBuf&, const api::GetBucketDiffCommand&) const override;
- void onEncode(GBBuf&, const api::ApplyBucketDiffCommand&) const override;
- void onEncode(GBBuf&, const api::RequestBucketInfoReply&) const override;
- void onEncode(GBBuf&, const api::NotifyBucketChangeCommand&) const override;
- void onEncode(GBBuf&, const api::NotifyBucketChangeReply&) const override;
- void onEncode(GBBuf&, const api::SplitBucketCommand&) const override;
- void onEncode(GBBuf&, const api::CreateVisitorCommand&) const override;
- void onEncode(GBBuf&, const api::DestroyVisitorCommand&) const override;
- void onEncode(GBBuf&, const api::DestroyVisitorReply&) const override;
- void onEncode(GBBuf&, const api::RemoveLocationCommand&) const override;
- void onEncode(GBBuf&, const api::RemoveLocationReply&) const override;
- void onEncode(GBBuf&, const api::StatBucketCommand&) const override;
- void onEncode(GBBuf&, const api::StatBucketReply&) const override;
-
- // Not supported on 4.2, but implemented here for simplicity.
- void onEncode(GBBuf&, const api::SetBucketStateCommand&) const override;
- void onEncode(GBBuf&, const api::SetBucketStateReply&) const override;
-
- virtual void onEncodeBucketInfoCommand(GBBuf&, const api::BucketInfoCommand&) const;
- virtual void onEncodeBucketInfoReply(GBBuf&, const api::BucketInfoReply&) const = 0;
- virtual void onEncodeCommand(GBBuf&, const api::StorageCommand&) const = 0;
- virtual void onEncodeReply(GBBuf&, const api::StorageReply&) const = 0;
-
- virtual void onEncodeDiffEntry(GBBuf&, const api::GetBucketDiffCommand::Entry&) const;
- virtual void onEncode(GBBuf&, const api::ReturnCode&) const;
- SCmd::UP onDecodeGetCommand(BBuf&) const override;
- SCmd::UP onDecodeRemoveCommand(BBuf&) const override;
- SCmd::UP onDecodeRevertCommand(BBuf&) const override;
- SCmd::UP onDecodeCreateBucketCommand(BBuf&) const override;
- SCmd::UP onDecodeMergeBucketCommand(BBuf&) const override;
- SCmd::UP onDecodeGetBucketDiffCommand(BBuf&) const override;
- SCmd::UP onDecodeApplyBucketDiffCommand(BBuf&) const override;
- SRep::UP onDecodeRequestBucketInfoReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeNotifyBucketChangeCommand(BBuf&) const override;
- SRep::UP onDecodeNotifyBucketChangeReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeSplitBucketCommand(BBuf&) const override;
- SCmd::UP onDecodeSetBucketStateCommand(BBuf&) const override;
- SRep::UP onDecodeSetBucketStateReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeCreateVisitorCommand(BBuf&) const override;
- SCmd::UP onDecodeDestroyVisitorCommand(BBuf&) const override;
- SRep::UP onDecodeDestroyVisitorReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeRemoveLocationCommand(BBuf&) const override;
- SRep::UP onDecodeRemoveLocationReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeStatBucketCommand(BBuf&) const override;
- SRep::UP onDecodeStatBucketReply(const SCmd&, BBuf&) const override;
-
- virtual void onDecodeBucketInfoCommand(BBuf&, api::BucketInfoCommand&) const;
- virtual void onDecodeBucketInfoReply(BBuf&, api::BucketInfoReply&) const = 0;
- virtual void onDecodeCommand(BBuf& buf, api::StorageCommand& msg) const = 0;
- virtual void onDecodeReply(BBuf&, api::StorageReply&) const = 0;
-
- virtual void onDecodeDiffEntry(BBuf&, api::GetBucketDiffCommand::Entry&) const;
-};
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.cpp
deleted file mode 100644
index e49eb8842ff..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.cpp
+++ /dev/null
@@ -1,622 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "protocolserialization5_0.h"
-#include "serializationhelper.h"
-#include "storagecommand.h"
-#include "storagereply.h"
-#include <vespa/storageapi/message/bucketsplitting.h>
-#include <vespa/storageapi/message/visitor.h>
-#include <vespa/vdslib/state/clusterstate.h>
-#include <vespa/document/update/documentupdate.h>
-#include <vespa/document/bucket/fixed_bucket_spaces.h>
-#include <sstream>
-
-using document::BucketSpace;
-using document::FixedBucketSpaces;
-
-namespace storage::mbusprot {
-
-document::Bucket
-ProtocolSerialization5_0::getBucket(document::ByteBuffer& buf) const
-{
- document::BucketId bucketId(SH::getLong(buf));
- return document::Bucket(FixedBucketSpaces::default_space(), bucketId);
-}
-
-void
-ProtocolSerialization5_0::putBucket(const document::Bucket& bucket, vespalib::GrowableByteBuffer& buf) const
-{
- buf.putLong(bucket.getBucketId().getRawId());
- if (bucket.getBucketSpace() != FixedBucketSpaces::default_space()) {
- std::ostringstream ost;
- ost << "Bucket with bucket space " << bucket.getBucketSpace() << " cannot be serialized on old storageapi protocol.";
- throw vespalib::IllegalArgumentException(ost.str(), VESPA_STRLOC);
- }
-}
-
-document::BucketSpace
-ProtocolSerialization5_0::getBucketSpace(document::ByteBuffer&) const
-{
- return FixedBucketSpaces::default_space();
-}
-
-void
-ProtocolSerialization5_0::putBucketSpace(document::BucketSpace bucketSpace, vespalib::GrowableByteBuffer&) const
-{
- if (bucketSpace != FixedBucketSpaces::default_space()) {
- std::ostringstream ost;
- ost << "Bucket space " << bucketSpace << " cannot be serialized on old storageapi protocol.";
- throw vespalib::IllegalArgumentException(ost.str(), VESPA_STRLOC);
- }
-}
-
-api::BucketInfo
-ProtocolSerialization5_0::getBucketInfo(document::ByteBuffer& buf) const
-{
- uint32_t crc(SH::getInt(buf));
- uint32_t doccount(SH::getInt(buf));
- uint32_t docsize(SH::getInt(buf));
- uint32_t metacount(SH::getInt(buf));
- uint32_t usedsize(SH::getInt(buf));
- return api::BucketInfo(crc, doccount, docsize, metacount, usedsize);
-}
-
-void
-ProtocolSerialization5_0::putBucketInfo(const api::BucketInfo& info, vespalib::GrowableByteBuffer& buf) const
-{
- buf.putInt(info.getChecksum());
- buf.putInt(info.getDocumentCount());
- buf.putInt(info.getTotalDocumentSize());
- buf.putInt(info.getMetaCount());
- buf.putInt(info.getUsedFileSize());
-}
-
-void
-ProtocolSerialization5_0::onEncodeReply(GBBuf& buf, const api::StorageReply& msg) const
-{
- SH::putReturnCode(msg.getResult(), buf);
- buf.putLong(msg.getMsgId());
- buf.putByte(msg.getPriority());
-}
-
-void
-ProtocolSerialization5_0::onDecodeReply(BBuf& buf, api::StorageReply& msg) const
-{
- msg.setResult(SH::getReturnCode(buf));
- msg.forceMsgId(SH::getLong(buf));
- msg.setPriority(SH::getByte(buf));
-}
-
-void
-ProtocolSerialization5_0::onEncodeCommand(GBBuf& buf, const api::StorageCommand& msg) const
-{
- buf.putLong(msg.getMsgId());
- buf.putByte(msg.getPriority());
- buf.putShort(msg.getSourceIndex());
- buf.putInt(0); // LoadType 'default'
-}
-
-void
-ProtocolSerialization5_0::onDecodeCommand(BBuf& buf, api::StorageCommand& msg) const
-{
- msg.forceMsgId(SH::getLong(buf));
- uint8_t priority = SH::getByte(buf);
- msg.setPriority(priority);
- msg.setSourceIndex(SH::getShort(buf));
- (void)SH::getInt(buf); // LoadType
-}
-
-
-ProtocolSerialization5_0::ProtocolSerialization5_0(const std::shared_ptr<const document::DocumentTypeRepo>& repo)
- : ProtocolSerialization4_2(repo)
-{
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::PutReply& msg) const
-{
- buf.putBoolean(msg.wasFound());
- onEncodeBucketInfoReply(buf, msg);
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::PutCommand& msg) const
-{
- SH::putDocument(msg.getDocument().get(), buf);
- putBucket(msg.getBucket(), buf);
- buf.putLong(msg.getTimestamp());
- buf.putLong(msg.getUpdateTimestamp());
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodePutCommand(BBuf& buf) const
-{
- document::Document::SP doc(SH::getDocument(buf, getTypeRepo()));
- document::Bucket bucket = getBucket(buf);
- api::Timestamp ts(SH::getLong(buf));
- auto msg = std::make_unique<api::PutCommand>(bucket, doc, ts);
- msg->setUpdateTimestamp(SH::getLong(buf));
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodePutReply(const SCmd& cmd, BBuf& buf) const
-{
- bool wasFound = SH::getBoolean(buf);
- auto msg = std::make_unique<api::PutReply>(static_cast<const api::PutCommand&>(cmd), wasFound);
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::UpdateReply& msg) const
-{
- buf.putLong(msg.getOldTimestamp());
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeUpdateReply(const SCmd& cmd, BBuf& buf) const
-{
- api::Timestamp oldTimestamp(SH::getLong(buf));
- auto msg = std::make_unique<api::UpdateReply>(static_cast<const api::UpdateCommand&>(cmd), oldTimestamp);
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::GetReply& msg) const
-{
- SH::putDocument(msg.getDocument().get(), buf);
- // Old protocol version doesn't understand tombstones. Make it appear as Not Found.
- buf.putLong(msg.is_tombstone() ? api::Timestamp(0) : msg.getLastModifiedTimestamp());
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeGetReply(const SCmd& cmd, BBuf& buf) const
-{
- try {
- document::Document::SP doc(SH::getDocument(buf, getTypeRepo()));
- api::Timestamp lastModified(SH::getLong(buf));
- auto msg = std::make_unique<api::GetReply>(static_cast<const api::GetCommand&>(cmd), doc,lastModified);
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
- } catch (std::exception& e) {
- auto msg = std::make_unique<api::GetReply>(static_cast<const api::GetCommand&>(cmd), document::Document::SP(),0);
- msg->setResult(api::ReturnCode(api::ReturnCode::UNPARSEABLE, e.what()));
- return msg;
- }
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::RemoveReply& msg) const
-{
- buf.putLong(msg.getOldTimestamp());
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeRemoveReply(const SCmd& cmd, BBuf& buf) const
-{
- api::Timestamp oldTimestamp(SH::getLong(buf));
- auto msg = std::make_unique<api::RemoveReply>(static_cast<const api::RemoveCommand&>(cmd), oldTimestamp);
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::UpdateCommand& msg) const
-{
- document::DocumentUpdate* update = msg.getUpdate().get();
- if (update) {
- vespalib::nbostream stream;
- update->serializeHEAD(stream);
- buf.putInt(stream.size());
- buf.putBytes(stream.peek(), stream.size());
- } else {
- buf.putInt(0);
- }
-
- putBucket(msg.getBucket(), buf);
- buf.putLong(msg.getTimestamp());
- buf.putLong(msg.getOldTimestamp());
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeUpdateCommand(BBuf& buf) const
-{
- document::DocumentUpdate::SP update;
-
- uint32_t size = SH::getInt(buf);
- if (size != 0) {
- update = document::DocumentUpdate::createHEAD(getTypeRepo(), vespalib::nbostream(buf.getBufferAtPos(), size));
- buf.incPos(size);
- }
-
- document::Bucket bucket = getBucket(buf);
- api::Timestamp timestamp(SH::getLong(buf));
- api::UpdateCommand::UP msg = std::make_unique<api::UpdateCommand>(bucket, update, timestamp);
- msg->setOldTimestamp(SH::getLong(buf));
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::RevertReply& msg) const
-{
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeRevertReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::RevertReply>(static_cast<const api::RevertCommand&>(cmd));
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::CreateBucketReply& msg) const
-{
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeCreateBucketReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::CreateBucketReply>(static_cast<const api::CreateBucketCommand&>(cmd));
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::DeleteBucketCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- onEncodeBucketInfoCommand(buf, msg);
- putBucketInfo(msg.getBucketInfo(), buf);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeDeleteBucketCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- auto msg = std::make_unique<api::DeleteBucketCommand>(bucket);
- onDecodeBucketInfoCommand(buf, *msg);
- if (buf.getRemaining() >= SH::BUCKET_INFO_SERIALIZED_SIZE) {
- msg->setBucketInfo(getBucketInfo(buf));
- }
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::DeleteBucketReply& msg) const
-{
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeDeleteBucketReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::DeleteBucketReply>(static_cast<const api::DeleteBucketCommand&>(cmd));
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::MergeBucketCommand& msg) const
-{
- ProtocolSerialization4_2::onEncode(buf, msg);
-
- buf.putInt(msg.getClusterStateVersion());
- const std::vector<uint16_t>& chain(msg.getChain());
- buf.putShort(chain.size());
- for (std::size_t i = 0; i < chain.size(); ++i) {
- buf.putShort(chain[i]);
- }
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeMergeBucketCommand(BBuf& buf) const
-{
- api::StorageCommand::UP cmd = ProtocolSerialization4_2::onDecodeMergeBucketCommand(buf);
- uint32_t clusterStateVersion = SH::getInt(buf);
- uint16_t chainSize = SH::getShort(buf);
- std::vector<uint16_t> chain;
- chain.reserve(chainSize);
- for (std::size_t i = 0; i < chainSize; ++i) {
- uint16_t index = SH::getShort(buf);
- chain.push_back(index);
- }
- api::MergeBucketCommand& mergeCmd = static_cast<api::MergeBucketCommand&>(*cmd);
- mergeCmd.setChain(chain);
- mergeCmd.setClusterStateVersion(clusterStateVersion);
- return cmd;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::MergeBucketReply& msg) const
-{
- onEncodeBucketReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeMergeBucketReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::MergeBucketReply>(static_cast<const api::MergeBucketCommand&>(cmd));
- onDecodeBucketReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::GetBucketDiffReply& msg) const
-{
- const std::vector<api::GetBucketDiffCommand::Entry>& entries(msg.getDiff());
- buf.putInt(entries.size());
- for (uint32_t i=0; i<entries.size(); ++i) {
- onEncodeDiffEntry(buf, entries[i]);
- }
- onEncodeBucketReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeGetBucketDiffReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::GetBucketDiffReply>(static_cast<const api::GetBucketDiffCommand&>(cmd));
- std::vector<api::GetBucketDiffCommand::Entry>& entries(msg->getDiff());
- uint32_t entryCount = SH::getInt(buf);
- if (entryCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(entryCount);
- }
- entries.resize(entryCount);
- for (uint32_t i=0; i<entries.size(); ++i) {
- onDecodeDiffEntry(buf, entries[i]);
- }
- onDecodeBucketReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::ApplyBucketDiffReply& msg) const
-{
- const std::vector<api::ApplyBucketDiffCommand::Entry>& entries(msg.getDiff());
- buf.putInt(entries.size());
- for (uint32_t i=0; i<entries.size(); ++i) {
- onEncodeDiffEntry(buf, entries[i]._entry);
- buf.putString(entries[i]._docName);
- buf.putInt(entries[i]._headerBlob.size());
- buf.putBytes(&entries[i]._headerBlob[0], entries[i]._headerBlob.size());
- buf.putInt(entries[i]._bodyBlob.size());
- buf.putBytes(&entries[i]._bodyBlob[0], entries[i]._bodyBlob.size());
- }
- onEncodeBucketInfoReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeApplyBucketDiffReply(const SCmd& cmd,
- BBuf& buf) const
-{
- auto msg = std::make_unique<api::ApplyBucketDiffReply>(static_cast<const api::ApplyBucketDiffCommand&>(cmd));
- std::vector<api::ApplyBucketDiffCommand::Entry>& entries(msg->getDiff());
- uint32_t entryCount = SH::getInt(buf);
- if (entryCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(entryCount);
- }
- entries.resize(entryCount);
- for (uint32_t i=0; i<entries.size(); ++i) {
- onDecodeDiffEntry(buf, entries[i]._entry);
- entries[i]._docName = SH::getString(buf);
- uint32_t headerSize = SH::getInt(buf);
- if (headerSize > buf.getRemaining()) {
- buf.incPos(headerSize);
- }
- entries[i]._headerBlob.resize(headerSize);
- buf.getBytes(&entries[i]._headerBlob[0], entries[i]._headerBlob.size());
- uint32_t bodySize = SH::getInt(buf);
- if (bodySize > buf.getRemaining()) {
- buf.incPos(bodySize);
- }
- entries[i]._bodyBlob.resize(bodySize);
- buf.getBytes(&entries[i]._bodyBlob[0], entries[i]._bodyBlob.size());
- }
- onDecodeBucketInfoReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::SplitBucketReply& msg) const
-{
- const std::vector<api::SplitBucketReply::Entry>& entries(msg.getSplitInfo());
- buf.putInt(entries.size());
- for (std::vector<api::SplitBucketReply::Entry>::const_iterator it
- = entries.begin(); it != entries.end(); ++it)
- {
- buf.putLong(it->first.getRawId());
- putBucketInfo(it->second, buf);
- }
- onEncodeBucketReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeSplitBucketReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::SplitBucketReply>(static_cast<const api::SplitBucketCommand&>(cmd));
- std::vector<api::SplitBucketReply::Entry>& entries(msg->getSplitInfo());
- uint32_t targetCount = SH::getInt(buf);
- if (targetCount > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(targetCount);
- }
- entries.resize(targetCount);
- for (std::vector<api::SplitBucketReply::Entry>::iterator it
- = entries.begin(); it != entries.end(); ++it)
- {
- it->first = document::BucketId(SH::getLong(buf));
- it->second = getBucketInfo(buf);
- }
- onDecodeBucketReply(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::JoinBucketsCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- buf.putInt(msg.getSourceBuckets().size());
- for (uint32_t i=0, n=msg.getSourceBuckets().size(); i<n; ++i) {
- buf.putLong(msg.getSourceBuckets()[i].getRawId());
- }
- buf.putByte(msg.getMinJoinBits());
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeJoinBucketsCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- auto msg = std::make_unique<api::JoinBucketsCommand>(bucket);
- uint32_t size = SH::getInt(buf);
- if (size > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(size);
- }
- std::vector<document::BucketId>& entries(msg->getSourceBuckets());
- for (uint32_t i=0; i<size; ++i) {
- entries.push_back(document::BucketId(SH::getLong(buf)));
- }
- msg->setMinJoinBits(SH::getByte(buf));
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::JoinBucketsReply& msg) const
-{
- putBucketInfo(msg.getBucketInfo(), buf);
- onEncodeBucketReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeJoinBucketsReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::JoinBucketsReply>(static_cast<const api::JoinBucketsCommand&>(cmd));
- msg->setBucketInfo(getBucketInfo(buf));
- onDecodeBucketReply(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_0::onEncodeBucketInfoReply(GBBuf& buf, const api::BucketInfoReply& msg) const
-{
- onEncodeBucketReply(buf, msg);
- putBucketInfo(msg.getBucketInfo(), buf);
-}
-
-void
-ProtocolSerialization5_0::onDecodeBucketInfoReply(BBuf& buf, api::BucketInfoReply& msg) const
-{
- onDecodeBucketReply(buf, msg);
- msg.setBucketInfo(getBucketInfo(buf));
-}
-
-void
-ProtocolSerialization5_0::onEncodeBucketReply(GBBuf& buf, const api::BucketReply& msg) const
-{
- onEncodeReply(buf, msg);
- buf.putLong(msg.hasBeenRemapped() ? msg.getBucketId().getRawId() : 0);
-}
-
-void
-ProtocolSerialization5_0::onDecodeBucketReply(BBuf& buf, api::BucketReply& msg) const
-{
- onDecodeReply(buf, msg);
- document::BucketId bucket(SH::getLong(buf));
- if (bucket.getRawId() != 0) {
- msg.remapBucketId(bucket);
- }
-}
-
-void
-ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::CreateVisitorReply& msg) const
-{
- onEncodeReply(buf, msg);
- buf.putInt(msg.getVisitorStatistics().getBucketsVisited());
- buf.putLong(msg.getVisitorStatistics().getDocumentsVisited());
- buf.putLong(msg.getVisitorStatistics().getBytesVisited());
- buf.putLong(msg.getVisitorStatistics().getDocumentsReturned());
- buf.putLong(msg.getVisitorStatistics().getBytesReturned());
- buf.putLong(0);
- buf.putLong(0);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_0::onDecodeCreateVisitorReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::CreateVisitorReply>(static_cast<const api::CreateVisitorCommand&>(cmd));
- onDecodeReply(buf, *msg);
-
- vdslib::VisitorStatistics vs;
- vs.setBucketsVisited(SH::getInt(buf));
- vs.setDocumentsVisited(SH::getLong(buf));
- vs.setBytesVisited(SH::getLong(buf));
- vs.setDocumentsReturned(SH::getLong(buf));
- vs.setBytesReturned(SH::getLong(buf));
- SH::getLong(buf);
- SH::getLong(buf);
- msg->setVisitorStatistics(vs);
-
- return msg;
-}
-
-void ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::RequestBucketInfoCommand& msg) const
-{
- const std::vector<document::BucketId>& buckets(msg.getBuckets());
- buf.putInt(buckets.size());
- for (uint32_t i=0; i<buckets.size(); ++i) {
- buf.putLong(buckets[i].getRawId());
- }
- putBucketSpace(msg.getBucketSpace(), buf);
- if (buckets.size() == 0) {
- buf.putShort(msg.getDistributor());
- buf.putString(msg.getSystemState().toString());
- buf.putString(msg.getDistributionHash());
- }
-
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeRequestBucketInfoCommand(BBuf& buf) const
-{
- std::vector<document::BucketId> buckets(SH::getInt(buf));
- for (uint32_t i=0; i<buckets.size(); ++i) {
- buckets[i] = document::BucketId(SH::getLong(buf));
- }
- api::RequestBucketInfoCommand::UP msg;
- BucketSpace bucketSpace = getBucketSpace(buf);
- if (buckets.size() != 0) {
- msg.reset(new api::RequestBucketInfoCommand(bucketSpace, buckets));
- } else {
- int distributor = SH::getShort(buf);
- lib::ClusterState state(SH::getString(buf));
- msg.reset(new api::RequestBucketInfoCommand(bucketSpace, distributor, state, SH::getString(buf)));
- }
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_0::onEncode(GBBuf& buf, const api::CreateVisitorCommand& cmd) const
-{
- ProtocolSerialization4_2::onEncode(buf, cmd);
-
- buf.putInt(0); // Unused
- buf.putInt(cmd.getMaxBucketsPerVisitor());
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_0::onDecodeCreateVisitorCommand(BBuf& buf) const
-{
- api::StorageCommand::UP cvc = ProtocolSerialization4_2::onDecodeCreateVisitorCommand(buf);
- SH::getInt(buf); // Unused
-
- static_cast<api::CreateVisitorCommand*>(cvc.get())->setMaxBucketsPerVisitor(SH::getInt(buf));
-
- static_cast<api::CreateVisitorCommand*>(cvc.get())->setVisitorDispatcherVersion(50);
- return cvc;
-}
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.h b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.h
deleted file mode 100644
index 8de2edab17f..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_0.h
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#pragma once
-
-#include "protocolserialization4_2.h"
-
-namespace storage::mbusprot {
-
-class ProtocolSerialization5_0 : public ProtocolSerialization4_2 {
-public:
- ProtocolSerialization5_0(const std::shared_ptr<const document::DocumentTypeRepo>&);
-
- document::Bucket getBucket(document::ByteBuffer& buf) const override;
- void putBucket(const document::Bucket& bucket, vespalib::GrowableByteBuffer& buf) const override;
- document::BucketSpace getBucketSpace(document::ByteBuffer& buf) const override;
- void putBucketSpace(document::BucketSpace bucketSpace, vespalib::GrowableByteBuffer& buf) const override;
- api::BucketInfo getBucketInfo(document::ByteBuffer& buf) const override;
- void putBucketInfo(const api::BucketInfo& info, vespalib::GrowableByteBuffer& buf) const override;
-
- void onEncode(GBBuf&, const api::PutCommand&) const override;
- void onEncode(GBBuf&, const api::PutReply&) const override;
- void onEncode(GBBuf&, const api::UpdateCommand&) const override;
- void onEncode(GBBuf&, const api::UpdateReply&) const override;
- void onEncode(GBBuf&, const api::GetReply&) const override;
- void onEncode(GBBuf&, const api::RemoveReply&) const override;
- void onEncode(GBBuf&, const api::RevertReply&) const override;
- void onEncode(GBBuf&, const api::CreateBucketReply&) const override;
- void onEncode(GBBuf&, const api::DeleteBucketCommand&) const override;
- void onEncode(GBBuf&, const api::DeleteBucketReply&) const override;
- void onEncode(GBBuf&, const api::MergeBucketCommand&) const override;
- void onEncode(GBBuf&, const api::MergeBucketReply&) const override;
- void onEncode(GBBuf&, const api::GetBucketDiffReply&) const override;
- void onEncode(GBBuf&, const api::ApplyBucketDiffReply&) const override;
- void onEncode(GBBuf&, const api::SplitBucketReply&) const override;
- void onEncode(GBBuf&, const api::JoinBucketsCommand&) const override;
- void onEncode(GBBuf&, const api::JoinBucketsReply&) const override;
- void onEncode(GBBuf&, const api::RequestBucketInfoCommand&) const override;
-
- void onEncodeBucketInfoReply(GBBuf&, const api::BucketInfoReply&) const override;
- virtual void onEncodeBucketReply(GBBuf&, const api::BucketReply&) const;
-
- void onEncode(GBBuf&, const api::CreateVisitorCommand& msg) const override;
- void onEncode(GBBuf&, const api::CreateVisitorReply& msg) const override;
- void onEncodeCommand(GBBuf&, const api::StorageCommand&) const override;
- void onEncodeReply(GBBuf&, const api::StorageReply&) const override;
-
- SCmd::UP onDecodePutCommand(BBuf&) const override;
- SRep::UP onDecodePutReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeUpdateCommand(BBuf&) const override;
- SRep::UP onDecodeUpdateReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeGetReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeRemoveReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeRevertReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeCreateBucketReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeDeleteBucketCommand(BBuf&) const override;
- SRep::UP onDecodeDeleteBucketReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeMergeBucketCommand(BBuf&) const override;
- SRep::UP onDecodeMergeBucketReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeGetBucketDiffReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeApplyBucketDiffReply(const SCmd&, BBuf&) const override;
- SRep::UP onDecodeSplitBucketReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeJoinBucketsCommand(BBuf& buf) const override;
- SRep::UP onDecodeJoinBucketsReply(const SCmd& cmd, BBuf& buf) const override;
- SCmd::UP onDecodeCreateVisitorCommand(BBuf&) const override;
- SCmd::UP onDecodeRequestBucketInfoCommand(BBuf& buf) const override;
-
- void onDecodeBucketInfoReply(BBuf&, api::BucketInfoReply&) const override;
- virtual void onDecodeBucketReply(BBuf&, api::BucketReply&) const;
- SRep::UP onDecodeCreateVisitorReply(const SCmd& cmd, BBuf& buf) const override;
- void onDecodeCommand(BBuf& buf, api::StorageCommand& msg) const override;
- void onDecodeReply(BBuf&, api::StorageReply&) const override;
-};
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.cpp
deleted file mode 100644
index 97ceceac33d..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "protocolserialization5_1.h"
-#include "serializationhelper.h"
-#include "storagecommand.h"
-#include "storagereply.h"
-#include <vespa/storageapi/message/bucketsplitting.h>
-#include <vespa/storageapi/message/visitor.h>
-
-using document::BucketSpace;
-
-namespace storage::mbusprot {
-
-api::BucketInfo
-ProtocolSerialization5_1::getBucketInfo(document::ByteBuffer& buf) const
-{
- uint64_t lastModified(SH::getLong(buf));
- uint32_t crc(SH::getInt(buf));
- uint32_t doccount(SH::getInt(buf));
- uint32_t docsize(SH::getInt(buf));
- uint32_t metacount(SH::getInt(buf));
- uint32_t usedsize(SH::getInt(buf));
- uint8_t flags(SH::getByte(buf));
- bool ready = (flags & BUCKET_READY) != 0;
- bool active = (flags & BUCKET_ACTIVE) != 0;
- return api::BucketInfo(crc, doccount, docsize,
- metacount, usedsize,
- ready, active, lastModified);
-}
-
-void
-ProtocolSerialization5_1::putBucketInfo(
- const api::BucketInfo& info, vespalib::GrowableByteBuffer& buf) const
-{
- buf.putLong(info.getLastModified());
- buf.putInt(info.getChecksum());
- buf.putInt(info.getDocumentCount());
- buf.putInt(info.getTotalDocumentSize());
- buf.putInt(info.getMetaCount());
- buf.putInt(info.getUsedFileSize());
- uint8_t flags = (info.isReady() ? BUCKET_READY : 0) |
- (info.isActive() ? BUCKET_ACTIVE : 0);
- buf.putByte(flags);
-}
-
-ProtocolSerialization5_1::ProtocolSerialization5_1(
- const std::shared_ptr<const document::DocumentTypeRepo>& repo)
- : ProtocolSerialization5_0(repo)
-{
-}
-
-void ProtocolSerialization5_1::onEncode(GBBuf& buf, const api::SetBucketStateCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- buf.putByte(static_cast<uint8_t>(msg.getState()));
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_1::onDecodeSetBucketStateCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- api::SetBucketStateCommand::BUCKET_STATE state(
- static_cast<api::SetBucketStateCommand::BUCKET_STATE>(SH::getByte(buf)));
- auto msg = std::make_unique<api::SetBucketStateCommand>(bucket, state);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_1::onEncode(GBBuf& buf, const api::SetBucketStateReply& msg) const
-{
- onEncodeBucketReply(buf, msg);
-}
-
-api::StorageReply::UP
-ProtocolSerialization5_1::onDecodeSetBucketStateReply(const SCmd& cmd, BBuf& buf) const
-{
- auto msg = std::make_unique<api::SetBucketStateReply>(static_cast<const api::SetBucketStateCommand&>(cmd));
- onDecodeBucketReply(buf, *msg);
- return msg;
-}
-
-void ProtocolSerialization5_1::onEncode(GBBuf& buf, const api::GetCommand& msg) const
-{
- buf.putString(msg.getDocumentId().toString());
- putBucket(msg.getBucket(), buf);
- buf.putLong(msg.getBeforeTimestamp());
- buf.putString(msg.getFieldSet());
- onEncodeCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_1::onDecodeGetCommand(BBuf& buf) const
-{
- document::DocumentId did(SH::getString(buf));
- document::Bucket bucket = getBucket(buf);
- api::Timestamp beforeTimestamp(SH::getLong(buf));
- std::string fieldSet(SH::getString(buf));
- auto msg = std::make_unique<api::GetCommand>(bucket, did, fieldSet, beforeTimestamp);
- onDecodeCommand(buf, *msg);
- return msg;
-}
-
-void
-ProtocolSerialization5_1::onEncode(GBBuf& buf, const api::CreateVisitorCommand& msg) const
-{
- putBucketSpace(msg.getBucketSpace(), buf);
- buf.putString(msg.getLibraryName());
- buf.putString(msg.getInstanceId());
- buf.putString(msg.getDocumentSelection());
- buf.putInt(msg.getVisitorCmdId());
- buf.putString(msg.getControlDestination());
- buf.putString(msg.getDataDestination());
- buf.putInt(msg.getMaximumPendingReplyCount());
- buf.putLong(msg.getFromTime());
- buf.putLong(msg.getToTime());
-
- buf.putInt(msg.getBuckets().size());
- for (uint32_t i = 0; i < msg.getBuckets().size(); i++) {
- buf.putLong(msg.getBuckets()[i].getRawId());
- }
-
- buf.putBoolean(msg.visitRemoves());
- buf.putString(msg.getFieldSet());
- buf.putBoolean(msg.visitInconsistentBuckets());
- buf.putInt(vespalib::count_ms(msg.getQueueTimeout()));
- msg.getParameters().serialize(buf);
-
- onEncodeCommand(buf, msg);
-
- buf.putInt(0); // Unused
- buf.putInt(msg.getMaxBucketsPerVisitor());
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_1::onDecodeCreateVisitorCommand(BBuf& buf) const
-{
- BucketSpace bucketSpace = getBucketSpace(buf);
- vespalib::stringref libraryName = SH::getString(buf);
- vespalib::stringref instanceId = SH::getString(buf);
- vespalib::stringref selection = SH::getString(buf);
- auto msg = std::make_unique<api::CreateVisitorCommand>(bucketSpace, libraryName, instanceId, selection);
- msg->setVisitorCmdId(SH::getInt(buf));
- msg->setControlDestination(SH::getString(buf));
- msg->setDataDestination(SH::getString(buf));
- msg->setMaximumPendingReplyCount(SH::getInt(buf));
-
- msg->setFromTime(SH::getLong(buf));
- msg->setToTime(SH::getLong(buf));
- uint32_t count = SH::getInt(buf);
-
- if (count > buf.getRemaining()) {
- // Trigger out of bounds exception rather than out of memory error
- buf.incPos(count);
- }
-
- for (uint32_t i = 0; i < count; i++) {
- msg->getBuckets().push_back(document::BucketId(SH::getLong(buf)));
- }
-
- if (SH::getBoolean(buf)) {
- msg->setVisitRemoves();
- }
-
- msg->setFieldSet(SH::getString(buf));
-
- if (SH::getBoolean(buf)) {
- msg->setVisitInconsistentBuckets();
- }
- msg->setQueueTimeout(std::chrono::milliseconds(SH::getInt(buf)));
- msg->getParameters().deserialize(buf);
-
- onDecodeCommand(buf, *msg);
- SH::getInt(buf); // Unused
- msg->setMaxBucketsPerVisitor(SH::getInt(buf));
- msg->setVisitorDispatcherVersion(50);
- return msg;
-}
-
-void ProtocolSerialization5_1::onEncode(GBBuf& buf, const api::CreateBucketCommand& msg) const
-{
- putBucket(msg.getBucket(), buf);
- buf.putBoolean(msg.getActive());
- onEncodeBucketInfoCommand(buf, msg);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_1::onDecodeCreateBucketCommand(BBuf& buf) const
-{
- document::Bucket bucket = getBucket(buf);
- bool setActive = SH::getBoolean(buf);
- auto msg = std::make_unique<api::CreateBucketCommand>(bucket);
- msg->setActive(setActive);
- onDecodeBucketInfoCommand(buf, *msg);
- return msg;
-}
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.h b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.h
deleted file mode 100644
index bfad492e653..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_1.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#pragma once
-
-#include "protocolserialization5_0.h"
-
-namespace storage::mbusprot {
-
-class ProtocolSerialization5_1 : public ProtocolSerialization5_0
-{
- enum BucketState {
- BUCKET_READY = 0x1,
- BUCKET_ACTIVE = 0x2,
- };
-public:
- ProtocolSerialization5_1(const std::shared_ptr<const document::DocumentTypeRepo>&);
-
- api::BucketInfo getBucketInfo(document::ByteBuffer& buf) const override;
- void putBucketInfo(const api::BucketInfo& info, vespalib::GrowableByteBuffer& buf) const override;
-
-protected:
- void onEncode(GBBuf&, const api::SetBucketStateCommand&) const override;
- void onEncode(GBBuf&, const api::SetBucketStateReply&) const override;
- void onEncode(GBBuf&, const api::GetCommand&) const override;
- void onEncode(GBBuf&, const api::CreateVisitorCommand&) const override;
- void onEncode(GBBuf&, const api::CreateBucketCommand&) const override;
-
- SCmd::UP onDecodeSetBucketStateCommand(BBuf&) const override;
- SRep::UP onDecodeSetBucketStateReply(const SCmd&, BBuf&) const override;
- SCmd::UP onDecodeGetCommand(BBuf&) const override;
- SCmd::UP onDecodeCreateVisitorCommand(BBuf&) const override;
- SCmd::UP onDecodeCreateBucketCommand(BBuf&) const override;
-};
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.cpp
deleted file mode 100644
index 10aa9d69fbc..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-// @author Vegard Sjonfjell
-
-#include "protocolserialization5_2.h"
-#include "storagecommand.h"
-#include "serializationhelper.h"
-
-namespace storage::mbusprot {
-
-using documentapi::TestAndSetCondition;
-
-void ProtocolSerialization5_2::onEncode(GBBuf & buf, const api::PutCommand & cmd) const
-{
- ProtocolSerialization5_0::onEncode(buf, cmd);
- encodeTasCondition(buf, cmd);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_2::onDecodePutCommand(BBuf & buf) const
-{
- auto cmd = ProtocolSerialization5_0::onDecodePutCommand(buf);
- decodeTasCondition(*cmd, buf);
- return cmd;
-}
-
-void ProtocolSerialization5_2::onEncode(GBBuf & buf, const api::RemoveCommand & cmd) const
-{
- ProtocolSerialization4_2::onEncode(buf, cmd);
- encodeTasCondition(buf, cmd);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_2::onDecodeRemoveCommand(BBuf & buf) const
-{
- auto cmd = ProtocolSerialization4_2::onDecodeRemoveCommand(buf);
- decodeTasCondition(*cmd, buf);
- return cmd;
-}
-
-void ProtocolSerialization5_2::onEncode(GBBuf & buf, const api::UpdateCommand & cmd) const
-{
- ProtocolSerialization5_0::onEncode(buf, cmd);
- encodeTasCondition(buf, cmd);
-}
-
-api::StorageCommand::UP
-ProtocolSerialization5_2::onDecodeUpdateCommand(BBuf & buf) const
-{
- auto cmd = ProtocolSerialization5_0::onDecodeUpdateCommand(buf);
- decodeTasCondition(*cmd, buf);
- return cmd;
-}
-
-void ProtocolSerialization5_2::decodeTasCondition(api::StorageCommand & storageCmd, BBuf & buf) {
- auto & cmd = static_cast<api::TestAndSetCommand &>(storageCmd);
- cmd.setCondition(TestAndSetCondition(SH::getString(buf)));
-}
-
-void ProtocolSerialization5_2::encodeTasCondition(GBBuf & buf, const api::StorageCommand & storageCmd) {
- auto & cmd = static_cast<const api::TestAndSetCommand &>(storageCmd);
- buf.putString(cmd.getCondition().getSelection());
-}
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.h b/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.h
deleted file mode 100644
index e56b9942fa5..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization5_2.h
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-// @author Vegard Sjonfjell
-
-#pragma once
-
-#include "protocolserialization5_1.h"
-#include <vespa/vespalib/util/growablebytebuffer.h>
-#include <vespa/storageapi/message/persistence.h>
-
-namespace storage::mbusprot {
-
-class ProtocolSerialization5_2 : public ProtocolSerialization5_1
-{
-public:
- ProtocolSerialization5_2(const std::shared_ptr<const document::DocumentTypeRepo>& repo)
- : ProtocolSerialization5_1(repo)
- {}
-
-protected:
- void onEncode(GBBuf &, const api::PutCommand &) const override;
- void onEncode(GBBuf &, const api::RemoveCommand &) const override;
- void onEncode(GBBuf &, const api::UpdateCommand &) const override;
-
- SCmd::UP onDecodePutCommand(BBuf &) const override;
- SCmd::UP onDecodeRemoveCommand(BBuf &) const override;
- SCmd::UP onDecodeUpdateCommand(BBuf &) const override;
-
- static void decodeTasCondition(api::StorageCommand & cmd, BBuf & buf);
- static void encodeTasCondition(GBBuf & buf, const api::StorageCommand & cmd);
-};
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.cpp b/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.cpp
deleted file mode 100644
index 799aff8f8b3..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#include "protocolserialization6_0.h"
-#include "serializationhelper.h"
-
-namespace storage::mbusprot {
-
-ProtocolSerialization6_0::ProtocolSerialization6_0(const std::shared_ptr<const document::DocumentTypeRepo> &repo)
- : ProtocolSerialization5_2(repo)
-{
-}
-
-document::Bucket
-ProtocolSerialization6_0::getBucket(document::ByteBuffer &buf) const
-{
- document::BucketSpace bucketSpace(SH::getLong(buf));
- document::BucketId bucketId(SH::getLong(buf));
- return document::Bucket(bucketSpace, bucketId);
-}
-
-void
-ProtocolSerialization6_0::putBucket(const document::Bucket &bucket, vespalib::GrowableByteBuffer &buf) const
-{
- buf.putLong(bucket.getBucketSpace().getId());
- buf.putLong(bucket.getBucketId().getRawId());
-}
-
-document::BucketSpace
-ProtocolSerialization6_0::getBucketSpace(document::ByteBuffer &buf) const
-{
- return document::BucketSpace(SH::getLong(buf));
-}
-
-void
-ProtocolSerialization6_0::putBucketSpace(document::BucketSpace bucketSpace, vespalib::GrowableByteBuffer &buf) const
-{
- buf.putLong(bucketSpace.getId());
-}
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.h b/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.h
deleted file mode 100644
index 5467cf6c5d2..00000000000
--- a/storage/src/vespa/storageapi/mbusprot/protocolserialization6_0.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-#pragma once
-
-#include "protocolserialization5_2.h"
-
-namespace storage::mbusprot {
-
-/**
- * Protocol serialization version adding decoding and encoding
- * of bucket space to almost all commands.
- */
-class ProtocolSerialization6_0 : public ProtocolSerialization5_2
-{
-public:
- ProtocolSerialization6_0(const std::shared_ptr<const document::DocumentTypeRepo> &repo);
-
- document::Bucket getBucket(document::ByteBuffer &buf) const override;
- void putBucket(const document::Bucket &bucket, vespalib::GrowableByteBuffer &buf) const override;
- document::BucketSpace getBucketSpace(document::ByteBuffer &buf) const override;
- void putBucketSpace(document::BucketSpace bucketSpace, vespalib::GrowableByteBuffer &buf) const override;
-};
-
-}
diff --git a/storage/src/vespa/storageapi/mbusprot/storageprotocol.cpp b/storage/src/vespa/storageapi/mbusprot/storageprotocol.cpp
index 3cf54860f7c..a59e5827523 100644
--- a/storage/src/vespa/storageapi/mbusprot/storageprotocol.cpp
+++ b/storage/src/vespa/storageapi/mbusprot/storageprotocol.cpp
@@ -6,6 +6,7 @@
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/document/util/stringutil.h>
#include <vespa/document/bucket/fixed_bucket_spaces.h>
+#include <cassert>
#include <sstream>
#include <vespa/log/bufferedlogger.h>
@@ -16,11 +17,7 @@ namespace storage::mbusprot {
mbus::string StorageProtocol::NAME = "StorageProtocol";
StorageProtocol::StorageProtocol(const std::shared_ptr<const document::DocumentTypeRepo> repo)
- : _serializer5_0(repo),
- _serializer5_1(repo),
- _serializer5_2(repo),
- _serializer6_0(repo),
- _serializer7_0(repo)
+ : _serializer7_0(repo)
{
}
@@ -33,20 +30,7 @@ StorageProtocol::createPolicy(const mbus::string&, const mbus::string&) const
}
namespace {
- vespalib::Version version7_0(7, 41, 19);
- vespalib::Version version6_0(6, 240, 0);
- vespalib::Version version5_2(5, 93, 30);
- vespalib::Version version5_1(5, 1, 0);
- vespalib::Version version5_0(5, 0, 12);
- vespalib::Version version5_0beta(4, 3, 0);
-}
-
-
-static bool
-suppressEncodeWarning(const api::StorageMessage *msg)
-{
- const auto *req = dynamic_cast<const api::RequestBucketInfoCommand *>(msg);
- return ((req != nullptr) && (req->getBucketSpace() != document::FixedBucketSpaces::default_space()));
+vespalib::Version version7_0(7, 41, 19);
}
static mbus::Blob
@@ -82,46 +66,23 @@ StorageProtocol::encode(const vespalib::Version& version,
const StorageMessage & message(dynamic_cast<const StorageMessage &>(routable));
try {
- if (message.getInternalMessage().get() == 0) {
- throw vespalib::IllegalArgumentException(
- "Given storage message wrapper does not contain a "
- "storage message.",
- VESPA_STRLOC);
- }
+ assert(message.getInternalMessage());
+ if (version < version7_0) {
+ LOGBP(error,
+ "Cannot encode message on version %s."
+ "Minimum version is %s. Cannot serialize %s.",
+ version.toString().c_str(),
+ version7_0.toString().c_str(),
+ message.getInternalMessage()->toString().c_str());
- if (version < version5_1) {
- if (version < version5_0beta) {
- LOGBP(warning,
- "No support for using messagebus for version %s."
- "Minimum version is %s. Thus we cannot serialize %s.",
- version.toString().c_str(),
- version5_0beta.toString().c_str(),
- message.getInternalMessage()->toString().c_str());
-
- return mbus::Blob(0);
- } else {
- return encodeMessage(_serializer5_0, routable, message, version5_0, version);
- }
- } else if (version < version5_2) {
- return encodeMessage(_serializer5_1, routable, message, version5_1, version);
- } else {
- if (version < version6_0) {
- return encodeMessage(_serializer5_2, routable, message, version5_2, version);
- } else if (version < version7_0) {
- return encodeMessage(_serializer6_0, routable, message, version6_0, version);
- } else {
- return encodeMessage(_serializer7_0, routable, message, version7_0, version);
- }
+ return mbus::Blob(0);
}
-
+ return encodeMessage(_serializer7_0, routable, message, version7_0, version);
} catch (std::exception & e) {
- if (!(version < version6_0 &&
- suppressEncodeWarning(message.getInternalMessage().get()))) {
- LOGBP(warning, "Failed to encode %s storage protocol message %s: %s",
- version.toString().c_str(),
- message.getInternalMessage()->toString().c_str(),
- e.what());
- }
+ LOGBP(warning, "Failed to encode %s storage protocol message %s: %s",
+ version.toString().c_str(),
+ message.getInternalMessage()->toString().c_str(),
+ e.what());
}
return mbus::Blob(0);
@@ -168,27 +129,14 @@ StorageProtocol::decode(const vespalib::Version & version,
static_cast<api::MessageType::Id>(SerializationHelper::getInt(buf)));
StorageMessage::UP message;
- if (version < version5_1) {
- if (version < version5_0beta) {
- LOGBP(error,
- "No support for using messagebus for version %s."
- "Minimum version is %s.",
- version.toString().c_str(),
- version5_0beta.toString().c_str());
- } else {
- return decodeMessage(_serializer5_0, data, type, version5_0, version);
- }
- } else if (version < version5_2) {
- return decodeMessage(_serializer5_1, data, type, version5_1, version);
- } else {
- if (version < version6_0) {
- return decodeMessage(_serializer5_2, data, type, version5_2, version);
- } else if (version < version7_0) {
- return decodeMessage(_serializer6_0, data, type, version6_0, version);
- } else {
- return decodeMessage(_serializer7_0, data, type, version7_0, version);
- }
+ if (version < version7_0) {
+ LOGBP(error,
+ "Cannot decode message on version %s. Minimum version is %s.",
+ version.toString().c_str(),
+ version7_0.toString().c_str());
+ return mbus::Routable::UP();
}
+ return decodeMessage(_serializer7_0, data, type, version7_0, version);
} catch (std::exception & e) {
std::ostringstream ost;
ost << "Failed to decode " << version.toString() << " messagebus "
@@ -196,7 +144,6 @@ StorageProtocol::decode(const vespalib::Version & version,
document::StringUtil::printAsHex(ost, data.data(), data.size());
LOGBP(warning, "%s", ost.str().c_str());
}
-
return mbus::Routable::UP();
}
diff --git a/storage/src/vespa/storageapi/mbusprot/storageprotocol.h b/storage/src/vespa/storageapi/mbusprot/storageprotocol.h
index 591009c9832..dbea21a4a9f 100644
--- a/storage/src/vespa/storageapi/mbusprot/storageprotocol.h
+++ b/storage/src/vespa/storageapi/mbusprot/storageprotocol.h
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
-#include "protocolserialization5_2.h"
-#include "protocolserialization6_0.h"
#include "protocolserialization7.h"
#include <vespa/messagebus/iprotocol.h>
@@ -23,10 +21,6 @@ public:
mbus::Blob encode(const vespalib::Version&, const mbus::Routable&) const override;
mbus::Routable::UP decode(const vespalib::Version&, mbus::BlobRef) const override;
private:
- ProtocolSerialization5_0 _serializer5_0;
- ProtocolSerialization5_1 _serializer5_1;
- ProtocolSerialization5_2 _serializer5_2;
- ProtocolSerialization6_0 _serializer6_0;
ProtocolSerialization7 _serializer7_0;
};
diff --git a/streamingvisitors/src/vespa/searchvisitor/hitcollector.cpp b/streamingvisitors/src/vespa/searchvisitor/hitcollector.cpp
index bded8af16cc..10e6c6aa68a 100644
--- a/streamingvisitors/src/vespa/searchvisitor/hitcollector.cpp
+++ b/streamingvisitors/src/vespa/searchvisitor/hitcollector.cpp
@@ -154,8 +154,9 @@ HitCollector::getFeatureSet(IRankProgram &rankProgram,
names.reserve(resolver.num_features());
for (size_t i = 0; i < resolver.num_features(); ++i) {
vespalib::string name = resolver.name_of(i);
- if (feature_rename_map.contains(name)) {
- name = feature_rename_map[name];
+ auto iter = feature_rename_map.find(name);
+ if (iter != feature_rename_map.end()) {
+ name = iter->second;
}
names.emplace_back(name);
}
diff --git a/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.cpp b/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.cpp
index 656e9eed132..fac801550d4 100644
--- a/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.cpp
+++ b/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.cpp
@@ -1,14 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vsm/vsm/docsumconfig.h>
-#include <vespa/searchsummary/docsummary/docsumfieldwriter.h>
+#include <vespa/searchsummary/docsummary/copy_dfw.h>
+#include <vespa/searchsummary/docsummary/empty_dfw.h>
#include <vespa/searchsummary/docsummary/matched_elements_filter_dfw.h>
+#include <vespa/searchsummary/docsummary/resultconfig.h>
#include <vespa/searchlib/common/matching_elements_fields.h>
#include <vespa/vsm/config/config-vsmfields.h>
#include <vespa/vsm/config/config-vsmsummary.h>
using search::MatchingElementsFields;
-using search::docsummary::IDocsumFieldWriter;
+using search::docsummary::DocsumFieldWriter;
+using search::docsummary::CopyDFW;
using search::docsummary::EmptyDFW;
using search::docsummary::MatchedElementsFilterDFW;
using search::docsummary::ResultConfig;
@@ -40,10 +43,10 @@ DynamicDocsumConfig::DynamicDocsumConfig(search::docsummary::IDocsumEnvironment*
{
}
-IDocsumFieldWriter::UP
+std::unique_ptr<DocsumFieldWriter>
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc, std::shared_ptr<search::MatchingElementsFields> matching_elems_fields)
{
- IDocsumFieldWriter::UP fieldWriter;
+ std::unique_ptr<DocsumFieldWriter> fieldWriter;
if ((overrideName == "staticrank") ||
(overrideName == "ranklog") ||
(overrideName == "label") ||
@@ -55,8 +58,16 @@ DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string &
fieldWriter = std::make_unique<EmptyDFW>();
rc = true;
} else if ((overrideName == "attribute") ||
- (overrideName == "attributecombiner") ||
- (overrideName == "geopos")) {
+ (overrideName == "attributecombiner")) {
+ if (!argument.empty() && argument != fieldName) {
+ auto fw = std::make_unique<CopyDFW>();
+ const ResultConfig& resultConfig = getResultConfig();
+ if (fw->Init(resultConfig, argument.c_str())) {
+ fieldWriter = std::move(fw);
+ }
+ }
+ rc = true;
+ } else if (overrideName == "geopos") {
rc = true;
} else if ((overrideName == "matchedattributeelementsfilter") ||
(overrideName == "matchedelementsfilter")) {
diff --git a/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.h b/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.h
index 11010c04e90..a660c544d7d 100644
--- a/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.h
+++ b/streamingvisitors/src/vespa/vsm/vsm/docsumconfig.h
@@ -20,7 +20,7 @@ private:
public:
DynamicDocsumConfig(search::docsummary::IDocsumEnvironment* env, search::docsummary::DynamicDocsumWriter* writer, std::shared_ptr<VsmfieldsConfig> vsm_fields_config);
private:
- std::unique_ptr<search::docsummary::IDocsumFieldWriter>
+ std::unique_ptr<search::docsummary::DocsumFieldWriter>
createFieldWriter(const string & fieldName, const string & overrideName,
const string & cf, bool & rc, std::shared_ptr<search::MatchingElementsFields> matching_elems_fields) override;
};
diff --git a/streamingvisitors/src/vespa/vsm/vsm/docsumfilter.cpp b/streamingvisitors/src/vespa/vsm/vsm/docsumfilter.cpp
index 70759feb41c..5bcead79f97 100644
--- a/streamingvisitors/src/vespa/vsm/vsm/docsumfilter.cpp
+++ b/streamingvisitors/src/vespa/vsm/vsm/docsumfilter.cpp
@@ -2,6 +2,8 @@
#include "docsumfilter.h"
#include "slimefieldwriter.h"
+#include <vespa/searchsummary/docsummary/check_undefined_value_visitor.h>
+#include <vespa/searchsummary/docsummary/i_docsum_store_document.h>
#include <vespa/searchsummary/docsummary/summaryfieldconverter.h>
#include <vespa/document/base/exceptions.h>
#include <vespa/document/fieldvalue/iteratorhandler.h>
@@ -118,6 +120,67 @@ public:
namespace vsm {
+namespace {
+
+/**
+ * Class providing access to a document retrieved from an IDocsumStore
+ * (vsm::DocsumFilter). VSM specific transforms might be applied when
+ * accessing some fields.
+ **/
+class DocsumStoreVsmDocument : public IDocsumStoreDocument
+{
+ const document::Document* _document;
+public:
+ DocsumStoreVsmDocument(const document::Document* document);
+ ~DocsumStoreVsmDocument() override;
+ std::unique_ptr<document::FieldValue> get_field_value(const vespalib::string& field_name) const override;
+ void insert_summary_field(const vespalib::string& field_name, vespalib::slime::Inserter& inserter) const override;
+ void insert_document_id(vespalib::slime::Inserter& inserter) const override;
+};
+
+DocsumStoreVsmDocument::DocsumStoreVsmDocument(const document::Document* document)
+ : _document(document)
+{
+}
+
+DocsumStoreVsmDocument::~DocsumStoreVsmDocument() = default;
+
+std::unique_ptr<document::FieldValue>
+DocsumStoreVsmDocument::get_field_value(const vespalib::string& field_name) const
+{
+ if (_document != nullptr) {
+ const document::Field & field = _document->getField(field_name);
+ auto value(field.getDataType().createFieldValue());
+ if (value) {
+ if (_document->getValue(field, *value)) {
+ return value;
+ }
+ }
+ }
+ return {};
+}
+
+void
+DocsumStoreVsmDocument::insert_summary_field(const vespalib::string& field_name, vespalib::slime::Inserter& inserter) const
+{
+ auto field_value = get_field_value(field_name);
+ if (field_value) {
+ SummaryFieldConverter::insert_summary_field(*field_value, inserter);
+ }
+}
+
+void
+DocsumStoreVsmDocument::insert_document_id(vespalib::slime::Inserter& inserter) const
+{
+ if (_document) {
+ auto id = _document->getId().toString();
+ vespalib::Memory id_view(id.data(), id.size());
+ inserter.insertString(id_view);
+ }
+}
+
+}
+
FieldPath
copyPathButFirst(const FieldPath & rhs) {
// skip the element that correspond to the start field value
@@ -320,12 +383,19 @@ DocsumFilter::writeSlimeField(const DocsumFieldSpec & fieldSpec,
LOG(debug, "writeSlimeField: About to write field '%d' as Slime: field value = '%s'",
fieldId.getId(), fv->toString().c_str());
SlimeFieldWriter writer;
+ CheckUndefinedValueVisitor check_undefined;
if (! fieldSpec.hasIdentityMapping()) {
writer.setInputFields(fieldSpec.getInputFields());
+ } else {
+ fv->accept(check_undefined);
+ }
+ if (!check_undefined.is_undefined()) {
+ writer.convert(*fv);
+ const vespalib::stringref out = writer.out();
+ packer.AddLongString(out.data(), out.size());
+ } else {
+ packer.AddEmpty();
}
- writer.convert(*fv);
- const vespalib::stringref out = writer.out();
- packer.AddLongString(out.data(), out.size());
} else {
LOG(debug, "writeSlimeField: Field value not set for field '%d'", fieldId.getId());
packer.AddEmpty();
@@ -407,7 +477,7 @@ DocsumFilter::writeEmpty(ResType type, ResultPacker & packer)
packer.AddShort(std::numeric_limits<int16_t>::min());
break;
case RES_BYTE:
- packer.AddByte(0); // byte fields are unsigned so we have no 'notdefined' value.
+ packer.AddByte(std::numeric_limits<int8_t>::min());
break;
case RES_FLOAT:
packer.AddFloat(std::numeric_limits<float>::quiet_NaN());
@@ -441,7 +511,12 @@ DocsumFilter::getMappedDocsum(uint32_t id)
const Document & doc = _docsumCache->getDocSum(id);
_packer.Init(resClass->GetClassID());
- for (FieldSpecList::iterator it(_fields.begin()), end = _fields.end(); it != end; ++it) {
+ uint32_t entry_idx = 0;
+ for (FieldSpecList::iterator it(_fields.begin()), end = _fields.end(); it != end; ++it, ++entry_idx) {
+ if (entry_idx != _packer.get_entry_idx()) {
+ // Entry is not present in docsum blob
+ continue;
+ }
ResType type = it->getResultType();
if (type == RES_JSONSTRING) {
// this really means 'structured data'
@@ -451,7 +526,13 @@ DocsumFilter::getMappedDocsum(uint32_t id)
const DocsumFieldSpec::FieldIdentifier & fieldId = it->getInputFields()[0];
const document::FieldValue * field = doc.getField(fieldId.getId());
if (field != nullptr) {
- writeField(*field, fieldId.getPath(), type, _packer);
+ CheckUndefinedValueVisitor check_undefined;
+ field->accept(check_undefined);
+ if (!check_undefined.is_undefined()) {
+ writeField(*field, fieldId.getPath(), type, _packer);
+ } else {
+ writeEmpty(type, _packer); // void input
+ }
} else {
writeEmpty(type, _packer); // void input
}
@@ -468,7 +549,9 @@ DocsumFilter::getMappedDocsum(uint32_t id)
uint32_t buflen;
bool ok = _packer.GetDocsumBlob(&buf, &buflen);
if (ok) {
- return DocsumStoreValue(buf, buflen);
+ const auto* storage_doc = dynamic_cast<const StorageDocument *>(&doc);
+ const document::Document *doc_doc = (storage_doc != nullptr && storage_doc->valid()) ? &storage_doc->docDoc() : nullptr;
+ return DocsumStoreValue(buf, buflen, std::make_unique<DocsumStoreVsmDocument>(doc_doc));
} else {
return DocsumStoreValue(nullptr, 0);
}
diff --git a/streamingvisitors/src/vespa/vsm/vsm/vsm-adapter.cpp b/streamingvisitors/src/vespa/vsm/vsm/vsm-adapter.cpp
index 5507532d4f3..fa4bc6d9b14 100644
--- a/streamingvisitors/src/vespa/vsm/vsm/vsm-adapter.cpp
+++ b/streamingvisitors/src/vespa/vsm/vsm/vsm-adapter.cpp
@@ -9,6 +9,7 @@
LOG_SETUP(".vsm.vsm-adapter");
using search::docsummary::ResConfigEntry;
+using search::docsummary::DocsumBlobEntryFilter;
using search::docsummary::KeywordExtractor;
using search::MatchingElements;
using config::ConfigSnapshot;
@@ -135,7 +136,20 @@ VSMAdapter::configure(const VSMConfigSnapshot & snapshot)
LOG(debug, "configureVsmSummary(): outputclass='%s'", vsmSummary->outputclass.c_str()); // UlfC: debugging
// init result config
- std::unique_ptr<ResultConfig> resCfg(new ResultConfig());
+ DocsumBlobEntryFilter docsum_blob_entry_filter;
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_INT);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_SHORT);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_BOOL);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_BYTE);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_FLOAT);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_DOUBLE);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_INT64);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_STRING);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_DATA);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_LONG_DATA);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_TENSOR);
+ docsum_blob_entry_filter.add_skip(search::docsummary::RES_FEATUREDATA);
+ std::unique_ptr<ResultConfig> resCfg(new ResultConfig(docsum_blob_entry_filter));
if ( ! resCfg->ReadConfig(*summary.get(), _configId.c_str())) {
throw std::runtime_error("(re-)configuration of VSM (docsum tools) failed due to bad summary config");
}
diff --git a/tenant-base/pom.xml b/tenant-base/pom.xml
index 2da5dcf77c1..b50f14558d6 100644
--- a/tenant-base/pom.xml
+++ b/tenant-base/pom.xml
@@ -39,6 +39,7 @@
<test-framework.version>${vespaversion}</test-framework.version>
<target_jdk_version>17</target_jdk_version>
<maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version>
+ <maven-dependency-plugin.version>3.3.0</maven-dependency-plugin.version>
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
<junit.version>5.8.1</junit.version> <!-- Keep in sync with hosted-tenant-base and tenant-cd until all direct use is removed -->
<endpoint>https://api.vespa-external.aws.oath.cloud:4443</endpoint>
@@ -312,6 +313,12 @@
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>${maven-dependency-plugin.version}</version>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
diff --git a/tenant-cd-api/abi-spec.json b/tenant-cd-api/abi-spec.json
index 11ec9f73be2..f072d9de169 100644
--- a/tenant-cd-api/abi-spec.json
+++ b/tenant-cd-api/abi-spec.json
@@ -15,6 +15,70 @@
],
"fields": []
},
+ "ai.vespa.hosted.cd.DisabledInInstances": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "ai.vespa.hosted.cd.DisabledInRegions": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "ai.vespa.hosted.cd.EnabledInInstances": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "ai.vespa.hosted.cd.EnabledInRegions": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
"ai.vespa.hosted.cd.Endpoint": {
"superClass": "java.lang.Object",
"interfaces": [],
diff --git a/tenant-cd-api/pom.xml b/tenant-cd-api/pom.xml
index f8411cc74d1..f6c0b662c97 100644
--- a/tenant-cd-api/pom.xml
+++ b/tenant-cd-api/pom.xml
@@ -59,6 +59,21 @@
<scope>compile</scope>
</dependency>
<dependency>
+ <groupId>org.opentest4j</groupId>
+ <artifactId>opentest4j</artifactId>
+ <version>1.2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apiguardian</groupId>
+ <artifactId>apiguardian-api</artifactId>
+ <version>1.1.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.platform</groupId>
+ <artifactId>junit-platform-commons</artifactId>
+ <version>1.8.1</version>
+ </dependency>
+ <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>vespa-feed-client-api</artifactId>
<version>${project.version}</version>
diff --git a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInInstances.java b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInInstances.java
new file mode 100644
index 00000000000..4a14509459a
--- /dev/null
+++ b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInInstances.java
@@ -0,0 +1,43 @@
+package ai.vespa.hosted.cd;
+
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.ExecutionCondition;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.util.AnnotationUtils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @author jonmv
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
+@ExtendWith(DisabledInInstancesCondition.class)
+public @interface DisabledInInstances {
+
+ /** One or more instances that this should be disabled in. */
+ String[] value();
+
+}
+
+class DisabledInInstancesCondition implements ExecutionCondition {
+
+ @Override
+ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
+ Optional<DisabledInInstances> annotation = AnnotationUtils.findAnnotation(context.getElement(), DisabledInInstances.class);
+ if (annotation.isEmpty())
+ return ConditionEvaluationResult.enabled(DisabledInInstances.class.getSimpleName() + " is not present");
+
+ List<String> disablingInstances = List.of(annotation.get().value());
+ String thisInstance = TestRuntime.get().application().instance();
+ String reason = "Disabled in: %s. Current instance: %s.".formatted(disablingInstances.isEmpty() ? "no instances" : "instances " + String.join(", ", disablingInstances), thisInstance);
+ return disablingInstances.contains(thisInstance) ? ConditionEvaluationResult.disabled(reason) : ConditionEvaluationResult.enabled(reason);
+ }
+
+} \ No newline at end of file
diff --git a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInRegions.java b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInRegions.java
new file mode 100644
index 00000000000..aeb6a001726
--- /dev/null
+++ b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/DisabledInRegions.java
@@ -0,0 +1,44 @@
+package ai.vespa.hosted.cd;
+
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.ExecutionCondition;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.util.AnnotationUtils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Function;
+
+/**
+ * @author jonmv
+ */
+@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@ExtendWith(DisabledInRegionsCondition.class)
+public @interface DisabledInRegions {
+
+ /** One or more regions that this should be disabled in. */
+ String[] value();
+
+}
+
+class DisabledInRegionsCondition implements ExecutionCondition {
+
+ @Override
+ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
+ Optional<DisabledInRegions> annotation = AnnotationUtils.findAnnotation(context.getElement(), DisabledInRegions.class);
+ if (annotation.isEmpty())
+ return ConditionEvaluationResult.enabled(DisabledInRegions.class.getSimpleName() + " is not present");
+
+ List<String> disablingRegions = List.of(annotation.get().value());
+ String thisRegion = TestRuntime.get().application().instance();
+ String reason = "Disabled in: %s. Current region: %s.".formatted(disablingRegions.isEmpty() ? "no regions" : "regions " + String.join(", ", disablingRegions), thisRegion);
+ return disablingRegions.contains(thisRegion) ? ConditionEvaluationResult.disabled(reason) : ConditionEvaluationResult.enabled(reason);
+ }
+
+} \ No newline at end of file
diff --git a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInInstances.java b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInInstances.java
new file mode 100644
index 00000000000..dfe22dacb11
--- /dev/null
+++ b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInInstances.java
@@ -0,0 +1,43 @@
+package ai.vespa.hosted.cd;
+
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.ExecutionCondition;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.util.AnnotationUtils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @author jonmv
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
+@ExtendWith(EnabledInInstancesCondition.class)
+public @interface EnabledInInstances {
+
+ /** One or more instances that this should be enabled in. */
+ String[] value();
+
+}
+
+class EnabledInInstancesCondition implements ExecutionCondition {
+
+ @Override
+ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
+ Optional<EnabledInInstances> annotation = AnnotationUtils.findAnnotation(context.getElement(), EnabledInInstances.class);
+ if (annotation.isEmpty())
+ return ConditionEvaluationResult.enabled(EnabledInInstances.class.getSimpleName() + " is not present");
+
+ List<String> enablingInstances = List.of(annotation.get().value());
+ String thisInstance = TestRuntime.get().application().instance();
+ String reason = "Enabled in: %s. Current instance: %s.".formatted(enablingInstances.isEmpty() ? "no instances" : "instances " + String.join(", ", enablingInstances), thisInstance);
+ return enablingInstances.contains(thisInstance) ? ConditionEvaluationResult.enabled(reason) : ConditionEvaluationResult.disabled(reason);
+ }
+
+} \ No newline at end of file
diff --git a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInRegions.java b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInRegions.java
new file mode 100644
index 00000000000..db2e5ac5f95
--- /dev/null
+++ b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/EnabledInRegions.java
@@ -0,0 +1,43 @@
+package ai.vespa.hosted.cd;
+
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.ExecutionCondition;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.platform.commons.util.AnnotationUtils;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * @author jonmv
+ */
+@Target({ElementType.METHOD, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@ExtendWith(EnabledInRegionsCondition.class)
+public @interface EnabledInRegions {
+
+ /** One or more regions that this should be enabled in. */
+ String[] value();
+
+}
+
+class EnabledInRegionsCondition implements ExecutionCondition {
+
+ @Override
+ public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
+ Optional<EnabledInRegions> annotation = AnnotationUtils.findAnnotation(context.getElement(), EnabledInRegions.class);
+ if (annotation.isEmpty())
+ return ConditionEvaluationResult.enabled(EnabledInRegions.class.getSimpleName() + " is not present");
+
+ List<String> enablingRegions = List.of(annotation.get().value());
+ String thisRegion = TestRuntime.get().application().instance();
+ String reason = "Enabled in: %s. Current region: %s.".formatted(enablingRegions.isEmpty() ? "no regions" : "regions " + String.join(", ", enablingRegions), thisRegion);
+ return enablingRegions.contains(thisRegion) ? ConditionEvaluationResult.enabled(reason) : ConditionEvaluationResult.disabled(reason);
+ }
+
+} \ No newline at end of file
diff --git a/testutil/src/main/java/com/yahoo/test/JunitCompat.java b/testutil/src/main/java/com/yahoo/test/JunitCompat.java
new file mode 100644
index 00000000000..b771ffa0e22
--- /dev/null
+++ b/testutil/src/main/java/com/yahoo/test/JunitCompat.java
@@ -0,0 +1,65 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.test;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.List;
+
+/**
+ * Hack to support both junit4 and junit5
+ *
+ * @author bjorncs
+ */
+public class JunitCompat {
+ private JunitCompat() {}
+
+ public static <T> void assertEquals(T l, T r) {
+ List<Class<?>> argTypes = List.of(Object.class, Object.class);
+ List<Object> argValues = List.of(l, r);
+ invokeAssert("assertEquals", argTypes, argValues, argTypes, argValues);
+ }
+
+ public static void assertEquals(String msg, long l, long r) {
+ List<Class<?>> junit4ArgTypes = List.of(String.class, long.class, long.class);
+ List<Object> junit4ArgValues = List.of(msg, l, r);
+ List<Class<?>> junit5ArgTypes = List.of(long.class, long.class, String.class);
+ List<Object> junit5ArgValues = List.of(l, r, msg);
+ invokeAssert("assertEquals", junit4ArgTypes, junit4ArgValues, junit5ArgTypes, junit5ArgValues);
+ }
+
+ public static void assertTrue(String msg, boolean b) {
+ List<Class<?>> junit4ArgTypes = List.of(String.class, boolean.class);
+ List<Object> junit4ArgValues = List.of(msg, b);
+ List<Class<?>> junit5ArgTypes = List.of(boolean.class, String.class);
+ List<Object> junit5ArgValues = List.of(b, msg);
+ invokeAssert("assertTrue", junit4ArgTypes, junit4ArgValues, junit5ArgTypes, junit5ArgValues);
+ }
+
+ private static void invokeAssert(String method, List<Class<?>> junit4ArgTypes, List<Object> junit4ArgValues,
+ List<Class<?>> junit5ArgTypes, List<Object> junit5ArgValues) {
+ try {
+ invokeAssert("org.junit.jupiter.api.Assertions", method, junit5ArgTypes, junit5ArgValues);
+ } catch (ReflectiveOperationException e) {
+ try {
+ invokeAssert("org.junit.Assert", method, junit4ArgTypes, junit4ArgValues);
+ } catch (ReflectiveOperationException ex) {
+ throw new RuntimeException("Unable to find junit4 or junit5 on test classpath", ex);
+ }
+ }
+ }
+
+ private static void invokeAssert(String clazz, String method, List<Class<?>> argTypes, List<Object> argValues)
+ throws ReflectiveOperationException {
+ try {
+ Class<?> c = Class.forName(clazz);
+ Method m = c.getMethod(method, argTypes.toArray(new Class<?>[0]));
+ m.invoke(null, argValues.toArray());
+ } catch (InvocationTargetException e) {
+ if (e.getCause() instanceof AssertionError ae) {
+ throw ae;
+ } else {
+ throw new RuntimeException(e.getCause());
+ }
+ }
+ }
+}
diff --git a/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java b/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
index ed92171542c..0917355c50c 100644
--- a/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
+++ b/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
@@ -1,9 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
/**
* PartialOrderTester implements a partial order test for OrderTester
*
@@ -14,14 +11,14 @@ import static org.junit.Assert.assertTrue;
public class PartialOrderTester<T extends Comparable<T>> extends OrderTester<T> {
protected void lessTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be less than or equal to " + b, a.compareTo(b) <= 0);
+ JunitCompat.assertTrue(a + " must be less than or equal to " + b, a.compareTo(b) <= 0);
}
protected void greaterTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be greater than or equal to " + b, a.compareTo(b) >= 0);
+ JunitCompat.assertTrue(a + " must be greater than or equal to " + b, a.compareTo(b) >= 0);
}
protected void equalTest(T a, T b) throws AssertionError {
- assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
+ JunitCompat.assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
}
}
diff --git a/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java b/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
index e95bc056ba8..2b5f100ca50 100644
--- a/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
+++ b/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
@@ -1,9 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
/**
* TotalOrderTester implements a total order test for OrderTester
*
@@ -22,14 +19,14 @@ import static org.junit.Assert.assertTrue;
public class TotalOrderTester<T extends Comparable<? super T>> extends OrderTester<T> {
protected void lessTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be less than " + b, a.compareTo(b) <= -1);
+ JunitCompat.assertTrue(a + " must be less than " + b, a.compareTo(b) <= -1);
}
protected void greaterTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be greater than " + b, a.compareTo(b) >= 1);
+ JunitCompat.assertTrue(a + " must be greater than " + b, a.compareTo(b) >= 1);
}
protected void equalTest(T a, T b) throws AssertionError {
- assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
+ JunitCompat.assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
}
}
diff --git a/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java b/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
index 05532d2a504..f7112ee9379 100644
--- a/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
+++ b/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
@@ -5,11 +5,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
+import com.yahoo.test.JunitCompat;
import java.io.UncheckedIOException;
-import static org.junit.Assert.assertEquals;
-
/**
* @author Vegard Sjonfjell
*/
@@ -31,7 +30,7 @@ public class JsonTestHelper {
try {
JsonNode expected = mapper.readTree(expectedJson);
JsonNode actual = mapper.readTree(inputJson);
- assertEquals(expected, actual);
+ JunitCompat.assertEquals(expected, actual);
} catch (JsonProcessingException e) {
throw new RuntimeException("Exception when comparing json strings." , e);
}
@@ -57,4 +56,5 @@ public class JsonTestHelper {
throw new UncheckedIOException(e);
}
}
+
}
diff --git a/vdslib/src/test/java/com/yahoo/vdslib/distribution/DistributionTestFactory.java b/vdslib/src/test/java/com/yahoo/vdslib/distribution/DistributionTestFactory.java
index 084d0e9185d..915f8dd67d5 100644
--- a/vdslib/src/test/java/com/yahoo/vdslib/distribution/DistributionTestFactory.java
+++ b/vdslib/src/test/java/com/yahoo/vdslib/distribution/DistributionTestFactory.java
@@ -108,6 +108,7 @@ public class DistributionTestFactory extends CrossPlatformTestFactory {
}
}
+ @SuppressWarnings("deprecation")
private static StorDistributionConfig.Builder deserializeConfig(String s) {
return new StorDistributionConfig.Builder(
new ConfigGetter<>(StorDistributionConfig.class).getConfig("raw:" + s));
diff --git a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java
index 6b50ea4b360..2883191cc0a 100644
--- a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java
+++ b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java
@@ -76,17 +76,18 @@ public class ApplicationMojo extends AbstractMojo {
throw new IllegalArgumentException("compile version (" + compileVersion + ") cannot be higher than parent version (" + parentVersion + ")");
}
- String metaData = String.format("{\n" +
- " \"compileVersion\": \"%s\",\n" +
- " \"buildTime\": %d,\n" +
- " \"parentVersion\": %s\n" +
- "}",
+ String metaData = String.format("""
+ {
+ "compileVersion": "%s",
+ "buildTime": %d,
+ "parentVersion": %s
+ }
+ """,
compileVersion,
System.currentTimeMillis(),
parentVersion == null ? null : "\"" + parentVersion + "\"");
try {
- Files.write(applicationDestination.toPath().resolve("build-meta.json"),
- metaData.getBytes(StandardCharsets.UTF_8));
+ Files.writeString(applicationDestination.toPath().resolve("build-meta.json"), metaData);
}
catch (IOException e) {
throw new MojoExecutionException("Failed writing compile version and build time.", e);
diff --git a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/Version.java b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/Version.java
index 050871043ca..bf7180f6705 100644
--- a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/Version.java
+++ b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/Version.java
@@ -3,7 +3,6 @@ package com.yahoo.container.plugin.mojo;
import java.util.Comparator;
import java.util.Objects;
-import static java.lang.Integer.min;
import static java.lang.Integer.parseInt;
/**
diff --git a/vespa-athenz/pom.xml b/vespa-athenz/pom.xml
index 580910799c1..55482dd1fed 100644
--- a/vespa-athenz/pom.xml
+++ b/vespa-athenz/pom.xml
@@ -22,6 +22,12 @@
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -38,11 +44,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -52,6 +53,30 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<!-- compile -->
@@ -90,6 +115,10 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency> <!-- needed by auth-core -->
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzIdentity.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzIdentity.java
index 14d0cddc61f..9c29e2d92ef 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzIdentity.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzIdentity.java
@@ -1,13 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
-
+import java.net.URI;
/**
* @author bjorncs
*/
public interface AthenzIdentity {
AthenzDomain getDomain();
String getName();
+ default URI spiffeUri() {
+ return URI.create("spiffe://%s/sa/%s".formatted(getDomainName(), getName()));
+ }
default String getFullName() {
return getDomain().getName() + "." + getName();
}
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java
index 7f16505c500..d5b772e5bab 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java
@@ -150,7 +150,7 @@ public class DefaultZmsClient extends ClientBase implements ZmsClient {
@Override
public void addRoleMember(AthenzRole role, AthenzIdentity member, Optional<String> reason) {
URI uri = zmsUrl.resolve(String.format("domain/%s/role/%s/member/%s", role.domain().getName(), role.roleName(), member.getFullName()));
- MembershipEntity membership = new MembershipEntity.RoleMembershipEntity(member.getFullName(), true, role.roleName(), null);
+ MembershipEntity membership = new MembershipEntity.RoleMembershipEntity(member.getFullName(), true, role.roleName(), null, true);
RequestBuilder requestBuilder = RequestBuilder.put(uri)
@@ -176,7 +176,7 @@ public class DefaultZmsClient extends ClientBase implements ZmsClient {
.build();
return execute(request, response -> {
MembershipEntity membership = readEntity(response, MembershipEntity.GroupMembershipEntity.class);
- return membership.isMember;
+ return membership.isMember && membership.approved;
});
}
@@ -436,6 +436,20 @@ public class DefaultZmsClient extends ClientBase implements ZmsClient {
return QuotaUsage.calculateUsage(usageEntity, quotaEntity);
}
+ @Override
+ public void deleteSubdomain(AthenzDomain parent, String name) {
+ URI uri = zmsUrl.resolve(String.format("subdomain/%s/%s", parent.getName(), name));
+ HttpUriRequest request = RequestBuilder.delete(uri).build();
+ execute(request, response -> readEntity(response, Void.class));
+ }
+
+ @Override
+ public void deletePolicy(AthenzDomain domain, String athenzPolicy) {
+ var uri = zmsUrl.resolve(String.format("domain/%s/policy/%s", domain.getName(), athenzPolicy));
+ var request = RequestBuilder.delete(uri).build();
+ execute(request, response -> readEntity(response, Void.class));
+ }
+
public AthenzRoleInformation getFullRoleInformation(AthenzRole role) {
var uri = zmsUrl.resolve(String.format("domain/%s/role/%s?pending=true&auditLog=true", role.domain().getName(), role.roleName()));
var request = RequestBuilder.get(uri).build();
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/ZmsClient.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/ZmsClient.java
index e15af58cb76..0dd0d30200c 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/ZmsClient.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/ZmsClient.java
@@ -89,5 +89,9 @@ public interface ZmsClient extends Closeable {
QuotaUsage getQuotaUsage();
+ void deleteSubdomain(AthenzDomain parent, String name);
+
+ void deletePolicy(AthenzDomain domain, String athenzPolicy);
+
void close();
}
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/MembershipEntity.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/MembershipEntity.java
index dcffe006112..ef97fb02bfa 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/MembershipEntity.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/bindings/MembershipEntity.java
@@ -17,14 +17,17 @@ public class MembershipEntity {
public final String memberName;
public final boolean isMember;
public final String expiration;
+ public final boolean approved;
@JsonCreator
public MembershipEntity(@JsonProperty("memberName") String memberName,
@JsonProperty("isMember") boolean isMember,
- @JsonProperty("expiration") String expiration) {
+ @JsonProperty("expiration") String expiration,
+ @JsonProperty("approved") boolean approved) {
this.memberName = memberName;
this.isMember = isMember;
this.expiration = expiration;
+ this.approved = approved;
}
@JsonGetter("memberName")
@@ -49,8 +52,9 @@ public class MembershipEntity {
public RoleMembershipEntity(@JsonProperty("memberName") String memberName,
@JsonProperty("isMember") boolean isMember,
@JsonProperty("roleName") String roleName,
- @JsonProperty("expiration") String expiration) {
- super(memberName, isMember, expiration);
+ @JsonProperty("expiration") String expiration,
+ @JsonProperty("approved") boolean approved) {
+ super(memberName, isMember, expiration, approved);
this.roleName = roleName;
}
@@ -62,16 +66,13 @@ public class MembershipEntity {
}
public static class RoleMembershipDecisionEntity extends RoleMembershipEntity {
- public final boolean approved;
-
@JsonCreator
public RoleMembershipDecisionEntity(@JsonProperty("memberName") String memberName,
@JsonProperty("isMember") boolean isMember,
@JsonProperty("roleName") String roleName,
@JsonProperty("expiration") String expiration,
@JsonProperty("approved") boolean approved) {
- super(memberName, isMember, roleName, expiration);
- this.approved = approved;
+ super(memberName, isMember, roleName, expiration, approved);
}
}
@@ -83,8 +84,9 @@ public class MembershipEntity {
public GroupMembershipEntity(@JsonProperty("memberName") String memberName,
@JsonProperty("isMember") boolean isMember,
@JsonProperty("groupName") String groupName,
- @JsonProperty("expiration") String expiration) {
- super(memberName, isMember, expiration);
+ @JsonProperty("expiration") String expiration,
+ @JsonProperty("approved") boolean approved) {
+ super(memberName, isMember, expiration, approved);
this.groupName = groupName;
}
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/DefaultZtsClient.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/DefaultZtsClient.java
index 197af753442..262df8611f5 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/DefaultZtsClient.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/DefaultZtsClient.java
@@ -141,8 +141,8 @@ public class DefaultZtsClient extends ClientBase implements ZtsClient {
}
@Override
- public AthenzAccessToken getAccessToken(AthenzDomain domain) {
- return this.getAccessTokenImpl(List.of(new AthenzResourceName(domain, "domain")));
+ public AthenzAccessToken getAccessToken(AthenzDomain domain, List<AthenzIdentity> proxyPrincipals) {
+ return this.getAccessTokenImpl(List.of(new AthenzResourceName(domain, "domain")), proxyPrincipals);
}
@Override
@@ -150,16 +150,22 @@ public class DefaultZtsClient extends ClientBase implements ZtsClient {
List<AthenzResourceName> athenzResourceNames = athenzRole.stream()
.map(AthenzRole::toResourceName)
.collect(toList());
- return this.getAccessTokenImpl(athenzResourceNames);
+ return this.getAccessTokenImpl(athenzResourceNames, List.of());
}
- private AthenzAccessToken getAccessTokenImpl(List<AthenzResourceName> resources) {
+ private AthenzAccessToken getAccessTokenImpl(List<AthenzResourceName> resources, List<AthenzIdentity> proxyPrincipals) {
URI uri = ztsUrl.resolve("oauth2/token");
RequestBuilder requestBuilder = RequestBuilder.post(uri)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addParameter("grant_type", "client_credentials")
.addParameter("scope", resources.stream().map(AthenzResourceName::toResourceNameString).collect(Collectors.joining(" ")));
-
+ if (proxyPrincipals.size()>0) {
+ String proxyPrincipalString = proxyPrincipals.stream()
+ .map(AthenzIdentity::spiffeUri)
+ .map(URI::toString)
+ .collect(Collectors.joining(","));
+ requestBuilder.addParameter("proxy_principal_spiffe_uris", proxyPrincipalString);
+ }
HttpUriRequest request = requestBuilder.build();
return execute(request, response -> {
AccessTokenResponseEntity accessTokenResponseEntity = readEntity(response, AccessTokenResponseEntity.class);
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/ZtsClient.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/ZtsClient.java
index 30c8ab2fd50..c4be6d8ced7 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/ZtsClient.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/ZtsClient.java
@@ -106,7 +106,18 @@ public interface ZtsClient extends AutoCloseable {
* @param domain Target domain
* @return An Athenz access token
*/
- AthenzAccessToken getAccessToken(AthenzDomain domain);
+ default AthenzAccessToken getAccessToken(AthenzDomain domain) {
+ return getAccessToken(domain, List.of());
+ }
+
+ /**
+ * Fetch an access token for the target domain
+ *
+ * @param domain Target domain
+ * @param proxyPrincipals List of principals to allow proxying token
+ * @return An Athenz access token
+ */
+ AthenzAccessToken getAccessToken(AthenzDomain domain, List<AthenzIdentity> proxyPrincipals);
/**
* Fetch an access token for the target roles
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/utils/RoleCsrGenerator.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/utils/RoleCsrGenerator.java
index 92be935d293..5b129de412d 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/utils/RoleCsrGenerator.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zts/utils/RoleCsrGenerator.java
@@ -29,10 +29,10 @@ public class RoleCsrGenerator {
public Pkcs10Csr generateCsr(AthenzIdentity identity, AthenzRole role, KeyPair keyPair) {
return Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=" + role.toResourceNameString()), keyPair, SHA256_WITH_RSA)
.addSubjectAlternativeName(
- Type.DNS_NAME,
+ Type.DNS,
String.format("%s.%s.%s", identity.getName(), identity.getDomainName().replace(".", "-"), dnsSuffix))
.addSubjectAlternativeName(
- Type.RFC822_NAME,
+ Type.EMAIL,
String.format("%s@%s", identity.getFullName(), dnsSuffix))
.build();
}
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java
index e76384d4d8b..a032b23bfb3 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java
@@ -5,7 +5,7 @@ import com.yahoo.component.annotation.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateWithKey;
-import com.yahoo.security.tls.AutoReloadingX509KeyManager;
+import com.yahoo.security.AutoReloadingX509KeyManager;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.utils.SiaUtils;
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImpl.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImpl.java
index c92f7259e77..52ce860bfce 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImpl.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImpl.java
@@ -14,7 +14,7 @@ import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.Pkcs10Csr;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateWithKey;
-import com.yahoo.security.tls.MutableX509KeyManager;
+import com.yahoo.security.MutableX509KeyManager;
import com.yahoo.vespa.athenz.api.AthenzAccessToken;
import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.athenz.api.AthenzRole;
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/CsrGenerator.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/CsrGenerator.java
index 518f77ae79c..21ce30fd244 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/CsrGenerator.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/CsrGenerator.java
@@ -13,9 +13,9 @@ import java.security.KeyPair;
import java.util.Set;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_RSA;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
-import static com.yahoo.security.SubjectAlternativeName.Type.IP_ADDRESS;
-import static com.yahoo.security.SubjectAlternativeName.Type.RFC822_NAME;
+import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
+import static com.yahoo.security.SubjectAlternativeName.Type.IP;
+import static com.yahoo.security.SubjectAlternativeName.Type.EMAIL;
/**
* Generates a {@link Pkcs10Csr} for an instance.
@@ -41,14 +41,14 @@ public class CsrGenerator {
// and SAN dnsname <provider-unique-instance-id>.instanceid.athenz.<provider-dnsname-suffix>
Pkcs10CsrBuilder pkcs10CsrBuilder = Pkcs10CsrBuilder.fromKeypair(subject, keyPair, SHA256_WITH_RSA)
.addSubjectAlternativeName(
- DNS_NAME,
+ DNS,
String.format(
"%s.%s.%s",
instanceIdentity.getName(),
instanceIdentity.getDomainName().replace(".", "-"),
dnsSuffix))
- .addSubjectAlternativeName(DNS_NAME, getIdentitySAN(instanceId));
- ipAddresses.forEach(ip -> pkcs10CsrBuilder.addSubjectAlternativeName(new SubjectAlternativeName(IP_ADDRESS, ip)));
+ .addSubjectAlternativeName(DNS, getIdentitySAN(instanceId));
+ ipAddresses.forEach(ip -> pkcs10CsrBuilder.addSubjectAlternativeName(new SubjectAlternativeName(IP, ip)));
return pkcs10CsrBuilder.build();
}
@@ -58,8 +58,8 @@ public class CsrGenerator {
KeyPair keyPair) {
X500Principal principal = new X500Principal(String.format("OU=%s, cn=%s:role.%s", providerService, role.domain().getName(), role.roleName()));
return Pkcs10CsrBuilder.fromKeypair(principal, keyPair, SHA256_WITH_RSA)
- .addSubjectAlternativeName(DNS_NAME, getIdentitySAN(instanceId))
- .addSubjectAlternativeName(RFC822_NAME, String.format("%s.%s@%s", identity.getDomainName(), identity.getName(), dnsSuffix))
+ .addSubjectAlternativeName(DNS, getIdentitySAN(instanceId))
+ .addSubjectAlternativeName(EMAIL, String.format("%s.%s@%s", identity.getDomainName(), identity.getName(), dnsSuffix))
.build();
}
diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java
index bb62dc51603..9d47ce79f87 100644
--- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java
+++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/tls/AthenzX509CertificateUtils.java
@@ -12,9 +12,7 @@ import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
-import static com.yahoo.security.SubjectAlternativeName.Type.DNS_NAME;
-import static com.yahoo.security.SubjectAlternativeName.Type.RFC822_NAME;
-import static com.yahoo.security.SubjectAlternativeName.Type.UNIFORM_RESOURCE_IDENTIFIER;
+import static com.yahoo.security.SubjectAlternativeName.Type;
/**
* Utility methods for Athenz issued x509 certificates
@@ -34,7 +32,7 @@ public class AthenzX509CertificateUtils {
private static Optional<AthenzIdentity> getRoleIdentityFromEmail(List<SubjectAlternativeName> sans) {
return sans.stream()
- .filter(san -> san.getType() == RFC822_NAME)
+ .filter(san -> san.getType() == Type.EMAIL)
.map(com.yahoo.security.SubjectAlternativeName::getValue)
.map(AthenzX509CertificateUtils::getIdentityFromSanEmail)
.findFirst();
@@ -43,7 +41,7 @@ public class AthenzX509CertificateUtils {
private static Optional<AthenzIdentity> getRoleIdentityFromUri(List<SubjectAlternativeName> sans) {
String uriPrefix = "athenz://principal/";
return sans.stream()
- .filter(s -> s.getType() == UNIFORM_RESOURCE_IDENTIFIER && s.getValue().startsWith(uriPrefix))
+ .filter(s -> s.getType() == Type.URI && s.getValue().startsWith(uriPrefix))
.map(san -> {
String uriPath = URI.create(san.getValue()).getPath();
return AthenzIdentities.from(uriPath.substring(uriPrefix.length()));
@@ -52,7 +50,7 @@ public class AthenzX509CertificateUtils {
}
public static AthenzRole getRolesFromRoleCertificate(X509Certificate certificate) {
- String commonName = com.yahoo.security.X509CertificateUtils.getSubjectCommonNames(certificate).get(0);
+ String commonName = X509CertificateUtils.getSubjectCommonName(certificate).orElseThrow();
return AthenzRole.fromResourceNameString(commonName);
}
@@ -78,7 +76,7 @@ public class AthenzX509CertificateUtils {
String uriPrefix = "athenz://instanceid/";
return sans.stream()
.filter(san -> {
- if (san.getType() != UNIFORM_RESOURCE_IDENTIFIER) return false;
+ if (san.getType() != Type.URI) return false;
return san.getValue().startsWith(uriPrefix);
})
.map(san -> {
@@ -92,7 +90,7 @@ public class AthenzX509CertificateUtils {
String dnsNameDelimiter = ".instanceid.athenz.";
return sans.stream()
.filter(san -> {
- if (san.getType() != DNS_NAME) return false;
+ if (san.getType() != Type.DNS) return false;
return san.getValue().contains(dnsNameDelimiter);
})
.map(san -> {
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
index ff3d8d20797..d7d5428c11b 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -16,28 +13,28 @@ import static org.junit.Assert.fail;
public class AthenzDomainTest {
@Test
- public void domain_can_be_constructed_from_valid_string() {
+ void domain_can_be_constructed_from_valid_string() {
new AthenzDomain("home.john.my-app");
}
@Test
- public void invalid_domain_throws_exception() {
+ void invalid_domain_throws_exception() {
assertInvalid(() -> new AthenzDomain("endswithdot."));
assertInvalid(() -> new AthenzDomain(".startswithdot"));
}
@Test
- public void parent_domain_is_without_name_suffix() {
+ void parent_domain_is_without_name_suffix() {
assertEquals(new AthenzDomain("home.john"), new AthenzDomain("home.john.myapp").getParent());
}
@Test
- public void domain_name_suffix_is_the_suffix_after_last_dot() {
+ void domain_name_suffix_is_the_suffix_after_last_dot() {
assertEquals("myapp", new AthenzDomain("home.john.myapp").getNameSuffix());
}
@Test
- public void domain_without_dot_is_toplevel() {
+ void domain_without_dot_is_toplevel() {
assertTrue(new AthenzDomain("toplevel").isTopLevelDomain());
assertFalse(new AthenzDomain("not.toplevel").isTopLevelDomain());
}
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
index ececa45d5fb..a2de235906c 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -11,7 +11,7 @@ import static org.junit.Assert.*;
public class AthenzResourceNameTest {
@Test
- public void can_serialize_and_deserialize_to_string() {
+ void can_serialize_and_deserialize_to_string() {
AthenzResourceName resourceName = new AthenzResourceName(new AthenzDomain("domain"), "entity");
String resourceNameString = resourceName.toResourceNameString();
assertEquals("domain:entity", resourceNameString);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
index 7c4ee36926f..dd12bca03f3 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.athenz.api;
import com.yahoo.athenz.auth.util.CryptoException;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.PrivateKey;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
/**
@@ -19,14 +19,14 @@ public class NTokenGeneratorTest {
private final PrivateKey key = mock(PrivateKey.class);
@Test
- public void ntoken() {
+ void ntoken() {
var signer = new Signer("signature");
NTokenGenerator generator = new NTokenGenerator(signer, new ManualClock(Instant.ofEpochSecond(12L)), () -> 3L);
AthenzIdentity identity = new AthenzService("domain", "service");
NToken token = generator.setIdentity(identity)
- .setKeyVersion("0")
- .sign(key);
+ .setKeyVersion("0")
+ .sign(key);
assertEquals("v=S1;d=domain;n=service;k=0;a=3;t=12;e=612", signer.message);
assertSame(key, signer.key);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
index 39ab8294409..48ff3ab651a 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
@@ -2,14 +2,14 @@
package com.yahoo.vespa.athenz.aws;
import com.yahoo.vespa.athenz.api.AwsTemporaryCredentials;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author tokle
@@ -17,19 +17,19 @@ import static org.junit.Assert.assertFalse;
public class AwsCredentialsTest {
@Test
- public void refreshes_correctly() {
+ void refreshes_correctly() {
Clock clock = Clock.systemUTC();
// Does not require refresh when expires in 10 minutes
assertFalse(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(10)))));
// Requires refresh when expires in 3 minutes
- Assert.assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(3)))));
+ assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(3)))));
// Requires refresh when expired
- Assert.assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().minus(Duration.ofMinutes(1)))));
+ assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().minus(Duration.ofMinutes(1)))));
// Refreshes when no credentials provided
- Assert.assertTrue(AwsCredentials.shouldRefresh(null));
+ assertTrue(AwsCredentials.shouldRefresh(null));
}
private AwsTemporaryCredentials getCredentials(Instant expiration) {
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
index f502951572c..764b2d26006 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
@@ -7,9 +7,8 @@ import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
import com.yahoo.vespa.athenz.api.AthenzService;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.security.auth.x500.X500Principal;
import java.io.File;
@@ -22,27 +21,27 @@ import java.time.Duration;
import java.time.Instant;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bjorncs
*/
public class SiaIdentityProviderTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void constructs_ssl_context_from_file() throws IOException {
- File keyFile = tempDirectory.newFile();
+ void constructs_ssl_context_from_file() throws IOException {
+ File keyFile = File.createTempFile("junit", null, tempDirectory);
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
createPrivateKeyFile(keyFile, keypair);
X509Certificate certificate = createCertificate(keypair);
- File certificateFile = tempDirectory.newFile();
+ File certificateFile = File.createTempFile("junit", null, tempDirectory);
createCertificateFile(certificate, certificateFile);
- File trustStoreFile = tempDirectory.newFile();
+ File trustStoreFile = File.createTempFile("junit", null, tempDirectory);
createTrustStoreFile(certificate, trustStoreFile);
SiaIdentityProvider provider =
@@ -56,16 +55,16 @@ public class SiaIdentityProviderTest {
}
@Test
- public void constructs_ssl_context_with_pem_trust_store() throws IOException {
- File keyFile = tempDirectory.newFile();
+ void constructs_ssl_context_with_pem_trust_store() throws IOException {
+ File keyFile = File.createTempFile("junit", null, tempDirectory);
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
createPrivateKeyFile(keyFile, keypair);
X509Certificate certificate = createCertificate(keypair);
- File certificateFile = tempDirectory.newFile();
+ File certificateFile = File.createTempFile("junit", null, tempDirectory);
createCertificateFile(certificate, certificateFile);
- File trustStoreFile = tempDirectory.newFile();
+ File trustStoreFile = File.createTempFile("junit", null, tempDirectory);
createPemTrustStoreFile(certificate, trustStoreFile);
SiaIdentityProvider provider =
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java
index 81f2d2a08cb..d22a791fa60 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java
@@ -1,10 +1,10 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.identityprovider.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.athenz.identityprovider.api.IdentityType.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -12,7 +12,7 @@ import static org.junit.Assert.*;
public class VespaUniqueInstanceIdTest {
@Test
- public void can_serialize_to_and_deserialize_from_string() {
+ void can_serialize_to_and_deserialize_from_string() {
VespaUniqueInstanceId id =
new VespaUniqueInstanceId(1, "cluster-id", "instance", "application", "tenant", "region", "environment", TENANT);
String stringRepresentation = id.asDottedString();
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
index 21f2c84710a..c9d2ea581bb 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
@@ -14,12 +14,13 @@ import com.yahoo.security.Pkcs10CsrBuilder;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.test.ManualClock;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Path;
@@ -32,6 +33,7 @@ import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -44,8 +46,8 @@ import static org.mockito.Mockito.when;
*/
public class AthenzIdentityProviderImplTest {
- @Rule
- public TemporaryFolder tempDir = new TemporaryFolder();
+ @TempDir
+ public File tempDir;
public static final Duration certificateValidity = Duration.ofDays(30);
@@ -63,7 +65,7 @@ public class AthenzIdentityProviderImplTest {
private Path trustStoreFile;
private X509Certificate caCertificate;
- @Before
+ @BeforeEach
public void createTrustStoreFile() throws IOException {
caCertificate = X509CertificateBuilder
.fromKeypair(
@@ -74,7 +76,7 @@ public class AthenzIdentityProviderImplTest {
SignatureAlgorithm.SHA256_WITH_ECDSA,
BigInteger.ONE)
.build();
- trustStoreFile = tempDir.newFile().toPath();
+ trustStoreFile = File.createTempFile("junit", null, tempDir).toPath();
KeyStoreUtils.writeKeyStoreToFile(
KeyStoreBuilder.withType(KeyStoreType.JKS)
.withKeyEntry("default", caKeypair.getPrivate(), caCertificate)
@@ -82,17 +84,19 @@ public class AthenzIdentityProviderImplTest {
trustStoreFile);
}
- @Test(expected = AthenzIdentityProviderException.class)
- public void component_creation_fails_when_credentials_not_found() {
- AthenzCredentialsService credentialService = mock(AthenzCredentialsService.class);
- when(credentialService.registerInstance())
- .thenThrow(new RuntimeException("athenz unavailable"));
-
- new AthenzIdentityProviderImpl(IDENTITY_CONFIG, mock(Metric.class), trustStoreFile ,credentialService, mock(ScheduledExecutorService.class), new ManualClock(Instant.EPOCH));
+ @Test
+ void component_creation_fails_when_credentials_not_found() {
+ assertThrows(AthenzIdentityProviderException.class, () -> {
+ AthenzCredentialsService credentialService = mock(AthenzCredentialsService.class);
+ when(credentialService.registerInstance())
+ .thenThrow(new RuntimeException("athenz unavailable"));
+
+ new AthenzIdentityProviderImpl(IDENTITY_CONFIG, mock(Metric.class), trustStoreFile, credentialService, mock(ScheduledExecutorService.class), new ManualClock(Instant.EPOCH));
+ });
}
@Test
- public void metrics_updated_on_refresh() {
+ void metrics_updated_on_refresh() {
ManualClock clock = new ManualClock(Instant.EPOCH);
Metric metric = mock(Metric.class);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
index 5a3099aff76..5253fee0802 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.identityprovider.api.IdentityType;
import com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument;
import com.yahoo.vespa.athenz.identityprovider.api.VespaUniqueInstanceId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.time.Instant;
@@ -16,7 +16,7 @@ import java.util.HashSet;
import static com.yahoo.vespa.athenz.identityprovider.api.IdentityType.TENANT;
import static com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument.DEFAULT_DOCUMENT_VERSION;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -25,7 +25,7 @@ public class IdentityDocumentSignerTest {
public static final int KEY_VERSION = 0;
@Test
- public void generates_and_validates_signature() {
+ void generates_and_validates_signature() {
IdentityDocumentSigner signer = new IdentityDocumentSigner();
IdentityType identityType = TENANT;
VespaUniqueInstanceId id =
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
index fc0b0a9c85f..3e4f8541aaa 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
@@ -6,13 +6,13 @@ import com.yahoo.security.KeyUtils;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.identityprovider.api.VespaUniqueInstanceId;
import com.yahoo.security.Pkcs10Csr;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -24,7 +24,7 @@ public class InstanceCsrGeneratorTest {
private static final String ATHENZ_SERVICE = "foo.bar";
@Test
- public void it_generates_csr_with_correct_subject() {
+ void it_generates_csr_with_correct_subject() {
CsrGenerator csrGenerator = new CsrGenerator(DNS_SUFFIX, PROVIDER_SERVICE);
AthenzService service = new AthenzService(ATHENZ_SERVICE);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
index 1b5dc3b7a71..262bac012b8 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
@@ -4,9 +4,9 @@ package com.yahoo.vespa.athenz.utils;
import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class AthenzIdentitiesTest {
@Test
- public void athenz_identity_is_parsed_from_dot_separated_string() {
+ void athenz_identity_is_parsed_from_dot_separated_string() {
AthenzIdentity expectedIdentity = new AthenzService(new AthenzDomain("my.subdomain"), "myservicename");
String fullName = expectedIdentity.getFullName();
AthenzIdentity actualIdentity = AthenzIdentities.from(fullName);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
index 5b699be4088..e59d9998170 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
@@ -7,7 +7,7 @@ import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.tls.AthenzIdentityVerifier;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
@@ -21,8 +21,8 @@ import java.time.Instant;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static java.util.Collections.singleton;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -32,7 +32,7 @@ import static org.mockito.Mockito.when;
public class AthenzIdentityVerifierTest {
@Test
- public void verifies_certificate_with_athenz_service_as_common_name() throws Exception {
+ void verifies_certificate_with_athenz_service_as_common_name() throws Exception {
AthenzIdentity trustedIdentity = new AthenzService("mydomain", "alice");
AthenzIdentity unknownIdentity = new AthenzService("mydomain", "mallory");
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
index 62c187b8c2c..7be55ec18a8 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
@@ -3,29 +3,29 @@ package com.yahoo.vespa.athenz.utils;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
*/
public class SiaUtilsTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void it_finds_all_identity_names_from_files_in_sia_keys_directory() throws IOException {
- Path siaRoot = tempDirectory.getRoot().toPath();
+ void it_finds_all_identity_names_from_files_in_sia_keys_directory() throws IOException {
+ Path siaRoot = tempDirectory.toPath();
assertTrue(SiaUtils.findSiaServices(siaRoot).isEmpty());
Files.createDirectory(siaRoot.resolve("keys"));
AthenzService fooService = new AthenzService("my.domain.foo");
diff --git a/vespa-feed-client-api/abi-spec.json b/vespa-feed-client-api/abi-spec.json
index 5bd0acf82d3..a41932323b5 100644
--- a/vespa-feed-client-api/abi-spec.json
+++ b/vespa-feed-client-api/abi-spec.json
@@ -137,6 +137,7 @@
"public abstract ai.vespa.feed.client.FeedClientBuilder setCertificate(java.util.Collection, java.security.PrivateKey)",
"public abstract ai.vespa.feed.client.FeedClientBuilder setCertificate(java.security.cert.X509Certificate, java.security.PrivateKey)",
"public abstract ai.vespa.feed.client.FeedClientBuilder setDryrun(boolean)",
+ "public abstract ai.vespa.feed.client.FeedClientBuilder setSpeedTest(boolean)",
"public abstract ai.vespa.feed.client.FeedClientBuilder setCaCertificatesFile(java.nio.file.Path)",
"public abstract ai.vespa.feed.client.FeedClientBuilder setCaCertificates(java.util.Collection)",
"public abstract ai.vespa.feed.client.FeedClientBuilder setEndpointUris(java.util.List)",
diff --git a/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java b/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java
index 7ec5fbb02b7..b7c51a0c5c9 100644
--- a/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java
+++ b/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java
@@ -95,8 +95,12 @@ public interface FeedClientBuilder {
/** Sets client SSL certificate/key */
FeedClientBuilder setCertificate(X509Certificate certificate, PrivateKey privateKey);
+ /** Turns on dryrun mode, where each operation succeeds after a given delay, rather than being sent across the network. */
FeedClientBuilder setDryrun(boolean enabled);
+ /** Turns on speed test mode, where all feed operations are immediately acknowledged by the server. */
+ FeedClientBuilder setSpeedTest(boolean enabled);
+
/**
* Overrides JVM default SSL truststore
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
diff --git a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java
index e024f961e26..fd36749b109 100644
--- a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java
+++ b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java
@@ -39,6 +39,8 @@ class CliArguments {
private static final String CONNECTIONS_OPTION = "connections";
private static final String DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION = "disable-ssl-hostname-verification";
private static final String DRYRUN_OPTION = "dryrun";
+ private static final String SPEED_TEST_OPTION = "speed-test";
+ private static final String TEST_PAYLOAD_SIZE_OPTION = "test-payload-size";
private static final String ENDPOINT_OPTION = "endpoint";
private static final String FILE_OPTION = "file";
private static final String HEADER_OPTION = "header";
@@ -78,8 +80,19 @@ class CliArguments {
if (!args.hasOption(ENDPOINT_OPTION)) {
throw new CliArgumentsException("Endpoint must be specified");
}
- if (args.hasOption(FILE_OPTION) == args.hasOption(STDIN_OPTION)) {
- throw new CliArgumentsException(String.format("Either option '%s' or '%s' must be specified", FILE_OPTION, STDIN_OPTION));
+ if (args.hasOption(SPEED_TEST_OPTION)) {
+ if ( args.hasOption(FILE_OPTION) && (args.hasOption(STDIN_OPTION) || args.hasOption(TEST_PAYLOAD_SIZE_OPTION))
+ || args.hasOption(STDIN_OPTION) && args.hasOption(TEST_PAYLOAD_SIZE_OPTION)) {
+ throw new CliArgumentsException(String.format("At most one of '%s', '%s' and '%s' may be specified", FILE_OPTION, STDIN_OPTION, TEST_PAYLOAD_SIZE_OPTION));
+ }
+ }
+ else {
+ if (args.hasOption(FILE_OPTION) == args.hasOption(STDIN_OPTION)) {
+ throw new CliArgumentsException(String.format("Exactly one of '%s' and '%s' must be specified", FILE_OPTION, STDIN_OPTION));
+ }
+ if (args.hasOption(TEST_PAYLOAD_SIZE_OPTION)) {
+ throw new CliArgumentsException(String.format("Option '%s' can only be specified together with '%s'", TEST_PAYLOAD_SIZE_OPTION, SPEED_TEST_OPTION));
+ }
}
if (args.hasOption(CERTIFICATE_OPTION) != args.hasOption(PRIVATE_KEY_OPTION)) {
throw new CliArgumentsException(
@@ -166,6 +179,10 @@ class CliArguments {
boolean dryrunEnabled() { return has(DRYRUN_OPTION); }
+ boolean speedTest() { return has(SPEED_TEST_OPTION); }
+
+ OptionalInt testPayloadSize() throws CliArgumentsException { return intValue(TEST_PAYLOAD_SIZE_OPTION); }
+
Optional<URI> proxy() throws CliArgumentsException {
try {
URL url = (URL) arguments.getParsedOptionValue(PROXY_OPTION);
@@ -304,7 +321,17 @@ class CliArguments {
.build())
.addOption(Option.builder()
.longOpt(DRYRUN_OPTION)
- .desc("Enable dryrun mode where each operation succeeds after " + DryrunCluster.DELAY.toMillis() + "ms")
+ .desc("Let each operation succeed after " + DryrunCluster.DELAY.toMillis() + "ms, instead of sending it across the network ")
+ .build())
+ .addOption(Option.builder()
+ .longOpt(SPEED_TEST_OPTION)
+ .desc("Perform a network speed test, where the server immediately responds to each feed operation with a successful response. Requires Vespa version ≥ 8.35 on the server")
+ .build())
+ .addOption(Option.builder()
+ .longOpt(TEST_PAYLOAD_SIZE_OPTION)
+ .desc("Document JSON test payload size in bytes, for use with --speed-test; requires --file and -stdin to not be set; default is 1024")
+ .hasArg()
+ .type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(VERBOSE_OPTION)
diff --git a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliClient.java b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliClient.java
index 68b9cf6af0e..58afac885eb 100644
--- a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliClient.java
+++ b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliClient.java
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client.impl;
+import ai.vespa.feed.client.DocumentId;
import ai.vespa.feed.client.FeedClient;
import ai.vespa.feed.client.FeedClientBuilder;
import ai.vespa.feed.client.FeedException;
@@ -9,22 +10,35 @@ import ai.vespa.feed.client.JsonFeeder.ResultCallback;
import ai.vespa.feed.client.OperationStats;
import ai.vespa.feed.client.Result;
import ai.vespa.feed.client.ResultException;
+import ai.vespa.feed.client.impl.CliArguments.CliArgumentsException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
+import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
+import java.io.SequenceInputStream;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Duration;
+import java.time.Instant;
+import java.util.Enumeration;
import java.util.Map;
+import java.util.Random;
+import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static java.util.stream.Collectors.joining;
/**
* Main method for CLI interface
@@ -76,7 +90,7 @@ public class CliClient {
if (cliArgs.showProgress()) {
Thread progressPrinter = new Thread(() -> {
try {
- while ( ! latch.await(10, TimeUnit.SECONDS)) {
+ while (!latch.await(10, TimeUnit.SECONDS)) {
synchronized (printMonitor) {
printBenchmarkResult(System.nanoTime() - startNanos, successes.get(), failures.get(), feedClient.stats(), systemError);
}
@@ -89,9 +103,17 @@ public class CliClient {
}
feeder.feedMany(in, new ResultCallback() {
- @Override public void onNextResult(Result result, FeedException error) { handleResult(result, error, successes, failures, cliArgs); }
- @Override public void onError(FeedException error) { fatal.set(error); latch.countDown(); }
- @Override public void onComplete() { latch.countDown(); }
+ @Override
+ public void onNextResult(Result result, FeedException error) { handleResult(result, error, successes, failures, cliArgs); }
+
+ @Override
+ public void onError(FeedException error) {
+ fatal.set(error);
+ latch.countDown();
+ }
+
+ @Override
+ public void onComplete() { latch.countDown(); }
});
latch.await();
@@ -99,9 +121,11 @@ public class CliClient {
if (fatal.get() != null) throw fatal.get();
}
return 0;
- } catch (CliArguments.CliArgumentsException | IOException | FeedException e) {
+ }
+ catch (CliArguments.CliArgumentsException | IOException | FeedException e) {
return handleException(verbose, e);
- } catch (Exception e) {
+ }
+ catch (Exception e) {
return handleException(verbose, "Unknown failure: " + e.getMessage(), e);
}
}
@@ -111,7 +135,8 @@ public class CliClient {
failures.incrementAndGet();
if (args.showErrors()) synchronized (printMonitor) {
systemError.println(error.getMessage());
- if (error instanceof ResultException) ((ResultException) error).getTrace().ifPresent(systemError::println);
+ if (error instanceof ResultException)
+ ((ResultException) error).getTrace().ifPresent(systemError::println);
if (args.verboseSpecified()) error.printStackTrace(systemError);
}
}
@@ -136,6 +161,7 @@ public class CliClient {
cliArgs.caCertificates().ifPresent(builder::setCaCertificatesFile);
cliArgs.headers().forEach(builder::addRequestHeader);
builder.setDryrun(cliArgs.dryrunEnabled());
+ builder.setSpeedTest(cliArgs.speedTest());
cliArgs.doomSeconds().ifPresent(doom -> builder.setCircuitBreaker(new GracePeriodCircuitBreaker(Duration.ofSeconds(10),
Duration.ofSeconds(doom))));
cliArgs.proxy().ifPresent(builder::setProxy);
@@ -151,7 +177,9 @@ public class CliClient {
}
private InputStream createFeedInputStream(CliArguments cliArgs) throws CliArguments.CliArgumentsException, IOException {
- return cliArgs.readFeedFromStandardInput() ? systemIn : Files.newInputStream(cliArgs.inputFile().get());
+ return cliArgs.readFeedFromStandardInput() ? systemIn
+ : cliArgs.inputFile().isPresent() ? Files.newInputStream(cliArgs.inputFile().get())
+ : createDummyInputStream(cliArgs.testPayloadSize().orElse(1024));
}
private int handleException(boolean verbose, Exception e) { return handleException(verbose, e.getMessage(), e); }
@@ -165,8 +193,12 @@ public class CliClient {
}
private static class AcceptAllHostnameVerifier implements HostnameVerifier {
+
static final AcceptAllHostnameVerifier INSTANCE = new AcceptAllHostnameVerifier();
- @Override public boolean verify(String hostname, SSLSession session) { return true; }
+
+ @Override
+ public boolean verify(String hostname, SSLSession session) { return true; }
+
}
static void printBenchmarkResult(long durationNanos, long successes, long failures,
@@ -182,11 +214,13 @@ public class CliClient {
generator.writeNumberField("http.request.count", stats.requests());
generator.writeNumberField("http.request.bytes", stats.bytesSent());
+ writeFloatField(generator, "http.request.MBps", stats.bytesSent() * 1e3 / durationNanos, 3);
generator.writeNumberField("http.exception.count", stats.exceptions());
generator.writeNumberField("http.response.count", stats.responses());
generator.writeNumberField("http.response.bytes", stats.bytesReceived());
+ writeFloatField(generator, "http.response.MBps", stats.bytesReceived() * 1e3 / durationNanos, 3);
generator.writeNumberField("http.response.error.count", stats.responses() - stats.successes());
writeFloatField(generator, "http.response.latency.millis.min", stats.minLatencyMillis(), 3);
writeFloatField(generator, "http.response.latency.millis.avg", stats.averageLatencyMillis(), 3);
@@ -206,4 +240,31 @@ public class CliClient {
generator.writeNumber(String.format("%." + precision + "f", value));
}
-}
+ /** Creates an input stream that spits out random documents (id and data) for one minute. */
+ static InputStream createDummyInputStream(int payloadSize) {
+ Instant end = Instant.now().plusSeconds(60);
+ return createDummyInputStream(payloadSize, new Random(), () -> Instant.now().isBefore(end));
+ }
+
+ static InputStream createDummyInputStream(int payloadSize, Random random, BooleanSupplier hasNext) {
+ int idSize = 8;
+ String template = String.format("{ \"put\": \"id:test:test::%s\", \"fields\": { \"test\": \"%s\" } }\n",
+ IntStream.range(0, idSize).mapToObj(__ -> "*").collect(joining()),
+ IntStream.range(0, payloadSize).mapToObj(__ -> "#").collect(joining()));
+ byte[] buffer = template.getBytes(StandardCharsets.UTF_8);
+ int idIndex = template.indexOf('*');
+ int dataIndex = template.indexOf('#');
+
+ return new SequenceInputStream(new Enumeration<InputStream>() {
+ @Override public boolean hasMoreElements() {
+ return hasNext.getAsBoolean();
+ }
+ @Override public InputStream nextElement() {
+ for (int i = 0; i < idSize; i++) buffer[ idIndex + i] = (byte) ('a' + (random.nextInt(26)));
+ for (int i = 0; i < payloadSize; i++) buffer[dataIndex + i] = (byte) ('a' + (random.nextInt(26)));
+ return new ByteArrayInputStream(buffer);
+ }
+ });
+ }
+
+} \ No newline at end of file
diff --git a/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliArgumentsTest.java b/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliArgumentsTest.java
index 201a85ed09d..073ea4a58db 100644
--- a/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliArgumentsTest.java
+++ b/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliArgumentsTest.java
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client.impl;
+import ai.vespa.feed.client.impl.CliArguments.CliArgumentsException;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
@@ -63,16 +64,23 @@ class CliArgumentsTest {
}
@Test
- void fails_on_conflicting_parameters() {
- CliArguments.CliArgumentsException exception = assertThrows(
- CliArguments.CliArgumentsException.class,
- () -> CliArguments.fromRawArgs(new String[] {"--endpoint=https://endpoint", "--file=/path/to/file", "--stdin"}));
- assertEquals("Either option 'file' or 'stdin' must be specified", exception.getMessage());
+ void fails_on_conflicting_parameters() throws CliArgumentsException {
+ assertEquals("Exactly one of 'file' and 'stdin' must be specified",
+ assertThrows(CliArgumentsException.class,
+ () -> CliArguments.fromRawArgs(new String[] {"--endpoint=https://endpoint", "--file=/path/to/file", "--stdin"}))
+ .getMessage());
- exception = assertThrows(
- CliArguments.CliArgumentsException.class,
- () -> CliArguments.fromRawArgs(new String[] {"--endpoint=https://endpoint"}));
- assertEquals("Either option 'file' or 'stdin' must be specified", exception.getMessage());
+ assertEquals("Exactly one of 'file' and 'stdin' must be specified",
+ assertThrows(CliArgumentsException.class,
+ () -> CliArguments.fromRawArgs(new String[] {"--endpoint=https://endpoint"}))
+ .getMessage());
+
+ assertEquals("At most one of 'file', 'stdin' and 'test-payload-size' may be specified",
+ assertThrows(CliArgumentsException.class,
+ () -> CliArguments.fromRawArgs(new String[] {"--endpoint=https://endpoint", "--speed-test", "--test-payload-size=123", "--file=file"}))
+ .getMessage());
+
+ CliArguments.fromRawArgs(new String[] {"--endpoint=foo", "--speed-test"});
}
@Test
diff --git a/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliClientTest.java b/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliClientTest.java
new file mode 100644
index 00000000000..44dbf62966e
--- /dev/null
+++ b/vespa-feed-client-cli/src/test/java/ai/vespa/feed/client/impl/CliClientTest.java
@@ -0,0 +1,31 @@
+package ai.vespa.feed.client.impl;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * @author jonmv
+ */
+class CliClientTest {
+
+ @Test
+ void testDummyStream() throws IOException {
+ AtomicInteger count = new AtomicInteger(3);
+ InputStream in = CliClient.createDummyInputStream(4, new Random(0), () -> count.decrementAndGet() >= 0);
+ byte[] buffer = new byte[1 << 20];
+ int offset = 0, read;
+ while ((read = in.read(buffer, offset, buffer.length - offset)) >= 0) offset += read;
+ assertEquals("{ \"put\": \"id:test:test::ssxvnjhp\", \"fields\": { \"test\": \"dqdx\" } }\n" +
+ "{ \"put\": \"id:test:test::vcrastvy\", \"fields\": { \"test\": \"bcwv\" } }\n" +
+ "{ \"put\": \"id:test:test::mgnykrxv\", \"fields\": { \"test\": \"zxkg\" } }\n",
+ new String(buffer, 0, offset, StandardCharsets.UTF_8));
+ }
+
+}
diff --git a/vespa-feed-client-cli/src/test/resources/help.txt b/vespa-feed-client-cli/src/test/resources/help.txt
index 66d7c3521c2..e41a78bc932 100644
--- a/vespa-feed-client-cli/src/test/resources/help.txt
+++ b/vespa-feed-client-cli/src/test/resources/help.txt
@@ -10,8 +10,9 @@ Vespa feed client
connections
--disable-ssl-hostname-verification Disable SSL hostname
verification
- --dryrun Enable dryrun mode where each
- operation succeeds after 1ms
+ --dryrun Let each operation succeed after
+ 1ms, instead of sending it
+ across the network
--endpoint <arg> URI to feed endpoint
--file <arg> Path to feed file in JSON format
--header <arg> HTTP header on the form 'Name:
@@ -34,8 +35,19 @@ Vespa feed client
failure
--silent Disable periodic status printing
to stderr
+ --speed-test Perform a network speed test,
+ where the server immediately
+ responds to each feed operation
+ with a successful response.
+ Requires Vespa version ≥ 8.35 on
+ the server
--stdin Read JSON input from standard
input
+ --test-payload-size <arg> Document JSON test payload size
+ in bytes, for use with
+ --speed-test; requires --file
+ and -stdin to not be set;
+ default is 1024
--timeout <arg> Feed operation timeout (in
seconds)
--trace <arg> The trace level of network
diff --git a/vespa-feed-client/pom.xml b/vespa-feed-client/pom.xml
index 536637bdce2..8b7b82573c4 100644
--- a/vespa-feed-client/pom.xml
+++ b/vespa-feed-client/pom.xml
@@ -53,10 +53,33 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <release>${vespaClients.jdk.releaseVersion}</release>
- <showDeprecation>true</showDeprecation>
- </configuration>
+ <executions>
+ <execution>
+ <id>compile-java-${vespaClients.jdk.releaseVersion}</id>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ <configuration>
+ <release>${vespaClients.jdk.releaseVersion}</release>
+ <showDeprecation>true</showDeprecation>
+ </configuration>
+ </execution>
+ <execution>
+ <id>compile-java-9</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ <configuration>
+ <release>9</release>
+ <compileSourceRoots>
+ <compileSourceRoot>${project.basedir}/src/main/java9</compileSourceRoot>
+ </compileSourceRoots>
+ <outputDirectory>${project.build.outputDirectory}/META-INF/versions/9</outputDirectory>
+ <showDeprecation>true</showDeprecation>
+ </configuration>
+ </execution>
+ </executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/ApacheCluster.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/ApacheCluster.java
index 62cd56f21ce..decb5021f8f 100644
--- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/ApacheCluster.java
+++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/ApacheCluster.java
@@ -15,7 +15,6 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.net.URIAuthority;
import org.apache.hc.core5.reactor.IOReactorConfig;
-import org.apache.hc.core5.reactor.ssl.TlsDetails;
import org.apache.hc.core5.util.Timeout;
import javax.net.ssl.SSLContext;
@@ -131,10 +130,9 @@ class ApacheCluster implements Cluster {
throw new IllegalStateException("No adequate SSL cipher suites supported by the JVM");
ClientTlsStrategyBuilder tlsStrategyBuilder = ClientTlsStrategyBuilder.create()
- .setTlsDetailsFactory(sslEngine ->
- new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol()))
- .setCiphers(allowedCiphers)
- .setSslContext(sslContext);
+ .setTlsDetailsFactory(TlsDetailsFactory::create)
+ .setCiphers(allowedCiphers)
+ .setSslContext(sslContext);
if (builder.hostnameVerifier != null)
tlsStrategyBuilder.setHostnameVerifier(builder.hostnameVerifier);
diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/BenchmarkingCluster.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/BenchmarkingCluster.java
index f59eee25d42..0a1ad1ee9b7 100644
--- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/BenchmarkingCluster.java
+++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/BenchmarkingCluster.java
@@ -4,6 +4,7 @@ package ai.vespa.feed.client.impl;
import ai.vespa.feed.client.HttpResponse;
import ai.vespa.feed.client.OperationStats;
+import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -80,12 +81,13 @@ public class BenchmarkingCluster implements Cluster {
}
private OperationStats getStats() {
+ long requests = this.requests.get();
+
Map<Integer, Long> responses = new HashMap<>();
for (int code = 0; code < responsesByCode.length; code++)
if (responsesByCode[code] > 0)
responses.put(code, responsesByCode[code]);
- long requests = this.requests.get();
return new OperationStats(requests,
responses,
exceptions,
@@ -100,6 +102,14 @@ public class BenchmarkingCluster implements Cluster {
@Override
public void close() {
delegate.close();
+ Instant doom = Instant.now().plusSeconds(10);
+ while (Instant.now().isBefore(doom) && getStats().inflight() != 0)
+ try {
+ Thread.sleep(10);
+ }
+ catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
executor.shutdown();
}
diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java
index 134ad464618..c70cb7cd850 100644
--- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java
+++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java
@@ -49,6 +49,7 @@ public class FeedClientBuilderImpl implements FeedClientBuilder {
Collection<X509Certificate> caCertificates;
boolean benchmark = true;
boolean dryrun = false;
+ boolean speedTest = false;
URI proxy;
@@ -170,6 +171,12 @@ public class FeedClientBuilderImpl implements FeedClientBuilder {
return this;
}
+ @Override
+ public FeedClientBuilder setSpeedTest(boolean enabled) {
+ this.speedTest = enabled;
+ return this;
+ }
+
/**
* Overrides JVM default SSL truststore
* @param caCertificatesFile Path to PEM encoded file containing trusted certificates
diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/HttpFeedClient.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/HttpFeedClient.java
index c136d697a0b..80a107fbdc6 100644
--- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/HttpFeedClient.java
+++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/HttpFeedClient.java
@@ -41,6 +41,7 @@ class HttpFeedClient implements FeedClient {
private final Map<String, Supplier<String>> requestHeaders;
private final RequestStrategy requestStrategy;
private final AtomicBoolean closed = new AtomicBoolean();
+ private final boolean speedTest;
HttpFeedClient(FeedClientBuilderImpl builder) throws IOException {
this(builder, new HttpRequestStrategy(builder));
@@ -49,6 +50,7 @@ class HttpFeedClient implements FeedClient {
HttpFeedClient(FeedClientBuilderImpl builder, RequestStrategy requestStrategy) {
this.requestHeaders = new HashMap<>(builder.requestHeaders);
this.requestStrategy = requestStrategy;
+ this.speedTest = builder.speedTest;
}
@Override
@@ -90,7 +92,7 @@ class HttpFeedClient implements FeedClient {
throw new IllegalStateException("Client is closed");
HttpRequest request = new HttpRequest(method,
- getPath(documentId) + getQuery(params),
+ getPath(documentId) + getQuery(params, speedTest),
requestHeaders,
operationJson == null ? null : operationJson.getBytes(UTF_8), // TODO: make it bytes all the way?
params.timeout().orElse(null));
@@ -217,13 +219,14 @@ class HttpFeedClient implements FeedClient {
}
}
- static String getQuery(OperationParameters params) {
+ static String getQuery(OperationParameters params, boolean speedTest) {
StringJoiner query = new StringJoiner("&", "?", "").setEmptyValue("");
if (params.createIfNonExistent()) query.add("create=true");
params.testAndSetCondition().ifPresent(condition -> query.add("condition=" + encode(condition)));
params.timeout().ifPresent(timeout -> query.add("timeout=" + timeout.toMillis() + "ms"));
params.route().ifPresent(route -> query.add("route=" + encode(route)));
params.tracelevel().ifPresent(tracelevel -> query.add("tracelevel=" + tracelevel));
+ if (speedTest) query.add("dryRun=true");
return query.toString();
}
diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/TlsDetailsFactory.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/TlsDetailsFactory.java
new file mode 100644
index 00000000000..5183ce61761
--- /dev/null
+++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/TlsDetailsFactory.java
@@ -0,0 +1,16 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package ai.vespa.feed.client.impl;
+
+import org.apache.hc.core5.reactor.ssl.TlsDetails;
+
+import javax.net.ssl.SSLEngine;
+
+/**
+ * @author bjorncs
+ */
+public class TlsDetailsFactory {
+ private TlsDetailsFactory() {}
+
+ public static TlsDetails create(SSLEngine e) { return new TlsDetails(e.getSession(), "h2"); /*h2 == HTTP2*/ }
+}
+
diff --git a/vespa-feed-client/src/main/java9/ai/vespa/feed/client/impl/TlsDetailsFactory.java b/vespa-feed-client/src/main/java9/ai/vespa/feed/client/impl/TlsDetailsFactory.java
new file mode 100644
index 00000000000..f9903d9943d
--- /dev/null
+++ b/vespa-feed-client/src/main/java9/ai/vespa/feed/client/impl/TlsDetailsFactory.java
@@ -0,0 +1,20 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package ai.vespa.feed.client.impl;
+
+import org.apache.hc.core5.reactor.ssl.TlsDetails;
+
+import javax.net.ssl.SSLEngine;
+
+/**
+ * {@link SSLEngine#getApplicationProtocol()} is not available on all JDK8 versions
+ * (https://bugs.openjdk.org/browse/JDK-8051498)
+ *
+ * @author bjorncs
+ */
+public class TlsDetailsFactory {
+ private TlsDetailsFactory() {}
+
+ public static TlsDetails create(SSLEngine e) {
+ return new TlsDetails(e.getSession(), e.getApplicationProtocol());
+ }
+}
diff --git a/vespa-hadoop/pom.xml b/vespa-hadoop/pom.xml
index 8060a2d67a1..4dd0ade7499 100644
--- a/vespa-hadoop/pom.xml
+++ b/vespa-hadoop/pom.xml
@@ -220,19 +220,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>${vespaClients.jdk.releaseVersion}</release>
diff --git a/vespa-maven-plugin/pom.xml b/vespa-maven-plugin/pom.xml
index 8f46e5ff35f..c7ea54a3977 100644
--- a/vespa-maven-plugin/pom.xml
+++ b/vespa-maven-plugin/pom.xml
@@ -49,12 +49,6 @@
<artifactId>tenant-cd-api</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- </dependency>
-
<dependency>
<groupId>org.ow2.asm</groupId>
diff --git a/vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/CompileVersionMojo.java b/vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/CompileVersionMojo.java
index 707da31b5ef..4e5c80e1099 100644
--- a/vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/CompileVersionMojo.java
+++ b/vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/CompileVersionMojo.java
@@ -6,6 +6,7 @@ import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.w3c.dom.Element;
+import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -28,7 +29,7 @@ public class CompileVersionMojo extends AbstractVespaMojo {
@Override
protected void doExecute() throws IOException {
Path output = Paths.get(outputFile).toAbsolutePath();
- OptionalInt allowMajor = majorVersion(Paths.get("src/main/application/deployment.xml"));
+ OptionalInt allowMajor = majorVersion(new File(project.getBasedir(), "src/main/application/deployment.xml").toPath());
String compileVersion = controller.compileVersion(id, allowMajor);
if (allowMajor.isPresent()) {
getLog().info("Allowing major version " + allowMajor.getAsInt() + ".");
diff --git a/vespa-osgi-testrunner/pom.xml b/vespa-osgi-testrunner/pom.xml
index ebb1240a198..d89fbe1cf89 100644
--- a/vespa-osgi-testrunner/pom.xml
+++ b/vespa-osgi-testrunner/pom.xml
@@ -27,6 +27,12 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>tenant-cd-api</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -37,23 +43,47 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
- <version>5.8.2</version>
+ <version>5.8.1</version>
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.junit.platform</groupId>
+ <artifactId>junit-platform-commons</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.opentest4j</groupId>
+ <artifactId>opentest4j</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apiguardian</groupId>
+ <artifactId>apiguardian-api</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
- <version>1.8.2</version>
+ <version>1.8.1</version>
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.junit.platform</groupId>
+ <artifactId>junit-platform-commons</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.opentest4j</groupId>
+ <artifactId>opentest4j</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apiguardian</groupId>
+ <artifactId>apiguardian-api</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -65,12 +95,6 @@
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>tenant-cd-api</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>config-provisioning</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
@@ -80,6 +104,11 @@
<artifactId>org.apache.felix.framework</artifactId>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
</dependencies>
<build>
diff --git a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java
index 54f0941208d..d0e8663731a 100644
--- a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java
+++ b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/JunitRunner.java
@@ -4,28 +4,23 @@ package com.yahoo.vespa.testrunner;
import ai.vespa.cloud.Environment;
import ai.vespa.cloud.SystemInfo;
import ai.vespa.cloud.Zone;
-import ai.vespa.hosted.cd.InconclusiveTestException;
import ai.vespa.hosted.cd.internal.TestRuntimeProvider;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.annotation.Inject;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.vespa.defaults.Defaults;
-import com.yahoo.vespa.testrunner.TestReport.ContainerNode;
-import com.yahoo.vespa.testrunner.TestReport.FailureNode;
-import com.yahoo.vespa.testrunner.TestReport.Status;
import org.junit.jupiter.engine.JupiterTestEngine;
+import org.junit.platform.engine.discovery.ClassSelector;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherConfig;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
-import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import java.time.Clock;
import java.util.Collection;
import java.util.List;
-import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.concurrent.CompletableFuture;
@@ -64,9 +59,7 @@ public class JunitRunner extends AbstractComponent implements TestRunner {
this(Clock.systemUTC(),
testRuntimeProvider,
new TestBundleLoader(osgiFramework)::loadTestClasses,
- (discoveryRequest, listeners) -> LauncherFactory.create(LauncherConfig.builder()
- .addTestEngines(new JupiterTestEngine())
- .build()).execute(discoveryRequest, listeners));
+ JunitRunner::executeTests);
uglyHackSetCredentialsRootSystemProperty(config, systemInfo.zone());
@@ -82,6 +75,24 @@ public class JunitRunner extends AbstractComponent implements TestRunner {
this.testRuntimeProvider = testRuntimeProvider;
}
+ private static void executeTests(LauncherDiscoveryRequest discoveryRequest, TestExecutionListener[] listeners) {
+ var launcher = LauncherFactory.create(LauncherConfig.builder()
+ .addTestEngines(new JupiterTestEngine())
+ .build());
+ ClassLoader context = Thread.currentThread().getContextClassLoader();
+ try {
+ // Pick the bundle class loader of the first user test class, from the test class selector.
+ discoveryRequest.getSelectorsByType(ClassSelector.class).stream()
+ .map(selector -> selector.getJavaClass().getClassLoader())
+ .findAny().ifPresent(Thread.currentThread()::setContextClassLoader);
+
+ launcher.execute(discoveryRequest, listeners);
+ }
+ finally {
+ Thread.currentThread().setContextClassLoader(context);
+ }
+ }
+
@Override
public CompletableFuture<?> test(Suite suite, byte[] testConfig) {
if (execution != null && ! execution.isDone()) {
diff --git a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReport.java b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReport.java
index 9aae329d7fb..1641bd7802f 100644
--- a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReport.java
+++ b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReport.java
@@ -20,6 +20,7 @@ import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
+import java.util.logging.Level;
import java.util.logging.LogRecord;
import static java.util.Arrays.copyOf;
@@ -52,7 +53,7 @@ public class TestReport {
if (thrown instanceof OutOfMemoryError) throw (Error) thrown;
TestReport failed = new TestReport(clock, suite);
failed.complete();
- failed.root().children.add(new FailureNode(failed.root(), thrown, suite));
+ failed.root().children.add(new FailureNode(failed.root(), clock.instant(), thrown, suite));
return failed;
}
@@ -126,7 +127,7 @@ public class TestReport {
synchronized (monitor) {
Status status = Status.successful;
if (thrown != null) {
- FailureNode failure = new FailureNode(current, thrown, suite);
+ FailureNode failure = new FailureNode(current, clock.instant(), thrown, suite);
current.children.add(failure);
status = failure.status();
}
@@ -271,22 +272,35 @@ public class TestReport {
}
- public static class FailureNode extends Node {
+ public static class FailureNode extends NamedNode {
private final Throwable thrown;
private final Suite suite;
- public FailureNode(NamedNode parent, Throwable thrown, Suite suite) {
- super(parent);
- this.thrown = thrown;
+ public FailureNode(NamedNode parent, Instant now, Throwable thrown, Suite suite) {
+ super(parent, null, thrown.toString(), now);
trimStackTraces(thrown, JunitRunner.class.getName());
+ this.thrown = thrown;
this.suite = suite;
+
+ LogRecord record = new LogRecord(levelOf(status()), null);
+ record.setThrown(thrown);
+ record.setInstant(now);
+ OutputNode child = new OutputNode(this);
+ child.log.add(record);
+ children.add(child);
}
public Throwable thrown() {
return thrown;
}
+ @Override
+ public Duration duration() {
+ return Duration.ZERO;
+ }
+
+ @Override
public Status status() {
return suite == Suite.PRODUCTION_TEST && thrown instanceof InconclusiveTestException
? Status.inconclusive
@@ -297,16 +311,20 @@ public class TestReport {
public enum Status {
- // Must be kept in order of increasing severity.
- successful,
+ // Must be kept in order of increasing importance.
skipped,
aborted,
+ successful,
inconclusive,
failed,
error;
}
+ static Level levelOf(Status status) {
+ return status.compareTo(Status.failed) >= 0 ? Level.SEVERE : status == Status.successful ? Level.INFO : Level.WARNING;
+ }
+
/**
* Recursively trims stack traces for the given throwable and its causes/suppressed.
* This is based on the assumption that the relevant stack is anything above the first native
diff --git a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReportGeneratingListener.java b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReportGeneratingListener.java
index 0d767f5aa8a..5bc9fda6835 100644
--- a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReportGeneratingListener.java
+++ b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestReportGeneratingListener.java
@@ -110,7 +110,7 @@ class TestReportGeneratingListener implements TestExecutionListener {
? report.abort(testIdentifier)
: report.complete(testIdentifier, testExecutionResult.getThrowable().orElse(null));
Status status = node.status();
- Level level = status.compareTo(Status.failed) >= 0 ? SEVERE : status.compareTo(Status.skipped) >= 0 ? WARNING : INFO;
+ Level level = TestReport.levelOf(status);
if (testIdentifier.isContainer()) {
if (testIdentifier.getParentIdObject().isPresent()) {
diff --git a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestRunnerHandler.java b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestRunnerHandler.java
index b1ca6c84b75..756c3f55ab3 100644
--- a/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestRunnerHandler.java
+++ b/vespa-osgi-testrunner/src/main/java/com/yahoo/vespa/testrunner/TestRunnerHandler.java
@@ -1,6 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.testrunner;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
import com.yahoo.component.annotation.Inject;
import com.yahoo.component.provider.ComponentRegistry;
import com.yahoo.container.jdisc.EmptyResponse;
@@ -9,11 +11,8 @@ import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.ThreadedHttpRequestHandler;
import com.yahoo.exception.ExceptionUtils;
import com.yahoo.restapi.MessageResponse;
-import com.yahoo.restapi.SlimeJsonResponse;
-import com.yahoo.slime.Cursor;
-import com.yahoo.slime.Slime;
-import com.yahoo.vespa.testrunner.TestReport.ContainerNode;
import com.yahoo.vespa.testrunner.TestReport.FailureNode;
+import com.yahoo.vespa.testrunner.TestReport.NamedNode;
import com.yahoo.vespa.testrunner.TestReport.Node;
import com.yahoo.vespa.testrunner.TestReport.OutputNode;
import com.yahoo.vespa.testrunner.TestReport.TestNode;
@@ -21,6 +20,7 @@ import com.yahoo.yolean.Exceptions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.OutputStream;
import java.io.PrintStream;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -42,6 +42,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
public class TestRunnerHandler extends ThreadedHttpRequestHandler {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
+ private static final JsonFactory factory = new JsonFactory();
private final TestRunner testRunner;
@@ -79,15 +80,13 @@ public class TestRunnerHandler extends ThreadedHttpRequestHandler {
long fetchRecordsAfter = Optional.ofNullable(request.getProperty("after"))
.map(Long::parseLong)
.orElse(-1L);
- return new SlimeJsonResponse(logToSlime(testRunner.getLog(fetchRecordsAfter)));
+ return new CustomJsonResponse(out -> render(out, testRunner.getLog(fetchRecordsAfter)));
case "/tester/v1/status":
return new MessageResponse(testRunner.getStatus().name());
case "/tester/v1/report":
TestReport report = testRunner.getReport();
- if (report == null)
- return new EmptyResponse(200);
-
- return new SlimeJsonResponse(toSlime(report));
+ if (report == null) return new EmptyResponse(204);
+ else return new CustomJsonResponse(out -> render(out, report));
}
return new MessageResponse(Status.NOT_FOUND, "Not found: " + request.getUri().getPath());
}
@@ -113,31 +112,30 @@ public class TestRunnerHandler extends ThreadedHttpRequestHandler {
return path.substring(lastSlash + 1);
}
- static Slime logToSlime(Collection<LogRecord> log) {
- Slime slime = new Slime();
- Cursor root = slime.setObject();
- Cursor recordArray = root.setArray("logRecords");
- logArrayToSlime(recordArray, log);
- return slime;
- }
-
- static void logArrayToSlime(Cursor recordArray, Collection<LogRecord> log) {
- log.forEach(record -> {
- Cursor recordObject = recordArray.addObject();
- recordObject.setLong("id", record.getSequenceNumber());
- recordObject.setLong("at", record.getMillis());
- recordObject.setString("type", typeOf(record.getLevel()));
- String message = record.getMessage();
+ private static void render(OutputStream out, Collection<LogRecord> log) throws IOException {
+ var json = factory.createGenerator(out);
+ json.writeStartObject();
+ json.writeArrayFieldStart("logRecords");
+ for (LogRecord record : log) {
+ String message = record.getMessage() == null ? "" : record.getMessage();
if (record.getThrown() != null) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
record.getThrown().printStackTrace(new PrintStream(buffer));
- message += "\n" + buffer;
+ message += (message.isEmpty() ? "" : "\n") + buffer;
}
- recordObject.setString("message", message);
- });
+ json.writeStartObject();
+ json.writeNumberField("id", record.getSequenceNumber());
+ json.writeNumberField("at", record.getMillis());
+ json.writeStringField("type", typeOf(record.getLevel()));
+ json.writeStringField("message", message);
+ json.writeEndObject();
+ }
+ json.writeEndArray();
+ json.writeEndObject();
+ json.close();
}
- public static String typeOf(Level level) {
+ private static String typeOf(Level level) {
return level.getName().equals("html") ? "html"
: level.intValue() < Level.INFO.intValue() ? "debug"
: level.intValue() < Level.WARNING.intValue() ? "info"
@@ -145,85 +143,54 @@ public class TestRunnerHandler extends ThreadedHttpRequestHandler {
: "error";
}
- private static Slime toSlime(TestReport report) {
- var slime = new Slime();
- var root = slime.setObject();
+ private static void render(OutputStream out, TestReport report) throws IOException {
+ JsonGenerator json = factory.createGenerator(out);
+ json.writeStartObject();
- toSlime(root.setObject("report"), (Node) report.root());
+ json.writeFieldName("report");
+ render(json, (Node) report.root());
- // TODO jonmv: remove
- Map<TestReport.Status, Long> tally = report.root().tally();
- var summary = root.setObject("summary");
- summary.setLong("success", tally.getOrDefault(TestReport.Status.successful, 0L));
- summary.setLong("failed", tally.getOrDefault(TestReport.Status.failed, 0L) + tally.getOrDefault(TestReport.Status.error, 0L));
- summary.setLong("ignored", tally.getOrDefault(TestReport.Status.skipped, 0L));
- summary.setLong("aborted", tally.getOrDefault(TestReport.Status.aborted, 0L));
- summary.setLong("inconclusive", tally.getOrDefault(TestReport.Status.inconclusive, 0L));
- toSlime(summary.setArray("failures"), root.setArray("output"), report.root());
-
- return slime;
+ json.writeEndObject();
+ json.close();
}
- static void toSlime(Cursor failuresArray, Cursor outputArray, Node node) {
- for (Node child : node.children())
- TestRunnerHandler.toSlime(failuresArray, outputArray, child);
-
- if (node instanceof FailureNode) {
- Cursor failureObject = failuresArray.addObject();
- failureObject.setString("testName", node.parent.name());
- failureObject.setString("testError", ((FailureNode) node).thrown().getMessage());
- failureObject.setString("exception", ExceptionUtils.getStackTraceAsString(((FailureNode) node).thrown()));
- }
- if (node instanceof OutputNode)
- for (LogRecord record : ((OutputNode) node).log())
- outputArray.addString(formatter.format(record.getInstant().atOffset(ZoneOffset.UTC)) + " " + record.getMessage());
- }
-
- static void toSlime(Cursor nodeObject, Node node) {
- if (node instanceof ContainerNode) toSlime(nodeObject, (ContainerNode) node);
- if (node instanceof TestNode) toSlime(nodeObject, (TestNode) node);
- if (node instanceof OutputNode) toSlime(nodeObject, (OutputNode) node);
- if (node instanceof FailureNode) toSlime(nodeObject, (FailureNode) node);
+ private static void render(JsonGenerator json, Node node) throws IOException {
+ json.writeStartObject();
+ if (node instanceof NamedNode) render(json, (NamedNode) node);
+ if (node instanceof OutputNode) render(json, (OutputNode) node);
if ( ! node.children().isEmpty()) {
- Cursor childrenArray = nodeObject.setArray("children");
- for (Node child : node.children)
- toSlime(childrenArray.addObject(), child);
+ json.writeArrayFieldStart("children");
+ for (Node child : node.children) {
+ render(json, child);
+ }
+ json.writeEndArray();
}
+ json.writeEndObject();
}
- static void toSlime(Cursor nodeObject, ContainerNode node) {
- nodeObject.setString("type", "container");
- nodeObject.setString("name", node.name());
- nodeObject.setString("status", node.status().name());
- nodeObject.setLong("start", node.start().toEpochMilli());
- nodeObject.setLong("duration", node.duration().toMillis());
- }
-
- static void toSlime(Cursor nodeObject, TestNode node) {
- nodeObject.setString("type", "test");
- nodeObject.setString("name", node.name());
- nodeObject.setString("status", node.status().name());
- nodeObject.setLong("start", node.start().toEpochMilli());
- nodeObject.setLong("duration", node.duration().toMillis());
+ private static void render(JsonGenerator json, NamedNode node) throws IOException {
+ String type = node instanceof FailureNode ? "failure" : node instanceof TestNode ? "test" : "container";
+ json.writeStringField("type", type);
+ json.writeStringField("name", node.name());
+ json.writeStringField("status", node.status().name());
+ json.writeNumberField("start", node.start().toEpochMilli());
+ json.writeNumberField("duration", node.duration().toMillis());
}
- static void toSlime(Cursor nodeObject, OutputNode node) {
- nodeObject.setString("type", "output");
- Cursor childrenArray = nodeObject.setArray("children");
+ private static void render(JsonGenerator json, OutputNode node) throws IOException {
+ json.writeStringField("type", "output");
+ json.writeArrayFieldStart("children");
for (LogRecord record : node.log()) {
- Cursor recordObject = childrenArray.addObject();
- recordObject.setString("message", (record.getLoggerName() == null ? "" : record.getLoggerName() + ": ") + record.getMessage());
- recordObject.setLong("at", record.getInstant().toEpochMilli());
- recordObject.setString("level", typeOf(record.getLevel()));
- if (record.getThrown() != null) recordObject.setString("trace", traceToString(record.getThrown()));
+ json.writeStartObject();
+ json.writeStringField("message", (record.getLoggerName() == null ? "" : record.getLoggerName() + ": ") +
+ (record.getMessage() != null ? record.getMessage() : "") +
+ (record.getThrown() != null ? (record.getMessage() != null ? "\n" : "") + traceToString(record.getThrown()) : ""));
+ json.writeNumberField("at", record.getInstant().toEpochMilli());
+ json.writeStringField("level", typeOf(record.getLevel()));
+ json.writeEndObject();
}
- }
-
- static void toSlime(Cursor nodeObject, FailureNode node) {
- nodeObject.setString("type", "failure");
- nodeObject.setString("status", node.status().name());
- nodeObject.setString("trace", traceToString(node.thrown()));
+ json.writeEndArray();
}
private static String traceToString(Throwable thrown) {
@@ -232,4 +199,36 @@ public class TestRunnerHandler extends ThreadedHttpRequestHandler {
return buffer.toString(UTF_8);
}
+ private interface Renderer {
+
+ void render(OutputStream out) throws IOException;
+
+ }
+
+ private static class CustomJsonResponse extends HttpResponse {
+
+ private final Renderer renderer;
+
+ private CustomJsonResponse(Renderer renderer) {
+ super(200);
+ this.renderer = renderer;
+ }
+
+ @Override
+ public void render(OutputStream outputStream) throws IOException {
+ renderer.render(outputStream);
+ }
+
+ @Override
+ public String getContentType() {
+ return "application/json";
+ }
+
+ @Override
+ public long maxPendingBytes() {
+ return 1 << 25; // 32MB
+ }
+
+ }
+
}
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledClassTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledClassTest.java
index 795bf8c6a1e..417ca4b6c9e 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledClassTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledClassTest.java
@@ -5,7 +5,7 @@ import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled("because")
-@Expect(skipped = 2, status = 1)
+@Expect(skipped = 2, status = 2)
public class DisabledClassTest {
@Test
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledTest.java
index 561ec81e865..be36954d1bb 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/DisabledTest.java
@@ -4,7 +4,7 @@ import com.yahoo.vespa.testrunner.Expect;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
-@Expect(skipped = 1, status = 1)
+@Expect(skipped = 1, status = 2)
public class DisabledTest {
@Test
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SampleTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SampleTest.java
index bc878353d4b..b0e5119c06e 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SampleTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SampleTest.java
@@ -71,7 +71,7 @@ public class SampleTest {
@Test
void successful() {
log.log(new Level("html", INFO.intValue()) { }, "<body />");
- log.log(INFO, "Very informative");
+ log.log(INFO, "Very informative: \"\\n\": \n");
log.log(WARNING, "Oh no", new IllegalArgumentException("error", new RuntimeException("wrapped")));
}
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SucceedingTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SucceedingTest.java
index 59a56a1c9c7..8fd25d618a9 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SucceedingTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/SucceedingTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.test.samples;
import com.yahoo.vespa.testrunner.Expect;
import org.junit.jupiter.api.Test;
-@Expect(successful = 1, status = 0)
+@Expect(successful = 1, status = 2)
public class SucceedingTest {
@Test
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/UsingTestRuntimeTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/UsingTestRuntimeTest.java
index 62547bd34bf..67b236f75a2 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/UsingTestRuntimeTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/test/samples/UsingTestRuntimeTest.java
@@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
-@Expect(successful = 1, status = 0)
+@Expect(successful = 1, status = 2)
public class UsingTestRuntimeTest {
@Test
diff --git a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/testrunner/TestRunnerHandlerTest.java b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/testrunner/TestRunnerHandlerTest.java
index 5ce737d7649..6d6fbbf2cf1 100644
--- a/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/testrunner/TestRunnerHandlerTest.java
+++ b/vespa-osgi-testrunner/src/test/java/com/yahoo/vespa/testrunner/TestRunnerHandlerTest.java
@@ -27,7 +27,6 @@ import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
-import java.util.logging.Level;
import java.util.logging.LogRecord;
import static com.yahoo.jdisc.http.HttpRequest.Method.GET;
@@ -136,14 +135,6 @@ class TestRunnerHandlerTest {
}
}
- /* Creates a LogRecord that has a known instant and sequence number to get predictable serialization results. */
- private static LogRecord logRecord(String logMessage) {
- LogRecord logRecord = new LogRecord(Level.INFO, logMessage);
- logRecord.setInstant(testInstant);
- logRecord.setSequenceNumber(0);
- return logRecord;
- }
-
private static class MockRunner implements TestRunner {
private final TestRunner.Status status;
diff --git a/vespa-osgi-testrunner/src/test/resources/output.json b/vespa-osgi-testrunner/src/test/resources/output.json
index 04682fa9f31..2b4aa9e5599 100644
--- a/vespa-osgi-testrunner/src/test/resources/output.json
+++ b/vespa-osgi-testrunner/src/test/resources/output.json
@@ -1,18 +1,24 @@
{
"logRecords": [
{
- "id": 3,
+ "id": 2,
"at": 0,
"type": "info",
"message": "spam"
},
{
- "id": 6,
+ "id": 5,
"at": 0,
"type": "info",
"message": "spam"
},
{
+ "id": 6,
+ "at": 0,
+ "type": "error",
+ "message": "java.lang.NoClassDefFoundError\n\tat com.yahoo.vespa.test.samples.SampleTest.error(SampleTest.java:87)\n"
+ },
+ {
"id": 9,
"at": 0,
"type": "info",
@@ -25,58 +31,106 @@
"message": "I have a bad feeling about this"
},
{
- "id": 14,
+ "id": 11,
+ "at": 0,
+ "type": "error",
+ "message": "org.opentest4j.AssertionFailedError: baz ==> expected: <foo> but was: <bar>\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)\n\tat org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)\n\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)\n\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1152)\n\tat com.yahoo.vespa.test.samples.SampleTest.failing(SampleTest.java:81)\n"
+ },
+ {
+ "id": 15,
"at": 0,
"type": "info",
"message": "spam"
},
{
- "id": 15,
+ "id": 16,
"at": 0,
"type": "info",
"message": "I'm here with Erwin today; Erwin, what can you tell us about your cat?"
},
{
- "id": 18,
+ "id": 17,
+ "at": 0,
+ "type": "warning",
+ "message": "ai.vespa.hosted.cd.InconclusiveTestException: the cat is both dead _and_ alive\n\tat com.yahoo.vespa.test.samples.SampleTest.inconclusive(SampleTest.java:93)\n"
+ },
+ {
+ "id": 20,
"at": 0,
"type": "info",
"message": "spam"
},
{
- "id": 19,
+ "id": 21,
"at": 0,
"type": "info",
"message": "<body />"
},
{
- "id": 20,
+ "id": 22,
"at": 0,
"type": "info",
- "message": "Very informative"
+ "message": "Very informative: \"\\n\": \n"
},
{
- "id": 21,
+ "id": 23,
"at": 0,
"type": "warning",
"message": "Oh no\njava.lang.IllegalArgumentException: error\n\tat com.yahoo.vespa.test.samples.SampleTest.successful(SampleTest.java:75)\nCaused by: java.lang.RuntimeException: wrapped\n\t... 1 more\n"
},
{
- "id": 25,
+ "id": 27,
"at": 0,
"type": "info",
"message": "spam"
},
{
- "id": 28,
+ "id": 30,
"at": 0,
"type": "info",
"message": "Catch me if you can!"
},
{
- "id": 35,
+ "id": 34,
+ "at": 0,
+ "type": "error",
+ "message": "org.opentest4j.AssertionFailedError: no charm\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:134)\n\tat com.yahoo.vespa.test.samples.SampleTest$Inner.lambda$others$1(SampleTest.java:105)\n"
+ },
+ {
+ "id": 38,
"at": 0,
"type": "info",
"message": "spam"
+ },
+ {
+ "id": 67,
+ "at": 0,
+ "type": "error",
+ "message": "org.opentest4j.AssertionFailedError\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:35)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:115)\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.test(FailingTestAndBothAftersTest.java:19)\n\tSuppressed: java.lang.RuntimeException\n\t\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.moreFail(FailingTestAndBothAftersTest.java:16)\n"
+ },
+ {
+ "id": 69,
+ "at": 0,
+ "type": "error",
+ "message": "java.lang.RuntimeException\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.fail(FailingTestAndBothAftersTest.java:13)\n"
+ },
+ {
+ "id": 72,
+ "at": 0,
+ "type": "error",
+ "message": "org.junit.platform.commons.JUnitException: @BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).\n"
+ },
+ {
+ "id": 76,
+ "at": 0,
+ "type": "error",
+ "message": "java.lang.NullPointerException\n\tat com.yahoo.vespa.test.samples.FailingExtensionTest$FailingExtension.<init>(FailingExtensionTest.java:19)\n"
+ },
+ {
+ "id": 80,
+ "at": 12000,
+ "type": "error",
+ "message": "java.lang.ClassNotFoundException: School's out all summer!\n"
}
]
}
diff --git a/vespa-osgi-testrunner/src/test/resources/report.json b/vespa-osgi-testrunner/src/test/resources/report.json
index 9c41a83a6b5..66ae6dd398c 100644
--- a/vespa-osgi-testrunner/src/test/resources/report.json
+++ b/vespa-osgi-testrunner/src/test/resources/report.json
@@ -58,8 +58,22 @@
},
{
"type": "failure",
+ "name": "java.lang.NoClassDefFoundError",
"status": "error",
- "trace": "java.lang.NoClassDefFoundError\n\tat com.yahoo.vespa.test.samples.SampleTest.error(SampleTest.java:87)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "java.lang.NoClassDefFoundError\n\tat com.yahoo.vespa.test.samples.SampleTest.error(SampleTest.java:87)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
},
@@ -87,8 +101,22 @@
},
{
"type": "failure",
+ "name": "org.opentest4j.AssertionFailedError: baz ==> expected: <foo> but was: <bar>",
"status": "failed",
- "trace": "org.opentest4j.AssertionFailedError: baz ==> expected: <foo> but was: <bar>\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)\n\tat org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)\n\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)\n\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1152)\n\tat com.yahoo.vespa.test.samples.SampleTest.failing(SampleTest.java:81)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "org.opentest4j.AssertionFailedError: baz ==> expected: <foo> but was: <bar>\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)\n\tat org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)\n\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)\n\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1152)\n\tat com.yahoo.vespa.test.samples.SampleTest.failing(SampleTest.java:81)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
},
@@ -123,8 +151,22 @@
},
{
"type": "failure",
+ "name": "ai.vespa.hosted.cd.InconclusiveTestException: the cat is both dead _and_ alive",
"status": "inconclusive",
- "trace": "ai.vespa.hosted.cd.InconclusiveTestException: the cat is both dead _and_ alive\n\tat com.yahoo.vespa.test.samples.SampleTest.inconclusive(SampleTest.java:93)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "ai.vespa.hosted.cd.InconclusiveTestException: the cat is both dead _and_ alive\n\tat com.yahoo.vespa.test.samples.SampleTest.inconclusive(SampleTest.java:93)\n",
+ "at": 0,
+ "level": "warning"
+ }
+ ]
+ }
+ ]
}
]
},
@@ -149,15 +191,14 @@
"level": "info"
},
{
- "message": "com.yahoo.vespa.test.samples.SampleTest: Very informative",
+ "message": "com.yahoo.vespa.test.samples.SampleTest: Very informative: \"\\n\": \n",
"at": 0,
"level": "info"
},
{
- "message": "com.yahoo.vespa.test.samples.SampleTest: Oh no",
+ "message": "com.yahoo.vespa.test.samples.SampleTest: Oh no\njava.lang.IllegalArgumentException: error\n\tat com.yahoo.vespa.test.samples.SampleTest.successful(SampleTest.java:75)\nCaused by: java.lang.RuntimeException: wrapped\n\t... 1 more\n",
"at": 0,
- "level": "warning",
- "trace": "java.lang.IllegalArgumentException: error\n\tat com.yahoo.vespa.test.samples.SampleTest.successful(SampleTest.java:75)\nCaused by: java.lang.RuntimeException: wrapped\n\t... 1 more\n"
+ "level": "warning"
}
]
}
@@ -215,8 +256,22 @@
"children": [
{
"type": "failure",
+ "name": "org.opentest4j.AssertionFailedError: no charm",
"status": "failed",
- "trace": "org.opentest4j.AssertionFailedError: no charm\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:134)\n\tat com.yahoo.vespa.test.samples.SampleTest$Inner.lambda$others$1(SampleTest.java:105)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "org.opentest4j.AssertionFailedError: no charm\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:134)\n\tat com.yahoo.vespa.test.samples.SampleTest$Inner.lambda$others$1(SampleTest.java:105)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
}
@@ -286,15 +341,43 @@
"children": [
{
"type": "failure",
+ "name": "org.opentest4j.AssertionFailedError",
"status": "failed",
- "trace": "org.opentest4j.AssertionFailedError\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:35)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:115)\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.test(FailingTestAndBothAftersTest.java:19)\n\tSuppressed: java.lang.RuntimeException\n\t\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.moreFail(FailingTestAndBothAftersTest.java:16)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "org.opentest4j.AssertionFailedError\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:35)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:115)\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.test(FailingTestAndBothAftersTest.java:19)\n\tSuppressed: java.lang.RuntimeException\n\t\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.moreFail(FailingTestAndBothAftersTest.java:16)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
},
{
"type": "failure",
+ "name": "java.lang.RuntimeException",
"status": "error",
- "trace": "java.lang.RuntimeException\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.fail(FailingTestAndBothAftersTest.java:13)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "java.lang.RuntimeException\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.fail(FailingTestAndBothAftersTest.java:13)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
},
@@ -307,8 +390,22 @@
"children": [
{
"type": "failure",
+ "name": "org.junit.platform.commons.JUnitException: @BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).",
"status": "error",
- "trace": "org.junit.platform.commons.JUnitException: @BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "org.junit.platform.commons.JUnitException: @BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
},
{
"type": "test",
@@ -342,8 +439,22 @@
"children": [
{
"type": "failure",
+ "name": "java.lang.NullPointerException",
"status": "error",
- "trace": "java.lang.NullPointerException\n\tat com.yahoo.vespa.test.samples.FailingExtensionTest$FailingExtension.<init>(FailingExtensionTest.java:19)\n"
+ "start": 0,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "java.lang.NullPointerException\n\tat com.yahoo.vespa.test.samples.FailingExtensionTest$FailingExtension.<init>(FailingExtensionTest.java:19)\n",
+ "at": 0,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
}
@@ -353,78 +464,23 @@
},
{
"type": "failure",
+ "name": "java.lang.ClassNotFoundException: School's out all summer!",
"status": "error",
- "trace": "java.lang.ClassNotFoundException: School's out all summer!\n"
- }
- ]
- },
- "summary": {
- "success": 3,
- "failed": 5,
- "ignored": 4,
- "aborted": 1,
- "inconclusive": 1,
- "failures": [
- {
- "testName": "error()",
- "testError": null,
- "exception": "java.lang.NoClassDefFoundError\n\tat com.yahoo.vespa.test.samples.SampleTest.error(SampleTest.java:87)\n"
- },
- {
- "testName": "failing()",
- "testError": "baz ==> expected: <foo> but was: <bar>",
- "exception": "org.opentest4j.AssertionFailedError: baz ==> expected: <foo> but was: <bar>\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)\n\tat org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)\n\tat org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)\n\tat org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1152)\n\tat com.yahoo.vespa.test.samples.SampleTest.failing(SampleTest.java:81)\n"
- },
- {
- "testName": "inconclusive(TestReporter)",
- "testError": "the cat is both dead _and_ alive",
- "exception": "ai.vespa.hosted.cd.InconclusiveTestException: the cat is both dead _and_ alive\n\tat com.yahoo.vespa.test.samples.SampleTest.inconclusive(SampleTest.java:93)\n"
- },
- {
- "testName": "third",
- "testError": "no charm",
- "exception": "org.opentest4j.AssertionFailedError: no charm\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:134)\n\tat com.yahoo.vespa.test.samples.SampleTest$Inner.lambda$others$1(SampleTest.java:105)\n"
- },
- {
- "testName": "test()",
- "testError": "",
- "exception": "org.opentest4j.AssertionFailedError\n\tat org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:35)\n\tat org.junit.jupiter.api.Assertions.fail(Assertions.java:115)\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.test(FailingTestAndBothAftersTest.java:19)\n\tSuppressed: java.lang.RuntimeException\n\t\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.moreFail(FailingTestAndBothAftersTest.java:16)\n"
- },
- {
- "testName": "FailingTestAndBothAftersTest",
- "testError": null,
- "exception": "java.lang.RuntimeException\n\tat com.yahoo.vespa.test.samples.FailingTestAndBothAftersTest.fail(FailingTestAndBothAftersTest.java:13)\n"
- },
- {
- "testName": "WrongBeforeAllTest",
- "testError": "@BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).",
- "exception": "org.junit.platform.commons.JUnitException: @BeforeAll method 'void com.yahoo.vespa.test.samples.WrongBeforeAllTest.wrong()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).\n"
- },
- {
- "testName": "test()",
- "testError": null,
- "exception": "java.lang.NullPointerException\n\tat com.yahoo.vespa.test.samples.FailingExtensionTest$FailingExtension.<init>(FailingExtensionTest.java:19)\n"
- },
- {
- "testName": "Production test",
- "testError": "School's out all summer!",
- "exception": "java.lang.ClassNotFoundException: School's out all summer!\n"
+ "start": 12000,
+ "duration": 0,
+ "children": [
+ {
+ "type": "output",
+ "children": [
+ {
+ "message": "java.lang.ClassNotFoundException: School's out all summer!\n",
+ "at": 12000,
+ "level": "error"
+ }
+ ]
+ }
+ ]
}
]
- },
- "output": [
- "00:00:00.000 spam",
- "00:00:00.000 spam",
- "00:00:00.000 spam",
- "00:00:00.000 I have a bad feeling about this",
- "00:00:00.000 spam",
- "00:00:00.000 I'm here with Erwin today; Erwin, what can you tell us about your cat?",
- "00:00:00.000 spam",
- "00:00:00.000 <body />",
- "00:00:00.000 Very informative",
- "00:00:00.000 Oh no",
- "00:00:00.000 spam",
- "00:00:00.000 Catch me if you can!",
- "00:00:00.000 spam"
- ]
+ }
}
diff --git a/vespabase/desc.services b/vespabase/desc.services
deleted file mode 100644
index b92af60e802..00000000000
--- a/vespabase/desc.services
+++ /dev/null
@@ -1,14 +0,0 @@
-CloudConfig Runtime Environment
-
-The services package contains (via dependencies)
-common runtime cloudconfig components.
-
-The services package adds a set of environment settings that are used by several
-of the control scripts and binaries that use cloud config. The
-current list looks like this:
-
-# set port_configserver_rpc
-# set addr_configserver
-
-These values allow the other components to locate the configuration
-server, thus enabling them to get their config.
diff --git a/vespabase/desc.vespa_base b/vespabase/desc.vespa_base
deleted file mode 100644
index 965fdaffdbb..00000000000
--- a/vespabase/desc.vespa_base
+++ /dev/null
@@ -1,36 +0,0 @@
-Vespa Runtime Environment
-
-The vespa_base package contains (via dependencies)
-common runtime Vespa components.
-
-Runtime libraries for c++ and java:
-
- * vespa_gcc3 vespa_gcc_runtime: C++ runtime
- * libiconv: Iconv shared library.
-
-General utilities:
-
- * vespa_log: Vespa log handling utilities.
- * vespa_gdb: A version of gdb that works with the Vespa compiler.
- * ywget: Commandline URL-getter.
-
-Required services that will always be present on a vespa node:
-
- * vespa_configd: The vespa service starter (config-sentinel).
- * vespa_config_proxy: Local daemon for communication with the
- configuration server.
- * vespa_logd: Local daemon for forwarding the vespa.log to the
- logserver.
- * vespa_slobrok: Service Location Broker used by the messaging layer.
-
-Settings for the runtime environment
-
-Vespa Base adds a set of environment settings that are used by several
-of the control scripts and binaries that are part of Vespa. The
-current list looks like this:
-
-# set port_configserver_rpc
-# set addr_configserver
-
-These values allow the other components to locate the configuration
-server, thus enabling them to get their config.
diff --git a/vespabase/desc.vespa_base_dev b/vespabase/desc.vespa_base_dev
deleted file mode 100644
index 1f05be94257..00000000000
--- a/vespabase/desc.vespa_base_dev
+++ /dev/null
@@ -1,35 +0,0 @@
-Vespa Developer libraries
-
-Vespa Base, in the package vespa_base_dev, contain a set of development
-libraries and utilities for use when developing you vespa service.
-The following is a short list.
-
-Vespa specific libraries:
-
- * vespa_config_dev: config code generator and include-files and
- libraries for the basic datatypes. Both for Java and C++.
- * vespa_log and vespa_log_dev: Log-handling utilities, and log
- libraries for Java and C++
- * vespa_document_dev: C++ headers and static library, and Java
- jar file, for working with Vespa document objects. This is the
- basic element of the Vespa framework.
- * vespa_slobrok and vespa_slobrok_dev: The actual Service
- Location Broker component, as well as C++ headers and libraries
- for being a slobrok client or server.
-
-Generic libraries:
-
- * vespa_fastlib and vespa_fastlib_dev: Misc utilities library
- containing unicode processing and an HTTP server, among other
- things. Used by some Vespa components for legacy reasons.
- * vespa_fastos_dev: OS abstraction layer and generic build
- management utilities.
- * vespa_fnet_dev: General purpose network library, with an RPC
- layer. C/C++ headers and libraries.
- * vespa_vespajlib_dev: Misc utility classes for Java.
- * vespa_vespalib_dev: Misc utility classes for C++.
-
-Development tools and 3rd party libraries:
-
- * vespa_boost_dev: Boost headers,
- prepared for use with the Vespa compiler.
diff --git a/vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/resource/DocumentV1ApiHandler.java b/vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/resource/DocumentV1ApiHandler.java
index 7f940e5695a..c72bc1ef4c5 100644
--- a/vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/resource/DocumentV1ApiHandler.java
+++ b/vespaclient-container-plugin/src/main/java/com/yahoo/document/restapi/resource/DocumentV1ApiHandler.java
@@ -20,7 +20,6 @@ import com.yahoo.document.DocumentUpdate;
import com.yahoo.document.FixedBucketSpaces;
import com.yahoo.document.TestAndSetCondition;
import com.yahoo.document.config.DocumentmanagerConfig;
-import com.yahoo.document.fieldset.AllFields;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.document.fieldset.DocumentOnly;
import com.yahoo.document.idstring.IdIdString;
@@ -169,6 +168,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
private static final String STREAM = "stream";
private static final String SLICES = "slices";
private static final String SLICE_ID = "sliceId";
+ private static final String DRY_RUN = "dryRun";
private final Clock clock;
private final Duration handlerTimeout;
@@ -362,6 +362,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
}
private ContentChannel getDocuments(HttpRequest request, DocumentPath path, ResponseHandler handler) {
+ disallow(request, DRY_RUN);
enqueueAndDispatch(request, handler, () -> {
boolean streamed = getProperty(request, STREAM, booleanParser).orElse(false);
VisitorParameters parameters = parseGetParameters(request, path, streamed);
@@ -374,6 +375,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
}
private ContentChannel postDocuments(HttpRequest request, DocumentPath path, ResponseHandler handler) {
+ disallow(request, DRY_RUN);
enqueueAndDispatch(request, handler, () -> {
StorageCluster destination = resolveCluster(Optional.of(requireProperty(request, DESTINATION_CLUSTER)), clusters);
VisitorParameters parameters = parseParameters(request, path);
@@ -388,6 +390,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
}
private ContentChannel putDocuments(HttpRequest request, DocumentPath path, ResponseHandler handler) {
+ disallow(request, DRY_RUN);
return new ForwardingContentChannel(in -> {
enqueueAndDispatch(request, handler, () -> {
StorageCluster cluster = resolveCluster(Optional.of(requireProperty(request, CLUSTER)), clusters);
@@ -406,6 +409,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
}
private ContentChannel deleteDocuments(HttpRequest request, DocumentPath path, ResponseHandler handler) {
+ disallow(request, DRY_RUN);
enqueueAndDispatch(request, handler, () -> {
VisitorParameters parameters = parseParameters(request, path);
parameters.setFieldSet(DocIdOnly.NAME);
@@ -420,6 +424,7 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
}
private ContentChannel getDocument(HttpRequest request, DocumentPath path, ResponseHandler handler) {
+ disallow(request, DRY_RUN);
enqueueAndDispatch(request, handler, () -> {
DocumentOperationParameters rawParameters = parametersFromRequest(request, CLUSTER, FIELD_SET);
if (rawParameters.fieldSet().isEmpty())
@@ -442,6 +447,11 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
private ContentChannel postDocument(HttpRequest request, DocumentPath path, ResponseHandler rawHandler) {
ResponseHandler handler = new MeasuringResponseHandler(rawHandler, com.yahoo.documentapi.metrics.DocumentOperationType.PUT, clock.instant());
+ if (getProperty(request, DRY_RUN, booleanParser).orElse(false)) {
+ handleFeedOperation(path, handler, new com.yahoo.documentapi.Response(-1));
+ return ignoredContent;
+ }
+
return new ForwardingContentChannel(in -> {
enqueueAndDispatch(request, handler, () -> {
DocumentPut put = parser.parsePut(in, path.id().toString());
@@ -459,6 +469,11 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
private ContentChannel putDocument(HttpRequest request, DocumentPath path, ResponseHandler rawHandler) {
ResponseHandler handler = new MeasuringResponseHandler(rawHandler, com.yahoo.documentapi.metrics.DocumentOperationType.UPDATE, clock.instant());
+ if (getProperty(request, DRY_RUN, booleanParser).orElse(false)) {
+ handleFeedOperation(path, handler, new com.yahoo.documentapi.Response(-1));
+ return ignoredContent;
+ }
+
return new ForwardingContentChannel(in -> {
enqueueAndDispatch(request, handler, () -> {
DocumentUpdate update = parser.parseUpdate(in, path.id().toString());
@@ -477,6 +492,11 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
private ContentChannel deleteDocument(HttpRequest request, DocumentPath path, ResponseHandler rawHandler) {
ResponseHandler handler = new MeasuringResponseHandler(rawHandler, com.yahoo.documentapi.metrics.DocumentOperationType.REMOVE, clock.instant());
+ if (getProperty(request, DRY_RUN, booleanParser).orElse(false)) {
+ handleFeedOperation(path, handler, new com.yahoo.documentapi.Response(-1));
+ return ignoredContent;
+ }
+
enqueueAndDispatch(request, handler, () -> {
DocumentRemove remove = new DocumentRemove(path.id());
getProperty(request, CONDITION).map(TestAndSetCondition::new).ifPresent(remove::setCondition);
@@ -1062,19 +1082,19 @@ public class DocumentV1ApiHandler extends AbstractRequestHandler {
private void updatePutMetrics(Outcome outcome) {
switch (outcome) {
- case SUCCESS: metric.add(MetricNames.SUCCEEDED, 1, null); break;
- case CONDITION_FAILED: metric.add(MetricNames.CONDITION_NOT_MET, 1, null); break;
- default: metric.add(MetricNames.FAILED, 1, null); break;
+ case SUCCESS -> metric.add(MetricNames.SUCCEEDED, 1, null);
+ case CONDITION_FAILED -> metric.add(MetricNames.CONDITION_NOT_MET, 1, null);
+ default -> metric.add(MetricNames.FAILED, 1, null);
}
}
private void updateUpdateMetrics(Outcome outcome, boolean create) {
if (create && outcome == Outcome.NOT_FOUND) outcome = Outcome.SUCCESS; // >_<
switch (outcome) {
- case SUCCESS: metric.add(MetricNames.SUCCEEDED, 1, null); break;
- case NOT_FOUND: metric.add(MetricNames.NOT_FOUND, 1, null); break;
- case CONDITION_FAILED: metric.add(MetricNames.CONDITION_NOT_MET, 1, null); break;
- default: metric.add(MetricNames.FAILED, 1, null); break;
+ case SUCCESS -> metric.add(MetricNames.SUCCEEDED, 1, null);
+ case NOT_FOUND -> metric.add(MetricNames.NOT_FOUND, 1, null);
+ case CONDITION_FAILED -> metric.add(MetricNames.CONDITION_NOT_MET, 1, null);
+ default -> metric.add(MetricNames.FAILED, 1, null);
}
}
diff --git a/vespaclient-container-plugin/src/test/java/com/yahoo/document/restapi/resource/DocumentV1ApiTest.java b/vespaclient-container-plugin/src/test/java/com/yahoo/document/restapi/resource/DocumentV1ApiTest.java
index 74a86b6a7b7..7f77ce9d0d5 100644
--- a/vespaclient-container-plugin/src/test/java/com/yahoo/document/restapi/resource/DocumentV1ApiTest.java
+++ b/vespaclient-container-plugin/src/test/java/com/yahoo/document/restapi/resource/DocumentV1ApiTest.java
@@ -524,6 +524,79 @@ public class DocumentV1ApiTest {
"}", response.readAll());
assertEquals(404, response.getStatus());
+ // GET with dryRun=true is an error
+ access.session.expect((__, ___) -> {
+ fail("Should not cause an actual feed operation");
+ return null;
+ });
+ response = driver.sendRequest("http://localhost/document/v1/space/music/number/1/two?dryRun=true");
+ assertSameJson("{" +
+ " \"pathId\": \"/document/v1/space/music/number/1/two\"," +
+ " \"message\": \"May not specify 'dryRun' at '/document/v1/space/music/number/1/two'\"\n" +
+ "}", response.readAll());
+ assertEquals(400, response.getStatus());
+
+ // POST with dryRun=true returns an immediate OK response
+ access.session.expect((__, ___) -> {
+ fail("Should not cause an actual feed operation");
+ return null;
+ });
+ response = driver.sendRequest("http://localhost/document/v1/space/music/number/1/two?dryRun=true", POST,
+ "NOT JSON, NOT PARSED");
+ assertSameJson("{" +
+ " \"pathId\": \"/document/v1/space/music/number/1/two\"," +
+ " \"id\": \"id:space:music:n=1:two\"" +
+ "}", response.readAll());
+ assertEquals(200, response.getStatus());
+
+ // PUT with dryRun=true returns an immediate OK response
+ access.session.expect((__, ___) -> {
+ fail("Should not cause an actual feed operation");
+ return null;
+ });
+ response = driver.sendRequest("http://localhost/document/v1/space/music/number/1/two?dryRun=true", PUT,
+ "NOT JSON, NOT PARSED");
+ assertSameJson("{" +
+ " \"pathId\": \"/document/v1/space/music/number/1/two\"," +
+ " \"id\": \"id:space:music:n=1:two\"" +
+ "}", response.readAll());
+ assertEquals(200, response.getStatus());
+
+ // DELETE with dryRun=true returns an immediate OK response
+ access.session.expect((__, ___) -> {
+ fail("Should not cause an actual feed operation");
+ return null;
+ });
+ response = driver.sendRequest("http://localhost/document/v1/space/music/number/1/two?dryRun=true", DELETE,
+ "NOT JSON, NOT PARSED");
+ assertSameJson("{" +
+ " \"pathId\": \"/document/v1/space/music/number/1/two\"," +
+ " \"id\": \"id:space:music:n=1:two\"" +
+ "}", response.readAll());
+ assertEquals(200, response.getStatus());
+
+ // PUT with a document update payload is a document update operation.
+ access.session.expect((update, parameters) -> {
+ DocumentUpdate expectedUpdate = new DocumentUpdate(doc3.getDataType(), doc3.getId());
+ expectedUpdate.addFieldUpdate(FieldUpdate.createAssign(doc3.getField("artist"), new StringFieldValue("Lisa Ekdahl")));
+ expectedUpdate.setCreateIfNonExistent(true);
+ assertEquals(expectedUpdate, update);
+ assertEquals(parameters(), parameters);
+ parameters.responseHandler().get().handleResponse(new UpdateResponse(0, true));
+ return new Result();
+ });
+ response = driver.sendRequest("http://localhost/document/v1/space/music/group/a/three?create=true&timeout=1e1s&dryRun=false", PUT,
+ "{" +
+ " \"fields\": {" +
+ " \"artist\": { \"assign\": \"Lisa Ekdahl\" }" +
+ " }" +
+ "}");
+ assertSameJson("{" +
+ " \"pathId\": \"/document/v1/space/music/group/a/three\"," +
+ " \"id\": \"id:space:music:g=a:three\"" +
+ "}", response.readAll());
+ assertEquals(200, response.getStatus());
+
// POST with a document payload is a document put operation.
access.session.expect((put, parameters) -> {
DocumentPut expectedPut = new DocumentPut(doc2);
@@ -566,28 +639,6 @@ public class DocumentV1ApiTest {
"}", response.readAll());
assertEquals(200, response.getStatus());
- // PUT with a document update payload is a document update operation.
- access.session.expect((update, parameters) -> {
- DocumentUpdate expectedUpdate = new DocumentUpdate(doc3.getDataType(), doc3.getId());
- expectedUpdate.addFieldUpdate(FieldUpdate.createAssign(doc3.getField("artist"), new StringFieldValue("Lisa Ekdahl")));
- expectedUpdate.setCreateIfNonExistent(true);
- assertEquals(expectedUpdate, update);
- assertEquals(parameters(), parameters);
- parameters.responseHandler().get().handleResponse(new UpdateResponse(0, true));
- return new Result();
- });
- response = driver.sendRequest("http://localhost/document/v1/space/music/group/a/three?create=true&timeout=1e1s", PUT,
- "{" +
- " \"fields\": {" +
- " \"artist\": { \"assign\": \"Lisa Ekdahl\" }" +
- " }" +
- "}");
- assertSameJson("{" +
- " \"pathId\": \"/document/v1/space/music/group/a/three\"," +
- " \"id\": \"id:space:music:g=a:three\"" +
- "}", response.readAll());
- assertEquals(200, response.getStatus());
-
// POST with no payload is a 400
access.session.expect((__, ___) -> { throw new AssertionError("Not supposed to happen"); });
response = driver.sendRequest("http://localhost/document/v1/space/music/number/1/two?condition=test%20it", POST, "");
diff --git a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerTest.java b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerTest.java
index f3ea8fb5a80..2fc34112517 100644
--- a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerTest.java
+++ b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerTest.java
@@ -25,7 +25,7 @@ public class FeedHandlerTest {
FeedHandler handler = new FeedHandler(
new RejectingContainerThreadpool(),
new CollectingMetric(),
- new DocumentTypeManager(new DocumentmanagerConfig.Builder().enablecompression(true).build()),
+ new DocumentTypeManager(new DocumentmanagerConfig.Builder().build()),
null /* session cache */,
MetricReceiver.nullImplementation);
var responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
diff --git a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerV3Test.java b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerV3Test.java
index dcabc1f338e..5b8b5b1827f 100644
--- a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerV3Test.java
+++ b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/FeedHandlerV3Test.java
@@ -108,7 +108,7 @@ public class FeedHandlerV3Test {
}
private FeedHandlerV3 setupFeederHandler(Executor threadPool) {
- DocumentTypeManager docMan = new DocumentTypeManager(new DocumentmanagerConfig.Builder().enablecompression(true).build());
+ DocumentTypeManager docMan = new DocumentTypeManager(new DocumentmanagerConfig.Builder().build());
FeedHandlerV3 feedHandlerV3 = new FeedHandlerV3(
threadPool,
metric,
diff --git a/vespaclient-core/src/main/java/com/yahoo/vespaclient/ClusterList.java b/vespaclient-core/src/main/java/com/yahoo/vespaclient/ClusterList.java
index d60463df581..c42d48b4821 100644
--- a/vespaclient-core/src/main/java/com/yahoo/vespaclient/ClusterList.java
+++ b/vespaclient-core/src/main/java/com/yahoo/vespaclient/ClusterList.java
@@ -20,6 +20,7 @@ public class ClusterList {
this.contentClusters = List.copyOf(contentClusters);
}
+ @SuppressWarnings("deprecation")
public ClusterList(String configId) {
this(new ConfigGetter<>(ClusterListConfig.class).getConfig(configId));
}
diff --git a/vespaclient-java/pom.xml b/vespaclient-java/pom.xml
index d0e04d1e692..3e5e7ca8025 100644
--- a/vespaclient-java/pom.xml
+++ b/vespaclient-java/pom.xml
@@ -13,11 +13,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -43,6 +38,12 @@
<groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<!-- Added explicitly to get commons-collections, which is excluded from container-dev -->
@@ -69,6 +70,11 @@
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/vespaclient-java/src/main/java/com/yahoo/vespasummarybenchmark/VespaSummaryBenchmark.java b/vespaclient-java/src/main/java/com/yahoo/vespasummarybenchmark/VespaSummaryBenchmark.java
index 49a8c7fc583..fae602425ae 100644
--- a/vespaclient-java/src/main/java/com/yahoo/vespasummarybenchmark/VespaSummaryBenchmark.java
+++ b/vespaclient-java/src/main/java/com/yahoo/vespasummarybenchmark/VespaSummaryBenchmark.java
@@ -28,6 +28,7 @@ import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -146,7 +147,7 @@ public class VespaSummaryBenchmark {
r.parameters().add(new Int8Value(CompressionType.NONE.getCode()));
r.parameters().add(new Int32Value(blob.length));
r.parameters().add(new DataValue(blob));
- target.invokeAsync(r, 100.0, waiter);
+ target.invokeAsync(r, Duration.ofSeconds(100), waiter);
}
try {
waiter.waitForReplies();
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
index 5edc9429c74..7268e892c7d 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
@@ -6,12 +6,12 @@ import com.yahoo.concurrent.Timer;
import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage;
import com.yahoo.documentapi.messagebus.protocol.UpdateDocumentMessage;
import com.yahoo.messagebus.EmptyReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class BenchmarkProgressPrinterTest {
@@ -22,7 +22,7 @@ public class BenchmarkProgressPrinterTest {
}
@Test
- public void testSimple() {
+ void testSimple() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DummyTimer timer = new DummyTimer();
timer.ms = 0;
@@ -72,7 +72,7 @@ public class BenchmarkProgressPrinterTest {
String val = output.toString().split("\n")[1];
String correctPattern = "62000, \\d+, \\d+, \\d+, \\d+, \\d+$";
- assertTrue("Value '" + val + "' does not match pattern '" + correctPattern + "'", val.matches(correctPattern));
+ assertTrue(val.matches(correctPattern), "Value '" + val + "' does not match pattern '" + correctPattern + "'");
}
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
index f1e81fdd3c6..495367ff4c3 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
@@ -7,12 +7,12 @@ import com.yahoo.documentapi.messagebus.protocol.DocumentIgnoredReply;
import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage;
import com.yahoo.documentapi.messagebus.protocol.UpdateDocumentMessage;
import com.yahoo.messagebus.EmptyReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ProgressPrinterTest {
@@ -23,7 +23,7 @@ public class ProgressPrinterTest {
}
@Test
- public void testSimple() {
+ void testSimple() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DummyTimer timer = new DummyTimer();
timer.ms = 0;
@@ -78,12 +78,12 @@ public class ProgressPrinterTest {
String correct =
"\rSuccessfully sent 2 messages so far" +
- "\rSuccessfully sent 3 messages so far" +
- "\n\n" +
- "Messages sent to vespa (route foobar) :\n" +
- "---------------------------------------\n" +
- "PutDocument:\tok: 2 msgs/sec: 0.03 failed: 0 ignored: 1 latency(min, max, avg): 0, 0, 0\n" +
- "UpdateDocument:\tok: 1 msgs/sec: 0.02 failed: 2 ignored: 0 latency(min, max, avg): 0, 0, 0\n";
+ "\rSuccessfully sent 3 messages so far" +
+ "\n\n" +
+ "Messages sent to vespa (route foobar) :\n" +
+ "---------------------------------------\n" +
+ "PutDocument:\tok: 2 msgs/sec: 0.03 failed: 0 ignored: 1 latency(min, max, avg): 0, 0, 0\n" +
+ "UpdateDocument:\tok: 1 msgs/sec: 0.02 failed: 2 ignored: 0 latency(min, max, avg): 0, 0, 0\n";
assertEquals(correct, val);
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
index d6e55a26a39..a26672c5f26 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
@@ -22,23 +22,15 @@ import com.yahoo.feedhandler.VespaFeedHandler;
import com.yahoo.text.Utf8;
import com.yahoo.vespaclient.config.FeederConfig;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class VespaFeederTestCase {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
- public void testParseArgs() throws Exception {
- String argsS="--abortondataerror false --abortonsenderror false --file foo.xml --maxpending 10" +
+ void testParseArgs() throws Exception {
+ String argsS = "--abortondataerror false --abortonsenderror false --file foo.xml --maxpending 10" +
" --maxfeedrate 29 --mode benchmark --noretry --route e6 --timeout 13 --trace 4" +
" --validate -v bar.xml --priority LOW_1";
@@ -63,23 +55,23 @@ public class VespaFeederTestCase {
}
@Test
- public void requireThatCreateIfNonExistentArgumentCanBeParsed() throws Exception {
- String argsS="--create-if-non-existent --file foo.xml";
+ void requireThatCreateIfNonExistentArgumentCanBeParsed() throws Exception {
+ String argsS = "--create-if-non-existent --file foo.xml";
Arguments arguments = new Arguments(argsS.split(" "), DummySessionFactory.createWithAutoReply());
assertTrue(arguments.getFeederConfig().createifnonexistent());
}
@Test
- public void requireThatnumThreadsBeParsed() throws Exception {
- String argsS="--numthreads 5";
+ void requireThatnumThreadsBeParsed() throws Exception {
+ String argsS = "--numthreads 5";
Arguments arguments = new Arguments(argsS.split(" "), DummySessionFactory.createWithAutoReply());
assertEquals(5, arguments.getNumThreads());
assertEquals(1, new Arguments("".split(" "), DummySessionFactory.createWithAutoReply()).getNumThreads());
}
@Test
- public void testHelp() throws Exception {
- String argsS="-h";
+ void testHelp() throws Exception {
+ String argsS = "-h";
try {
new Arguments(argsS.split(" "), null);
@@ -90,7 +82,7 @@ public class VespaFeederTestCase {
}
@Test
- public void requireCorrectInputTypeDetection() throws IOException {
+ void requireCorrectInputTypeDetection() throws IOException {
{
BufferedInputStream b = new BufferedInputStream(
new ByteArrayInputStream(Utf8.toBytes("[]")));
@@ -114,16 +106,16 @@ public class VespaFeederTestCase {
}
@Test
- public void testRenderErrors() {
+ void testRenderErrors() {
{
- String[] errors = { "foo" };
+ String[] errors = {"foo"};
assertRenderErrorOutput("Errors:\n" +
- "-------\n" +
- " foo\n", errors);
+ "-------\n" +
+ " foo\n", errors);
}
{
- String[] errors = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};
+ String[] errors = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};
assertRenderErrorOutput("First 10 errors (of 11):\n" +
"------------------------\n" +
" 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n", errors);
@@ -136,7 +128,7 @@ public class VespaFeederTestCase {
}
@Test
- public void testCreateProgressPrinter() throws Exception {
+ void testCreateProgressPrinter() throws Exception {
assert(getProgressPrinter("--mode benchmark") instanceof BenchmarkProgressPrinter);
assert(getProgressPrinter("") instanceof ProgressPrinter);
}
@@ -151,15 +143,16 @@ public class VespaFeederTestCase {
}
}
+ // TODO: Remove on Vespa 9
@Test
- @SuppressWarnings("removal") // TODO: Remove on Vespa 9
- public void feedFile() throws Exception {
+ @SuppressWarnings("removal")
+ void feedFile() throws Exception {
FeedFixture f = new FeedFixture();
Arguments arguments = new Arguments("--file src/test/files/myfeed.xml --priority LOW_1".split(" "), f.sessionFactory);
new VespaFeeder(arguments, f.typeManager).parseFiles(System.in, f.printStream);
assertEquals(3, f.sessionFactory.messages.size());
- assertEquals(DocumentProtocol.Priority.LOW_1, ((PutDocumentMessage)f.sessionFactory.messages.get(0)).getPriority()); // TODO: Remove on Vespa 9
+ assertEquals(DocumentProtocol.Priority.LOW_1, ((PutDocumentMessage) f.sessionFactory.messages.get(0)).getPriority()); // TODO: Remove on Vespa 9
assertEquals("id:test:news::foo", ((PutDocumentMessage) f.sessionFactory.messages.get(0)).getDocumentPut().getDocument().getId().toString());
DocumentUpdate update = ((UpdateDocumentMessage) f.sessionFactory.messages.get(1)).getDocumentUpdate();
assertEquals("id:test:news::foo", update.getId().toString());
@@ -170,7 +163,7 @@ public class VespaFeederTestCase {
}
@Test
- public void feedJson() throws Exception {
+ void feedJson() throws Exception {
FeedFixture feedFixture = feed("src/test/files/myfeed.json", true);
assertJsonFeedState(feedFixture);
@@ -190,7 +183,7 @@ public class VespaFeederTestCase {
}
@Test
- public void requireThatCreateIfNonExistentArgumentIsUsed() throws Exception {
+ void requireThatCreateIfNonExistentArgumentIsUsed() throws Exception {
FeedFixture f = new FeedFixture();
Arguments arguments = new Arguments("--file src/test/files/myfeed.xml --create-if-non-existent".split(" "), f.sessionFactory);
new VespaFeeder(arguments, f.typeManager).parseFiles(System.in, f.printStream);
@@ -201,10 +194,11 @@ public class VespaFeederTestCase {
}
@Test
- public void feedMalformedJson() throws Exception {
- exception.expect(VespaFeeder.FeedErrorException.class);
- exception.expectMessage("JsonParseException");
- feed("src/test/files/malformedfeed.json", false);
+ void feedMalformedJson() throws Exception {
+ Throwable exception = assertThrows(VespaFeeder.FeedErrorException.class, () -> {
+ feed("src/test/files/malformedfeed.json", false);
+ });
+ assertTrue(exception.getMessage().contains("JsonParseException"));
}
protected FeedFixture feed(String feed, boolean abortOnDataError) throws Exception {
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java b/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
index 0b828c91f91..c448e5d55f5 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
@@ -5,9 +5,7 @@ import com.yahoo.document.fieldset.AllFields;
import com.yahoo.document.fieldset.DocumentOnly;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -17,9 +15,7 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test class for {@link CommandLineOptions}
@@ -37,10 +33,6 @@ public class CommandLineOptionsTest {
}
};
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
private ClientParameters getParsedOptions(InputStream in, String... args) {
CommandLineOptions options = new CommandLineOptions(in);
return options.parseCommandLineArguments(args);
@@ -51,7 +43,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testDefaultOptions() {
+ void testDefaultOptions() {
ClientParameters params = getParsedOptions();
assertFalse(params.help);
assertFalse(params.documentIds.hasNext());
@@ -68,7 +60,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testValidOptions() {
+ void testValidOptions() {
ClientParameters params = getParsedOptions(
"--fieldset", "[fieldset]",
"--route", "dummyroute",
@@ -97,73 +89,78 @@ public class CommandLineOptionsTest {
}
@Test
- public void testInvalidCombination3() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Field set option can not be used in combination with print ids option.");
- getParsedOptions("--printids", "--fieldset", AllFields.NAME);
+ void testInvalidCombination3() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--printids", "--fieldset", AllFields.NAME);
+ });
+ assertTrue(exception.getMessage().contains("Field set option can not be used in combination with print ids option."));
}
@Test
- public void testInvalidCombination4() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Cluster and route options are mutually exclusive.");
- getParsedOptions("--route", "dummyroute", "--cluster", "dummycluster");
+ void testInvalidCombination4() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--route", "dummyroute", "--cluster", "dummycluster");
+ });
+ assertTrue(exception.getMessage().contains("Cluster and route options are mutually exclusive."));
}
@Test
- public void testInvalidPriority() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid priority: 16");
- getParsedOptions("--priority", "16");
+ void testInvalidPriority() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--priority", "16");
+ });
+ assertTrue(exception.getMessage().contains("Invalid priority: 16"));
}
@Test
- public void TestHighestPriority() {
+ void TestHighestPriority() {
ClientParameters params = getParsedOptions("--priority", "HIGHEST");
assertEquals(DocumentProtocol.Priority.HIGHEST, params.priority);
}
@Test
- public void TestHigh1PriorityAsNumber() {
+ void TestHigh1PriorityAsNumber() {
ClientParameters params = getParsedOptions("--priority", "2");
assertEquals(DocumentProtocol.Priority.HIGH_1, params.priority);
}
@Test
- public void testInvalidTraceLevel1() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid tracelevel: -1");
- getParsedOptions("--trace", "-1");
+ void testInvalidTraceLevel1() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--trace", "-1");
+ });
+ assertTrue(exception.getMessage().contains("Invalid tracelevel: -1"));
}
@Test
- public void testInvalidTraceLevel2() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid tracelevel: 10");
- getParsedOptions("--trace", "10");
+ void testInvalidTraceLevel2() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--trace", "10");
+ });
+ assertTrue(exception.getMessage().contains("Invalid tracelevel: 10"));
}
@Test
- public void testPrintids() {
+ void testPrintids() {
ClientParameters params = getParsedOptions("--printids");
assertEquals(DocIdOnly.NAME, params.fieldSet);
}
@Test
- public void testCluster() {
+ void testCluster() {
ClientParameters params = getParsedOptions("--cluster", "dummycluster");
assertEquals("dummycluster", params.cluster);
assertTrue(params.route.isEmpty());
}
@Test
- public void testHelp() {
+ void testHelp() {
ClientParameters params = getParsedOptions("--help");
assertTrue(params.help);
}
@Test
- public void testDocumentIdsFromInputStream() throws UnsupportedEncodingException {
+ void testDocumentIdsFromInputStream() throws UnsupportedEncodingException {
InputStream in = new ByteArrayInputStream("id:1 id:2 id:3".getBytes("UTF-8"));
ClientParameters params = getParsedOptions(in, "");
@@ -175,7 +172,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testPrintHelp() {
+ void testPrintHelp() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
PrintStream oldOut = System.out;
System.setOut(new PrintStream(outContent));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
index ce555e2c0f5..24e303d6fce 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
@@ -15,11 +15,9 @@ import com.yahoo.messagebus.Error;
import com.yahoo.messagebus.Reply;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import java.io.ByteArrayOutputStream;
@@ -31,8 +29,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
@@ -60,11 +57,7 @@ public class DocumentRetrieverTest {
private PrintStream oldOut;
private PrintStream oldErr;
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
- @Before
+ @BeforeEach
public void setUpStreams() {
oldOut = System.out;
oldErr = System.err;
@@ -72,7 +65,7 @@ public class DocumentRetrieverTest {
System.setErr(new PrintStream(errContent));
}
- @Before
+ @BeforeEach
public void prepareMessageBusMocks() {
this.mockedFactory = mock(DocumentAccessFactory.class);
this.mockedDocumentAccess = mock(MessageBusDocumentAccess.class);
@@ -81,7 +74,7 @@ public class DocumentRetrieverTest {
when(mockedDocumentAccess.createSyncSession(any())).thenReturn(mockedSession);
}
- @After
+ @AfterEach
public void cleanUpStreams() {
System.setOut(oldOut);
System.setErr(oldErr);
@@ -129,9 +122,10 @@ public class DocumentRetrieverTest {
params);
}
+ // TODO: Remove on Vespa 9
@Test
- @SuppressWarnings("removal") // TODO: Remove on Vespa 9
- public void testSendSingleMessage() throws DocumentRetrieverException {
+ @SuppressWarnings("removal")
+ void testSendSingleMessage() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPriority(DocumentProtocol.Priority.HIGH_1)
@@ -148,12 +142,12 @@ public class DocumentRetrieverTest {
verify(mockedSession, times(1)).syncSend(argThat((ArgumentMatcher<GetDocumentMessage>) o ->
o.getPriority().equals(DocumentProtocol.Priority.HIGH_1) && // TODO remove on Vespa 9
- !o.getRetryEnabled()));
+ !o.getRetryEnabled()));
assertContainsDocument(DOC_ID_1);
}
@Test
- public void testMultipleMessages() throws DocumentRetrieverException {
+ void testMultipleMessages() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1, DOC_ID_2, DOC_ID_3))
.build();
@@ -173,7 +167,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testJsonOutput() throws DocumentRetrieverException, IOException {
+ void testJsonOutput() throws DocumentRetrieverException, IOException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1, DOC_ID_2, DOC_ID_3))
.setJsonOutput(true)
@@ -197,7 +191,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testShutdownHook() throws DocumentRetrieverException {
+ void testShutdownHook() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.build();
@@ -213,7 +207,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testClusterLookup() throws DocumentRetrieverException {
+ void testClusterLookup() throws DocumentRetrieverException {
final String cluster = "storage",
expectedRoute = "[Content:cluster=storage]";
@@ -230,35 +224,37 @@ public class DocumentRetrieverTest {
}
@Test
- public void testInvalidClusterName() throws DocumentRetrieverException {
- exception.expect(DocumentRetrieverException.class);
- exception.expectMessage("The Vespa cluster contains the content clusters storage, not invalidclustername. Please select a valid vespa cluster.");
+ void testInvalidClusterName() throws DocumentRetrieverException {
+ Throwable exception = assertThrows(DocumentRetrieverException.class, () -> {
- ClientParameters params = createParameters()
- .setCluster("invalidclustername")
- .build();
+ ClientParameters params = createParameters()
+ .setCluster("invalidclustername")
+ .build();
- ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef("storage")));
+ ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef("storage")));
- DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList);
- documentRetriever.retrieveDocuments();
+ DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList);
+ documentRetriever.retrieveDocuments();
+ });
+ assertTrue(exception.getMessage().contains("The Vespa cluster contains the content clusters storage, not invalidclustername. Please select a valid vespa cluster."));
}
@Test
- public void testEmtpyClusterList() throws DocumentRetrieverException {
- exception.expect(DocumentRetrieverException.class);
- exception.expectMessage("The Vespa cluster does not have any content clusters declared.");
+ void testEmtpyClusterList() throws DocumentRetrieverException {
+ Throwable exception = assertThrows(DocumentRetrieverException.class, () -> {
- ClientParameters params = createParameters()
- .setCluster("invalidclustername")
- .build();
+ ClientParameters params = createParameters()
+ .setCluster("invalidclustername")
+ .build();
- DocumentRetriever documentRetriever = createDocumentRetriever(params);
- documentRetriever.retrieveDocuments();
+ DocumentRetriever documentRetriever = createDocumentRetriever(params);
+ documentRetriever.retrieveDocuments();
+ });
+ assertTrue(exception.getMessage().contains("The Vespa cluster does not have any content clusters declared."));
}
@Test
- public void testHandlingErrorFromMessageBus() throws DocumentRetrieverException {
+ void testHandlingErrorFromMessageBus() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.build();
@@ -274,7 +270,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testShowDocSize() throws DocumentRetrieverException {
+ void testShowDocSize() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setShowDocSize(true)
@@ -290,7 +286,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testPrintIdOnly() throws DocumentRetrieverException {
+ void testPrintIdOnly() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
@@ -305,7 +301,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testDocumentNotFound() throws DocumentRetrieverException {
+ void testDocumentNotFound() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
@@ -321,7 +317,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testTrace() throws DocumentRetrieverException {
+ void testTrace() throws DocumentRetrieverException {
final int traceLevel = 9;
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
index 8120e2f1d77..0a0bca8af0e 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
@@ -3,9 +3,9 @@ package com.yahoo.vespastat;
import com.yahoo.document.BucketId;
import com.yahoo.documentapi.messagebus.protocol.GetBucketListReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@@ -13,7 +13,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ public class BucketStatsPrinterTest {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final String bucketSpace = "default";
- @Before
+ @BeforeEach
public void mockBucketStatsRetriever() throws BucketStatsException {
retriever = mock(BucketStatsRetriever.class);
when(retriever.getBucketIdForType(any(), any())).thenReturn(new BucketId(0x42));
@@ -32,7 +32,7 @@ public class BucketStatsPrinterTest {
when(retriever.retrieveBucketStats(any(), any(), any(), any())).thenReturn("");
}
- @After
+ @AfterEach
public void resetOutputMock() {
out.reset();
}
@@ -50,7 +50,7 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintBucketIdForUserAndGroup() throws BucketStatsException {
+ void testShouldPrintBucketIdForUserAndGroup() throws BucketStatsException {
String output = retreiveAndPrintBucketStats(ClientParameters.SelectionType.USER, "1234", false);
assertTrue(output.contains("Generated 32-bit bucket id"));
@@ -59,13 +59,13 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintWarningIfBucketListEmpty() throws BucketStatsException {
+ void testShouldPrintWarningIfBucketListEmpty() throws BucketStatsException {
String output = retreiveAndPrintBucketStats(ClientParameters.SelectionType.USER, "1234", false);
assertTrue(output.contains("No actual files were stored for this bucket"));
}
@Test
- public void testShouldPrintBucketList() throws BucketStatsException {
+ void testShouldPrintBucketList() throws BucketStatsException {
List<GetBucketListReply.BucketInfo> bucketList = new ArrayList<>();
String dummyInfoString = "dummyinformation";
bucketList.add(new GetBucketListReply.BucketInfo(new BucketId(0), dummyInfoString));
@@ -76,7 +76,7 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintBucketStats() throws BucketStatsException {
+ void testShouldPrintBucketStats() throws BucketStatsException {
String dummyBucketStats = "dummystats";
GetBucketListReply.BucketInfo bucketInfo = new GetBucketListReply.BucketInfo(new BucketId(0), "dummy");
when(retriever.retrieveBucketList(any(), any())).thenReturn(Collections.singletonList(bucketInfo));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
index 39f8968d209..426c316027a 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
@@ -9,12 +9,13 @@ import com.yahoo.documentapi.messagebus.MessageBusSyncSession;
import com.yahoo.documentapi.messagebus.protocol.GetBucketListReply;
import com.yahoo.documentapi.messagebus.protocol.StatBucketReply;
import com.yahoo.messagebus.Error;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -31,7 +32,7 @@ public class BucketStatsRetrieverTest {
private final String bucketSpace = "default";
- @Before
+ @BeforeEach
public void prepareMessageBusMocks() {
this.mockedFactory = mock(DocumentAccessFactory.class);
this.mockedDocumentAccess = mock(MessageBusDocumentAccess.class);
@@ -41,7 +42,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testGetBucketId() throws BucketStatsException {
+ void testGetBucketId() throws BucketStatsException {
BucketStatsRetriever retriever = createRetriever();
assertEquals("BucketId(0x80000000000004d2)",
@@ -57,7 +58,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testRetrieveBucketList() throws BucketStatsException {
+ void testRetrieveBucketList() throws BucketStatsException {
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another"));
@@ -73,7 +74,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testRetrieveBucketStats() throws BucketStatsException {
+ void testRetrieveBucketStats() throws BucketStatsException {
String docId = "id:ns:type::another";
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId(docId));
@@ -88,9 +89,10 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testShutdownHook() {
+ void testShutdownHook() {
class MockShutdownRegistrar implements BucketStatsRetriever.ShutdownHookRegistrar {
public Runnable shutdownRunnable;
+
@Override
public void registerShutdownHook(Runnable runnable) {
shutdownRunnable = runnable;
@@ -104,24 +106,27 @@ public class BucketStatsRetrieverTest {
verify(mockedDocumentAccess, times(1)).shutdown();
}
- @Test(expected = BucketStatsException.class)
- public void testShouldFailOnReplyError() throws BucketStatsException {
- GetBucketListReply reply = new GetBucketListReply();
- reply.addError(new Error(0, "errormsg"));
- when(mockedSession.syncSend(any())).thenReturn(reply);
-
- createRetriever().retrieveBucketList(new BucketId(1), bucketSpace);
+ @Test
+ void testShouldFailOnReplyError() throws BucketStatsException {
+ assertThrows(BucketStatsException.class, () -> {
+ GetBucketListReply reply = new GetBucketListReply();
+ reply.addError(new Error(0, "errormsg"));
+ when(mockedSession.syncSend(any())).thenReturn(reply);
+
+ createRetriever().retrieveBucketList(new BucketId(1), bucketSpace);
+ });
}
@Test
- public void testRoute() throws BucketStatsException {
+ void testRoute() throws BucketStatsException {
String route = "default";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another"));
GetBucketListReply reply = new GetBucketListReply();
reply.getBuckets().add(new GetBucketListReply.BucketInfo(bucketId, "I like turtles!"));
when(mockedSession.syncSend(any())).thenReturn(reply);
- BucketStatsRetriever retriever = new BucketStatsRetriever(mockedFactory, route, t -> {});
+ BucketStatsRetriever retriever = new BucketStatsRetriever(mockedFactory, route, t -> {
+ });
retriever.retrieveBucketList(new BucketId(0), bucketSpace);
// Route is set at session-level, not per message sent.
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
index 4bfe9b68b65..b030120ac52 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespastat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class CommandLineOptionsTest {
@@ -16,12 +16,12 @@ public class CommandLineOptionsTest {
}
@Test
- public void testHelp() {
+ void testHelp() {
assertTrue(getParsedOptions("--help").help);
}
@Test
- public void testMultipleOptions() {
+ void testMultipleOptions() {
ClientParameters params = getParsedOptions("--dump", "--route", "dummyroute", "--user", "userid");
assertTrue(params.dumpData);
assertEquals("dummyroute", params.route);
@@ -30,7 +30,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testSelectionTypes() {
+ void testSelectionTypes() {
assertEquals(ClientParameters.SelectionType.USER, getParsedOptions("--user", "id").selectionType);
assertEquals(ClientParameters.SelectionType.DOCUMENT, getParsedOptions("--document", "id").selectionType);
assertEquals(ClientParameters.SelectionType.BUCKET, getParsedOptions("--bucket", "id").selectionType);
@@ -38,24 +38,28 @@ public class CommandLineOptionsTest {
assertEquals(ClientParameters.SelectionType.GID, getParsedOptions("--gid", "id").selectionType);
}
- @Test(expected = IllegalArgumentException.class)
- public void testMissingSelectionType() {
- getParsedOptions();
+ @Test
+ void testMissingSelectionType() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions();
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testFailOnMultipleDumpTypes() {
- getParsedOptions("--user", "id", "--document", "id", "--group", "id", "--gid", "id");
+ @Test
+ void testFailOnMultipleDumpTypes() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--user", "id", "--document", "id", "--group", "id", "--gid", "id");
+ });
}
@Test
- public void testForceDumpOnDocumentOrGid() {
+ void testForceDumpOnDocumentOrGid() {
assertTrue(getParsedOptions("--document", "docid").dumpData);
assertTrue(getParsedOptions("--gid", "gid").dumpData);
}
@Test
- public void testPrintHelp() {
+ void testPrintHelp() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
PrintStream oldOut = System.out;
System.setOut(new PrintStream(outContent));
@@ -71,17 +75,17 @@ public class CommandLineOptionsTest {
}
@Test
- public void bucket_space_is_default_unless_specified() {
+ void bucket_space_is_default_unless_specified() {
assertEquals("default", getParsedOptions("--user", "id").bucketSpace);
}
@Test
- public void can_specify_explicit_bucket_space() {
+ void can_specify_explicit_bucket_space() {
assertEquals("global", getParsedOptions("--user", "id", "--bucketspace", "global").bucketSpace);
}
@Test
- public void testDefaultRoute() {
+ void testDefaultRoute() {
assertEquals("default", getParsedOptions("--user", "dummyuser").route);
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
index 854d7ae9ad3..f109b0ad56b 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
@@ -2,33 +2,32 @@
package com.yahoo.vespavisit;
import com.yahoo.documentapi.VisitorDataHandler;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
-@RunWith(Parameterized.class)
public class StdOutVisitorHandlerTest {
- private final boolean jsonOutput;
+ private boolean jsonOutput;
- public StdOutVisitorHandlerTest(boolean jsonOutput) {
+ public void initStdOutVisitorHandlerTest(boolean jsonOutput) {
this.jsonOutput = jsonOutput;
}
- @Parameterized.Parameters(name = "jsonOutput={0}")
public static Object[] data() {
- return new Object[] { true, false};
+ return new Object[]{true, false};
}
- @Test
- public void printing_ids_for_zero_documents_produces_empty_output() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "jsonOutput={0}")
+ void printing_ids_for_zero_documents_produces_empty_output(boolean jsonOutput) {
+ initStdOutVisitorHandlerTest(jsonOutput);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StdOutVisitorHandler visitorHandler =
new StdOutVisitorHandler(/*printIds*/true, false, false, false, false, false, 0, jsonOutput, new PrintStream(out, true));
@@ -38,8 +37,10 @@ public class StdOutVisitorHandlerTest {
assertEquals("", output.trim());
}
- @Test
- public void printing_zero_documents_produces_empty_output() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "jsonOutput={0}")
+ void printing_zero_documents_produces_empty_output(boolean jsonOutput) {
+ initStdOutVisitorHandlerTest(jsonOutput);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StdOutVisitorHandler visitorHandler =
new StdOutVisitorHandler(/*printIds*/false, false, false, false, false, false, 0, jsonOutput, new PrintStream(out, true));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
index 42526a38df5..3a74ac39f43 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespavisit;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
public class VdsVisitTargetTestCase {
@Test
- public void testParametersSlobrok() throws Exception {
+ void testParametersSlobrok() throws Exception {
VdsVisitTarget target = new VdsVisitTarget();
target.parseArguments(new String[]{
"--bindtoslobrok", "myname",
@@ -30,11 +31,11 @@ public class VdsVisitTargetTestCase {
}
@Test
- public void testParametersPort() throws Exception {
+ void testParametersPort() throws Exception {
VdsVisitTarget target = new VdsVisitTarget();
target.parseArguments("--bindtosocket 1234".split(" "));
assertEquals(1234, target.getPort());
- assertEquals(null, target.getSlobrokAddress());
+ assertNull(target.getSlobrokAddress());
}
public void assertException(String params) {
@@ -48,7 +49,7 @@ public class VdsVisitTargetTestCase {
}
@Test
- public void testPortAndSlobrok() {
+ void testPortAndSlobrok() {
assertException("--bindtoslobrok foo --bindtosocket 1234");
assertException("--bindtoport foo");
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
index 55ac7761da3..a67fee0c0d6 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
@@ -3,22 +3,31 @@ package com.yahoo.vespavisit;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.document.select.parser.ParseException;
-import com.yahoo.documentapi.*;
+import com.yahoo.documentapi.AckToken;
+import com.yahoo.documentapi.ProgressToken;
+import com.yahoo.documentapi.VisitorControlHandler;
+import com.yahoo.documentapi.VisitorParameters;
+import com.yahoo.documentapi.VisitorResponse;
+import com.yahoo.documentapi.VisitorSession;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol;
import com.yahoo.messagebus.StaticThrottlePolicy;
import com.yahoo.messagebus.Trace;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;
import org.apache.commons.cli.Options;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class VdsVisitTestCase {
@@ -28,9 +37,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptions() throws Exception {
+ void testCommandLineShortOptions() throws Exception {
// short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-d", "foo.remote",
"-s", "'id.user=1234'",
"-f", "5678",
@@ -70,9 +79,9 @@ public class VdsVisitTestCase {
* @throws Exception
*/
@Test
- public void testCommandLineShortOptions2() throws Exception {
+ void testCommandLineShortOptions2() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-o", "654321",
"-i"
};
@@ -88,9 +97,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptionsPrintIdsOnly() throws Exception {
+ void testCommandLineShortOptionsPrintIdsOnly() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-i"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -104,9 +113,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineLongOptions() throws Exception {
+ void testCommandLineLongOptions() throws Exception {
// short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"--datahandler", "foo.remote",
"--selection", "'id.user=1234'",
"--from", "5678",
@@ -151,12 +160,12 @@ public class VdsVisitTestCase {
assertEquals("kittens", allParams.getCluster());
assertTrue(params.getThrottlePolicy() instanceof StaticThrottlePolicy);
- assertEquals(3, ((StaticThrottlePolicy)params.getThrottlePolicy()).getMaxPendingCount());
+ assertEquals(3, ((StaticThrottlePolicy) params.getThrottlePolicy()).getMaxPendingCount());
assertTrue(params.visitInconsistentBuckets());
assertEquals("fnord", params.getVisitorLibrary());
// TODO: FIXME? multiple library params doesn't work
- assertTrue(Arrays.equals("rargh".getBytes(), params.getLibraryParameters().get("asdf")));
+ assertArrayEquals("rargh".getBytes(), params.getLibraryParameters().get("asdf"));
//assertTrue(Arrays.equals("pie".getBytes(), params.getLibraryParameters().get("pinkie")));
assertEquals(555, allParams.getProcessTime());
assertEquals(2002, params.getMaxTotalHits());
@@ -171,7 +180,7 @@ public class VdsVisitTestCase {
printStream.flush();
String nl = System.getProperty("line.separator"); // the joys of running tests on windows
assertEquals(
- "Time out visitor after 123456789 ms." + nl +
+ "Time out visitor after 123456789 ms." + nl +
"Visiting documents matching: 'id.user=1234'" + nl +
"Visiting bucket space: outerspace" + nl +
"Visiting in the inclusive timestamp range 5678 - 9012." + nl +
@@ -193,7 +202,7 @@ public class VdsVisitTestCase {
private static String[] emptyArgList() { return new String[]{}; }
@Test
- public void visitor_priority_is_low1_by_default() throws Exception {
+ void visitor_priority_is_low1_by_default() throws Exception {
VdsVisit.VdsVisitParameters allParams = createMockArgumentParser().parse(emptyArgList());
VisitorParameters params = allParams.getVisitorParameters();
@@ -201,8 +210,8 @@ public class VdsVisitTestCase {
}
@Test
- public void testBadPriorityValue() throws Exception {
- String[] args = new String[] {
+ void testBadPriorityValue() throws Exception {
+ String[] args = new String[]{
"--priority", "super_hyper_important"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -215,9 +224,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptionsInvokeHelp() throws Exception {
+ void testCommandLineShortOptionsInvokeHelp() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-h"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -226,7 +235,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testAutoSelectClusterRoute() throws Exception {
+ void testAutoSelectClusterRoute() throws Exception {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
ClusterList clusterList = new ClusterList(clusterDefs);
@@ -236,7 +245,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testBadClusterName() throws Exception {
+ void testBadClusterName() throws Exception {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
ClusterList clusterList = new ClusterList(clusterDefs);
@@ -244,13 +253,13 @@ public class VdsVisitTestCase {
VdsVisit.resolveClusterRoute(clusterList, "borkbork");
} catch (IllegalArgumentException e) {
assertEquals("Your vespa cluster contains the content clusters 'storage', not 'borkbork'. " +
- "Please select a valid vespa cluster.",
- e.getMessage());
+ "Please select a valid vespa cluster.",
+ e.getMessage());
}
}
@Test
- public void testRequireClusterOptionIfMultipleClusters() {
+ void testRequireClusterOptionIfMultipleClusters() {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
clusterDefs.add(new ClusterDef("storage2"));
@@ -263,7 +272,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testExplicitClusterOptionWithMultipleClusters() {
+ void testExplicitClusterOptionWithMultipleClusters() {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
clusterDefs.add(new ClusterDef("storage2"));
@@ -274,7 +283,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testFailIfNoContentClustersAvailable() {
+ void testFailIfNoContentClustersAvailable() {
List<ClusterDef> clusterDefs = new ArrayList<>();
ClusterList clusterList = new ClusterList(clusterDefs);
try {
@@ -285,8 +294,8 @@ public class VdsVisitTestCase {
}
@Test
- public void testStatistics() throws Exception {
- String[] args = new String[] {
+ void testStatistics() throws Exception {
+ String[] args = new String[]{
"--statistics", "foo"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -400,7 +409,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testVdsVisitRunLogic() {
+ void testVdsVisitRunLogic() {
MockVisitorSessionAccessorFactory accessorFactory = new MockVisitorSessionAccessorFactory();
MockShutdownHookRegistrar shutdownHookRegistrar = new MockShutdownHookRegistrar();
VdsVisit vdsVisit = new VdsVisit(accessorFactory, shutdownHookRegistrar);
@@ -429,7 +438,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testVdsVisitRunLogicProgressFileNotYetCreated() {
+ void testVdsVisitRunLogicProgressFileNotYetCreated() {
MockVisitorSessionAccessorFactory accessorFactory = new MockVisitorSessionAccessorFactory();
MockShutdownHookRegistrar shutdownHookRegistrar = new MockShutdownHookRegistrar();
VdsVisit vdsVisit = new VdsVisit(accessorFactory, shutdownHookRegistrar);
diff --git a/vespajlib/abi-spec.json b/vespajlib/abi-spec.json
index 2c861dd2f1f..fbf1203acdf 100644
--- a/vespajlib/abi-spec.json
+++ b/vespajlib/abi-spec.json
@@ -3358,6 +3358,8 @@
"public static org.w3c.dom.Document getDocument(java.lang.String)",
"public static javax.xml.parsers.DocumentBuilder getDocumentBuilder()",
"public static javax.xml.parsers.DocumentBuilder getDocumentBuilder(java.lang.String, java.lang.ClassLoader)",
+ "public static javax.xml.parsers.DocumentBuilder getDocumentBuilder(boolean)",
+ "public static javax.xml.parsers.DocumentBuilder getDocumentBuilder(java.lang.String, java.lang.ClassLoader, boolean)",
"public static java.util.List getChildren(org.w3c.dom.Element)",
"public static java.util.List getChildren(org.w3c.dom.Element, java.lang.String)",
"public static java.lang.String getValue(org.w3c.dom.Element)",
@@ -3637,5 +3639,335 @@
"public abstract com.yahoo.vespa.objects.Serializer put(com.yahoo.vespa.objects.FieldBase, java.lang.String)"
],
"fields": []
+ },
+ "com.yahoo.yolean.Exceptions$RunnableThrowingIOException": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract void run()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract void run()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.Exceptions$SupplierThrowingIOException": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract java.lang.Object get()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.Exceptions": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>()",
+ "public static java.lang.String toMessageString(java.lang.Throwable)",
+ "public static java.util.Optional findCause(java.lang.Throwable, java.lang.Class)",
+ "public static void uncheck(com.yahoo.yolean.Exceptions$RunnableThrowingIOException)",
+ "public static void uncheckInterrupted(com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException)",
+ "public static void uncheckInterruptedAndRestoreFlag(com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException)",
+ "public static varargs void uncheck(com.yahoo.yolean.Exceptions$RunnableThrowingIOException, java.lang.String, java.lang.String[])",
+ "public static void uncheckAndIgnore(com.yahoo.yolean.Exceptions$RunnableThrowingIOException, java.lang.Class)",
+ "public static java.lang.Object uncheck(com.yahoo.yolean.Exceptions$SupplierThrowingIOException)",
+ "public static varargs java.lang.Object uncheck(com.yahoo.yolean.Exceptions$SupplierThrowingIOException, java.lang.String, java.lang.String[])",
+ "public static java.lang.Object uncheckAndIgnore(com.yahoo.yolean.Exceptions$SupplierThrowingIOException, java.lang.Class)",
+ "public static java.lang.RuntimeException throwUnchecked(java.lang.Throwable)"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.UncheckedInterruptedException": {
+ "superClass": "java.lang.RuntimeException",
+ "interfaces": [],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>(java.lang.String, java.lang.InterruptedException, boolean)",
+ "public void <init>(java.lang.InterruptedException, boolean)",
+ "public void <init>(java.lang.String, boolean)",
+ "public void <init>(java.lang.String, java.lang.InterruptedException)",
+ "public void <init>(java.lang.InterruptedException)",
+ "public java.lang.InterruptedException getCause()",
+ "public bridge synthetic java.lang.Throwable getCause()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.chain.After": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.chain.Before": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.chain.Provides": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.annotation.Annotation"
+ ],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract",
+ "annotation"
+ ],
+ "methods": [
+ "public abstract java.lang.String[] value()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.ConcurrentResourcePool": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.Iterable"
+ ],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>(java.util.function.Supplier)",
+ "public void preallocate(int)",
+ "public final java.lang.Object alloc()",
+ "public final void free(java.lang.Object)",
+ "public java.util.Iterator iterator()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.CopyOnWriteHashMap": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.util.Map"
+ ],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>()",
+ "public int size()",
+ "public boolean isEmpty()",
+ "public boolean containsKey(java.lang.Object)",
+ "public boolean containsValue(java.lang.Object)",
+ "public java.lang.Object get(java.lang.Object)",
+ "public java.lang.Object put(java.lang.Object, java.lang.Object)",
+ "public java.lang.Object remove(java.lang.Object)",
+ "public void putAll(java.util.Map)",
+ "public void clear()",
+ "public java.util.Set keySet()",
+ "public java.util.Collection values()",
+ "public java.util.Set entrySet()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.Memoized$Closer": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract void close(java.lang.Object)"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.Memoized": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.util.function.Supplier",
+ "java.lang.AutoCloseable"
+ ],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>(java.util.function.Supplier, com.yahoo.yolean.concurrent.Memoized$Closer)",
+ "public static com.yahoo.yolean.concurrent.Memoized of(java.util.function.Supplier)",
+ "public static com.yahoo.yolean.concurrent.Memoized combine(com.yahoo.yolean.concurrent.Memoized, java.util.function.Function, com.yahoo.yolean.concurrent.Memoized$Closer)",
+ "public java.lang.Object get()",
+ "public void close()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.ResourcePool": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.Iterable"
+ ],
+ "attributes": [
+ "public",
+ "final"
+ ],
+ "methods": [
+ "public void <init>(java.util.function.Supplier)",
+ "public java.lang.Object alloc()",
+ "public void free(java.lang.Object)",
+ "public java.util.Iterator iterator()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.concurrent.Sleeper": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public void sleep(java.time.Duration)",
+ "public void sleepChecked(java.time.Duration)",
+ "public void sleep(long)",
+ "public abstract void sleepChecked(long)"
+ ],
+ "fields": [
+ "public static final com.yahoo.yolean.concurrent.Sleeper DEFAULT",
+ "public static final com.yahoo.yolean.concurrent.Sleeper NOOP"
+ ]
+ },
+ "com.yahoo.yolean.concurrent.ThreadRobustList": {
+ "superClass": "java.lang.Object",
+ "interfaces": [
+ "java.lang.Iterable"
+ ],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>()",
+ "public void <init>(int)",
+ "public boolean isEmpty()",
+ "public void add(java.lang.Object)",
+ "public java.util.Iterator iterator()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.function.ThrowingConsumer": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract void accept(java.lang.Object)",
+ "public com.yahoo.yolean.function.ThrowingConsumer andThen(com.yahoo.yolean.function.ThrowingConsumer)"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.function.ThrowingFunction": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract java.lang.Object apply(java.lang.Object)",
+ "public com.yahoo.yolean.function.ThrowingFunction andThen(com.yahoo.yolean.function.ThrowingFunction)",
+ "public com.yahoo.yolean.function.ThrowingFunction compose(com.yahoo.yolean.function.ThrowingFunction)"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.function.ThrowingSupplier": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "interface",
+ "abstract"
+ ],
+ "methods": [
+ "public abstract java.lang.Object get()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.trace.TraceNode": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public"
+ ],
+ "methods": [
+ "public void <init>(java.lang.Object, long)",
+ "public com.yahoo.yolean.trace.TraceNode add(com.yahoo.yolean.trace.TraceNode)",
+ "public java.lang.Iterable descendants(java.lang.Class)",
+ "public java.lang.Object payload()",
+ "public long timestamp()",
+ "public com.yahoo.yolean.trace.TraceNode parent()",
+ "public java.lang.Iterable children()",
+ "public boolean isRoot()",
+ "public com.yahoo.yolean.trace.TraceNode root()",
+ "public com.yahoo.yolean.trace.TraceVisitor accept(com.yahoo.yolean.trace.TraceVisitor)",
+ "public java.lang.String toString()"
+ ],
+ "fields": []
+ },
+ "com.yahoo.yolean.trace.TraceVisitor": {
+ "superClass": "java.lang.Object",
+ "interfaces": [],
+ "attributes": [
+ "public",
+ "abstract"
+ ],
+ "methods": [
+ "public void <init>()",
+ "public abstract void visit(com.yahoo.yolean.trace.TraceNode)",
+ "public void entering(com.yahoo.yolean.trace.TraceNode)",
+ "public void leaving(com.yahoo.yolean.trace.TraceNode)"
+ ],
+ "fields": []
}
} \ No newline at end of file
diff --git a/vespajlib/pom.xml b/vespajlib/pom.xml
index c4d100aa10c..361e3a1f6ff 100644
--- a/vespajlib/pom.xml
+++ b/vespajlib/pom.xml
@@ -54,12 +54,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>yolean</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
<!-- test scope -->
<dependency>
diff --git a/vespajlib/src/main/java/ai/vespa/validation/PathValidator.java b/vespajlib/src/main/java/ai/vespa/validation/PathValidator.java
new file mode 100644
index 00000000000..0ae81e2315d
--- /dev/null
+++ b/vespajlib/src/main/java/ai/vespa/validation/PathValidator.java
@@ -0,0 +1,36 @@
+package ai.vespa.validation;
+
+import java.nio.file.Path;
+
+/**
+ * Path validations
+ *
+ * @author mortent
+ */
+public class PathValidator {
+
+ /**
+ * Validate that file is a child of basedir
+ * @param root Root directory to use for validation
+ * @param path Path to validate
+ * @throws IllegalArgumentException if path is not a child of root
+ */
+ public static void validateChildOf(Path root, Path path) {
+ if (!path.normalize().startsWith(root)) {
+ throw new IllegalArgumentException("Invalid path %s".formatted(path));
+ }
+ }
+
+ /**
+ * Resolves a path under a root path
+ * @param root root poth
+ * @param path child to resolve
+ * @return The resolved path
+ * @throws IllegalArgumentException If the provided child path does not resolve as child of root
+ */
+ public static Path resolveChildOf(Path root, String path) {
+ Path resolved = root.resolve(path);
+ validateChildOf(root, resolved);
+ return resolved;
+ }
+}
diff --git a/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java b/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java
new file mode 100644
index 00000000000..d30750692e9
--- /dev/null
+++ b/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java
@@ -0,0 +1,30 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.concurrent;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author bjorncs
+ */
+public class Threads {
+
+ private Threads() {}
+
+ /** Returns all threads in JVM */
+ public static Collection<Thread> getAllThreads() {
+ ThreadGroup root = Thread.currentThread().getThreadGroup();
+ ThreadGroup parent;
+ while ((parent = root.getParent()) != null) {
+ root = parent;
+ }
+ // The number of threads may increase between activeCount() and enumerate()
+ Thread[] threads = new Thread[root.activeCount() + 100];
+ int count;
+ while ((count = root.enumerate(threads, true)) == threads.length) {
+ threads = new Thread[threads.length + 1000];
+ }
+ return List.of(Arrays.copyOf(threads, count));
+ }
+}
diff --git a/vespajlib/src/main/java/com/yahoo/text/XML.java b/vespajlib/src/main/java/com/yahoo/text/XML.java
index c6f235f486c..6aa42773ac0 100644
--- a/vespajlib/src/main/java/com/yahoo/text/XML.java
+++ b/vespajlib/src/main/java/com/yahoo/text/XML.java
@@ -1,17 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.text;
-import java.io.File;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -20,6 +9,16 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* Static XML utility methods
*
@@ -453,7 +452,7 @@ public class XML {
* @throws RuntimeException if we fail to create one
*/
public static DocumentBuilder getDocumentBuilder() {
- return getDocumentBuilder("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null);
+ return getDocumentBuilder("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null, true);
}
/**
@@ -465,12 +464,43 @@ public class XML {
* @return a DocumentBuilder
*/
public static DocumentBuilder getDocumentBuilder(String implementation, ClassLoader classLoader) {
+ return getDocumentBuilder(true);
+ }
+
+ /**
+ * Creates a new XML DocumentBuilder
+ *
+ * @return a DocumentBuilder
+ * @throws RuntimeException if we fail to create one
+ * @param namespaceAware Whether the parser should be aware of xml namespaces
+ */
+ public static DocumentBuilder getDocumentBuilder(boolean namespaceAware) {
+ return getDocumentBuilder("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", null, namespaceAware);
+ }
+
+ /**
+ * Creates a new XML DocumentBuilder
+ *
+ * @param implementation which jaxp implementation should be used
+ * @param classLoader which class loader should be used when getting a new DocumentBuilder
+ * @param namespaceAware Whether the parser should be aware of xml namespaces
+ * @throws RuntimeException if we fail to create one
+ * @return a DocumentBuilder
+ */
+ public static DocumentBuilder getDocumentBuilder(String implementation, ClassLoader classLoader, boolean namespaceAware) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(implementation, classLoader);
- factory.setNamespaceAware(true);
- factory.setXIncludeAware(true);
- // Prevent XXE
+ factory.setNamespaceAware(namespaceAware);
+ // Disable include directives. If enabled this allows inclusion of any resource, such as file:/// and
+ // http:///, and these are read even if the document eventually fails to parse
+ factory.setXIncludeAware(false);
+ // Prevent XXE by disabling DOCTYPE declarations
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ // Disable any kind of external entities. These likely cannot be exploited when doctype is disallowed, but
+ // it's better to leave them disabled in any case. See
+ // https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Could not create an XML builder", e);
diff --git a/yolean/src/main/java/com/yahoo/yolean/Exceptions.java b/vespajlib/src/main/java/com/yahoo/yolean/Exceptions.java
index 89b4e76368b..89b4e76368b 100644
--- a/yolean/src/main/java/com/yahoo/yolean/Exceptions.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/Exceptions.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java b/vespajlib/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java
index d3317b5fb26..d3317b5fb26 100644
--- a/yolean/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/UncheckedInterruptedException.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/chain/After.java b/vespajlib/src/main/java/com/yahoo/yolean/chain/After.java
index a02408bb616..a02408bb616 100644
--- a/yolean/src/main/java/com/yahoo/yolean/chain/After.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/chain/After.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/chain/Before.java b/vespajlib/src/main/java/com/yahoo/yolean/chain/Before.java
index 7bbba8ded5f..7bbba8ded5f 100644
--- a/yolean/src/main/java/com/yahoo/yolean/chain/Before.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/chain/Before.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/chain/Provides.java b/vespajlib/src/main/java/com/yahoo/yolean/chain/Provides.java
index b8bf40686cb..b8bf40686cb 100644
--- a/yolean/src/main/java/com/yahoo/yolean/chain/Provides.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/chain/Provides.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/chain/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/chain/package-info.java
index e767e192ad7..e767e192ad7 100644
--- a/yolean/src/main/java/com/yahoo/yolean/chain/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/chain/package-info.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java
index 0e91a44bf5d..0e91a44bf5d 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ConcurrentResourcePool.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java
index 536d9ab15c1..536d9ab15c1 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMap.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/Memoized.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/Memoized.java
index 8e2b7b7a7eb..8e2b7b7a7eb 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/Memoized.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/Memoized.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java
index ffc761ad625..ffc761ad625 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ResourcePool.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java
index 530be935bc1..530be935bc1 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/Sleeper.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java
index f6d8b68416c..f6d8b68416c 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/ThreadRobustList.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/concurrent/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/package-info.java
index 1e89d85714e..1e89d85714e 100644
--- a/yolean/src/main/java/com/yahoo/yolean/concurrent/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/concurrent/package-info.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java
index 0860c7c34b4..0860c7c34b4 100644
--- a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingConsumer.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java
index 6e459509b1d..6e459509b1d 100644
--- a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingFunction.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java
index 348c1c739ee..348c1c739ee 100644
--- a/yolean/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/function/ThrowingSupplier.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/function/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/function/package-info.java
index e55b39c478f..e55b39c478f 100644
--- a/yolean/src/main/java/com/yahoo/yolean/function/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/function/package-info.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/package-info.java
index c9f2b088688..c9f2b088688 100644
--- a/yolean/src/main/java/com/yahoo/yolean/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/package-info.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/system/CatchSignals.java b/vespajlib/src/main/java/com/yahoo/yolean/system/CatchSignals.java
index 572d8fba122..572d8fba122 100644
--- a/yolean/src/main/java/com/yahoo/yolean/system/CatchSignals.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/system/CatchSignals.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/system/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/system/package-info.java
index cf3a4f33e1a..cf3a4f33e1a 100644
--- a/yolean/src/main/java/com/yahoo/yolean/system/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/system/package-info.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/trace/TraceNode.java b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java
index fd19c1b1388..fd19c1b1388 100644
--- a/yolean/src/main/java/com/yahoo/yolean/trace/TraceNode.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java
index 1b3507777b7..1b3507777b7 100644
--- a/yolean/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceVisitor.java
diff --git a/yolean/src/main/java/com/yahoo/yolean/trace/package-info.java b/vespajlib/src/main/java/com/yahoo/yolean/trace/package-info.java
index dabc8217025..dabc8217025 100644
--- a/yolean/src/main/java/com/yahoo/yolean/trace/package-info.java
+++ b/vespajlib/src/main/java/com/yahoo/yolean/trace/package-info.java
diff --git a/vespajlib/src/test/java/ai/vespa/validation/PathValidatorTest.java b/vespajlib/src/test/java/ai/vespa/validation/PathValidatorTest.java
new file mode 100644
index 00000000000..a2c1bd6bd0c
--- /dev/null
+++ b/vespajlib/src/test/java/ai/vespa/validation/PathValidatorTest.java
@@ -0,0 +1,35 @@
+package ai.vespa.validation;
+
+import org.junit.Test;
+
+import java.nio.file.Path;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class PathValidatorTest {
+
+ @Test
+ public void testPathValidation() {
+ Path root = Path.of("/foo/");
+
+ assertOk(Path.of("/foo/bar"), root);
+ assertOk(Path.of("/foo/foo2/bar"), root);
+ assertOk(Path.of("/foo/foo2/../bar"), root);
+ assertOk(Path.of("/foo/../foo/bar"), root);
+ assertOk(Path.of("/bar/../foo/../foo/bar"), root);
+
+ assertInvalid(Path.of("/foo/../bar"), root);
+ assertInvalid(Path.of("/foo/bar/../../bar"), root);
+ }
+
+ private void assertOk(Path path, Path root) {
+ PathValidator.validateChildOf(root, path);
+ }
+
+ private void assertInvalid(Path path, Path root) {
+ IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class,
+ () -> PathValidator.validateChildOf(root, path));
+ assertEquals("Invalid path %s".formatted(path), illegalArgumentException.getMessage());
+ }
+}
diff --git a/yolean/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java b/vespajlib/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java
index 53cf3efe363..53cf3efe363 100644
--- a/yolean/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/ExceptionsTestCase.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java
index 3f2526172a9..3f2526172a9 100644
--- a/yolean/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/CopyOnWriteHashMapTest.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java
index 7f2f49c75f2..7f2f49c75f2 100644
--- a/yolean/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/MemoizedTest.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java
index c2edaf1fb00..c2edaf1fb00 100644
--- a/yolean/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/concurrent/ThreadRobustListTestCase.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java b/vespajlib/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java
index 66a27235088..66a27235088 100644
--- a/yolean/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/system/CatchSignalsTestCase.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java b/vespajlib/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java
index 3019b646867..3019b646867 100644
--- a/yolean/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/trace/TraceNodeTestCase.java
diff --git a/yolean/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java b/vespajlib/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java
index 4eaa5b0241e..4eaa5b0241e 100644
--- a/yolean/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java
+++ b/vespajlib/src/test/java/com/yahoo/yolean/trace/TraceVisitorTestCase.java
diff --git a/vespalib/CMakeLists.txt b/vespalib/CMakeLists.txt
index 69bd709c613..609c825dafa 100644
--- a/vespalib/CMakeLists.txt
+++ b/vespalib/CMakeLists.txt
@@ -101,6 +101,7 @@ vespa_define_module(
src/tests/net/socket_spec
src/tests/net/sync_crypto_socket
src/tests/net/tls/auto_reloading_tls_crypto_engine
+ src/tests/net/tls/capabilities
src/tests/net/tls/direct_buffer_bio
src/tests/net/tls/openssl_impl
src/tests/net/tls/policy_checking_certificate_verifier
diff --git a/vespalib/src/apps/vespa-tsan-digest/tsan_digest.cpp b/vespalib/src/apps/vespa-tsan-digest/tsan_digest.cpp
index 2117db276d8..d015cdb0f89 100644
--- a/vespalib/src/apps/vespa-tsan-digest/tsan_digest.cpp
+++ b/vespalib/src/apps/vespa-tsan-digest/tsan_digest.cpp
@@ -220,7 +220,7 @@ public:
++raw_reports;
}
std::vector<vespalib::string> make_keys() const override {
- return {fmt("raw:%zu", get_hash(_lines))};
+ return {fmt("raw:%" PRIu64, get_hash(_lines))};
}
void merge(const Report &) override { ++_count; }
size_t count() const override { return _count; }
@@ -277,7 +277,7 @@ public:
std::vector<vespalib::string> make_keys() const override {
std::vector<vespalib::string> result;
for (const auto &node: _nodes) {
- result.push_back(fmt("race:%zu", node.trace.hash()));
+ result.push_back(fmt("race:%" PRIu64, node.trace.hash()));
}
return result;
}
diff --git a/vespalib/src/tests/datastore/buffer_type/buffer_type_test.cpp b/vespalib/src/tests/datastore/buffer_type/buffer_type_test.cpp
index 6988e41add1..de7d899e68a 100644
--- a/vespalib/src/tests/datastore/buffer_type/buffer_type_test.cpp
+++ b/vespalib/src/tests/datastore/buffer_type/buffer_type_test.cpp
@@ -27,7 +27,7 @@ struct Setup {
_allocGrowFactor(0.5),
_resizing(false)
{}
- Setup(const Setup& rhs);
+ Setup(const Setup& rhs) noexcept;
Setup &minArrays(uint32_t value) { _minArrays = value; return *this; }
Setup &used(size_t value) { _usedElems = value; return *this; }
Setup &needed(size_t value) { _neededElems = value; return *this; }
@@ -36,7 +36,7 @@ struct Setup {
Setup &resizing(bool value) { _resizing = value; return *this; }
};
-Setup::Setup(const Setup& rhs)
+Setup::Setup(const Setup& rhs) noexcept
: _minArrays(rhs._minArrays),
_usedElems(rhs._usedElems.load(std::memory_order_relaxed)),
_neededElems(rhs._neededElems),
diff --git a/vespalib/src/tests/net/tls/capabilities/CMakeLists.txt b/vespalib/src/tests/net/tls/capabilities/CMakeLists.txt
new file mode 100644
index 00000000000..4e366674d36
--- /dev/null
+++ b/vespalib/src/tests/net/tls/capabilities/CMakeLists.txt
@@ -0,0 +1,10 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+vespa_add_executable(vespalib_net_tls_capabilities_test_app TEST
+ SOURCES
+ capabilities_test.cpp
+ DEPENDS
+ vespalib
+)
+vespa_add_test(NAME vespalib_net_tls_capabilities_test_app
+ COMMAND vespalib_net_tls_capabilities_test_app)
+
diff --git a/vespalib/src/tests/net/tls/capabilities/capabilities_test.cpp b/vespalib/src/tests/net/tls/capabilities/capabilities_test.cpp
new file mode 100644
index 00000000000..4a20200c631
--- /dev/null
+++ b/vespalib/src/tests/net/tls/capabilities/capabilities_test.cpp
@@ -0,0 +1,196 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include <vespa/vespalib/net/tls/capability_set.h>
+#include <vespa/vespalib/testkit/test_kit.h>
+
+using namespace vespalib;
+using namespace vespalib::net::tls;
+using namespace std::string_view_literals;
+
+TEST("Capability instances are equality comparable") {
+ auto cap1 = Capability::content_document_api();
+ auto cap2 = Capability::content_document_api();
+ auto cap3 = Capability::content_storage_api();
+ EXPECT_EQUAL(cap1, cap2);
+ EXPECT_EQUAL(cap2, cap1);
+ EXPECT_NOT_EQUAL(cap1, cap3);
+}
+
+TEST("CapabilitySet instances are equality comparable") {
+ const auto cap1 = Capability::content_document_api();
+ const auto cap2 = Capability::content_search_api();
+
+ const auto all_caps = CapabilitySet::make_with_all_capabilities();
+ const auto set_12_a = CapabilitySet::of({cap1, cap2});
+ const auto set_12_b = CapabilitySet::of({cap1, cap2});
+ const auto set_1 = CapabilitySet::of({cap1});
+ const auto empty = CapabilitySet::make_empty();
+
+ EXPECT_EQUAL(all_caps, all_caps);
+ EXPECT_EQUAL(empty, empty);
+ EXPECT_EQUAL(set_12_a, set_12_b);
+ EXPECT_EQUAL(set_12_b, set_12_a);
+
+ EXPECT_NOT_EQUAL(all_caps, empty);
+ EXPECT_NOT_EQUAL(set_12_a, set_1);
+ EXPECT_NOT_EQUAL(set_12_a, all_caps);
+ EXPECT_NOT_EQUAL(set_1, empty);
+}
+
+TEST("Can get underlying name of all Capability instances") {
+ EXPECT_EQUAL(Capability::content_storage_api().name(), "vespa.content.storage_api"sv);
+ EXPECT_EQUAL(Capability::content_document_api().name(), "vespa.content.document_api"sv);
+ EXPECT_EQUAL(Capability::content_search_api().name(), "vespa.content.search_api"sv);
+ EXPECT_EQUAL(Capability::slobrok_api().name(), "vespa.slobrok.api"sv);
+ EXPECT_EQUAL(Capability::content_status_pages().name(), "vespa.content.status_pages"sv);
+ EXPECT_EQUAL(Capability::content_metrics_api().name(), "vespa.content.metrics_api"sv);
+ EXPECT_EQUAL(Capability::content_cluster_controller_internal_state_api().name(),
+ "vespa.content.cluster_controller.internal_state_api"sv);
+}
+
+TEST("Capability instances can be stringified") {
+ EXPECT_EQUAL(Capability::content_storage_api().to_string(), "Capability(vespa.content.storage_api)");
+}
+
+namespace {
+
+void check_capability_mapping(const std::string& name, Capability expected) {
+ auto cap = Capability::find_capability(name);
+ ASSERT_TRUE(cap.has_value());
+ EXPECT_EQUAL(*cap, expected);
+}
+
+void check_capability_set_mapping(const std::string& name, CapabilitySet expected) {
+ auto caps = CapabilitySet::find_capability_set(name);
+ ASSERT_TRUE(caps.has_value());
+ EXPECT_EQUAL(*caps, expected);
+}
+
+}
+
+TEST("All known capabilities can be looked up by name") {
+ check_capability_mapping("vespa.content.storage_api", Capability::content_storage_api());
+ check_capability_mapping("vespa.content.document_api", Capability::content_document_api());
+ check_capability_mapping("vespa.content.search_api", Capability::content_search_api());
+ check_capability_mapping("vespa.slobrok.api", Capability::slobrok_api());
+ check_capability_mapping("vespa.content.status_pages", Capability::content_status_pages());
+ check_capability_mapping("vespa.content.metrics_api", Capability::content_metrics_api());
+ check_capability_mapping("vespa.content.cluster_controller.internal_state_api",
+ Capability::content_cluster_controller_internal_state_api());
+}
+
+TEST("Unknown capability name returns nullopt") {
+ EXPECT_FALSE(Capability::find_capability("vespa.content.stale_cat_memes").has_value());
+}
+
+TEST("CapabilitySet instances can be stringified") {
+ EXPECT_EQUAL(CapabilitySet::content_node().to_string(),
+ "CapabilitySet({vespa.content.storage_api, vespa.content.document_api, vespa.slobrok.api})");
+}
+
+TEST("All known capability sets can be looked up by name") {
+ check_capability_set_mapping("vespa.content_node", CapabilitySet::content_node());
+ check_capability_set_mapping("vespa.container_node", CapabilitySet::container_node());
+ check_capability_set_mapping("vespa.telemetry", CapabilitySet::telemetry());
+ check_capability_set_mapping("vespa.cluster_controller_node", CapabilitySet::cluster_controller_node());
+ check_capability_set_mapping("vespa.config_server", CapabilitySet::config_server());
+}
+
+TEST("Unknown capability set name returns nullopt") {
+ EXPECT_FALSE(CapabilitySet::find_capability_set("vespa.unicorn_launcher").has_value());
+}
+
+TEST("Resolving a capability set adds all its underlying capabilities") {
+ CapabilitySet caps;
+ EXPECT_TRUE(caps.resolve_and_add("vespa.content_node"));
+ // Slightly suboptimal; this test will fail if the default set of capabilities for vespa.content_node changes.
+ EXPECT_EQUAL(caps.count(), 3u);
+ EXPECT_FALSE(caps.empty());
+ EXPECT_TRUE(caps.contains(Capability::content_storage_api()));
+ EXPECT_TRUE(caps.contains(Capability::content_document_api()));
+ EXPECT_TRUE(caps.contains(Capability::slobrok_api()));
+ EXPECT_FALSE(caps.contains(Capability::content_search_api()));
+}
+
+TEST("Resolving a single capability adds it to the underlying capabilities") {
+ CapabilitySet caps;
+ EXPECT_TRUE(caps.resolve_and_add("vespa.slobrok.api"));
+ EXPECT_EQUAL(caps.count(), 1u);
+ EXPECT_FALSE(caps.empty());
+ EXPECT_TRUE(caps.contains(Capability::slobrok_api()));
+ EXPECT_FALSE(caps.contains(Capability::content_storage_api()));
+}
+
+TEST("Resolving an unknown capability set returns false and does not add anything") {
+ CapabilitySet caps;
+ EXPECT_FALSE(caps.resolve_and_add("vespa.distributors_evil_twin_with_an_evil_goatee"));
+ EXPECT_EQUAL(caps.count(), 0u);
+ EXPECT_TRUE(caps.empty());
+}
+
+TEST("Resolving multiple capabilities/sets adds union of capabilities") {
+ CapabilitySet caps;
+ EXPECT_TRUE(caps.resolve_and_add("vespa.content_node")); // CapabilitySet
+ EXPECT_TRUE(caps.resolve_and_add("vespa.container_node")); // ditto
+ EXPECT_EQUAL(caps, CapabilitySet::of({Capability::content_storage_api(), Capability::content_document_api(),
+ Capability::slobrok_api(), Capability::content_search_api()}));
+ EXPECT_TRUE(caps.resolve_and_add("vespa.content.metrics_api")); // Capability (single)
+ EXPECT_EQUAL(caps, CapabilitySet::of({Capability::content_storage_api(), Capability::content_document_api(),
+ Capability::slobrok_api(), Capability::content_search_api(),
+ Capability::content_metrics_api()}));
+}
+
+TEST("Default-constructed CapabilitySet has no capabilities") {
+ CapabilitySet caps;
+ EXPECT_EQUAL(caps.count(), 0u);
+ EXPECT_TRUE(caps.empty());
+ EXPECT_FALSE(caps.contains(Capability::content_storage_api()));
+}
+
+TEST("CapabilitySet can be created with all capabilities") {
+ auto caps = CapabilitySet::make_with_all_capabilities();
+ EXPECT_EQUAL(caps.count(), CapabilitySet::max_count());
+ EXPECT_TRUE(caps.contains(Capability::content_storage_api()));
+ EXPECT_TRUE(caps.contains(Capability::content_metrics_api()));
+ // ... we just assume the rest are present as well.
+}
+
+TEST("CapabilitySet::contains_all() requires an intersection of capabilities") {
+ auto cap1 = Capability::content_document_api();
+ auto cap2 = Capability::content_search_api();
+ auto cap3 = Capability::content_storage_api();
+
+ const auto all_caps = CapabilitySet::make_with_all_capabilities();
+ auto set_123 = CapabilitySet::of({cap1, cap2, cap3});
+ auto set_13 = CapabilitySet::of({cap1, cap3});
+ auto set_2 = CapabilitySet::of({cap2});
+ auto set_23 = CapabilitySet::of({cap2, cap3});
+ auto empty = CapabilitySet::make_empty();
+
+ // Sets contain themselves
+ EXPECT_TRUE(all_caps.contains_all(all_caps));
+ EXPECT_TRUE(set_13.contains_all(set_13));
+ EXPECT_TRUE(set_2.contains_all(set_2));
+ EXPECT_TRUE(empty.contains_all(empty));
+
+ // Supersets contain subsets
+ EXPECT_TRUE(all_caps.contains_all(set_123));
+ EXPECT_TRUE(all_caps.contains_all(set_13));
+ EXPECT_TRUE(set_123.contains_all(set_13));
+ EXPECT_TRUE(set_2.contains_all(empty));
+
+ // Subsets do not contain supersets
+ EXPECT_FALSE(set_123.contains_all(all_caps));
+ EXPECT_FALSE(set_13.contains_all(set_123));
+ EXPECT_FALSE(empty.contains_all(set_2));
+
+ // Partially overlapping sets are not contained in each other
+ EXPECT_FALSE(set_13.contains_all(set_23));
+ EXPECT_FALSE(set_23.contains_all(set_13));
+
+ // Fully disjoint sets are not contained in each other
+ EXPECT_FALSE(set_2.contains_all(set_13));
+ EXPECT_FALSE(set_13.contains_all(set_2));
+}
+
+TEST_MAIN() { TEST_RUN_ALL(); }
diff --git a/vespalib/src/tests/net/tls/openssl_impl/openssl_impl_test.cpp b/vespalib/src/tests/net/tls/openssl_impl/openssl_impl_test.cpp
index 1de10939bea..3d19c335c19 100644
--- a/vespalib/src/tests/net/tls/openssl_impl/openssl_impl_test.cpp
+++ b/vespalib/src/tests/net/tls/openssl_impl/openssl_impl_test.cpp
@@ -542,7 +542,7 @@ struct PrintingCertificateCallback : CertificateVerificationCallback {
for (auto& dns : peer_creds.dns_sans) {
fprintf(stderr, "Got a DNS SAN entry: %s\n", dns.c_str());
}
- return VerificationResult::make_authorized_for_all_roles();
+ return VerificationResult::make_authorized_with_all_capabilities();
}
};
@@ -551,7 +551,7 @@ struct MockCertificateCallback : CertificateVerificationCallback {
mutable PeerCredentials creds; // only used in single thread testing context
VerificationResult verify(const PeerCredentials& peer_creds) const override {
creds = peer_creds;
- return VerificationResult::make_authorized_for_all_roles();
+ return VerificationResult::make_authorized_with_all_capabilities();
}
};
@@ -712,6 +712,29 @@ TEST_F("Server allows client with certificate that DOES match peer policy", Cert
EXPECT_TRUE(f.handshake());
}
+TEST_F("Authz policy-derived peer capabilities are propagated to CryptoCodec", CertFixture) {
+ auto server_ck = f.create_ca_issued_peer_cert({}, {{"DNS:hello.world.example.com"}});
+ auto authorized = authorized_peers({policy_with({required_san_dns("stale.memes.example.com")},
+ CapabilitySet::of({Capability::content_search_api(),
+ Capability::content_status_pages()})),
+ policy_with({required_san_dns("fresh.memes.example.com")},
+ CapabilitySet::make_with_all_capabilities())});
+ f.reset_server_with_cert_opts(server_ck, std::move(authorized));
+ auto client_ck = f.create_ca_issued_peer_cert({}, {{"DNS:stale.memes.example.com"}});
+ f.reset_client_with_cert_opts(client_ck, AuthorizedPeers::allow_all_authenticated());
+
+ ASSERT_TRUE(f.handshake());
+
+ // Note: "inversion" of client <-> server is because the capabilities are that of the _peer_.
+ auto client_caps = f.server->granted_capabilities();
+ auto server_caps = f.client->granted_capabilities();
+ // Server (from client's PoV) implicitly has all capabilities since client doesn't specify any policies
+ EXPECT_EQUAL(server_caps, CapabilitySet::make_with_all_capabilities());
+ // Client (from server's PoV) only has capabilities for the rule matching its DNS SAN entry
+ EXPECT_EQUAL(client_caps, CapabilitySet::of({Capability::content_search_api(),
+ Capability::content_status_pages()}));
+}
+
void reset_peers_with_server_authz_mode(CertFixture& f, AuthorizationMode authz_mode) {
auto ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
diff --git a/vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp b/vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp
index fa2bc1a2eaf..c456d7e2a5c 100644
--- a/vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp
+++ b/vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp
@@ -127,9 +127,9 @@ bool verify(AuthorizedPeers authorized_peers, const PeerCredentials& peer_creds)
return verifier->verify(peer_creds).success();
}
-AssumedRoles verify_roles(AuthorizedPeers authorized_peers, const PeerCredentials& peer_creds) {
+CapabilitySet verify_capabilities(AuthorizedPeers authorized_peers, const PeerCredentials& peer_creds) {
auto verifier = create_verify_callback_from(std::move(authorized_peers));
- return verifier->verify(peer_creds).steal_assumed_roles();
+ return verifier->verify(peer_creds).granted_capabilities();
}
TEST("Default-constructed AuthorizedPeers does not allow all authenticated peers") {
@@ -142,14 +142,16 @@ TEST("Specially constructed set of policies allows all authenticated peers") {
EXPECT_TRUE(verify(allow_all, creds_with_dns_sans({{"anything.goes"}})));
}
-TEST("specially constructed set of policies returns wildcard role set") {
+TEST("specially constructed set of policies returns full capability set") {
auto allow_all = AuthorizedPeers::allow_all_authenticated();
- EXPECT_EQUAL(verify_roles(allow_all, creds_with_dns_sans({{"anything.goes"}})), AssumedRoles::make_wildcard_role());
+ EXPECT_EQUAL(verify_capabilities(allow_all, creds_with_dns_sans({{"anything.goes"}})),
+ CapabilitySet::make_with_all_capabilities());
}
-TEST("policy without explicit role set implicitly returns wildcard role set") {
+TEST("policy without explicit capability set implicitly returns full capability set") {
auto authorized = authorized_peers({policy_with({required_san_dns("yolo.swag")})});
- EXPECT_EQUAL(verify_roles(authorized, creds_with_dns_sans({{"yolo.swag"}})), AssumedRoles::make_wildcard_role());
+ EXPECT_EQUAL(verify_capabilities(authorized, creds_with_dns_sans({{"yolo.swag"}})),
+ CapabilitySet::make_with_all_capabilities());
}
TEST("Non-empty policies do not allow all authenticated peers") {
@@ -246,11 +248,11 @@ struct MultiPolicyMatchFixture {
};
MultiPolicyMatchFixture::MultiPolicyMatchFixture()
- : authorized(authorized_peers({policy_with({required_san_dns("hello.world")}, assumed_roles({"r1"})),
- policy_with({required_san_dns("foo.bar")}, assumed_roles({"r2"})),
- policy_with({required_san_dns("zoid.berg")}, assumed_roles({"r2", "r3"})),
- policy_with({required_san_dns("secret.sauce")}, AssumedRoles::make_wildcard_role()),
- policy_with({required_san_uri("zoid://be.rg/")}, assumed_roles({"r4"}))}))
+ : authorized(authorized_peers({policy_with({required_san_dns("hello.world")}, CapabilitySet::of({cap_1()})),
+ policy_with({required_san_dns("foo.bar")}, CapabilitySet::of({cap_2()})),
+ policy_with({required_san_dns("zoid.berg")}, CapabilitySet::of({cap_2(), cap_3()})),
+ policy_with({required_san_dns("secret.sauce")}, CapabilitySet::make_with_all_capabilities()),
+ policy_with({required_san_uri("zoid://be.rg/")}, CapabilitySet::of({cap_4()}))}))
{}
MultiPolicyMatchFixture::~MultiPolicyMatchFixture() = default;
@@ -262,32 +264,37 @@ TEST_F("peer verifies if it matches at least 1 policy of multiple", MultiPolicyM
EXPECT_TRUE(verify(f.authorized, creds_with_uri_sans({{"zoid://be.rg/"}})));
}
-TEST_F("role set is returned for single matched policy", MultiPolicyMatchFixture) {
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"hello.world"}})), assumed_roles({"r1"}));
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"foo.bar"}})), assumed_roles({"r2"}));
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"zoid.berg"}})), assumed_roles({"r2", "r3"}));
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"secret.sauce"}})), AssumedRoles::make_wildcard_role());
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_uri_sans({{"zoid://be.rg/"}})), assumed_roles({"r4"}));
+TEST_F("capability set is returned for single matched policy", MultiPolicyMatchFixture) {
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"hello.world"}})),
+ CapabilitySet::of({cap_1()}));
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"foo.bar"}})),
+ CapabilitySet::of({cap_2()}));
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"zoid.berg"}})),
+ CapabilitySet::of({cap_2(), cap_3()}));
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"secret.sauce"}})),
+ CapabilitySet::make_with_all_capabilities());
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_uri_sans({{"zoid://be.rg/"}})),
+ CapabilitySet::of({cap_4()}));
}
TEST_F("peer verifies if it matches multiple policies", MultiPolicyMatchFixture) {
EXPECT_TRUE(verify(f.authorized, creds_with_dns_sans({{"hello.world"}, {"zoid.berg"}})));
}
-TEST_F("union role set is returned if multiple policies match", MultiPolicyMatchFixture) {
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"zoid.berg"}})),
- assumed_roles({"r1", "r2", "r3"}));
- // Wildcard role is tracked as a distinct role string
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"secret.sauce"}})),
- assumed_roles({"r1", "r2", "*"}));
+TEST_F("union capability set is returned if multiple policies match", MultiPolicyMatchFixture) {
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"zoid.berg"}})),
+ CapabilitySet::of({cap_1(), cap_2(), cap_3()}));
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"secret.sauce"}})),
+ CapabilitySet::make_with_all_capabilities());
}
TEST_F("peer must match at least 1 of multiple policies", MultiPolicyMatchFixture) {
EXPECT_FALSE(verify(f.authorized, creds_with_dns_sans({{"does.not.exist"}})));
}
-TEST_F("empty role set is returned if no policies match", MultiPolicyMatchFixture) {
- EXPECT_EQUAL(verify_roles(f.authorized, creds_with_dns_sans({{"does.not.exist"}})), AssumedRoles::make_empty());
+TEST_F("empty capability set is returned if no policies match", MultiPolicyMatchFixture) {
+ EXPECT_EQUAL(verify_capabilities(f.authorized, creds_with_dns_sans({{"does.not.exist"}})),
+ CapabilitySet::make_empty());
}
TEST("CN requirement without glob pattern is matched as exact string") {
@@ -308,62 +315,32 @@ TEST("CN requirement can include glob wildcards") {
EXPECT_FALSE(verify(authorized, creds_with_cn("world")));
}
-TEST("AssumedRoles by default contains no roles") {
- AssumedRoles roles;
- EXPECT_TRUE(roles.empty());
- EXPECT_FALSE(roles.can_assume_role("foo"));
- auto empty = AssumedRoles::make_empty();
- EXPECT_EQUAL(roles, empty);
-}
-
-TEST("AssumedRoles can be constructed with an explicit set of roles") {
- auto roles = AssumedRoles::make_for_roles({"foo", "bar"});
- EXPECT_TRUE(roles.can_assume_role("foo"));
- EXPECT_TRUE(roles.can_assume_role("bar"));
- EXPECT_FALSE(roles.can_assume_role("baz"));
-}
-
-TEST("AssumedRoles wildcard role can assume any role") {
- auto roles = AssumedRoles::make_wildcard_role();
- EXPECT_TRUE(roles.can_assume_role("foo"));
- EXPECT_TRUE(roles.can_assume_role("bar"));
-}
-
-TEST("AssumedRolesBuilder builds union set of added roles") {
- AssumedRolesBuilder builder;
- builder.add_union(AssumedRoles::make_for_roles({"hello", "world"}));
- builder.add_union(AssumedRoles::make_for_roles({"hello", "moon"}));
- builder.add_union(AssumedRoles::make_for_roles({"goodbye", "moon"}));
- auto roles = builder.build_with_move();
- EXPECT_EQUAL(roles, AssumedRoles::make_for_roles({"hello", "goodbye", "moon", "world"}));
-}
-
TEST("VerificationResult is not authorized by default") {
VerificationResult result;
EXPECT_FALSE(result.success());
- EXPECT_TRUE(result.assumed_roles().empty());
+ EXPECT_TRUE(result.granted_capabilities().empty());
}
TEST("VerificationResult can be explicitly created as not authorized") {
auto result = VerificationResult::make_not_authorized();
EXPECT_FALSE(result.success());
- EXPECT_TRUE(result.assumed_roles().empty());
+ EXPECT_TRUE(result.granted_capabilities().empty());
}
-TEST("VerificationResult can be pre-authorized for all roles") {
- auto result = VerificationResult::make_authorized_for_all_roles();
+TEST("VerificationResult can be pre-authorized with all capabilities") {
+ auto result = VerificationResult::make_authorized_with_all_capabilities();
EXPECT_TRUE(result.success());
- EXPECT_FALSE(result.assumed_roles().empty());
- EXPECT_TRUE(result.assumed_roles().can_assume_role("foo"));
+ EXPECT_FALSE(result.granted_capabilities().empty());
+ EXPECT_EQUAL(result.granted_capabilities(), CapabilitySet::make_with_all_capabilities());
}
-TEST("VerificationResult can be pre-authorized for an explicit set of roles") {
- auto result = VerificationResult::make_authorized_for_roles(AssumedRoles::make_for_roles({"elden", "ring"}));
+TEST("VerificationResult can be pre-authorized for an explicit set of capabilities") {
+ auto result = VerificationResult::make_authorized_with_capabilities(CapabilitySet::of({cap_2(), cap_3()}));
EXPECT_TRUE(result.success());
- EXPECT_FALSE(result.assumed_roles().empty());
- EXPECT_TRUE(result.assumed_roles().can_assume_role("elden"));
- EXPECT_TRUE(result.assumed_roles().can_assume_role("ring"));
- EXPECT_FALSE(result.assumed_roles().can_assume_role("O you don't have the right"));
+ EXPECT_FALSE(result.granted_capabilities().empty());
+ EXPECT_TRUE(result.granted_capabilities().contains(cap_2()));
+ EXPECT_TRUE(result.granted_capabilities().contains(cap_3()));
+ EXPECT_FALSE(result.granted_capabilities().contains(cap_1()));
}
// TODO test CN _and_ SAN
diff --git a/vespalib/src/tests/net/tls/transport_options/transport_options_reading_test.cpp b/vespalib/src/tests/net/tls/transport_options/transport_options_reading_test.cpp
index be2c63b03f2..8d49bdbf73d 100644
--- a/vespalib/src/tests/net/tls/transport_options/transport_options_reading_test.cpp
+++ b/vespalib/src/tests/net/tls/transport_options/transport_options_reading_test.cpp
@@ -198,6 +198,68 @@ TEST("unknown fields are ignored at parse-time") {
EXPECT_TRUE(read_options_from_json_string(json).get() != nullptr); // And no exception thrown.
}
+TEST("policy without explicit capabilities implicitly get all capabilities") {
+ const char* json = R"({
+ "required-credentials":[
+ {"field": "SAN_DNS", "must-match": "hello.world"}
+ ]
+ })";
+ EXPECT_EQUAL(authorized_peers({policy_with({required_san_dns("hello.world")},
+ CapabilitySet::make_with_all_capabilities())}),
+ parse_policies(json).authorized_peers());
+}
+
+TEST("specifying a capability set adds all its underlying capabilities") {
+ const char* json = R"({
+ "required-credentials":[
+ {"field": "SAN_DNS", "must-match": "*.cool-content-clusters.example" }
+ ],
+ "capabilities": ["vespa.content_node"]
+ })";
+ EXPECT_EQUAL(authorized_peers({policy_with({required_san_dns("*.cool-content-clusters.example")},
+ CapabilitySet::content_node())}),
+ parse_policies(json).authorized_peers());
+}
+
+TEST("can specify single leaf capabilities") {
+ const char* json = R"({
+ "required-credentials":[
+ {"field": "SAN_DNS", "must-match": "*.cool-content-clusters.example" }
+ ],
+ "capabilities": ["vespa.content.metrics_api", "vespa.slobrok.api"]
+ })";
+ EXPECT_EQUAL(authorized_peers({policy_with({required_san_dns("*.cool-content-clusters.example")},
+ CapabilitySet::of({Capability::content_metrics_api(),
+ Capability::slobrok_api()}))}),
+ parse_policies(json).authorized_peers());
+}
+
+TEST("specifying multiple capability sets adds union of underlying capabilities") {
+ const char* json = R"({
+ "required-credentials":[
+ {"field": "SAN_DNS", "must-match": "*.cool-content-clusters.example" }
+ ],
+ "capabilities": ["vespa.content_node", "vespa.container_node"]
+ })";
+ CapabilitySet caps;
+ caps.add_all(CapabilitySet::content_node());
+ caps.add_all(CapabilitySet::container_node());
+ EXPECT_EQUAL(authorized_peers({policy_with({required_san_dns("*.cool-content-clusters.example")}, caps)}),
+ parse_policies(json).authorized_peers());
+}
+
+TEST("empty capabilities array is not allowed") {
+ const char* json = R"({
+ "required-credentials":[
+ {"field": "SAN_DNS", "must-match": "*.cool-content-clusters.example" }
+ ],
+ "capabilities": []
+ })";
+ EXPECT_EXCEPTION(parse_policies(json), vespalib::IllegalArgumentException,
+ "\"capabilities\" array must either be not present (implies "
+ "all capabilities) or contain at least one capability name");
+}
+
// TODO test parsing of multiple policies
TEST_MAIN() { TEST_RUN_ALL(); }
diff --git a/vespalib/src/tests/util/generationhandler_stress/generation_handler_stress_test.cpp b/vespalib/src/tests/util/generationhandler_stress/generation_handler_stress_test.cpp
index 57c765b8e44..74af25b54a8 100644
--- a/vespalib/src/tests/util/generationhandler_stress/generation_handler_stress_test.cpp
+++ b/vespalib/src/tests/util/generationhandler_stress/generation_handler_stress_test.cpp
@@ -48,11 +48,11 @@ struct IndirectContext {
static constexpr size_t values_size = 65536;
uint64_t _values[values_size];
- IndirectContext();
+ IndirectContext() noexcept;
uint64_t* calc_value_ptr(uint64_t idx) { return &_values[(idx & (values_size - 1))]; }
};
-IndirectContext::IndirectContext()
+IndirectContext::IndirectContext() noexcept
: _value_ptr(nullptr),
_pad(),
_values()
diff --git a/vespalib/src/vespa/vespalib/net/CMakeLists.txt b/vespalib/src/vespa/vespalib/net/CMakeLists.txt
index e3eb32d3775..05c404ec2a7 100644
--- a/vespalib/src/vespa/vespalib/net/CMakeLists.txt
+++ b/vespalib/src/vespa/vespalib/net/CMakeLists.txt
@@ -9,6 +9,7 @@ endif()
vespa_add_library(vespalib_vespalib_net OBJECT
SOURCES
async_resolver.cpp
+ connection_auth_context.cpp
crypto_engine.cpp
crypto_socket.cpp
selector.cpp
diff --git a/vespalib/src/vespa/vespalib/net/connection_auth_context.cpp b/vespalib/src/vespa/vespalib/net/connection_auth_context.cpp
new file mode 100644
index 00000000000..5dd41b3b4d5
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/connection_auth_context.cpp
@@ -0,0 +1,21 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "connection_auth_context.h"
+
+namespace vespalib::net {
+
+ConnectionAuthContext::ConnectionAuthContext(tls::PeerCredentials peer_credentials,
+ tls::CapabilitySet capabilities) noexcept
+ : _peer_credentials(std::move(peer_credentials)),
+ _capabilities(std::move(capabilities))
+{
+}
+
+ConnectionAuthContext::ConnectionAuthContext(const ConnectionAuthContext&) = default;
+ConnectionAuthContext& ConnectionAuthContext::operator=(const ConnectionAuthContext&) = default;
+ConnectionAuthContext::ConnectionAuthContext(ConnectionAuthContext&&) noexcept = default;
+ConnectionAuthContext& ConnectionAuthContext::operator=(ConnectionAuthContext&&) noexcept = default;
+
+ConnectionAuthContext::~ConnectionAuthContext() = default;
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/connection_auth_context.h b/vespalib/src/vespa/vespalib/net/connection_auth_context.h
new file mode 100644
index 00000000000..fc9815f8b8e
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/connection_auth_context.h
@@ -0,0 +1,29 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#pragma once
+
+// TODO consider moving out of tls sub-namespace
+#include <vespa/vespalib/net/tls/peer_credentials.h>
+#include <vespa/vespalib/net/tls/capability_set.h>
+
+namespace vespalib::net {
+
+class ConnectionAuthContext {
+ tls::PeerCredentials _peer_credentials;
+ tls::CapabilitySet _capabilities;
+public:
+ ConnectionAuthContext(tls::PeerCredentials peer_credentials,
+ tls::CapabilitySet capabilities) noexcept;
+
+ ConnectionAuthContext(const ConnectionAuthContext&);
+ ConnectionAuthContext& operator=(const ConnectionAuthContext&);
+ ConnectionAuthContext(ConnectionAuthContext&&) noexcept;
+ ConnectionAuthContext& operator=(ConnectionAuthContext&&) noexcept;
+
+ ~ConnectionAuthContext();
+
+ const tls::PeerCredentials& peer_credentials() const noexcept { return _peer_credentials; }
+ const tls::CapabilitySet& capabilities() const noexcept { return _capabilities; }
+};
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/crypto_socket.cpp b/vespalib/src/vespa/vespalib/net/crypto_socket.cpp
index 8d3116339a3..0ae90be8539 100644
--- a/vespalib/src/vespa/vespalib/net/crypto_socket.cpp
+++ b/vespalib/src/vespa/vespalib/net/crypto_socket.cpp
@@ -1,9 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "crypto_socket.h"
+#include <vespa/vespalib/net/connection_auth_context.h>
namespace vespalib {
CryptoSocket::~CryptoSocket() = default;
+std::unique_ptr<net::ConnectionAuthContext>
+CryptoSocket::make_auth_context()
+{
+ return std::make_unique<net::ConnectionAuthContext>(
+ net::tls::PeerCredentials(),
+ net::tls::CapabilitySet::make_with_all_capabilities());
+}
+
} // namespace vespalib
diff --git a/vespalib/src/vespa/vespalib/net/crypto_socket.h b/vespalib/src/vespa/vespalib/net/crypto_socket.h
index a6ed6553bbe..9ae2af08084 100644
--- a/vespalib/src/vespa/vespalib/net/crypto_socket.h
+++ b/vespalib/src/vespa/vespalib/net/crypto_socket.h
@@ -7,6 +7,8 @@
namespace vespalib {
+namespace net { class ConnectionAuthContext; }
+
/**
* Abstraction of a low-level async network socket which can produce
* io events and allows encrypting written data and decrypting read
@@ -143,6 +145,18 @@ struct CryptoSocket {
**/
virtual void drop_empty_buffers() = 0;
+ /**
+ * If the underlying transport channel supports authn/authz,
+ * returns a new ConnectionAuthContext object containing the verified
+ * credentials of the peer as well as the resulting peer capabilities
+ * inferred by our own policy matching.
+ *
+ * If the underlying transport channel does _not_ support authn/authz
+ * (such as a plaintext connection) a dummy context is returned which
+ * offers _all_ capabilities.
+ */
+ [[nodiscard]] virtual std::unique_ptr<net::ConnectionAuthContext> make_auth_context();
+
virtual ~CryptoSocket();
};
diff --git a/vespalib/src/vespa/vespalib/net/tls/CMakeLists.txt b/vespalib/src/vespa/vespalib/net/tls/CMakeLists.txt
index a94d088b6a8..5be2e0d4387 100644
--- a/vespalib/src/vespa/vespalib/net/tls/CMakeLists.txt
+++ b/vespalib/src/vespa/vespalib/net/tls/CMakeLists.txt
@@ -1,9 +1,10 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
vespa_add_library(vespalib_vespalib_net_tls OBJECT
SOURCES
- assumed_roles.cpp
authorization_mode.cpp
auto_reloading_tls_crypto_engine.cpp
+ capability.cpp
+ capability_set.cpp
crypto_codec.cpp
crypto_codec_adapter.cpp
maybe_tls_crypto_engine.cpp
diff --git a/vespalib/src/vespa/vespalib/net/tls/assumed_roles.cpp b/vespalib/src/vespa/vespalib/net/tls/assumed_roles.cpp
deleted file mode 100644
index 672458d0024..00000000000
--- a/vespalib/src/vespa/vespalib/net/tls/assumed_roles.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#include "assumed_roles.h"
-#include <vespa/vespalib/stllike/asciistream.h>
-#include <algorithm>
-#include <ostream>
-
-namespace vespalib::net::tls {
-
-const string AssumedRoles::WildcardRole("*");
-
-AssumedRoles::AssumedRoles() = default;
-
-AssumedRoles::AssumedRoles(RoleSet assumed_roles)
- : _assumed_roles(std::move(assumed_roles))
-{}
-
-AssumedRoles::AssumedRoles(const AssumedRoles&) = default;
-AssumedRoles& AssumedRoles::operator=(const AssumedRoles&) = default;
-AssumedRoles::AssumedRoles(AssumedRoles&&) noexcept = default;
-AssumedRoles& AssumedRoles::operator=(AssumedRoles&&) noexcept = default;
-AssumedRoles::~AssumedRoles() = default;
-
-bool AssumedRoles::can_assume_role(const string& role) const noexcept {
- return (_assumed_roles.contains(role) || _assumed_roles.contains(WildcardRole));
-}
-
-std::vector<string> AssumedRoles::ordered_roles() const {
- std::vector<string> roles;
- for (const auto& r : _assumed_roles) {
- roles.emplace_back(r);
- }
- std::sort(roles.begin(), roles.end());
- return roles;
-}
-
-bool AssumedRoles::operator==(const AssumedRoles& rhs) const noexcept {
- return (_assumed_roles == rhs._assumed_roles);
-}
-
-void AssumedRoles::print(asciistream& os) const {
- os << "AssumedRoles(roles: [";
- auto roles = ordered_roles();
- for (size_t i = 0; i < roles.size(); ++i) {
- if (i > 0) {
- os << ", ";
- }
- os << roles[i];
- }
- os << "])";
-}
-
-asciistream& operator<<(asciistream& os, const AssumedRoles& res) {
- res.print(os);
- return os;
-}
-
-std::ostream& operator<<(std::ostream& os, const AssumedRoles& res) {
- os << to_string(res);
- return os;
-}
-
-string to_string(const AssumedRoles& res) {
- asciistream os;
- os << res;
- return os.str();
-}
-
-AssumedRoles AssumedRoles::make_for_roles(RoleSet assumed_roles) {
- return AssumedRoles(std::move(assumed_roles));
-}
-
-AssumedRoles AssumedRoles::make_wildcard_role() {
- return AssumedRoles(RoleSet({WildcardRole}));
-}
-
-AssumedRoles AssumedRoles::make_empty() {
- return {};
-}
-
-AssumedRolesBuilder::AssumedRolesBuilder() = default;
-AssumedRolesBuilder::~AssumedRolesBuilder() = default;
-
-void AssumedRolesBuilder::add_union(const AssumedRoles& roles) {
- // TODO fix hash_set iterator range insert()
- for (const auto& role : roles.unordered_roles()) {
- _wip_roles.insert(role);
- }
-}
-
-AssumedRoles AssumedRolesBuilder::build_with_move() {
- return AssumedRoles::make_for_roles(std::move(_wip_roles));
-}
-
-}
-
diff --git a/vespalib/src/vespa/vespalib/net/tls/assumed_roles.h b/vespalib/src/vespa/vespalib/net/tls/assumed_roles.h
deleted file mode 100644
index 00d800916fd..00000000000
--- a/vespalib/src/vespa/vespalib/net/tls/assumed_roles.h
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-#pragma once
-
-#include <vespa/vespalib/stllike/hash_set.h>
-#include <vespa/vespalib/stllike/string.h>
-#include <vector>
-#include <iosfwd>
-
-namespace vespalib { class asciistream; }
-
-namespace vespalib::net::tls {
-
-/**
- * Encapsulates a set of roles that requests over a particular authenticated
- * connection can assume, based on the authorization rules it matched during mTLS
- * handshaking.
- *
- * If at least one role is a wildcard ('*') role, the connection can assume _any_
- * possible role. This is the default when no role constraints are specified in
- * the TLS configuration file (legacy behavior). However, a default-constructed
- * AssumedRoles instance does not allow any roles to be assumed.
- */
-class AssumedRoles {
-public:
- using RoleSet = hash_set<string>;
-private:
- RoleSet _assumed_roles;
-
- static const string WildcardRole;
-
- explicit AssumedRoles(RoleSet assumed_roles);
-public:
- AssumedRoles();
- AssumedRoles(const AssumedRoles&);
- AssumedRoles& operator=(const AssumedRoles&);
- AssumedRoles(AssumedRoles&&) noexcept;
- AssumedRoles& operator=(AssumedRoles&&) noexcept;
- ~AssumedRoles();
-
- [[nodiscard]] bool empty() const noexcept {
- return _assumed_roles.empty();
- }
-
- /**
- * Returns true iff `role` is present in the role set OR the role set contains
- * the special wildcard role.
- */
- [[nodiscard]] bool can_assume_role(const string& role) const noexcept;
-
- [[nodiscard]] const RoleSet& unordered_roles() const noexcept {
- return _assumed_roles;
- }
-
- [[nodiscard]] std::vector<string> ordered_roles() const;
-
- bool operator==(const AssumedRoles& rhs) const noexcept;
-
- void print(asciistream& os) const;
-
- static AssumedRoles make_for_roles(RoleSet assumed_roles);
- static AssumedRoles make_wildcard_role(); // Allows assuming _all_ possible roles
- static AssumedRoles make_empty(); // Matches _no_ possible roles
-};
-
-asciistream& operator<<(asciistream&, const AssumedRoles&);
-std::ostream& operator<<(std::ostream&, const AssumedRoles&);
-string to_string(const AssumedRoles&);
-
-class AssumedRolesBuilder {
- AssumedRoles::RoleSet _wip_roles;
-public:
- AssumedRolesBuilder();
- ~AssumedRolesBuilder();
-
- void add_union(const AssumedRoles& roles);
- [[nodiscard]] bool empty() const noexcept { return _wip_roles.empty(); }
- [[nodiscard]] AssumedRoles build_with_move();
-};
-
-}
diff --git a/vespalib/src/vespa/vespalib/net/tls/capability.cpp b/vespalib/src/vespa/vespalib/net/tls/capability.cpp
new file mode 100644
index 00000000000..64de250e60d
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/tls/capability.cpp
@@ -0,0 +1,62 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "capability.h"
+#include <vespa/vespalib/stllike/hash_map.hpp>
+#include <vespa/vespalib/stllike/asciistream.h>
+#include <array>
+
+namespace vespalib::net::tls {
+
+namespace {
+
+using namespace std::string_view_literals;
+
+// Important: must match 1-1 with CapabilityId values!
+constexpr std::array<std::string_view, Capability::max_value_count()> capability_names = {
+ "vespa.content.storage_api"sv,
+ "vespa.content.document_api"sv,
+ "vespa.content.search_api"sv,
+ "vespa.content.cluster_controller.internal_state_api"sv,
+ "vespa.slobrok.api"sv,
+ "vespa.content.status_pages"sv,
+ "vespa.content.metrics_api"sv,
+};
+
+} // anon ns
+
+std::string_view Capability::name() const noexcept {
+ return capability_names[id_as_idx()];
+}
+
+string Capability::to_string() const {
+ asciistream os;
+ // TODO asciistream should be made std::string_view-aware
+ os << "Capability(" << stringref(name().data(), name().length()) << ')';
+ return os.str();
+}
+
+std::optional<Capability> Capability::find_capability(const string& cap_name) noexcept {
+ static const hash_map<string, Capability> name_to_cap({
+ {"vespa.content.storage_api", content_storage_api()},
+ {"vespa.content.document_api", content_document_api()},
+ {"vespa.content.search_api", content_search_api()},
+ {"vespa.content.cluster_controller.internal_state_api", content_cluster_controller_internal_state_api()},
+ {"vespa.slobrok.api", slobrok_api()},
+ {"vespa.content.status_pages", content_status_pages()},
+ {"vespa.content.metrics_api", content_metrics_api()},
+ });
+ auto iter = name_to_cap.find(cap_name);
+ return (iter != name_to_cap.end()) ? std::optional<Capability>(iter->second) : std::nullopt;
+}
+
+std::ostream& operator<<(std::ostream& os, const Capability& cap) {
+ os << cap.to_string();
+ return os;
+}
+
+asciistream& operator<<(asciistream& os, const Capability& cap) {
+ os << cap.to_string();
+ return os;
+}
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/tls/capability.h b/vespalib/src/vespa/vespalib/net/tls/capability.h
new file mode 100644
index 00000000000..842e3f3a363
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/tls/capability.h
@@ -0,0 +1,104 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
+#include <vespa/vespalib/stllike/string.h>
+#include <bitset>
+#include <iosfwd>
+#include <optional>
+#include <string_view>
+#include <vector>
+
+namespace vespalib { class asciistream; }
+
+namespace vespalib::net::tls {
+
+/**
+ * A capability represents the ability to access a distinct service or API
+ * plane in Vespa (such as the Document API).
+ *
+ * Capability instances are intended to be very cheap to pass and store by value.
+ */
+class Capability {
+private:
+ // Each ID value corresponds to a unique single-bit position.
+ // These values shall never be exposed outside the running process, i.e. they
+ // must be possible to change arbitrarily internally across versions.
+ enum class Id : uint32_t {
+ ContentStorageApi = 0, // Must start at zero
+ ContentDocumentApi,
+ ContentSearchApi,
+ ContentClusterControllerInternalStateApi,
+ SlobrokApi,
+ ContentStatusPages,
+ ContentMetricsApi,
+ // When adding a capability ID to the end, max_value_count() MUST be updated
+ };
+public:
+ constexpr static size_t max_value_count() noexcept {
+ // This must refer to the highest possible CapabilityId enum value.
+ return static_cast<size_t>(Id::ContentMetricsApi) + 1;
+ }
+private:
+ Id _cap_id;
+
+ friend class CapabilitySet; // CapabilitySet needs to know the raw IDs for bit set bookkeeping
+
+ constexpr Id id() const noexcept { return _cap_id; }
+ constexpr uint32_t id_as_idx() const noexcept { return static_cast<uint32_t>(_cap_id); }
+
+ constexpr explicit Capability(Id cap_id) noexcept : _cap_id(cap_id) {}
+
+ constexpr static Capability of(Id id) noexcept {
+ return Capability(id);
+ }
+
+public:
+ Capability() = delete; // Only valid capabilities can be created.
+
+ constexpr bool operator==(const Capability& rhs) const noexcept {
+ return (_cap_id == rhs._cap_id);
+ }
+
+ constexpr bool operator!=(const Capability& rhs) const noexcept {
+ return !(*this == rhs);
+ }
+
+ std::string_view name() const noexcept;
+ string to_string() const;
+
+ static std::optional<Capability> find_capability(const string& cap_name) noexcept;
+
+ constexpr static Capability content_storage_api() noexcept {
+ return Capability(Id::ContentStorageApi);
+ }
+
+ constexpr static Capability content_document_api() noexcept {
+ return Capability(Id::ContentDocumentApi);
+ }
+
+ constexpr static Capability content_search_api() noexcept {
+ return Capability(Id::ContentSearchApi);
+ }
+
+ constexpr static Capability content_cluster_controller_internal_state_api() noexcept {
+ return Capability(Id::ContentClusterControllerInternalStateApi);
+ }
+
+ constexpr static Capability slobrok_api() noexcept {
+ return Capability(Id::SlobrokApi);
+ }
+
+ constexpr static Capability content_status_pages() noexcept {
+ return Capability(Id::ContentStatusPages);
+ }
+
+ constexpr static Capability content_metrics_api() noexcept {
+ return Capability(Id::ContentMetricsApi);
+ }
+
+};
+
+std::ostream& operator<<(std::ostream&, const Capability& cap);
+asciistream& operator<<(asciistream&, const Capability& cap);
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/tls/capability_set.cpp b/vespalib/src/vespa/vespalib/net/tls/capability_set.cpp
new file mode 100644
index 00000000000..3663694e31a
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/tls/capability_set.cpp
@@ -0,0 +1,95 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+
+#include "capability_set.h"
+#include <vespa/vespalib/stllike/hash_map.hpp>
+#include <vespa/vespalib/stllike/asciistream.h>
+#include <cassert>
+
+namespace vespalib::net::tls {
+
+string CapabilitySet::to_string() const {
+ asciistream os;
+ os << "CapabilitySet({";
+ bool emit_comma = false;
+ for_each_capability([&emit_comma, &os](Capability cap) {
+ if (emit_comma) {
+ os << ", ";
+ } else {
+ emit_comma = true;
+ }
+ // TODO let asciistream and std::string_view play along
+ os << stringref(cap.name().data(), cap.name().size());
+ });
+ os << "})";
+ return os.str();
+}
+
+std::optional<CapabilitySet> CapabilitySet::find_capability_set(const string& cap_set_name) noexcept {
+ static const hash_map<string, CapabilitySet> name_to_cap_set({
+ {"vespa.content_node", content_node()},
+ {"vespa.container_node", container_node()},
+ {"vespa.telemetry", telemetry()},
+ {"vespa.cluster_controller_node", cluster_controller_node()},
+ {"vespa.config_server", config_server()}
+ });
+ auto iter = name_to_cap_set.find(cap_set_name);
+ return (iter != name_to_cap_set.end()) ? std::optional<CapabilitySet>(iter->second) : std::nullopt;
+}
+
+bool CapabilitySet::resolve_and_add(const string& set_or_cap_name) noexcept {
+ if (auto cap_set = find_capability_set(set_or_cap_name)) {
+ _capability_mask |= cap_set->_capability_mask;
+ return true;
+ } else if (auto cap = Capability::find_capability(set_or_cap_name)) {
+ _capability_mask |= cap_as_bit_set(*cap);
+ return true;
+ }
+ return false;
+}
+
+// Note: the capability set factory functions below are all just using constexpr and/or inline
+// functions, so the compiler will happily optimize them to just "return <constant bit pattern>".
+
+CapabilitySet CapabilitySet::content_node() noexcept {
+ return CapabilitySet::of({Capability::content_storage_api(),
+ Capability::content_document_api(),
+ Capability::slobrok_api()});
+}
+
+CapabilitySet CapabilitySet::container_node() noexcept {
+ return CapabilitySet::of({Capability::content_document_api(),
+ Capability::content_search_api(),
+ Capability::slobrok_api()});
+}
+
+CapabilitySet CapabilitySet::telemetry() noexcept {
+ return CapabilitySet::of({Capability::content_status_pages(),
+ Capability::content_metrics_api()});
+}
+
+CapabilitySet CapabilitySet::cluster_controller_node() noexcept {
+ return CapabilitySet::of({Capability::content_cluster_controller_internal_state_api(),
+ Capability::slobrok_api()});
+}
+
+CapabilitySet CapabilitySet::config_server() noexcept {
+ return CapabilitySet::of({/*TODO define required capabilities*/});
+}
+
+CapabilitySet CapabilitySet::make_with_all_capabilities() noexcept {
+ BitSet bit_set;
+ bit_set.flip(); // All cap bits set
+ return CapabilitySet(bit_set);
+}
+
+std::ostream& operator<<(std::ostream& os, const CapabilitySet& cap_set) {
+ os << cap_set.to_string();
+ return os;
+}
+
+asciistream& operator<<(asciistream& os, const CapabilitySet& cap_set) {
+ os << cap_set.to_string();
+ return os;
+}
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/tls/capability_set.h b/vespalib/src/vespa/vespalib/net/tls/capability_set.h
new file mode 100644
index 00000000000..f86b043ee7b
--- /dev/null
+++ b/vespalib/src/vespa/vespalib/net/tls/capability_set.h
@@ -0,0 +1,117 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+#pragma once
+
+#include "capability.h"
+#include <vespa/vespalib/stllike/string.h>
+#include <vespa/vespalib/stllike/hash_set.h>
+#include <bitset>
+#include <initializer_list>
+#include <iosfwd>
+#include <optional>
+#include <vector>
+
+namespace vespalib { class asciistream; }
+
+namespace vespalib::net::tls {
+
+/**
+ * A CapabilitySet efficiently represents a finite set (possibly empty) of individual
+ * capabilities and allows for both single and set-based membership tests.
+ *
+ * Factory functions are provided for all predefined Vespa capability sets.
+ *
+ * CapabilitySet instances are intended to be very cheap to pass and store by value.
+ */
+class CapabilitySet {
+ using BitSet = std::bitset<Capability::max_value_count()>;
+ BitSet _capability_mask;
+
+ constexpr static uint32_t cap_as_bit_pos(const Capability& cap) noexcept {
+ return cap.id_as_idx();
+ }
+
+ constexpr static BitSet cap_as_bit_set(const Capability& cap) noexcept {
+ static_assert(Capability::max_value_count() <= 32); // Must fit into uint32_t bitmask
+ return {uint32_t(1) << cap_as_bit_pos(cap)};
+ }
+
+ explicit constexpr CapabilitySet(BitSet capabilities) noexcept
+ : _capability_mask(capabilities)
+ {}
+public:
+ constexpr CapabilitySet() noexcept = default;
+ constexpr ~CapabilitySet() = default;
+
+ string to_string() const;
+
+ bool operator==(const CapabilitySet& rhs) const noexcept {
+ return (_capability_mask == rhs._capability_mask);
+ }
+
+ [[nodiscard]] bool empty() const noexcept {
+ return _capability_mask.none();
+ }
+ size_t count() const noexcept {
+ return _capability_mask.count();
+ }
+ constexpr static size_t max_count() noexcept {
+ return Capability::max_value_count();
+ }
+
+ [[nodiscard]] constexpr bool contains(Capability cap) const noexcept {
+ return _capability_mask[cap_as_bit_pos(cap)];
+ }
+ [[nodiscard]] bool contains_all(CapabilitySet caps) const noexcept {
+ return ((_capability_mask & caps._capability_mask) == caps._capability_mask);
+ }
+
+ void add(const Capability& cap) noexcept {
+ _capability_mask |= cap_as_bit_set(cap);
+ }
+ void add_all(const CapabilitySet& cap_set) noexcept {
+ _capability_mask |= cap_set._capability_mask;
+ }
+
+ template <typename Func>
+ void for_each_capability(Func f) const noexcept(noexcept(f(Capability::content_storage_api()))) {
+ for (size_t i = 0; i < _capability_mask.size(); ++i) {
+ if (_capability_mask[i]) {
+ f(Capability::of(static_cast<Capability::Id>(i)));
+ }
+ }
+ }
+
+ /**
+ * Since we have two capability naming "tiers", resolving is done in two steps:
+ * 1. Check if the name matches a known capability _set_ name. If so, add
+ * all unique capabilities within the set to our own working set. Return true.
+ * 2. Check if the name matches a known single capability. If so, add that
+ * capability to our own working set. Return true.
+ * 3. Otherwise, return false.
+ */
+ [[nodiscard]] bool resolve_and_add(const string& set_or_cap_name) noexcept;
+
+ static std::optional<CapabilitySet> find_capability_set(const string& cap_set_name) noexcept;
+
+ static CapabilitySet of(std::initializer_list<Capability> caps) noexcept {
+ CapabilitySet set;
+ for (const auto& cap : caps) {
+ set._capability_mask |= cap_as_bit_set(cap);
+ }
+ return set;
+ }
+
+ static CapabilitySet content_node() noexcept;
+ static CapabilitySet container_node() noexcept;
+ static CapabilitySet telemetry() noexcept;
+ static CapabilitySet cluster_controller_node() noexcept;
+ static CapabilitySet config_server() noexcept;
+
+ static CapabilitySet make_with_all_capabilities() noexcept;
+ static CapabilitySet make_empty() noexcept { return CapabilitySet(); };
+};
+
+std::ostream& operator<<(std::ostream&, const CapabilitySet& cap_set);
+asciistream& operator<<(asciistream&, const CapabilitySet& cap_set);
+
+}
diff --git a/vespalib/src/vespa/vespalib/net/tls/certificate_verification_callback.h b/vespalib/src/vespa/vespalib/net/tls/certificate_verification_callback.h
index f4d8d39206b..c670d54273e 100644
--- a/vespalib/src/vespa/vespalib/net/tls/certificate_verification_callback.h
+++ b/vespalib/src/vespa/vespalib/net/tls/certificate_verification_callback.h
@@ -22,7 +22,7 @@ struct CertificateVerificationCallback {
// and it is signed by a trusted CA.
struct AcceptAllPreVerifiedCertificates : CertificateVerificationCallback {
VerificationResult verify([[maybe_unused]] const PeerCredentials& peer_creds) const override {
- return VerificationResult::make_authorized_for_all_roles(); // yolo
+ return VerificationResult::make_authorized_with_all_capabilities(); // yolo
}
};
diff --git a/vespalib/src/vespa/vespalib/net/tls/crypto_codec.h b/vespalib/src/vespa/vespalib/net/tls/crypto_codec.h
index fc729d7dd6a..8b2f258199b 100644
--- a/vespalib/src/vespa/vespalib/net/tls/crypto_codec.h
+++ b/vespalib/src/vespa/vespalib/net/tls/crypto_codec.h
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
+#include "capability_set.h"
#include <vespa/vespalib/net/socket_address.h>
#include <memory>
@@ -54,7 +55,6 @@ struct DecodeResult {
struct TlsContext;
struct PeerCredentials;
-class AssumedRoles;
// TODO move to different namespace, not dependent on TLS?
@@ -185,9 +185,9 @@ public:
[[nodiscard]] virtual const PeerCredentials& peer_credentials() const noexcept = 0;
/**
- * Union set of all assumed roles in the peer policy rules that fully matched the peer's credentials.
+ * Union set of all granted capabilities in the peer policy rules that fully matched the peer's credentials.
*/
- [[nodiscard]] virtual const AssumedRoles& assumed_roles() const noexcept = 0;
+ [[nodiscard]] virtual CapabilitySet granted_capabilities() const noexcept = 0;
/*
* Creates an implementation defined CryptoCodec that provides at least TLSv1.2
diff --git a/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.cpp b/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.cpp
index 03170ae0f68..a50acc55bd0 100644
--- a/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.cpp
@@ -1,6 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "crypto_codec_adapter.h"
+#include <vespa/vespalib/net/connection_auth_context.h>
#include <assert.h>
namespace vespalib::net::tls {
@@ -208,4 +209,10 @@ CryptoCodecAdapter::drop_empty_buffers()
_output.drop_if_empty();
}
+std::unique_ptr<net::ConnectionAuthContext>
+CryptoCodecAdapter::make_auth_context()
+{
+ return std::make_unique<net::ConnectionAuthContext>(_codec->peer_credentials(), _codec->granted_capabilities());
+}
+
} // namespace vespalib::net::tls
diff --git a/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.h b/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.h
index 1d5b57dc9b2..4b3c66cbc3c 100644
--- a/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.h
+++ b/vespalib/src/vespa/vespalib/net/tls/crypto_codec_adapter.h
@@ -46,6 +46,7 @@ public:
ssize_t flush() override;
ssize_t half_close() override;
void drop_empty_buffers() override;
+ std::unique_ptr<net::ConnectionAuthContext> make_auth_context() override;
};
} // namespace vespalib::net::tls
diff --git a/vespalib/src/vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h b/vespalib/src/vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h
index 5be2146b349..ca7237bfa9a 100644
--- a/vespalib/src/vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h
+++ b/vespalib/src/vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h
@@ -4,8 +4,8 @@
#include <vespa/vespalib/crypto/openssl_typedefs.h>
#include <vespa/vespalib/net/socket_address.h>
#include <vespa/vespalib/net/socket_spec.h>
-#include <vespa/vespalib/net/tls/assumed_roles.h>
#include <vespa/vespalib/net/tls/crypto_codec.h>
+#include <vespa/vespalib/net/tls/capability_set.h>
#include <vespa/vespalib/net/tls/peer_credentials.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <memory>
@@ -58,7 +58,7 @@ class OpenSslCryptoCodecImpl : public CryptoCodec {
std::optional<DeferredHandshakeParams> _deferred_handshake_params;
std::optional<HandshakeResult> _deferred_handshake_result;
PeerCredentials _peer_credentials;
- AssumedRoles _assumed_roles;
+ CapabilitySet _granted_capabilities;
public:
~OpenSslCryptoCodecImpl() override;
@@ -103,8 +103,8 @@ public:
return _peer_credentials;
}
- [[nodiscard]] const AssumedRoles& assumed_roles() const noexcept override {
- return _assumed_roles;
+ [[nodiscard]] CapabilitySet granted_capabilities() const noexcept override {
+ return _granted_capabilities;
}
const SocketAddress& peer_address() const noexcept { return _peer_address; }
@@ -120,8 +120,8 @@ public:
void set_peer_credentials(PeerCredentials peer_credentials) {
_peer_credentials = std::move(peer_credentials);
}
- void set_assumed_roles(AssumedRoles assumed_roles) {
- _assumed_roles = std::move(assumed_roles);
+ void set_granted_capabilities(CapabilitySet granted_capabilities) {
+ _granted_capabilities = granted_capabilities;
}
private:
OpenSslCryptoCodecImpl(std::shared_ptr<OpenSslTlsContextImpl> ctx,
diff --git a/vespalib/src/vespa/vespalib/net/tls/impl/openssl_tls_context_impl.cpp b/vespalib/src/vespa/vespalib/net/tls/impl/openssl_tls_context_impl.cpp
index 3810140854b..d7977f6cd2a 100644
--- a/vespalib/src/vespa/vespalib/net/tls/impl/openssl_tls_context_impl.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/impl/openssl_tls_context_impl.cpp
@@ -488,7 +488,7 @@ bool OpenSslTlsContextImpl::verify_trusted_certificate(::X509_STORE_CTX* store_c
// Store away credentials and role set for later use by requests that arrive over this connection.
// TODO encapsulate as const shared_ptr to immutable object to better facilitate sharing?
codec_impl.set_peer_credentials(std::move(creds));
- codec_impl.set_assumed_roles(authz_result.steal_assumed_roles());
+ codec_impl.set_granted_capabilities(authz_result.granted_capabilities());
} catch (std::exception& e) {
LOGBT(error, codec_impl.peer_address().ip_address(),
"Got exception during certificate verification callback for peer '%s': %s",
diff --git a/vespalib/src/vespa/vespalib/net/tls/peer_policies.cpp b/vespalib/src/vespa/vespalib/net/tls/peer_policies.cpp
index a4e651f3f19..eaa6a8c2298 100644
--- a/vespalib/src/vespa/vespalib/net/tls/peer_policies.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/peer_policies.cpp
@@ -123,13 +123,14 @@ PeerPolicy::PeerPolicy() = default;
PeerPolicy::PeerPolicy(std::vector<RequiredPeerCredential> required_peer_credentials)
: _required_peer_credentials(std::move(required_peer_credentials)),
- _assumed_roles(AssumedRoles::make_wildcard_role())
-{}
+ _granted_capabilities(CapabilitySet::make_with_all_capabilities())
+{
+}
PeerPolicy::PeerPolicy(std::vector<RequiredPeerCredential> required_peer_credentials,
- AssumedRoles assumed_roles)
+ CapabilitySet granted_capabilities)
: _required_peer_credentials(std::move(required_peer_credentials)),
- _assumed_roles(std::move(assumed_roles))
+ _granted_capabilities(granted_capabilities)
{}
PeerPolicy::~PeerPolicy() = default;
@@ -170,7 +171,7 @@ std::ostream& operator<<(std::ostream& os, const RequiredPeerCredential& cred) {
std::ostream& operator<<(std::ostream& os, const PeerPolicy& policy) {
os << "PeerPolicy(";
print_joined(os, policy.required_peer_credentials(), ", ");
- os << ")";
+ os << ", " << policy.granted_capabilities().to_string() << ")";
return os;
}
diff --git a/vespalib/src/vespa/vespalib/net/tls/peer_policies.h b/vespalib/src/vespa/vespalib/net/tls/peer_policies.h
index 6eab8c2c9b2..3314e5e4adf 100644
--- a/vespalib/src/vespa/vespalib/net/tls/peer_policies.h
+++ b/vespalib/src/vespa/vespalib/net/tls/peer_policies.h
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
-#include "assumed_roles.h"
+#include "capability_set.h"
#include <vespa/vespalib/stllike/string.h>
#include <memory>
#include <vector>
@@ -50,26 +50,26 @@ public:
class PeerPolicy {
// _All_ credentials must match for the policy itself to match.
std::vector<RequiredPeerCredential> _required_peer_credentials;
- AssumedRoles _assumed_roles;
+ CapabilitySet _granted_capabilities;
public:
PeerPolicy();
- // This policy is created with a wildcard role set, i.e. full access.
+ // This policy is created with a full capability set, i.e. unrestricted access.
explicit PeerPolicy(std::vector<RequiredPeerCredential> required_peer_credentials);
PeerPolicy(std::vector<RequiredPeerCredential> required_peer_credentials,
- AssumedRoles assumed_roles);
+ CapabilitySet granted_capabilities);
~PeerPolicy();
bool operator==(const PeerPolicy& rhs) const noexcept {
return ((_required_peer_credentials == rhs._required_peer_credentials) &&
- (_assumed_roles == rhs._assumed_roles));
+ (_granted_capabilities == rhs._granted_capabilities));
}
[[nodiscard]] const std::vector<RequiredPeerCredential>& required_peer_credentials() const noexcept {
return _required_peer_credentials;
}
- [[nodiscard]] const AssumedRoles& assumed_roles() const noexcept {
- return _assumed_roles;
+ [[nodiscard]] const CapabilitySet& granted_capabilities() const noexcept {
+ return _granted_capabilities;
}
};
diff --git a/vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp b/vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp
index 4018e20225e..d9dbca6e808 100644
--- a/vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp
@@ -71,16 +71,16 @@ PolicyConfiguredCertificateVerifier::~PolicyConfiguredCertificateVerifier() = de
VerificationResult PolicyConfiguredCertificateVerifier::verify(const PeerCredentials& peer_creds) const {
if (_authorized_peers.allows_all_authenticated()) {
- return VerificationResult::make_authorized_for_all_roles();
+ return VerificationResult::make_authorized_with_all_capabilities();
}
- AssumedRolesBuilder roles_builder;
+ CapabilitySet caps;
for (const auto& policy : _authorized_peers.peer_policies()) {
if (matches_all_policy_requirements(peer_creds, policy)) {
- roles_builder.add_union(policy.assumed_roles());
+ caps.add_all(policy.granted_capabilities());
}
}
- if (!roles_builder.empty()) {
- return VerificationResult::make_authorized_for_roles(roles_builder.build_with_move());
+ if (!caps.empty()) {
+ return VerificationResult::make_authorized_with_capabilities(std::move(caps));
} else {
return VerificationResult::make_not_authorized();
}
diff --git a/vespalib/src/vespa/vespalib/net/tls/tls_crypto_socket.h b/vespalib/src/vespa/vespalib/net/tls/tls_crypto_socket.h
index 0d036fdad4b..01d20155bd1 100644
--- a/vespalib/src/vespa/vespalib/net/tls/tls_crypto_socket.h
+++ b/vespalib/src/vespa/vespalib/net/tls/tls_crypto_socket.h
@@ -7,7 +7,7 @@
namespace vespalib {
struct TlsCryptoSocket : public CryptoSocket {
- ~TlsCryptoSocket();
+ ~TlsCryptoSocket() override;
virtual void inject_read_data(const char *buf, size_t len) = 0;
};
diff --git a/vespalib/src/vespa/vespalib/net/tls/transport_security_options_reading.cpp b/vespalib/src/vespa/vespalib/net/tls/transport_security_options_reading.cpp
index 2e80135813d..94281d3ef41 100644
--- a/vespalib/src/vespa/vespalib/net/tls/transport_security_options_reading.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/transport_security_options_reading.cpp
@@ -5,6 +5,8 @@
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/io/mapped_file_input.h>
#include <vespa/vespalib/data/memory_input.h>
+#include <vespa/vespalib/net/tls/capability_set.h>
+#include <vespa/vespalib/stllike/hash_set.h>
namespace vespalib::net::tls {
@@ -24,7 +26,8 @@ namespace vespalib::net::tls {
{ "field":"CN", "must-match": "*.config.blarg"},
{ "field":"SAN_DNS", "must-match": "*.fancy.config.blarg"}
],
- "name": "funky config servers"
+ "name": "funky config servers",
+ "capabilities": ["vespa.content.coolstuff"]
}
]
}
@@ -68,8 +71,7 @@ RequiredPeerCredential parse_peer_credential(const Inspector& req_entry) {
return RequiredPeerCredential(field, std::move(match));
}
-PeerPolicy parse_peer_policy(const Inspector& peer_entry) {
- auto& creds = peer_entry["required-credentials"];
+std::vector<RequiredPeerCredential> parse_peer_credentials(const Inspector& creds) {
if (creds.children() == 0) {
throw IllegalArgumentException("\"required-credentials\" array can't be empty (would allow all peers)");
}
@@ -77,7 +79,31 @@ PeerPolicy parse_peer_policy(const Inspector& peer_entry) {
for (size_t i = 0; i < creds.children(); ++i) {
required_creds.emplace_back(parse_peer_credential(creds[i]));
}
- return PeerPolicy(std::move(required_creds));
+ return required_creds;
+}
+
+CapabilitySet parse_capabilities(const Inspector& caps) {
+ CapabilitySet capabilities;
+ if (caps.valid() && (caps.children() == 0)) {
+ throw IllegalArgumentException("\"capabilities\" array must either be not present (implies "
+ "all capabilities) or contain at least one capability name");
+ } else if (caps.valid()) {
+ for (size_t i = 0; i < caps.children(); ++i) {
+ // TODO warn if resolve_and_add returns false; means capability is unknown!
+ (void)capabilities.resolve_and_add(caps[i].asString().make_string());
+ }
+ } else {
+ // If no capabilities are specified, all are implicitly granted.
+ // This avoids breaking every legacy mTLS app ever.
+ capabilities = CapabilitySet::make_with_all_capabilities();
+ }
+ return capabilities;
+}
+
+PeerPolicy parse_peer_policy(const Inspector& peer_entry) {
+ auto required_creds = parse_peer_credentials(peer_entry["required-credentials"]);
+ auto capabilities = parse_capabilities(peer_entry["capabilities"]);
+ return {std::move(required_creds), std::move(capabilities)};
}
AuthorizedPeers parse_authorized_peers(const Inspector& authorized_peers) {
diff --git a/vespalib/src/vespa/vespalib/net/tls/verification_result.cpp b/vespalib/src/vespa/vespalib/net/tls/verification_result.cpp
index e4833f59f47..f1e50d3115e 100644
--- a/vespalib/src/vespa/vespalib/net/tls/verification_result.cpp
+++ b/vespalib/src/vespa/vespalib/net/tls/verification_result.cpp
@@ -8,8 +8,8 @@ namespace vespalib::net::tls {
VerificationResult::VerificationResult() = default;
-VerificationResult::VerificationResult(AssumedRoles assumed_roles)
- : _assumed_roles(std::move(assumed_roles))
+VerificationResult::VerificationResult(CapabilitySet granted_capabilities)
+ : _granted_capabilities(std::move(granted_capabilities))
{}
VerificationResult::VerificationResult(const VerificationResult&) = default;
@@ -23,19 +23,19 @@ void VerificationResult::print(asciistream& os) const {
if (!success()) {
os << "NOT AUTHORIZED";
} else {
- os << _assumed_roles;
+ os << _granted_capabilities;
}
os << ')';
}
VerificationResult
-VerificationResult::make_authorized_for_roles(AssumedRoles assumed_roles) {
- return VerificationResult(std::move(assumed_roles));
+VerificationResult::make_authorized_with_capabilities(CapabilitySet granted_capabilities) {
+ return VerificationResult(std::move(granted_capabilities));
}
VerificationResult
-VerificationResult::make_authorized_for_all_roles() {
- return VerificationResult(AssumedRoles::make_wildcard_role());
+VerificationResult::make_authorized_with_all_capabilities() {
+ return VerificationResult(CapabilitySet::make_with_all_capabilities());
}
VerificationResult
diff --git a/vespalib/src/vespa/vespalib/net/tls/verification_result.h b/vespalib/src/vespa/vespalib/net/tls/verification_result.h
index 2de89269ba4..92b32ad92f7 100644
--- a/vespalib/src/vespa/vespalib/net/tls/verification_result.h
+++ b/vespalib/src/vespa/vespalib/net/tls/verification_result.h
@@ -1,7 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
-#include "assumed_roles.h"
+#include "capability_set.h"
#include <vespa/vespalib/stllike/string.h>
#include <iosfwd>
@@ -13,14 +13,14 @@ namespace vespalib::net::tls {
* The result of evaluating configured mTLS authorization rules against the
* credentials presented by a successfully authenticated peer certificate.
*
- * This result contains the union set of all roles specified by the matching
- * authorization rules. If no rules matched, the set will be empty. The role
+ * This result contains the union set of all capabilities granted by the matching
+ * authorization rules. If no rules matched, the set will be empty. The capability
* set will also be empty for a default-constructed instance.
*/
class VerificationResult {
- AssumedRoles _assumed_roles;
+ CapabilitySet _granted_capabilities;
- explicit VerificationResult(AssumedRoles assumed_roles);
+ explicit VerificationResult(CapabilitySet granted_capabilities);
public:
VerificationResult();
VerificationResult(const VerificationResult&);
@@ -29,22 +29,19 @@ public:
VerificationResult& operator=(VerificationResult&&) noexcept;
~VerificationResult();
- // Returns true iff at least one assumed role has been granted.
+ // Returns true iff at least one capability been granted.
[[nodiscard]] bool success() const noexcept {
- return !_assumed_roles.empty();
+ return !_granted_capabilities.empty();
}
- [[nodiscard]] const AssumedRoles& assumed_roles() const noexcept {
- return _assumed_roles;
- }
- [[nodiscard]] AssumedRoles steal_assumed_roles() noexcept {
- return std::move(_assumed_roles);
+ [[nodiscard]] const CapabilitySet& granted_capabilities() const noexcept {
+ return _granted_capabilities;
}
void print(asciistream& os) const;
- static VerificationResult make_authorized_for_roles(AssumedRoles assumed_roles);
- static VerificationResult make_authorized_for_all_roles();
+ static VerificationResult make_authorized_with_capabilities(CapabilitySet granted_capabilities);
+ static VerificationResult make_authorized_with_all_capabilities();
static VerificationResult make_not_authorized();
};
diff --git a/vespalib/src/vespa/vespalib/process/process.cpp b/vespalib/src/vespa/vespalib/process/process.cpp
index 7749ffdff65..5827546d0b4 100644
--- a/vespalib/src/vespa/vespalib/process/process.cpp
+++ b/vespalib/src/vespa/vespalib/process/process.cpp
@@ -10,6 +10,7 @@
#include <sys/types.h>
#include <sys/wait.h>
+#include <csignal>
#include <unistd.h>
#include <fcntl.h>
diff --git a/vespalib/src/vespa/vespalib/stllike/hash_fun.h b/vespalib/src/vespa/vespalib/stllike/hash_fun.h
index 4900fcd5a2b..daedddbba1b 100644
--- a/vespalib/src/vespa/vespalib/stllike/hash_fun.h
+++ b/vespalib/src/vespa/vespalib/stllike/hash_fun.h
@@ -69,10 +69,10 @@ size_t hashValue(const char *str) noexcept;
size_t hashValue(const void *str, size_t sz) noexcept;
struct hash_strings {
- size_t operator() (const vespalib::string & arg) const noexcept { return hashValue(arg.c_str()); }
+ size_t operator() (const vespalib::string & arg) const noexcept { return hashValue(arg.data(), arg.size()); }
size_t operator() (vespalib::stringref arg) const noexcept { return hashValue(arg.data(), arg.size()); }
size_t operator() (const char * arg) const noexcept { return hashValue(arg); }
- size_t operator() (const std::string& arg) const noexcept { return hashValue(arg.c_str()); }
+ size_t operator() (const std::string& arg) const noexcept { return hashValue(arg.data(), arg.size()); }
};
template<> struct hash<const char *> : hash_strings { };
diff --git a/vespalib/src/vespa/vespalib/test/peer_policy_utils.cpp b/vespalib/src/vespa/vespalib/test/peer_policy_utils.cpp
index 82d7b9ea07b..c139b1391e0 100644
--- a/vespalib/src/vespa/vespalib/test/peer_policy_utils.cpp
+++ b/vespalib/src/vespa/vespalib/test/peer_policy_utils.cpp
@@ -16,25 +16,29 @@ RequiredPeerCredential required_san_uri(vespalib::stringref pattern) {
return {RequiredPeerCredential::Field::SAN_URI, pattern};
}
-AssumedRoles assumed_roles(const std::vector<string>& roles) {
- // TODO fix hash_set iterator range ctor to make this a one-liner
- AssumedRoles::RoleSet role_set;
- for (const auto& role : roles) {
- role_set.insert(role);
- }
- return AssumedRoles::make_for_roles(std::move(role_set));
-}
-
PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds) {
return PeerPolicy(std::move(creds));
}
-PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds, AssumedRoles roles) {
- return {std::move(creds), std::move(roles)};
+PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds, CapabilitySet capabilities) {
+ return {std::move(creds), std::move(capabilities)};
}
AuthorizedPeers authorized_peers(std::vector<PeerPolicy> peer_policies) {
return AuthorizedPeers(std::move(peer_policies));
}
+Capability cap_1() {
+ return Capability::content_search_api();
+}
+Capability cap_2() {
+ return Capability::content_storage_api();
+}
+Capability cap_3() {
+ return Capability::content_document_api();
+}
+Capability cap_4() {
+ return Capability::slobrok_api();
+}
+
}
diff --git a/vespalib/src/vespa/vespalib/test/peer_policy_utils.h b/vespalib/src/vespa/vespalib/test/peer_policy_utils.h
index 72e9fde20de..5c6a97cc2c3 100644
--- a/vespalib/src/vespa/vespalib/test/peer_policy_utils.h
+++ b/vespalib/src/vespa/vespalib/test/peer_policy_utils.h
@@ -2,15 +2,20 @@
#pragma once
#include <vespa/vespalib/net/tls/peer_policies.h>
+#include <vespa/vespalib/net/tls/capability_set.h>
namespace vespalib::net::tls {
RequiredPeerCredential required_cn(vespalib::stringref pattern);
RequiredPeerCredential required_san_dns(vespalib::stringref pattern);
RequiredPeerCredential required_san_uri(vespalib::stringref pattern);
-AssumedRoles assumed_roles(const std::vector<string>& roles);
PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds);
-PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds, AssumedRoles roles);
+PeerPolicy policy_with(std::vector<RequiredPeerCredential> creds, CapabilitySet capabilities);
AuthorizedPeers authorized_peers(std::vector<PeerPolicy> peer_policies);
+// Some shortcuts for valid capabilities:
+Capability cap_1();
+Capability cap_2();
+Capability cap_3();
+Capability cap_4();
}
diff --git a/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.cpp b/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.cpp
index 6db97ff0761..e7f43de8f92 100644
--- a/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.cpp
+++ b/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.cpp
@@ -6,7 +6,7 @@ namespace vespalib {
//-----------------------------------------------------------------------------
-AdaptiveSequencedExecutor::Strand::Strand()
+AdaptiveSequencedExecutor::Strand::Strand() noexcept
: state(State::IDLE),
queue()
{
diff --git a/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.h b/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.h
index fbebf8b4e4c..fee9b8a61f8 100644
--- a/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.h
+++ b/vespalib/src/vespa/vespalib/util/adaptive_sequenced_executor.h
@@ -80,7 +80,7 @@ private:
enum class State { IDLE, WAITING, ACTIVE };
State state;
ArrayQueue<TaggedTask> queue;
- Strand();
+ Strand() noexcept;
~Strand();
};
diff --git a/vespalib/src/vespa/vespalib/util/signalhandler.cpp b/vespalib/src/vespa/vespalib/util/signalhandler.cpp
index b00fe1718c9..68368269c59 100644
--- a/vespalib/src/vespa/vespalib/util/signalhandler.cpp
+++ b/vespalib/src/vespa/vespalib/util/signalhandler.cpp
@@ -2,6 +2,9 @@
#include "signalhandler.h"
#include "backtrace.h"
+#ifdef __APPLE__
+#define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED
+#endif
#include <boost/stacktrace/safe_dump_to.hpp> // Header-only dependency
#include <boost/stacktrace/frame.hpp>
#include <array>
diff --git a/vespalog/src/logctl/logctl.cpp b/vespalog/src/logctl/logctl.cpp
index 478e5e471fb..4cf44e9cd22 100644
--- a/vespalog/src/logctl/logctl.cpp
+++ b/vespalog/src/logctl/logctl.cpp
@@ -41,8 +41,8 @@ usage(const char *name)
"are controlled:\n"
" x. : Matches only component x\n"
" x : Matches component x and all its sub-components\n\n"
- "Example: %s qrserver:log all=on,spam=off,debug=off : For service\n"
- "qrserver, set log and all sub-components of log to enable all\n"
+ "Example: %s container:log all=on,spam=off,debug=off : For service\n"
+ "container, set log and all sub-components of log to enable all\n"
"except spam and debug.\n\n", name, name, name);
}
diff --git a/vespamalloc/CMakeLists.txt b/vespamalloc/CMakeLists.txt
index df8e38653bb..af71d8b7d82 100644
--- a/vespamalloc/CMakeLists.txt
+++ b/vespamalloc/CMakeLists.txt
@@ -26,7 +26,6 @@ vespa_define_module(
src/vespamalloc/util
)
-vespa_install_script(bin/parsememorydump.pl vespa-malloc-parse-memorydump.pl bin)
else()
install(DIRECTORY DESTINATION lib64/vespa)
endif()
diff --git a/vespamalloc/bin/parsememorydump.pl b/vespamalloc/bin/parsememorydump.pl
deleted file mode 100755
index 95c70859b9a..00000000000
--- a/vespamalloc/bin/parsememorydump.pl
+++ /dev/null
@@ -1,314 +0,0 @@
-#!/usr/bin/perl -w
-# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-
-# This is a tool to parse the output given by vespamalloc when dumping all
-# memory usage with stacktraces.
-#
-# This tool will try to group similar stack traces together, identify them,
-# and show a report of how much memory you use for various tasks in the given
-# dump.
-#
-# Suggested usage:
-# - Manually rotate your vespa.log file.
-# - Send signal to vespamalloc to make it dump stack traces.
-# - When dump is done, cat all the log files generated in correct order into
-# one file.
-# - Send this file to STDIN of this script.
-#
-# By doing it like this, it's easy to rerun this script and to update it to
-# work with anything encountered in your report that this script doesn't
-# currently handle.
-#
-# It is for instance likely, that you need to add some more regexes to match
-# unknown stack traces into appropriate groups.
-
-use strict;
-
-# If this variable is set, unrecognized stack traces will be concatenated to
-# one unrecognized chunk.
-my $combineUnrecognizedStacks = 1;
-# If this variable is set, all stack traces are shown, no matter if they are
-# recognized or not.
-my $showRecognizedStacks = 0;
-# If this variable is set, memory usage is grouped on the first word in the
-# group name. Thus, by using a proper name convention, one can distinguish
-# how much memory are used on various parts of the system
-my $sortOnCategories = 1;
-
-# These patterns are used to recognized what memory is used for based on the
-# stacktrace of the allocation. The keys are regular expressions that can match
-# stacktraces. The value is the group name this allocation will be marked as if
-# the trace matches the regex. If matching multiple entries, the first entry
-# found will be the match.
-
-# Note that as I made this tool to analyze VDS memory usage, the stuff added is
-# just stuff I found using memory in that current run. We should probably add
-# more patterns as needed.
-my %patterns = (
-
- 'FRT_MemoryTub::BigAlloc.*mbus::MessageBus::send.*' => 'RPC send messagebus message - big alloc',
- 'FRT_MemoryTub::BigAlloc.*storage::rpc::Destination::sendRequest', => 'RPC send storage API command - big alloc',
- 'FRT_RPCRequestPool::AllocRPCRequest.*storage::rpc::Destination::sendRequest' => 'RPC send storage API command',
-
- 'FNET_DataBuffer::Shrink.*FNET_Connection::HandleWriteEvent' => 'RPC shrinked write buffer',
- 'FNET_DataBuffer::Shrink.*FNET_Connection::HandleReadEvent' => 'RPC shrinked read buffer',
-
- 'FRT_MemoryTub::BigAlloc.*FRT_RPCRequestPacket::Decode.*FNET_Connection::HandleReadEvent' => 'RPC read event - decode - big alloc',
- 'FRT_RPCRequestPool::AllocRPCRequest.*FNET_Connection::HandlePacket.*FNET_Connection::HandleReadEvent' => 'RPC read event - handle packet',
- 'FNET_DataBuffer::Pack.*FNET_Connection::HandleReadEvent' => 'RPC packed read buffer',
- 'FNET_DataBuffer::Pack.*FNET_Connection::HandleWriteEvent' => 'RPC packed write buffer',
- 'FNET_PacketQueue_NoLock::ExpandBuf.*FNET_Connection::HandleWriteEvent()' => 'RPC expand write buffer',
- 'FNET_ChannelPool::AllocChannelCluster.*storage::rpc::Destination::sendRequest' => 'RPC storage API alloc channel cluster',
-
- 'storage::SlotFileBuffer::getAlignedBuffer.*SlotFileImpl::close' => 'Persistence layer - move buffer to cache',
- 'storage::SlotFileBuffer::getAlignedBuffer.*SlotFileBuffer::getBuffer' => 'Persistence layer - Get aligned buffer',
- 'storage::SlotFileBuffer::getInputBuffer' => 'Persistence layer - Input buffer',
- 'storage::SlotFileBuffer::getIndexBuffer' => 'Persistence layer - Index buffer',
- 'storage::SlotFileBuffer::getOutputBuffer' => 'Persistence layer - Output buffer',
-
- 'storage::api::\S*::makeReply.*storage::MessageDispatcher::handleCommand' => 'Messages - Replies stored in message dispatcher',
- 'document::SerializableArray::onDeserialize.*storage::CommunicationManager::onEvent\(std::auto_ptr<storage::rpc::Event>\)'
- => 'Messages - Documents from storage API messages - serializable arrays',
- 'document::SerializableDocumentSharedPointer.*storage::rpc::Handle::onEvent\(std::auto_ptr<storage::rpc::Event>\)'
- => 'Messages - Documents from storage API messages - original byte buffers',
- 'storage::api::StorageMessageAddress::create.*storage::rpc::Handle::onEvent\(std::auto_ptr<storage::rpc::Event>\)'
- => 'Messages - Storage API message addresses',
- 'document::IdString::createIdString.*storage::api::StorageMessage::onDeserialize'
- => 'Messages - Document identifiers',
- 'storage::api::ApplyBucketDiffCommand::Entry::Entry.*storage::FileStorThread::run'
- => 'Messages - Merge apply entries',
- 'storage::api::ApplyBucketDiffCommand::Entry::Entry.*storage::api::StorageMessage::onDeserialize'
- => 'Messages - Merge apply entries',
- => 'Messages - Queued multi operation commands - cloned for local use in message dispatcher',
-
- 'storage::BufHolder::reserve.*storage::FileStorThread::onGetIterCommand' => 'Visiting - Downsized docblocks',
- 'storage::BufHolder::resize.*storage::FileStorThread::onGetIterCommand' => 'Visiting - Upsized docblocks',
-
- 'JudyLIns.*storage::StorBucketDatabase::(get|insert)' => 'Bucket database - Judy',
- 'JudyLDel.*WrappedEntry::remove' => 'Bucket database - Judy',
- 'std::vector<.*storage::LockableMap.*::WrappedEntry::remove()' => 'Bucket database - Lockable map lock list',
-
- 'document::Printable::toString'
- => 'Other - Temporary data created during toString operations',
-
- 'metrics::MetricsManager::getSnapshotForConsumer' => 'Metrics - Snapshot created',
- 'storage::BucketManagerMetrics::BucketManagerMetrics\(\)' => 'Metrics - Stored metrics',
- 'storage::FileStorThreadMetrics::FileStorThreadMetrics\(std::basic_string' => 'Metrics - Stored metrics',
- 'metrics::MetricsSet::addAll' => 'Metrics - Add all',
- 'storage::StatusMetricConsumer::run\(\)' => 'Metrics',
-
- 'slobrok::api::MirrorAPI::PerformTask\(\)' => 'Slobrok - Mirror API perform task'
-
-);
-
-my $signal;
-my $starttime;
-my $size;
-my %vals;
-my %counts;
-
-my $mallocfault;
-my $local = 0;
-my $global = 0;
-my $globwaste = 0;
-
-# Go through all the input gotten on STDIN.
-foreach (<>) {
- if (/^(\d+)\.\d+\s+\S+\s+\d+\s+\S+\s+\S+\s+warning\s+(.*)$/) {
- # We only care for warnings to logs printed by vespamalloc
- my ($time, $line) = ($1, $2);
- if ($line =~ /SignalHandler (\d+) caught/) {
- # If a dump is just starting, reset all the variables that keeps
- # state
- $signal = $1;
- $size = 0;
- %vals = ();
- %counts = ();
- $local = 0;
- $global = 0;
- $globwaste = 0;
- $mallocfault = undef;
- $starttime = $time;
- print "\nProcessing dump from " . localtime($starttime) . "\n";
- } elsif ($line =~ /^SignalHandler $signal done/) {
- # If we are at the end of the vespamalloc report, print a report of
- # what we have found.
- &printReport();
- $starttime = undef;
- } elsif (!$starttime) {
- # Ignore output that is not within dump
- } elsif ($line =~ /^SC\s*\d+\(\s*(\d+)\)\s*GetAlloc\(\s*(\d+)\)\s*GetFree\(\s*\d+\)\s*ExChangeAlloc\(\s*(\d+)\)\s*ExChangeFree\(\s*(\d+)\)\s*ExactAlloc\(\s*(\d+)\)\s*Returned\(\s*(\d+)\)\s*Malloc\(\s*(\d+)\)\s*/) {
- # Track size groups allocated in hopes of figuring out how much data
- # waste there is in vespa malloc
- my ($size, $get, $exalloc, $exfree, $exact, $returned, $malloc) = ($1, $2, $3, $4, $5, $6, $7);
- #print "$line\n";
- #print "Size $size, GetAlloc $get, ExChangeAlloc $exalloc, ExChangeFree $exfree, ExactAlloc $exact, Returned $returned, Malloc $malloc\n";
- my $mult = 65536;
- if ($size > $mult) { $mult = $size; }
- my $alloced = $get + $exalloc + $exact;
- my $ret = $exfree + $returned;
- if ($size != 2097152) {
- #print "Adding ($alloced - $ret) * $mult = " . (($alloced - $ret) * $mult) . "\n";
- my $global = ($alloced - $ret) * $mult;
- my $waste = $malloc * 1024 * 1024 - ($alloced - $ret) * $mult;
- #print "Size $size - Global $global - Waste $waste\n";
- #$global += ($alloced - $ret) * $mult;
- if ($waste >= 0) {
- $global += $global;
- $globwaste += $waste;
- } else {
- $mallocfault = 1;
- }
- } else {
- $mallocfault = 1;
- }
- } elsif ($line =~ /SC\s*\d+\(\s*(\d+)\)\s*Local\(\s*(\d+)\)/) {
- # Track size groups allocated in hopes of figuring out how much data
- # waste there is in vespa malloc
-
- #print "Local $1 * $2 = ".($1 * $2)."\n";
- $local += $1 * $2;
- } elsif ($line =~ /^SizeClass\s*(\d+)/) {
- #print "$line\n";
- } elsif ($line =~ /^(Usage)/) {
- print "Vespa Malloc $line\n";
- } elsif ($line =~ /(DataSegment|Free|Start)/) {
- } elsif ($line =~ /^(\d+)\s+:\s+\{\s+\S+\s+\S+\s+(\S+[^\}]*)/) {
- # This should match any stacktrace reported. Add this stacktrace
- # to the report.
- my ($count, $value) = ($1, $2);
- # Unify stack trace
- $value =~ s/0x[0-9a-f]+//g;
- $value =~ s/\(\d+\)//g;
- $value =~ s/\(\)//g;
- # Remove multiple UNKNOWN lines in backtrace
- my @stack = split /\s+/, $value;
- $value = '';
- my $last = "";
- foreach (@stack) {
- my $current = &cppfilt($_);
- if ($last !~ /UNKNOWN/ || $current !~ /UNKNOWN/) { # Don't print multiple unknown entries after one another
- $value .= "\n " . &cppfilt($_);
- }
- $last = $current;
- }
- # Detect known stack traces
-
- #print "$count - $value\n";
- my $replaced = 0;
- foreach my $pat (keys %patterns) {
- #print "Does $value match $pat?\n";
- if ($value =~ /$pat/s) {
- if ($showRecognizedStacks) {
- $value = $patterns{$pat} . $value;
- } else {
- $value = $patterns{$pat};
- }
- $replaced = 1;
- last;
- }
- }
- if (!$replaced) {
- if ($combineUnrecognizedStacks) {
- $value = "Unrecognized memory allocations";
- } elsif ($sortOnCategories) {
- $value = "Unrecognized memory allocations" . $value;
- }
- }
- if (exists $vals{$value}) {
- $vals{$value} += $count * $size;
- $counts{$value} += $count;
- } else {
- $vals{$value} = $count * $size;
- $counts{$value} = $count;
- }
- } elsif ($line =~ /^Allocated Blocks SC\s*\d+\(\s*(\d+)/) {
- $size = $1;
- #print "Size: $1\n";
- } else {
- #print "$line\n";
- }
- } else {
- #print "$_";
- }
-}
-if ($starttime) {
- print "Input stopped in incomplete trace.\n";
-}
-
-exit(0);
-
-my %filtered;
-
-sub cppfilt {
- my $val = $_[0];
- if ($val =~ /UNKNOWN/) {
- return "UNKNOWN";
- } elsif (exists $filtered{$val}) {
- return $filtered{$val};
- } else {
- my $result = `c++filt $val`;
- chomp $result;
- $filtered{$val} = $result;
- return $result;
- }
-}
-
-sub getByteString {
- my $val = $_[0];
- if ($val < 5000) {
- return sprintf("%d B", $val);
- } elsif ($val < 5000000) {
- return sprintf("%d kB", $val / 1024);
- } else {
- return sprintf("%d MB", $val / (1024 * 1024));
- }
-}
-
-sub printReport {
- print "Total vespa malloc unused thread local data: " . &getByteString($local) . "\n";
- #print "Total global data: $global\n";
- print "Total vespa malloc global waste data: " . &getByteString($globwaste). "\n";
-
- my $total = 0;
- foreach (keys %vals) {
- $total += $vals{$_};
- }
- if (defined $mallocfault) {
- print "Warning: Some sketchy numbers from vespa malloc, so global and thread local "
- . "data is probably inaccurate.\n";
- }
-
- print "\nSummary of allocated data:\n";
- print &getByteString($total) . " bytes tracked total\n";
-
- if ($sortOnCategories) {
- my %categories;
- foreach (keys %vals) {
- if (/^\s*(\S+)/) {
- my $category = $1;
- if (exists $categories{$category}) {
- ${$categories{$category}}[0] += $vals{$_};
- push @{$categories{$category}}, $_;
- } else {
- $categories{$category} = [ $vals{$_}, $_ ];
- }
- }
- }
- foreach (sort { ${$categories{$b}}[0] <=> ${$categories{$a}}[0] } keys %categories) {
- my @values = @{ $categories{$_} };
- print &getByteString($values[0]) . " - $_\n";
- shift @values;
-
- foreach my $val (sort { $vals{$b} <=> $vals{$a} } @values) {
- my $stack = $val;
- $stack =~ s/\n/\n /sg;
- print " " . &getByteString($vals{$val}) . " - " . $counts{$val} . " allocations - $stack\n";
- }
- }
- } else {
- foreach (sort { $vals{$b} <=> $vals{$a} } keys %vals) {
- print &getByteString($vals{$_}) . " - " . $counts{$_} . " allocations - $_\n";
- }
- }
-}
diff --git a/yolean/.gitignore b/yolean/.gitignore
deleted file mode 100644
index 12251442258..00000000000
--- a/yolean/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/target
-/pom.xml.build
diff --git a/yolean/OWNERS b/yolean/OWNERS
deleted file mode 100644
index 569bf1cc3a1..00000000000
--- a/yolean/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-bjorncs
diff --git a/yolean/README.sh b/yolean/README.sh
deleted file mode 100755
index 628d5a6a2dd..00000000000
--- a/yolean/README.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/sh
-# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-if [ -z ${VERSION} ]; then
- echo "Environment VERSION not set." >&2
- exit 1;
-fi
-cat <<EOF
-
-Yolean is a collection of Java utility classes that may be useful
-across various products. INclusion here has a higher threshold than
-vespajlib.
-
-EOF
diff --git a/yolean/abi-spec.json b/yolean/abi-spec.json
deleted file mode 100644
index 5085f67811c..00000000000
--- a/yolean/abi-spec.json
+++ /dev/null
@@ -1,332 +0,0 @@
-{
- "com.yahoo.yolean.Exceptions$RunnableThrowingIOException": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract void run()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract void run()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.Exceptions$SupplierThrowingIOException": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract java.lang.Object get()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.Exceptions": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>()",
- "public static java.lang.String toMessageString(java.lang.Throwable)",
- "public static java.util.Optional findCause(java.lang.Throwable, java.lang.Class)",
- "public static void uncheck(com.yahoo.yolean.Exceptions$RunnableThrowingIOException)",
- "public static void uncheckInterrupted(com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException)",
- "public static void uncheckInterruptedAndRestoreFlag(com.yahoo.yolean.Exceptions$RunnableThrowingInterruptedException)",
- "public static varargs void uncheck(com.yahoo.yolean.Exceptions$RunnableThrowingIOException, java.lang.String, java.lang.String[])",
- "public static void uncheckAndIgnore(com.yahoo.yolean.Exceptions$RunnableThrowingIOException, java.lang.Class)",
- "public static java.lang.Object uncheck(com.yahoo.yolean.Exceptions$SupplierThrowingIOException)",
- "public static varargs java.lang.Object uncheck(com.yahoo.yolean.Exceptions$SupplierThrowingIOException, java.lang.String, java.lang.String[])",
- "public static java.lang.Object uncheckAndIgnore(com.yahoo.yolean.Exceptions$SupplierThrowingIOException, java.lang.Class)",
- "public static java.lang.RuntimeException throwUnchecked(java.lang.Throwable)"
- ],
- "fields": []
- },
- "com.yahoo.yolean.UncheckedInterruptedException": {
- "superClass": "java.lang.RuntimeException",
- "interfaces": [],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>(java.lang.String, java.lang.InterruptedException, boolean)",
- "public void <init>(java.lang.InterruptedException, boolean)",
- "public void <init>(java.lang.String, boolean)",
- "public void <init>(java.lang.String, java.lang.InterruptedException)",
- "public void <init>(java.lang.InterruptedException)",
- "public java.lang.InterruptedException getCause()",
- "public bridge synthetic java.lang.Throwable getCause()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.chain.After": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.annotation.Annotation"
- ],
- "attributes": [
- "public",
- "interface",
- "abstract",
- "annotation"
- ],
- "methods": [
- "public abstract java.lang.String[] value()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.chain.Before": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.annotation.Annotation"
- ],
- "attributes": [
- "public",
- "interface",
- "abstract",
- "annotation"
- ],
- "methods": [
- "public abstract java.lang.String[] value()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.chain.Provides": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.annotation.Annotation"
- ],
- "attributes": [
- "public",
- "interface",
- "abstract",
- "annotation"
- ],
- "methods": [
- "public abstract java.lang.String[] value()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.ConcurrentResourcePool": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.Iterable"
- ],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>(java.util.function.Supplier)",
- "public void preallocate(int)",
- "public final java.lang.Object alloc()",
- "public final void free(java.lang.Object)",
- "public java.util.Iterator iterator()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.CopyOnWriteHashMap": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.util.Map"
- ],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>()",
- "public int size()",
- "public boolean isEmpty()",
- "public boolean containsKey(java.lang.Object)",
- "public boolean containsValue(java.lang.Object)",
- "public java.lang.Object get(java.lang.Object)",
- "public java.lang.Object put(java.lang.Object, java.lang.Object)",
- "public java.lang.Object remove(java.lang.Object)",
- "public void putAll(java.util.Map)",
- "public void clear()",
- "public java.util.Set keySet()",
- "public java.util.Collection values()",
- "public java.util.Set entrySet()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.Memoized$Closer": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract void close(java.lang.Object)"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.Memoized": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.util.function.Supplier",
- "java.lang.AutoCloseable"
- ],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>(java.util.function.Supplier, com.yahoo.yolean.concurrent.Memoized$Closer)",
- "public static com.yahoo.yolean.concurrent.Memoized of(java.util.function.Supplier)",
- "public static com.yahoo.yolean.concurrent.Memoized combine(com.yahoo.yolean.concurrent.Memoized, java.util.function.Function, com.yahoo.yolean.concurrent.Memoized$Closer)",
- "public java.lang.Object get()",
- "public void close()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.ResourcePool": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.Iterable"
- ],
- "attributes": [
- "public",
- "final"
- ],
- "methods": [
- "public void <init>(java.util.function.Supplier)",
- "public java.lang.Object alloc()",
- "public void free(java.lang.Object)",
- "public java.util.Iterator iterator()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.concurrent.Sleeper": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public void sleep(java.time.Duration)",
- "public void sleepChecked(java.time.Duration)",
- "public void sleep(long)",
- "public abstract void sleepChecked(long)"
- ],
- "fields": [
- "public static final com.yahoo.yolean.concurrent.Sleeper DEFAULT",
- "public static final com.yahoo.yolean.concurrent.Sleeper NOOP"
- ]
- },
- "com.yahoo.yolean.concurrent.ThreadRobustList": {
- "superClass": "java.lang.Object",
- "interfaces": [
- "java.lang.Iterable"
- ],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>()",
- "public void <init>(int)",
- "public boolean isEmpty()",
- "public void add(java.lang.Object)",
- "public java.util.Iterator iterator()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.function.ThrowingConsumer": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract void accept(java.lang.Object)",
- "public com.yahoo.yolean.function.ThrowingConsumer andThen(com.yahoo.yolean.function.ThrowingConsumer)"
- ],
- "fields": []
- },
- "com.yahoo.yolean.function.ThrowingFunction": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract java.lang.Object apply(java.lang.Object)",
- "public com.yahoo.yolean.function.ThrowingFunction andThen(com.yahoo.yolean.function.ThrowingFunction)",
- "public com.yahoo.yolean.function.ThrowingFunction compose(com.yahoo.yolean.function.ThrowingFunction)"
- ],
- "fields": []
- },
- "com.yahoo.yolean.function.ThrowingSupplier": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "interface",
- "abstract"
- ],
- "methods": [
- "public abstract java.lang.Object get()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.trace.TraceNode": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public"
- ],
- "methods": [
- "public void <init>(java.lang.Object, long)",
- "public com.yahoo.yolean.trace.TraceNode add(com.yahoo.yolean.trace.TraceNode)",
- "public java.lang.Iterable descendants(java.lang.Class)",
- "public java.lang.Object payload()",
- "public long timestamp()",
- "public com.yahoo.yolean.trace.TraceNode parent()",
- "public java.lang.Iterable children()",
- "public boolean isRoot()",
- "public com.yahoo.yolean.trace.TraceNode root()",
- "public com.yahoo.yolean.trace.TraceVisitor accept(com.yahoo.yolean.trace.TraceVisitor)",
- "public java.lang.String toString()"
- ],
- "fields": []
- },
- "com.yahoo.yolean.trace.TraceVisitor": {
- "superClass": "java.lang.Object",
- "interfaces": [],
- "attributes": [
- "public",
- "abstract"
- ],
- "methods": [
- "public void <init>()",
- "public abstract void visit(com.yahoo.yolean.trace.TraceNode)",
- "public void entering(com.yahoo.yolean.trace.TraceNode)",
- "public void leaving(com.yahoo.yolean.trace.TraceNode)"
- ],
- "fields": []
- }
-} \ No newline at end of file
diff --git a/yolean/pom.xml b/yolean/pom.xml
deleted file mode 100644
index a767e6dfcdd..00000000000
--- a/yolean/pom.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>parent</artifactId>
- <version>8-SNAPSHOT</version>
- <relativePath>../parent/pom.xml</relativePath>
- </parent>
- <artifactId>yolean</artifactId>
- <version>8-SNAPSHOT</version>
- <packaging>container-plugin</packaging>
- <name>${project.artifactId}</name>
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>annotations</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>bundle-plugin</artifactId>
- <extensions>true</extensions>
- </plugin>
- <plugin>
- <!-- Needed for IntelliJ -->
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>abi-check-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/zkfacade/pom.xml b/zkfacade/pom.xml
index 0360b9ce91f..17be17d8302 100644
--- a/zkfacade/pom.xml
+++ b/zkfacade/pom.xml
@@ -31,18 +31,6 @@
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
- <artifactId>vespajlib</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- <exclusions>
- <exclusion>
- <groupId>org.lz4</groupId>
- <artifactId>lz4-java</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
<artifactId>zookeeper-server-common</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
diff --git a/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorCompletionWaiter.java b/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorCompletionWaiter.java
index 241ffbfd4d3..d5207c6fab8 100644
--- a/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorCompletionWaiter.java
+++ b/zkfacade/src/main/java/com/yahoo/vespa/curator/CuratorCompletionWaiter.java
@@ -44,7 +44,7 @@ class CuratorCompletionWaiter implements Curator.CompletionWaiter {
throw new RuntimeException(e);
}
if (respondents.size() < barrierMemberCount()) {
- throw new CompletionTimeoutException("Timed out waiting for peer config servers to complete operation " +
+ throw new CompletionTimeoutException("Timed out waiting for config servers to complete operation " +
"(waited for barrier " + barrierPath + ")." +
"Got response from " + respondents + ", but need response from " +
"at least " + barrierMemberCount() + " server(s). " +
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/api/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/api/package-info.java
index a11b83fbdd0..ef2f1732a5e 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/api/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/api/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.api;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/api/transaction/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/api/transaction/package-info.java
index 057c1c5505c..33e58865082 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/api/transaction/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/api/transaction/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.api.transaction;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/listen/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/listen/package-info.java
index e0a7cc2d42a..acffcc0998c 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/listen/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/listen/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.listen;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/package-info.java
index 5896beaf69a..ab7fac0e20a 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/recipes/atomic/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/recipes/atomic/package-info.java
index 09e33125703..50c95084655 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/recipes/atomic/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/recipes/atomic/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.recipes.atomic;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/recipes/barriers/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/recipes/barriers/package-info.java
index 17cd18722c6..7c0613fa468 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/recipes/barriers/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/recipes/barriers/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.recipes.barriers;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/recipes/cache/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/recipes/cache/package-info.java
index 5b882f83f39..1728e179e5e 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/recipes/cache/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/recipes/cache/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.recipes.cache;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/recipes/locks/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/recipes/locks/package-info.java
index 9c9644d717d..737ec2b2978 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/recipes/locks/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/recipes/locks/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.recipes.locks;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/framework/state/package-info.java b/zkfacade/src/main/java/org/apache/curator/framework/state/package-info.java
index d956561314b..010d2b1afdd 100644
--- a/zkfacade/src/main/java/org/apache/curator/framework/state/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/framework/state/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.framework.state;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/package-info.java b/zkfacade/src/main/java/org/apache/curator/package-info.java
index e8ffc14e54e..fa007a89313 100644
--- a/zkfacade/src/main/java/org/apache/curator/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zkfacade/src/main/java/org/apache/curator/retry/package-info.java b/zkfacade/src/main/java/org/apache/curator/retry/package-info.java
index b2d2a27c98e..05128a3acbf 100644
--- a/zkfacade/src/main/java/org/apache/curator/retry/package-info.java
+++ b/zkfacade/src/main/java/org/apache/curator/retry/package-info.java
@@ -1,5 +1,5 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-@ExportPackage(version = @Version(major = 5, minor = 2, micro = 1))
+@ExportPackage(version = @Version(major = 5, minor = 3, micro = 0))
package org.apache.curator.retry;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
diff --git a/zookeeper-client-common/pom.xml b/zookeeper-client-common/pom.xml
index 5eafd040e79..c3dc4629702 100644
--- a/zookeeper-client-common/pom.xml
+++ b/zookeeper-client-common/pom.xml
@@ -40,8 +40,13 @@
<!-- compile scope -->
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java b/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
index 7ffce79b67a..6248424d8da 100644
--- a/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
+++ b/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.zookeeper.client;
import com.yahoo.security.tls.TlsContext;
import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
@@ -17,8 +17,8 @@ import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_CLIENTA
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_CONTEXT_SUPPLIER_CLASS_PROPERTY;
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_ENABLED_CIPHERSUITES_PROPERTY;
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_ENABLED_PROTOCOLS_PROPERTY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests the zookeeper client config builder.
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertNull;
public class ZkClientConfigBuilderTest {
@Test
- public void config_when_not_using_tls_context() {
+ void config_when_not_using_tls_context() {
ZkClientConfigBuilder builder = new ZkClientConfigBuilder(null);
ZKClientConfig config = builder.toConfig();
assertEquals("false", config.getProperty(CLIENT_SECURE_PROPERTY));
@@ -36,7 +36,7 @@ public class ZkClientConfigBuilderTest {
}
@Test
- public void config_when_using_system_tls_context() {
+ void config_when_using_system_tls_context() {
ZkClientConfigBuilder builder = new ZkClientConfigBuilder(new MockTlsContext());
ZKClientConfig config = builder.toConfig();
assertEquals("true", config.getProperty(CLIENT_SECURE_PROPERTY));
diff --git a/zookeeper-server/CMakeLists.txt b/zookeeper-server/CMakeLists.txt
index 42ecff1cc96..b5b1641c54e 100644
--- a/zookeeper-server/CMakeLists.txt
+++ b/zookeeper-server/CMakeLists.txt
@@ -1,4 +1,4 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
add_subdirectory(zookeeper-server-common)
add_subdirectory(zookeeper-server)
-add_subdirectory(zookeeper-server-3.7.1)
+add_subdirectory(zookeeper-server-3.8.0)
diff --git a/zookeeper-server/README b/zookeeper-server/README
index 2f4845dad29..e8218ca2149 100644
--- a/zookeeper-server/README
+++ b/zookeeper-server/README
@@ -2,7 +2,7 @@ Vespa ZooKeeper server interface
Subdirectory zookeeper-server has code for the zookeeper server
version we use by default, testing out new versions can be done by
-copying zookeeper-server dir to zookeeper-server-<version> and
+copying zookeeper-server dir to zookeeper-server-<version>,
updating CMakeLists.txt and pom.xml in that directory and pom.xml and
CMakeLists.txt in this directory. Selecting zookeeper server version
-is done with feature flag ZOOKEEPER_SERVER_VERSION.
+that is used runtime is done with feature flag ZOOKEEPER_SERVER_VERSION.
diff --git a/zookeeper-server/pom.xml b/zookeeper-server/pom.xml
index b9cc4478bc2..cf19f15e71f 100644
--- a/zookeeper-server/pom.xml
+++ b/zookeeper-server/pom.xml
@@ -14,7 +14,7 @@
<modules>
<module>zookeeper-server-common</module>
<module>zookeeper-server</module>
- <module>zookeeper-server-3.7.1</module>
+ <module>zookeeper-server-3.8.0</module>
</modules>
<dependencies>
<dependency>
diff --git a/zookeeper-server/zookeeper-server-3.7.1/CMakeLists.txt b/zookeeper-server/zookeeper-server-3.8.0/CMakeLists.txt
index 6afd812ef07..e0fcc05c90a 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/CMakeLists.txt
+++ b/zookeeper-server/zookeeper-server-3.8.0/CMakeLists.txt
@@ -1,2 +1,2 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-install_jar(zookeeper-server-3.7.1-jar-with-dependencies.jar)
+install_jar(zookeeper-server-3.8.0-jar-with-dependencies.jar)
diff --git a/zookeeper-server/zookeeper-server-3.7.1/pom.xml b/zookeeper-server/zookeeper-server-3.8.0/pom.xml
index ea0e61075f1..f6c8952849c 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/pom.xml
+++ b/zookeeper-server/zookeeper-server-3.8.0/pom.xml
@@ -8,11 +8,11 @@
<version>8-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
- <artifactId>zookeeper-server-3.7.1</artifactId>
+ <artifactId>zookeeper-server-3.8.0</artifactId>
<packaging>container-plugin</packaging>
<version>8-SNAPSHOT</version>
<properties>
- <zookeeper.version>3.7.1</zookeeper.version>
+ <zookeeper.version>3.8.0</zookeeper.version>
</properties>
<dependencies>
<dependency>
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java
index e94110af2fb..e94110af2fb 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/ReconfigurableVespaZooKeeperServer.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java
index 66742b0e05b..66742b0e05b 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaMtlsAuthenticationProvider.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java
index 47ec03367c1..47ec03367c1 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaQuorumPeer.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java
index ae7bf8d84f5..ae7bf8d84f5 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java
index 48f95d28910..48f95d28910 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperServerImpl.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/common/NetUtils.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/common/NetUtils.java
index 33ec9b1303a..33ec9b1303a 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/common/NetUtils.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/common/NetUtils.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java
index fdfe0fe8467..fdfe0fe8467 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/main/java/org/apache/zookeeper/server/VespaNettyServerCnxnFactory.java
diff --git a/zookeeper-server/zookeeper-server-3.7.1/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java b/zookeeper-server/zookeeper-server-3.8.0/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java
index db643d76e0d..db643d76e0d 100644
--- a/zookeeper-server/zookeeper-server-3.7.1/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java
+++ b/zookeeper-server/zookeeper-server-3.8.0/src/test/java/com/yahoo/vespa/zookeper/VespaZooKeeperTest.java
diff --git a/zookeeper-server/zookeeper-server-common/src/test/java/com/yahoo/vespa/zookeeper/ConfiguratorTest.java b/zookeeper-server/zookeeper-server-common/src/test/java/com/yahoo/vespa/zookeeper/ConfiguratorTest.java
index d2361853436..6dcdc76a593 100644
--- a/zookeeper-server/zookeeper-server-common/src/test/java/com/yahoo/vespa/zookeeper/ConfiguratorTest.java
+++ b/zookeeper-server/zookeeper-server-common/src/test/java/com/yahoo/vespa/zookeeper/ConfiguratorTest.java
@@ -5,12 +5,12 @@ import com.yahoo.cloud.config.ZookeeperServerConfig;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.tls.AuthorizationMode;
+import com.yahoo.security.tls.AuthorizedPeers;
import com.yahoo.security.tls.DefaultTlsContext;
import com.yahoo.security.tls.HostnameVerification;
import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.PeerAuthentication;
import com.yahoo.security.tls.TlsContext;
-import com.yahoo.security.tls.policy.AuthorizedPeers;
import com.yahoo.yolean.Exceptions;
import org.junit.Before;
import org.junit.Rule;
diff --git a/zookeeper-server/zookeeper-server/CMakeLists.txt b/zookeeper-server/zookeeper-server/CMakeLists.txt
index 98cb495e4b6..c99916fafad 100644
--- a/zookeeper-server/zookeeper-server/CMakeLists.txt
+++ b/zookeeper-server/zookeeper-server/CMakeLists.txt
@@ -1,4 +1,4 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-install_jar(zookeeper-server-3.7.0-jar-with-dependencies.jar)
+install_jar(zookeeper-server-3.7.1-jar-with-dependencies.jar)
# Make symlink so that we have a default version, should be done only in zookeeper-server module
-install_symlink(lib/jars/zookeeper-server-3.7.0-jar-with-dependencies.jar lib/jars/zookeeper-server-jar-with-dependencies.jar)
+install_symlink(lib/jars/zookeeper-server-3.7.1-jar-with-dependencies.jar lib/jars/zookeeper-server-jar-with-dependencies.jar)
diff --git a/zookeeper-server/zookeeper-server/pom.xml b/zookeeper-server/zookeeper-server/pom.xml
index 72cb21b2362..ea0e61075f1 100644
--- a/zookeeper-server/zookeeper-server/pom.xml
+++ b/zookeeper-server/zookeeper-server/pom.xml
@@ -8,11 +8,11 @@
<version>8-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
- <artifactId>zookeeper-server-3.7.0</artifactId>
+ <artifactId>zookeeper-server-3.7.1</artifactId>
<packaging>container-plugin</packaging>
<version>8-SNAPSHOT</version>
<properties>
- <zookeeper.version>3.7.0</zookeeper.version>
+ <zookeeper.version>3.7.1</zookeeper.version>
</properties>
<dependencies>
<dependency>